Example #1
0
def center_two_dee():
    """
    Center the selected transform onto the camera view.
    """
    mmapi.load_plugin()

    cam_shp = __get_camera()
    if cam_shp is None:
        LOG.warning('Please select an active viewport to get a camera.')
        return
    cam_tfm = maya.cmds.listRelatives(cam_shp, parent=True)[0]

    save_sel = maya.cmds.ls(selection=True, long=True) or []

    # Create centering node network.
    nodes = maya.cmds.ls(selection=True, long=True, type='transform') or []
    if len(nodes) == 0:
        __remove_reprojection(cam_tfm, cam_shp)
    elif len(nodes) == 1:
        reproj_nodes = __find_reprojection_nodes(cam_tfm, cam_shp)
        if len(reproj_nodes) > 0:
            maya.cmds.delete(reproj_nodes)
        __connect_camera_and_transform(cam_tfm, cam_shp, nodes[0])
    elif len(nodes) > 1:
        msg = 'Please select only 1 node to center on.'
        LOG.error(msg)

    if len(save_sel) > 0:
        maya.cmds.select(save_sel, replace=True)
    return
Example #2
0
def main():
    """
    Convert all selected transforms into 2D markers under a camera.
    """
    # Get camera
    model_editor = utils_viewport.get_active_model_editor()
    if model_editor is None:
        msg = 'Please select an active 3D viewport.'
        LOG.warning(msg)
        return

    cam_tfm, cam_shp = utils_viewport.get_viewport_camera(model_editor)
    if cam_shp is None:
        LOG.error('Please select an active viewport to get a camera.')
        return
    if utils_camera.is_startup_cam(cam_shp) is True:
        LOG.error("Cannot create Markers in 'persp' camera.")
        return

    # Get transforms
    nodes = maya.cmds.ls(
        selection=True,
        long=True,
        type='transform',
    ) or []
    if len(nodes) == 0:
        LOG.warning('Please select one or more transform nodes.')
        return

    mmapi.load_plugin()
    try:
        # Turn off Maya UI
        maya.mel.eval('paneLayout -e -manage false $gMainPane')

        # Compute the Marker Data.
        start_frame, end_frame = utils_time.get_maya_timeline_range_outer()
        mkr_data_list = __convert_nodes_to_marker_data_list(
            cam_tfm,
            cam_shp,
            nodes,
            start_frame,
            end_frame,
        )

        cam = mmapi.Camera(shape=cam_shp)
        mkr_list = mayareadfile.create_nodes(
            mkr_data_list,
            cam=cam,
            mkr_grp=None,
            with_bundles=True,
        )
        mkr_nodes = [mkr.get_node() for mkr in mkr_list]
    except:
        raise
    finally:
        # Turn on Maya UI
        maya.mel.eval('paneLayout -e -manage true $gMainPane')
    if len(mkr_nodes) > 0:
        maya.cmds.select(mkr_nodes, replace=True)
    return
def __create_node(mkr_data, cam, mkr_grp, with_bundles):
    """
    Create a Marker object from a MarkerData object.
    """
    if isinstance(mkr_data, interface.MarkerData) is False:
        msg = 'mkr_data must be of type: %r'
        raise TypeError(msg % interface.MarkerData.__name__)
    if isinstance(with_bundles, bool) is False:
        msg = 'with_bundles must be of type: %r'
        raise TypeError(msg % bool.__name__)

    name = mkr_data.get_name()
    mkr_name = mmapi.get_new_marker_name(name)
    bnd_name = mmapi.get_new_bundle_name(name)
    bnd = None
    mmapi.load_plugin()
    if with_bundles is True:
        bnd = mmapi.Bundle().create_node(bnd_name)
    if cam and mkr_grp:
        cam = None
    mkr = mmapi.Marker().create_node(name=mkr_name,
                                     cam=cam,
                                     mkr_grp=mkr_grp,
                                     bnd=bnd)
    return mkr, bnd
