Python maya.OpenMaya.MFnDagNode() Examples

The following are 18 code examples of maya.OpenMaya.MFnDagNode(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module maya.OpenMaya , or try the search function .
Example #1
Source File: instanceAlongCurve.py    From instanceAlongCurve with MIT License 6 votes vote down vote up
def getFnFromPlug(plug, fnType):
    node = getSingleSourceObjectFromPlug(plug)

    # Get Fn from a DAG path to get the world transformations correctly
    if node is not None:
        path = OpenMaya.MDagPath()
        trFn = OpenMaya.MFnDagNode(node)
        trFn.getPath(path)

        path.extendToShape()

        if path.node().hasFn(fnType):
            return path

    return None

# TODO: cache this data to prevent recalculating when there is no manipulator being updated 
Example #2
Source File: instanceAlongCurve.py    From instanceAlongCurve with MIT License 6 votes vote down vote up
def getCurveFn(self):
        inputCurvePlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.inputCurveAttr)
        curve = getSingleSourceObjectFromPlug(inputCurvePlug)

        # Get Fn from a DAG path to get the world transformations correctly
        if curve is not None:
            path = OpenMaya.MDagPath()
            trFn = OpenMaya.MFnDagNode(curve)
            trFn.getPath(path)

            path.extendToShape()

            if path.node().hasFn(OpenMaya.MFn.kNurbsCurve):
                return OpenMaya.MFnNurbsCurve(path)

        return None

    # Calculate expected instances by the instancing mode 
Example #3
Source File: onionSkinRendererCore.py    From onionSkinRenderer with MIT License 6 votes vote down vote up
def createCallbacks(self):
        # frame changed callback
        # needed for changing the relative keyframe display
        self.mTimeCallbackId = om.MEventMessage.addEventCallback('timeChanged', self.setRelativeFrames)
        # iterate over all cameras add the callback
        # using old api because new doesn't include iterator over dep nodes
        dgit = oldOm.MItDependencyNodes(oldOm.MFn.kCamera)

        while not dgit.isDone():
            t = oldOm.MFnDagNode(dgit.thisNode()).parent(0)
            if t is not None:
                self.mCameraMovedCallbackIds.append(
                    oldOm.MNodeMessage.addAttributeChangedCallback(t, self.cameraMovedCB))
            dgit.next()


    # removing them when the ui is closed 
Example #4
Source File: node_utils.py    From spore with MIT License 6 votes vote down vote up
def get_instancer(spore_node, as_string=True):
    """ return the instancer node connected to a given spore node
    :param spore_node:
    :param as_string: if true return node name else return mObject """

    node_fn = get_dgfn_from_dagpath(spore_node)
    instance_plug = node_fn.findPlug('instanceData')
    plugs = om.MPlugArray()
    instancer_plugs = om.MPlugArray()
    instance_geo = []

    if not instance_plug.isNull():
        if instance_plug.connectedTo(plugs, False, True):
            node = plugs[0].node()
            node_fn = om.MFnDagNode(node)
            if as_string:
                return node_fn.fullPathName()
            else:
                return node 
Example #5
Source File: spore_sampler.py    From spore with MIT License 5 votes vote down vote up
def altitude_filter(self, min_altitude, max_altitude, min_fuzziness, max_fuzziness):
        """ filter points based on y position relative to bounding box """

        in_mesh = node_utils.get_connected_in_mesh(self.target, False)
        dag_fn = om.MFnDagNode(in_mesh)

        bb = dag_fn.boundingBox()
        bb_y_min = bb.min().y
        height = bb.height()

        invalid_ids = []
        for i, (position, _, _, _, _) in enumerate(self.point_data):
            y_normalized = position[1] - bb_y_min
            pos_rel = y_normalized / height

            if pos_rel < min_altitude:
                if pos_rel < min_altitude - min_fuzziness:
                    invalid_ids.append(i)

                elif min_altitude - pos_rel > random.uniform(0, min_fuzziness):
                    invalid_ids.append(i)

            elif pos_rel > max_altitude:
                if pos_rel > max_altitude + max_fuzziness:
                    invalid_ids.append(i)

                elif abs(max_altitude - pos_rel) > random.uniform(0, max_fuzziness):
                    invalid_ids.append(i)

        invalid_ids = sorted(invalid_ids, reverse=True)
        [self.point_data.remove(index) for index in invalid_ids] 