Example #4
0
def run_connect_markers_to_active_collection(**kwargs):
    import mmSolver.tools.userpreferences.constant as userprefs_const
    import mmSolver.tools.userpreferences.lib as userprefs_lib

    # Enable a toggle to turn on or off this affect.
    config = userprefs_lib.get_config()
    key = userprefs_const.REG_EVNT_ADD_NEW_MKR_TO_KEY
    run_event = userprefs_lib.get_value(config, key)
    if run_event == userprefs_const.REG_EVNT_ADD_NEW_MKR_TO_NONE_VALUE:
        return

    LOG.debug("run_connect_markers_to_active_collection: %s", kwargs)
    s = time.time()
    import mmSolver.api as mmapi
    import mmSolver.tools.solver.lib.state as state_lib
    mmapi.load_plugin()

    col = state_lib.get_active_collection()
    if col is None:
        return

    mkr = kwargs.get('mkr')
    if isinstance(mkr, list):
        col.add_marker_list(mkr)
    elif isinstance(mkr, mmapi.Marker):
        col.add_marker(mkr)

    e = time.time()
    LOG.debug("run_connect_markers_to_active_collection: time=%s", e - s)
    return
Example #5
0
def ensure_plugin_loaded():
    """
    Loads all plug-ins required for Solver tool.

    :raises: mmapi.SolverNotAvailable
    """
    mmapi.load_plugin()
    name = 'mmSolver'
    if name not in dir(maya.cmds):
        raise mmapi.SolverNotAvailable
    return
Example #6
0
def create_reprojection_on_camera(cam_tfm, cam_shp):
    """
    Create a mmReprojection node, then connect it up as needed.
    """
    try:
        node = maya.cmds.createNode('mmReprojection')
    except RuntimeError:
        # Do not force loading the plug-in each time the tool is
        # run, only if an error happens.
        mmapi.load_plugin()
        try:
            node = maya.cmds.createNode('mmReprojection')
        except RuntimeError:
            raise

    # Connect camera attributes
    maya.cmds.connectAttr(cam_tfm + '.worldMatrix',
                          node + '.cameraWorldMatrix')
    maya.cmds.connectAttr(cam_shp + '.focalLength', node + '.focalLength')
    maya.cmds.connectAttr(cam_shp + '.cameraAperture',
                          node + '.cameraAperture')
    maya.cmds.connectAttr(cam_shp + '.filmOffset', node + '.filmOffset')
    maya.cmds.connectAttr(cam_shp + '.filmFit', node + '.filmFit')
    maya.cmds.connectAttr(cam_shp + '.nearClipPlane', node + '.nearClipPlane')
    maya.cmds.connectAttr(cam_shp + '.farClipPlane', node + '.farClipPlane')
    maya.cmds.connectAttr(cam_shp + '.cameraScale', node + '.cameraScale')

    # Connect render settings attributes
    resolution_factor = 10000.0
    mult_node = maya.cmds.createNode('multiplyDivide')
    maya.cmds.setAttr(mult_node + '.input2X', resolution_factor)
    maya.cmds.setAttr(mult_node + '.input2Y', resolution_factor)
    maya.cmds.connectAttr(cam_shp + '.horizontalFilmAperture',
                          mult_node + '.input1X')
    maya.cmds.connectAttr(cam_shp + '.verticalFilmAperture',
                          mult_node + '.input1Y')
    maya.cmds.connectAttr(mult_node + '.outputX', node + '.imageWidth')
    maya.cmds.connectAttr(mult_node + '.outputY', node + '.imageHeight')

    # Connect Pan to camera.pan
    maya.cmds.connectAttr(node + '.outPan', cam_shp + '.pan')

    # Turn on 'Pan/Zoom'
    plug = cam_shp + '.panZoomEnabled'
    locked = maya.cmds.getAttr(plug, lock=True)
    if locked is False:
        maya.cmds.setAttr(plug, True)
    return node
Example #7
0
def convert_to_marker():
    """
    Center the selected transform onto the camera view.
    """
    # Get camera
    cam_shp = __get_camera()
    if cam_shp is None:
        LOG.warning('Please select an active viewport to get a camera.')
        return
    cam_tfm = maya.cmds.listRelatives(cam_shp, parent=True)[0]

    # Get transforms
    nodes = maya.cmds.ls(
        selection=True,
        long=True,
        type='transform',
    ) or []
    if len(nodes) == 0:
        LOG.warning('Please select one or more transform nodes.')
        return

    mmapi.load_plugin()
    try:
        # Turn off Maya UI
        maya.mel.eval('paneLayout -e -manage false $gMainPane')

        # Compute the Marker Data.
        start_frame, end_frame = __get_timeline_range_inner()
        mkr_data_list = __convert_nodes_to_marker_data_list(
            cam_tfm, cam_shp, nodes, start_frame, end_frame)

        cam = mmapi.Camera(shape=cam_shp)
        mayareadfile.create_nodes(
            mkr_data_list,
            cam=cam,
            mkr_grp=None,
            with_bundles=False,
        )
    except:
        raise
    finally:
        maya.mel.eval(
            'paneLayout -e -manage true $gMainPane')  # turn on Maya UI
    return
Example #8
0
def main():
    """
    Switch to 'place marker at' tool.
    """
    mmapi.load_plugin()

    if maya.cmds.draggerContext(const.CTX, exists=True):
        maya.cmds.deleteUI(const.CTX)

    maya.cmds.draggerContext(const.CTX,
                             prePressCommand=on_pre_press,
                             pressCommand=on_press,
                             releaseCommand=on_release,
                             holdCommand=on_hold,
                             dragCommand=on_drag,
                             finalize=tool_clean_up,
                             name=const.CTX,
                             cursor='crossHair')
    maya.cmds.setToolTo(const.CTX)
Example #9
0
def __create_node(mkr_data, cam, mkr_grp, with_bundles):
    """
    Create a Marker object from a MarkerData object.

    :param mkr_data: The data to create the Marker with.
    :type mkr_data: MarkerData

    :param cam: Camera to create marker node underneath.
    :type cam: Camera

    :param mkr_grp: MarkerGroup to create marker underneath
    :type mkr_grp: MarkerGroup

    :param with_bundles: Create the Marker with Bundle attached?
    :type with_bundles: bool

    :returns: Created Marker and Bundle objects. If with_bundles is
              False, the Bundle object will be None.
    :rtype: (Marker, Bundle or None)
    """
    if isinstance(mkr_data, interface.MarkerData) is False:
        msg = 'mkr_data must be of type: %r'
        raise TypeError(msg % interface.MarkerData.__name__)
    if isinstance(with_bundles, bool) is False:
        msg = 'with_bundles must be of type: %r'
        raise TypeError(msg % bool.__name__)

    name = mkr_data.get_name()
    mkr_name = mmapi.get_new_marker_name(name)
    bnd_name = mmapi.get_new_bundle_name(name)
    bnd = None
    mmapi.load_plugin()
    if with_bundles is True:
        bnd = mmapi.Bundle().create_node(bnd_name)
    if cam and mkr_grp:
        cam = None
    mkr = mmapi.Marker().create_node(
        name=mkr_name,
        cam=cam,
        mkr_grp=mkr_grp,
        bnd=bnd)
    return mkr, bnd
Example #10
0
def remove():
    """
    Remove the centering nodes in the current active viewport.
    """
    model_editor = viewport_utils.get_active_model_editor()
    if model_editor is None:
        msg = 'Please select an active 3D viewport.'
        LOG.warning(msg)
        return

    cam_tfm, cam_shp = viewport_utils.get_viewport_camera(model_editor)
    if cam_shp is None:
        msg = 'Please select an active 3D viewport to get a camera.'
        LOG.warning(msg)
        return

    try:
        mmapi.set_solver_running(True)
        mmapi.load_plugin()
        reproject_utils.remove_reprojection_from_camera(cam_tfm, cam_shp)
        reproject_utils.reset_pan_zoom(cam_tfm, cam_shp)
    finally:
        mmapi.set_solver_running(False)
    return