Example #6
Source File: instanceAlongCurve.py    From instanceAlongCurve with MIT License 5 votes vote down vote up
def findShadingGroup(self, dagPath):

        # Search in children first before extending to shape
        for child in xrange(dagPath.childCount()):
            childDagPath = OpenMaya.MDagPath()
            fnDagNode = OpenMaya.MFnDagNode(dagPath.child(child))
            fnDagNode.getPath(childDagPath)

            fnSet = self.findShadingGroup(childDagPath)

            if fnSet is not None:
                return fnSet

        if self.hasShapeBelow(dagPath):
            dagPath.extendToShape()
            fnDepNode = OpenMaya.MFnDependencyNode(dagPath.node())

            instPlugArray = fnDepNode.findPlug("instObjGroups")
            instPlugArrayElem = instPlugArray.elementByLogicalIndex(dagPath.instanceNumber())

            if instPlugArrayElem.isConnected():
                connectedPlugs = OpenMaya.MPlugArray()      
                instPlugArrayElem.connectedTo(connectedPlugs, False, True)

                if connectedPlugs.length() == 1:
                    sgNode = connectedPlugs[0].node()

                    if sgNode.hasFn(OpenMaya.MFn.kSet):
                        return OpenMaya.MFnSet(sgNode)

        return None 
Example #7
Source File: instanceAlongCurve.py    From instanceAlongCurve with MIT License 5 votes vote down vote up
def getInputTransformFn(self):

        inputTransformPlug = self.getInputTransformPlug()
        transform = getSingleSourceObjectFromPlug(inputTransformPlug)

        # Get Fn from a DAG path to get the world transformations correctly
        if transform is not None and transform.hasFn(OpenMaya.MFn.kTransform):
                path = OpenMaya.MDagPath()
                trFn = OpenMaya.MFnDagNode(transform)
                trFn.getPath(path)
                return OpenMaya.MFnTransform(path)

        return None 
Example #8
Source File: instanceAlongCurve.py    From instanceAlongCurve with MIT License 5 votes vote down vote up
def getNodeTransformFn(self):
        dagNode = OpenMaya.MFnDagNode(self.thisMObject())
        dagPath = OpenMaya.MDagPath()
        dagNode.getPath(dagPath)
        return OpenMaya.MFnDagNode(dagPath.transform()) 
Example #9
Source File: cmdx.py    From cmdx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def editCurve(parent, points, degree=1, form=kOpen):
    assert isinstance(parent, DagNode), (
        "parent must be of type cmdx.DagNode"
    )

    degree = min(3, max(1, degree))

    cvs = om1.MPointArray()
    curveFn = om1.MFnNurbsCurve()

    for point in points:
        cvs.append(om1.MPoint(*point))

    mobj = curveFn.createWithEditPoints(cvs,
                                        degree,
                                        form,
                                        False,
                                        False,
                                        True,
                                        _encode1(parent.path()))

    mod = om1.MDagModifier()
    mod.renameNode(mobj, parent.name(namespace=True) + "Shape")
    mod.doIt()

    def undo():
        mod.deleteNode(mobj)
        mod.doIt()

    def redo():
        mod.undoIt()

    commit(undo, redo)

    shapeFn = om1.MFnDagNode(mobj)
    return encode(shapeFn.fullPathName()) 
Example #10
Source File: test_performance.py    From cmdx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_createNode_performance():
    """createNode cmdx vs cmds > 2x"""

    versions = (
        ("mel", lambda: mel.eval("createNode \"transform\"")),
        ("cmds", lambda: cmds.createNode("transform")),
        ("cmdx", lambda: cmdx.createNode(cmdx.tTransform)),
        # ("PyMEL", lambda: pm.createNode("transform")),
        ("API 1.0", lambda: om1.MFnDagNode().create("transform")),
        ("API 2.0", lambda: om2.MFnDagNode().create("transform")),
    )

    for contender, test in versions:
        Compare(contender, "createNode", test, setup=New)

    cmdx_vs_cmds = (
        timings["createNode"]["cmds"]["percall"] /
        timings["createNode"]["cmdx"]["percall"]
    )

    cmdx_vs_api = (
        timings["createNode"]["API 2.0"]["percall"] /
        timings["createNode"]["cmdx"]["percall"]
    )

    assert_greater(cmdx_vs_cmds, 0.5)  # at most 2x slower than cmds
    assert_greater(cmdx_vs_api, 0.20)  # at most 5x slower than API 2.0 
Example #11
Source File: node_utils.py    From spore with MIT License 5 votes vote down vote up
def connect_to_instancer(transform_node, spore_node):
    """ connect a transform's matrix attribute to a instancer node
    that is connected to the given spore node """

    # get instancer's inputHierarchy plug
    instancer_node = get_instancer(spore_node, False)
    dg_fn = om.MFnDependencyNode(instancer_node)
    in_plug = dg_fn.findPlug('inputHierarchy')

    # get transform's matrix plug
    transform_node = get_mobject_from_name(transform_node)
    dag_fn = om.MFnDagNode(transform_node)
    matrix_plug = dag_fn.findPlug('matrix')

    # get first free plug and connect
    plug_id = in_plug.numElements() + 1
    dag_mod = om.MDagModifier()
    dag_mod.connect(matrix_plug, in_plug.elementByLogicalIndex(plug_id))
    dag_mod.doIt() 