Example #11
0
def main():
    """
    Screen-Space Bake.

    Usage:

    1) Select transform nodes.
    2) Activate viewport.
    3) Run tool.
    4) A new locator is created under the active camera
    """
    mmapi.load_plugin()

    editor = viewport_utils.get_active_model_editor()
    if editor is None:
        LOG.error('Please select an active viewport; editor=%r', editor)
        return
    cam_tfm, cam_shp = viewport_utils.get_viewport_camera(editor)
    if cam_tfm is None or cam_shp is None:
        LOG.error('Please select a camera; cam_tfm=%r cam_shp=%r',
                  cam_tfm, cam_shp)
        return
    cam = mmapi.Camera(transform=cam_tfm, shape=cam_shp)
    img_width = maya.cmds.getAttr(cam_shp + '.horizontalFilmAperture') * 100.0
    img_height = maya.cmds.getAttr(cam_shp + '.verticalFilmAperture') * 100.0

    nodes = maya.cmds.ls(
        selection=True,
        long=True,
        type='transform'
    ) or []
    if len(nodes) == 0:
        LOG.error('Please select transform nodes; %r', nodes)
        return

    start_frame, end_frame = utils_time.get_maya_timeline_range_inner()
    times = range(start_frame, end_frame+1)

    created_loc_tfms = []
    for node in nodes:
        grp_node, depth_tfm, loc_tfm, loc_shp = lib.create_screen_space_locator(cam)
        created_loc_tfms.append(loc_tfm)

        # BUG: If a camera has 'camera scale' attribute set other than
        # 1.0, the reprojected values will not be correct.
        values = maya.cmds.mmReprojection(
            node,
            camera=(cam_tfm, cam_shp),
            time=times,
            asMarkerCoordinate=True,
            imageResolution=(int(img_width), int(img_height)),
        )
        stop = len(values)
        step = 3

        plug = loc_tfm + '.translateX'
        values_x = values[0:stop:step]
        animfn_x = anim_utils.create_anim_curve_node_apione(
            times, values_x,
            node_attr=plug
        )

        plug = loc_tfm + '.translateY'
        values_y = values[1:stop:step]
        animfn_y = anim_utils.create_anim_curve_node_apione(
            times, values_y,
            node_attr=plug
        )

        plug = depth_tfm + '.scaleX'
        values_z = values[2:stop:step]
        animfn_z = anim_utils.create_anim_curve_node_apione(
            times, values_z,
            node_attr=plug
        )

    if len(created_loc_tfms) > 0:
        maya.cmds.select(created_loc_tfms, replace=True)

    # Trigger Maya to refresh.
    maya.cmds.currentTime(update=True)
    maya.cmds.refresh()
    return
Example #12
0
def main():
    """
    Center the selected transform onto the camera view.

    .. todo::

        - Allow 2D Center on selected vertices.

        - Support Stereo-camera setups (center both cameras, and ensure
          both have the same zoom).

        - Allow centering on multiple objects at once. We will center
          on the middle of all transforms.

    """
    model_editor = viewport_utils.get_active_model_editor()
    if model_editor is None:
        msg = 'Please select an active 3D viewport.'
        LOG.warning(msg)
        return

    cam_tfm, cam_shp = viewport_utils.get_viewport_camera(model_editor)
    if cam_shp is None:
        msg = 'Please select an active 3D viewport to get a camera.'
        LOG.warning(msg)
        return

    try:
        mmapi.set_solver_running(True)

        save_sel = maya.cmds.ls(selection=True, long=True) or []

        # Get selection
        nodes = maya.cmds.ls(
            selection=True,
            long=True,
            type='transform',
        ) or []

        # Filter out selected imagePlanes.
        nodes_tmp = list(nodes)
        nodes = []
        for node in nodes_tmp:
            shps = maya.cmds.listRelatives(
                node, shapes=True, fullPath=True, type='imagePlane') or []
            if len(shps) == 0:
                nodes.append(node)

        # Create centering node network.
        if len(nodes) == 0:
            msg = 'No objects selected, removing 2D centering.'
            LOG.warning(msg)
            mmapi.load_plugin()
            reproject_utils.remove_reprojection_from_camera(cam_tfm, cam_shp)
            reproject_utils.reset_pan_zoom(cam_tfm, cam_shp)
        elif len(nodes) == 1:
            msg = 'Applying 2D centering to %r'
            LOG.warning(msg, nodes)
            mmapi.load_plugin()
            reproj_nodes = reproject_utils.find_reprojection_nodes(
                cam_tfm, cam_shp)
            if len(reproj_nodes) > 0:
                maya.cmds.delete(reproj_nodes)

            reproj_node = reproject_utils.create_reprojection_on_camera(
                cam_tfm, cam_shp)
            reproject_utils.connect_transform_to_reprojection(
                nodes[0], reproj_node)
        elif len(nodes) > 1:
            msg = 'Please select only 1 node to center on.'
            LOG.error(msg)

        if len(save_sel) > 0:
            maya.cmds.select(save_sel, replace=True)
    finally:
        mmapi.set_solver_running(False)
    return
Example #13
0
def open_window():
    """Open the Load Marker GUI."""
    mmapi.load_plugin()
    import mmSolver.tools.loadmarker.ui.loadmarker_window as loadmarker_window
    loadmarker_window.main()
Example #14
0
def create_marker():
    """
    Create a new marker under the current viewport camera, or under
    the selected camera, if a camera is selected.
    """
    mmapi.load_plugin()

    sel = maya.cmds.ls(sl=True, long=True)
    node_filtered = filter_nodes.get_nodes(sel)
    cams = node_filtered['camera']
    cams = filter(is_not_startup_cam, cams)
    mkr_grps = node_filtered['markergroup']

    cam = None
    mkr_grp = None
    if len(cams) > 0 and len(mkr_grps) > 0:
        msg = 'Please select a camera or marker group; '
        msg += 'both node types are selected.'
        LOG.error(msg)

    elif len(cams) == 0 and len(mkr_grps) == 0:
        node = __get_camera()
        if node is None:
            msg = 'Please activate a viewport to get a camera.'
            LOG.error(msg)
            return
        if is_startup_cam(node) is True:
            msg = "Cannot create Markers in 'persp' camera."
            LOG.error(msg)
            return
        if maya.cmds.nodeType(node) == 'transform':
            cam = mmapi.Camera(transform=node)
        elif maya.cmds.nodeType(node) == 'camera':
            cam = mmapi.Camera(shape=node)
        else:
            LOG.error('Camera node is invalid; %r', node)
            return

    elif len(cams) > 0 and len(mkr_grps) == 0:
        node = cams[0]
        if maya.cmds.nodeType(node) == 'transform':
            cam = mmapi.Camera(transform=node)
        elif maya.cmds.nodeType(node) == 'camera':
            cam = mmapi.Camera(shape=node)
        else:
            LOG.error('Camera node is invalid; %r', node)
            return

    elif len(cams) == 0 and len(mkr_grps) > 0:
        node = mkr_grps[0]
        mkr_grp = mmapi.MarkerGroup(name=node)

    else:
        LOG.error('Should not get here.')

    bnd_name = mmapi.get_bundle_name('bundle1')
    bnd = mmapi.Bundle().create_node(
        name=bnd_name
    )

    mkr_name = mmapi.get_marker_name('marker1')
    mkr = mmapi.Marker().create_node(
        name=mkr_name,
        cam=cam,
        mkr_grp=mkr_grp,
        bnd=bnd
    )

    maya.cmds.select(mkr.get_node(), replace=True)
    return
Example #15
0
def main():
    """
    Create a new marker under the current viewport camera, or under
    the selected camera, if a camera is selected.
    """
    mmapi.load_plugin()

    sel = maya.cmds.ls(sl=True, long=True)
    node_filtered = mmapi.filter_nodes_into_categories(sel)
    cams = node_filtered['camera']
    cams = filter(utils_camera.is_not_startup_cam, cams)
    mkr_grps = node_filtered['markergroup']

    cam = None
    mkr_grp = None
    if len(cams) > 0 and len(mkr_grps) > 0:
        msg = ('Please select a camera or marker group; '
               'both node types are selected.')
        LOG.error(msg)

    elif len(cams) == 0 and len(mkr_grps) == 0:
        # Create a Marker under the active viewport camera.
        model_editor = utils_viewport.get_active_model_editor()
        if model_editor is None:
            msg = 'Please select an active 3D viewport.'
            LOG.warning(msg)
            return
        cam_tfm, cam_shp = utils_viewport.get_viewport_camera(model_editor)
        node = cam_shp
        if node is None:
            msg = 'Please select an active viewport to get a camera.'
            LOG.error(msg)
            return
        if utils_camera.is_startup_cam(node) is True:
            msg = "Cannot create Markers in 'persp' camera."
            LOG.error(msg)
            return
        if maya.cmds.nodeType(node) == 'transform':
            cam = mmapi.Camera(transform=node)
        elif maya.cmds.nodeType(node) == 'camera':
            cam = mmapi.Camera(shape=node)
        else:
            LOG.error('Camera node is invalid; %r', node)
            return

    elif len(cams) > 0 and len(mkr_grps) == 0:
        # Create a Marker under the selected camera.
        node = cams[0]
        if maya.cmds.nodeType(node) == 'transform':
            cam = mmapi.Camera(transform=node)
        elif maya.cmds.nodeType(node) == 'camera':
            cam = mmapi.Camera(shape=node)
        else:
            LOG.error('Camera node is invalid; %r', node)
            return

    elif len(cams) == 0 and len(mkr_grps) > 0:
        # Create a marker under the first selected Marker Group.
        node = mkr_grps[0]
        mkr_grp = mmapi.MarkerGroup(node=node)

    else:
        LOG.error('Should not get here.')

    bnd_name = mmapi.get_new_bundle_name('bundle1')
    bnd = mmapi.Bundle().create_node(name=bnd_name)

    mkr_name = mmapi.get_new_marker_name('marker1')
    mkr = mmapi.Marker().create_node(name=mkr_name,
                                     cam=cam,
                                     mkr_grp=mkr_grp,
                                     bnd=bnd)

    maya.cmds.select(mkr.get_node(), replace=True)
    return