Example #12
Source File: node_utils.py    From spore with MIT License 5 votes vote down vote up
def get_instanced_geo(spore_node):
    """ return a list of dag pathes of geometry transformes that
    are connected to the spore node's instancer
    @param spore_node str: the name of the spore node
    @return: list of string or None if no instancer is connected """

    node_fn = get_dgfn_from_dagpath(spore_node)
    instance_plug = node_fn.findPlug('instanceData')
    plugs = om.MPlugArray()
    instancer_plugs = om.MPlugArray()
    instance_geo = []

    if not instance_plug.isNull():
        if instance_plug.connectedTo(plugs, False, True):
            node = plugs[0].node()
            node_fn = om.MFnDagNode(node)
            inst_geo_plug = node_fn.findPlug('inputHierarchy')

            if not inst_geo_plug.isNull():
                for i in xrange(inst_geo_plug.numConnectedElements()):
                    input_plug = inst_geo_plug.elementByPhysicalIndex(i)

                    if input_plug.connectedTo(instancer_plugs, True, True):
                        geo_plug = instancer_plugs[0]
                        geo_node = geo_plug.node()
                        instance_geo.append(om.MFnDagNode(geo_node).fullPathName())

            dg_node_fn = om.MFnDependencyNode(node)
            instancer_node = dg_node_fn.name()

    return instance_geo 
Example #13
Source File: node_utils.py    From spore with MIT License 5 votes vote down vote up
def get_dagfn_from_dagpath(dagpath):
    """ return a dag-node functionset to a given dag-path """

    m_dagpath = get_dagpath_from_name(dagpath)
    return om.MFnDagNode(m_dagpath) 
Example #14
Source File: spore_command.py    From spore with MIT License 5 votes vote down vote up
def redoIt(self):
        """ redo """

        self.dag_mod_transform.doIt()
        self.dag_mod_spore.doIt()
        self.dag_mod_instancer.doIt()

        # get result
        result = []
        dg_fn = om.MFnDependencyNode(self.spore)
        result.append(dg_fn.name())
        dag_fn = om.MFnDagNode(self.instancer)
        result.append(dag_fn.fullPathName())
        self.clearResult()
        self.setResult(result) 
Example #15
Source File: spore_sampler.py    From spore with MIT License 5 votes vote down vote up
def voxelize(self, cell_size):
        """ partition the spatial domain with the given cellsize.
        than assign each point to the cell is spatialy belongs to.
        :return dict: where:
                      key == the cell index
                      value == list of points indexes from the point_data obj """

        partition = {}

        in_mesh = node_utils.get_connected_in_mesh(self.target, False)
        bb = om.MFnDagNode(in_mesh).boundingBox()

        self.w_count = int(math.ceil(bb.width() / cell_size))
        self.h_count = int(math.ceil(bb.height() / cell_size))
        self.d_count = int(math.ceil(bb.depth() / cell_size))

        bb_min = bb.min()
        for i in xrange(self.point_data.position.length()):
            p_normalized = self.point_data.position[i] - bb_min
            p_x = int(p_normalized.x / cell_size)
            p_y = int(p_normalized.y / cell_size)
            p_z = int(p_normalized.z / cell_size)

            index = p_x + p_y * self.w_count + p_z * self.w_count * self.h_count


            partition.setdefault(index, []).append(i)

        return partition 
Example #16
Source File: medic.py    From medic with MIT License 4 votes vote down vote up
def IsTemplated(_input):
   if not _input:
      return False

   dp = None

   if isinstance(_input, OpenMaya.MDagPath):
      dp = OpenMaya.MDagPath(_input)

   elif isinstance(_input, OpenMaya.MObject):
      try:
         dn = OpenMaya.MFnDagNode(_input)
         dp = OpenMaya.MDagPath()
         dn.getPath(dp)
      except:
         pass

   elif isinstance(_input, Node):
      if _input.isDag():
         dp = _input.getPath()

   elif isinstance(_input, basestring):
      sl = OpenMaya.MSelectionList()
      try:
         _dp = OpenMaya.MDagPath()
         sl.add(_input)
         sl.getDagPath(0, _dp)
         dp = _dp
      except:
         pass

   if dp:
      overridden = False
      while dp.length() > 0:
         dn = OpenMaya.MFnDagNode(dp)
         if not overridden:
            try:
               plug = dn.findPlug("overrideEnabled");
               if plug.asBool():
                  overridden = True
                  plug = dn.findPlug("overrideDisplayType")
                  if plug.asShort() == 1:
                     return True
            except:
               pass
         try:
            plug = dn.findPlug("template")
            if plug.asBool():
               return True
         except:
            pass
         try:
            dp.pop()
         except:
            break

   return False 