Example #16
0
def open_window():
    mmapi.load_plugin()
    import mmSolver.tools.loadmarker.ui.loadmarker_window as loadmarker_window
    loadmarker_window.main()
Example #17
0
def create_new_setup():
    """
    Create the default setup
    """
    maya.cmds.loadPlugin('matrixNodes', quiet=True)
    mmapi.load_plugin()

    # Create a camera and image plane (or validate and use the given one)
    cam_tfm = maya.cmds.createNode('transform', name='camera')
    cam_shp = maya.cmds.createNode('camera', name='cameraShape', parent=cam_tfm)
    cam = mmapi.Camera(shape=cam_shp)

    # Create image plane.
    img_pl_tfm, img_pl_shp = maya.cmds.imagePlane(camera=cam_shp)

    # Using a "To Size" fit mode will forcibly change the image to
    # stretch it to match the size given. Therefore it is important
    # the image plane size (including the aspect ratio) is correct.
    maya.cmds.setAttr('{}.fit'.format(img_pl_shp), 4)  # 4 = To Size

    # Image plane is almost at far-clipping plane distance.
    maya.cmds.setAttr('{}.depth'.format(img_pl_shp), 9990)

    # Darken the imagePlane.
    value = 0.5
    maya.cmds.setAttr(
        '{}.colorGain'.format(img_pl_shp),
        value, value, value, type='double3')

    # Make the image plane non-selectable.
    maya.cmds.setAttr('{}.overrideEnabled'.format(img_pl_shp), 1)
    maya.cmds.setAttr(
        '{}.overrideDisplayType'.format(img_pl_shp),
        2)  # 2 == 'Reference' display type.

    # Create a "Calibrate" marker group.
    mkr_grp = mmapi.MarkerGroup().create_node(cam=cam, name='calibrate')

    origin_mkr = mmapi.Marker().create_node(
        mkr_grp=mkr_grp,  name='originPoint')
    origin_mkr_node = origin_mkr.get_node()

    # Axis 1
    line_a = _create_line(cam, mkr_grp, 'LineA')
    line_b = _create_line(cam, mkr_grp, 'LineB')
    intersect_node_a, vp_a_mkr = _create_vanishing_point(
        line_a, line_b,
        mkr_grp)
    _set_default_axis_values(line_a, line_b, invert_x=False)
    # TODO: Create visualiser node for the line.

    # Axis 2
    line_c = _create_line(cam, mkr_grp, 'LineC')
    line_d = _create_line(cam, mkr_grp, 'LineD')
    intersect_node_b, vp_b_mkr = _create_vanishing_point(
        line_c, line_d,
        mkr_grp)
    _set_default_axis_values(line_c, line_d, invert_x=True)
    # TODO: Create visualiser node for the line.

    # Horizon Line
    horizon_line_mkr1, horizon_line_mkr2 = _create_line(
        cam, mkr_grp, 'HorizonLine')
    _set_default_horizon_values(horizon_line_mkr1, horizon_line_mkr2)
    horizon_line_mkr1_node = horizon_line_mkr1.get_node()
    horizon_line_mkr2_node = horizon_line_mkr2.get_node()
    # TODO: Create visualiser node for the line.

    # Create a mmCameraCalibrate node.
    calib_node = maya.cmds.createNode('mmCameraCalibrate')
    maya.cmds.setAttr(
        '{}.calibrationMode'.format(calib_node),
        3)  # 3 = "Two Vanishing Points".

    decompose_node = maya.cmds.createNode('decomposeMatrix')
    maya.cmds.setAttr(
        '{}.inputRotateOrder'.format(decompose_node),
        2)  # 2 = ZXY (good default for cameras aimed at the horizon.)

    maya.cmds.addAttr(
        calib_node,
        attributeType='float',
        minValue=0.0,
        defaultValue=1920.0,
        longName='imageWidth')
    maya.cmds.addAttr(
        calib_node,
        attributeType='float',
        minValue=0.0,
        defaultValue=1080.0,
        longName='imageHeight')
    maya.cmds.addAttr(
        calib_node,
        attributeType='float',
        minValue=0.0,
        defaultValue=1.0,
        longName='imagePixelAspectRatio')
    maya.cmds.addAttr(
        calib_node,
        attributeType='float',
        minValue=0.0,
        defaultValue=1.0,
        longName='imageAspectRatio')

    exp = (
        'imageAspectRatio = (imageWidth * imagePixelAspectRatio) / imageHeight;'
        'verticalFilmAperture = horizontalFilmAperture / imageAspectRatio;'
    )
    maya.cmds.expression(object=calib_node, string=exp)

    maya.cmds.addAttr(
        calib_node,
        attributeType='message',
        longName='vanishingPointNodeA')
    maya.cmds.addAttr(
        calib_node,
        attributeType='message',
        longName='vanishingPointNodeB')

    maya.cmds.addAttr(
        calib_node,
        attributeType='message',
        longName='horizonPointNodeA')
    maya.cmds.addAttr(
        calib_node,
        attributeType='message',
        longName='horizonPointNodeB')

    maya.cmds.addAttr(
        calib_node,
        attributeType='message',
        longName='originPointNode')

    # Create connections.
    src_dst_attr_list = [
        # Camera shape viewing attributes.
        ['{}.outCameraAperture'.format(calib_node),
         '{}.cameraAperture'.format(cam_shp)],
        ['{}.outFocalLength'.format(calib_node),
         '{}.focalLength'.format(cam_shp)],

        ['{}.outMatrix'.format(calib_node),
         '{}.inputMatrix'.format(decompose_node)],

        ['{}.outputTranslate'.format(decompose_node),
         '{}.translate'.format(cam_tfm)],
        ['{}.outputRotate'.format(decompose_node),
         '{}.rotate'.format(cam_tfm)],
        ['{}.inputRotateOrder'.format(decompose_node),
         '{}.rotateOrder'.format(cam_tfm)],

        # Connections so we can find the intersection values from the
        # calibration, without creating a dependency
        # 'attributeAffects' relationship in the DG.
        ['{}.message'.format(intersect_node_a),
         '{}.vanishingPointNodeA'.format(calib_node)],
        ['{}.message'.format(intersect_node_b),
         '{}.vanishingPointNodeB'.format(calib_node)],
        ['{}.message'.format(origin_mkr_node),
         '{}.originPointNode'.format(calib_node)],

        ['{}.message'.format(horizon_line_mkr1_node),
         '{}.horizonPointNodeA'.format(calib_node)],
        ['{}.message'.format(horizon_line_mkr2_node),
         '{}.horizonPointNodeB'.format(calib_node)],

        ['{}.coverageX'.format(img_pl_shp),
         '{}.imageWidth'.format(calib_node)],
        ['{}.coverageY'.format(img_pl_shp),
         '{}.imageHeight'.format(calib_node)],

        ['{}.horizontalFilmAperture'.format(cam_shp),
         '{}.sizeX'.format(img_pl_shp)],
        ['{}.verticalFilmAperture'.format(cam_shp),
         '{}.sizeY'.format(img_pl_shp)],
    ]
    for src, dst in src_dst_attr_list:
        if maya.cmds.isConnected(src, dst) is False:
            maya.cmds.connectAttr(src, dst)
    return
Example #18
0
def main():
    """
    Convert all selected transforms into 2D markers under a camera.
    """
    # Get camera
    model_editor = utils_viewport.get_active_model_editor()
    if model_editor is None:
        msg = 'Please select an active 3D viewport.'
        LOG.warning(msg)
        return

    cam_tfm, cam_shp = utils_viewport.get_viewport_camera(model_editor)
    if cam_shp is None:
        LOG.error('Please select an active viewport to get a camera.')
        return
    if utils_camera.is_startup_cam(cam_shp) is True:
        LOG.error("Cannot create Markers in 'persp' camera.")
        return

    # Get transforms
    nodes = maya.cmds.ls(
        selection=True,
        long=True,
        type='transform',
    ) or []
    if len(nodes) == 0:
        LOG.warning('Please select one or more transform nodes.')
        return

    mmapi.load_plugin()
    try:
        utils_viewport.viewport_turn_off()

        # Compute the Marker Data.
        start_frame, end_frame = utils_time.get_maya_timeline_range_outer()
        mkr_data_list = lib.convert_nodes_to_marker_data_list(
            cam_tfm,
            cam_shp,
            nodes,
            start_frame,
            end_frame,
        )

        # Get Camera
        cam = mmapi.Camera(shape=cam_shp)

        # Get or create Marker Group.
        mkr_grp = None
        mkr_grp_nodes = maya.cmds.ls(
            cam_tfm, dag=True, long=True, type='mmMarkerGroupTransform') or []
        mkr_grp_nodes = sorted(mkr_grp_nodes)
        if len(mkr_grp_nodes) == 0:
            mkr_grp = mmapi.MarkerGroup().create_node(cam=cam)
        else:
            mkr_grp = mmapi.MarkerGroup(node=mkr_grp_nodes[0])

        # Create Marker nodes
        mkr_list = mayareadfile.create_nodes(
            mkr_data_list,
            cam=cam,
            mkr_grp=mkr_grp,
            with_bundles=True,
        )
        mkr_nodes = [mkr.get_node() for mkr in mkr_list]
    finally:
        utils_viewport.viewport_turn_on()
    if len(mkr_nodes) > 0:
        maya.cmds.select(mkr_nodes, replace=True)
    return