Example #17
Source File: spore_command.py    From spore with MIT License 4 votes vote down vote up
def doIt(self, args):
        """ do """

        if not self.parse_args(args):
            return

        # create sporeNode and instancer
        self.spore_transform = self.dag_mod_transform.createNode('transform')
        self.spore = self.dag_mod_spore.createNode('sporeNode', self.spore_transform)
        self.instancer = self.dag_mod_instancer.createNode('instancer')

        # rename nodes
        if self.name:
            self.name = '{}_'.format(self.name)
        transform_name = self.unique_name('{}Spore'.format(self.name))
        spore_name = self.unique_name('{}SporeShape'.format(self.name))
        instancer_name = self.unique_name('{}SporeInstancer'.format(self.name))
        self.dag_mod_spore.renameNode(self.spore, spore_name)
        self.dag_mod_transform.renameNode(self.spore_transform, transform_name)
        self.dag_mod_instancer.renameNode(self.instancer, instancer_name)

        # get spore node plugs
        dag_fn = om.MFnDagNode(self.spore)
        in_mesh_plug = dag_fn.findPlug('inMesh')
        instance_data_plug = dag_fn.findPlug('instanceData')

        # get instancer plugs
        dg_fn = om.MFnDagNode(self.instancer)
        in_points_plug = dg_fn.findPlug('inputPoints')
        in_hierarchy_plug = dg_fn.findPlug('inputHierarchy')

        # get target out mesh plug
        dag_fn = om.MFnDagNode(self.target)
        out_mesh_plug = dag_fn.findPlug('outMesh')

        # get source matrix plugs
        matrix_plug_array = om.MPlugArray()
        for i in xrange(self.source.length()):
            dag_fn = om.MFnDagNode(self.source[i])
            matrix_plug = dag_fn.findPlug('matrix')
            matrix_plug_array.append(matrix_plug)

        # hook everything up
        self.dag_mod_spore.connect(instance_data_plug, in_points_plug)
        self.dag_mod_spore.connect(out_mesh_plug, in_mesh_plug)
        for i in xrange(matrix_plug_array.length()):
            in_plug = in_hierarchy_plug.elementByLogicalIndex(i)
            self.dag_mod_spore.connect(matrix_plug_array[i], in_plug)

        self.redoIt() 
Example #18
Source File: spore_sampler.py    From spore with MIT License 4 votes vote down vote up
def parse_args(self, args):
        """ parse command arguments """

        mode_map = {0: 'random',
                    1: 'jitter',
                    2: 'poisson3d',
                    3: 'poisson2d'}

        arg_data = om.MArgDatabase(self.syntax(), args)

        if arg_data.isFlagSet(K_SAMPLET_TYPE_FLAG):
            self.sample_type = arg_data.flagArgumentString(K_SAMPLET_TYPE_FLAG, 0)
        if arg_data.isFlagSet(K_NUM_SAMPLES_FLAG):
            self.num_samples = arg_data.flagArgumentInt(K_NUM_SAMPLES_FLAG, 0)
        if arg_data.isFlagSet(K_CELL_SIZE_FLAG):
            self.cell_size = arg_data.flagArgumentDouble(K_CELL_SIZE_FLAG, 0)
        if arg_data.isFlagSet(K_MIN_DISTANCE_FLAG):
            self.min_distance = arg_data.flagArgumentDouble(K_MIN_DISTANCE_FLAG, 0)

        selection = om.MSelectionList()
        arg_data.getObjects(selection)
        if selection.length() == 1:
            found = False
            node = om.MObject()
            selection.getDependNode(0, node)

            if node.hasFn(om.MFn.kDagNode):
                dag_fn = om.MFnDagNode(node)
                if dag_fn.typeName() == 'sporeNode':
                    self.target = node
                    found = True

                if dag_fn.typeName() == 'transform':
                    dag_path = om.MDagPath()
                    om.MDagPath.getAPathTo(node, dag_path)
                    try:
                        dag_path.extendToShape()
                    except:
                        raise RuntimeError('{} node has multiple shapes'.format(dag_path.fullPathName()))

                    dag_fn = om.MFnDagNode(dag_path)
                    self.target = dag_path.node()
                    found = True

            if found:
                if not self.sample_type:
                    type_plug = dag_fn.findPlug('emitType')
                    self.sample_type = mode_map[type_plug.asShort()]
                if not self.num_samples:
                    num_plug = dag_fn.findPlug('numSamples')
                    self.num_samples = num_plug.asInt()
                if not self.cell_size:
                    cell_plug = dag_fn.findPlug('cellSize')
                    self.cell_size = num_plug.asDouble()
                if not self.min_distance:
                    radius_plug = dag_fn.findPlug('minRadius')
                    self.cell_size = radius_plug.asDouble()

            else:
                raise RuntimeError('The sample command only works on sporeNodes')