Example #19
0
def main(frame_range_mode=None,
         start_frame=None,
         end_frame=None,
         bundle_position_mode=None,
         delete_static_anim_curves=None):
    """
    Convert all selected transforms into 2D markers under a camera.

    :param frame_range_mode: The type of frame range to use, see
       'mmSolver.utils.constant.FRAME_RANGE_MODE_*_VALUE' for more
       details.
    :type frame_range_mode: FRAME_RANGE_MODE_*_VALUE

    :param start_frame: The first frame to start converting the
       transform to a Marker.
    :type start_frame: int or None

    :param end_frame: The last frame to end converting the
       transform to a Marker.
    :type end_frame: int or None

    :param bundle_position_mode: The position for the newly created
       Bundle (connected to the Marker).
    :type bundle_position_mode: None or BUNDLE_POSITION_MODE_*

    :param delete_static_anim_curves: When enabled, this will remove
       all keyframes from the bundle, if the bundle is not animated.
    :type delete_static_anim_curves: bool

    """
    if frame_range_mode is None:
        value = configmaya.get_scene_option(
            const.CONFIG_FRAME_RANGE_MODE_KEY,
            default=const.DEFAULT_FRAME_RANGE_MODE)
        assert value in const.FRAME_RANGE_MODE_VALUES
        frame_range_mode = value

    if start_frame is None or end_frame is None:
        start_frame = configmaya.get_scene_option(
            const.CONFIG_FRAME_START_KEY, default=const.DEFAULT_FRAME_START)
        end_frame = configmaya.get_scene_option(
            const.CONFIG_FRAME_END_KEY, default=const.DEFAULT_FRAME_END)

    if bundle_position_mode is None:
        value = configmaya.get_scene_option(
            const.CONFIG_BUNDLE_POSITION_MODE_KEY,
            default=const.DEFAULT_BUNDLE_POSITION_MODE)
        bundle_position_mode = value

    if delete_static_anim_curves is None:
        value = configmaya.get_scene_option(
            const.CONFIG_DELETE_STATIC_ANIM_CURVES_KEY,
            default=const.DEFAULT_DELETE_STATIC_ANIM_CURVES)
        delete_static_anim_curves = value

    # Frame range
    time_utils.get_frame_range(frame_range_mode,
                               start_frame=start_frame,
                               end_frame=end_frame)

    # Get camera
    model_editor = utils_viewport.get_active_model_editor()
    if model_editor is None:
        msg = 'Please select an active 3D viewport.'
        LOG.warning(msg)
        return

    cam_tfm, cam_shp = utils_viewport.get_viewport_camera(model_editor)
    if cam_shp is None:
        LOG.error('Please select an active viewport to get a camera.')
        return
    if utils_camera.is_startup_cam(cam_shp) is True:
        LOG.error("Cannot create Markers in 'persp' camera.")
        return

    # Get transforms
    tfm_nodes = maya.cmds.ls(
        selection=True,
        long=True,
        type='transform',
    ) or []
    if len(tfm_nodes) == 0:
        LOG.warning('Please select one or more transform nodes.')
        return

    # Must ensure the plug-in is loaded, otherwise we won't have all
    # the functionality required.
    mmapi.load_plugin()

    with tools_utils.tool_context(pre_update_frame=True):
        mkr_nodes, bnd_nodes = lib.create_markers_from_transforms(
            cam_tfm, cam_shp, tfm_nodes, start_frame, end_frame,
            bundle_position_mode, delete_static_anim_curves)

    if len(mkr_nodes) > 0:
        maya.cmds.select(mkr_nodes, replace=True)
    return