Esempio n. 1
0
    def test_childPathsByFn(self):
        nodeParent = nodes.asMObject(cmds.polyCube(ch=False)[0])
        nodes.setParent(nodes.asMObject(self.node), nodeParent)

        child1 = nodes.asMObject(cmds.createNode("transform"))
        child2 = nodes.asMObject(cmds.createNode("transform"))
        nodes.setParent(child1, nodeParent)
        nodes.setParent(child2, nodeParent)
        dagPath = om.MFnDagNode(nodeParent).getPath()
        results = nodes.childPathsByFn(dagPath, om2.MFn.kTransform)
        self.assertEquals(len(results), 3)
        results = nodes.childPathsByFn(dagPath, om2.MFn.kMesh)
        self.assertEquals(len(results), 1)
Esempio n. 2
0
    def get_node_by_name(name):
        dagIterator = om.MItDag()
        dagNodeFn = om.MFnDagNode()

        while (not dagIterator.isDone()):
            dagObject = dagIterator.currentItem()
            dagNodeFn.setObject(dagObject)

            if dagNodeFn.name() == name:
                return dagObject

            dagIterator.next()

        return None
Esempio n. 3
0
    def get_overlap_uv_faces(self, meshName):
        """Return overlapping faces"""
        faces = []
        # find polygon mesh node
        selList = om.MSelectionList()
        selList.add(meshName)
        mesh = selList.getDependNode(0)
        if mesh.apiType() == om.MFn.kTransform:
            dagPath = selList.getDagPath(0)
            dagFn = om.MFnDagNode(dagPath)
            child = dagFn.child(0)
            if child.apiType() != om.MFn.kMesh:
                raise Exception("Can't find polygon mesh")
            mesh = child
        meshfn = om.MFnMesh(mesh)

        center, radius = self.create_bounding_circle(meshfn)
        for i in xrange(meshfn.numPolygons):
            rayb1, face1Orig, face1Vec = self.create_ray_given_face(meshfn, i)
            if not rayb1: continue
            cui = center[2 * i]
            cvi = center[2 * i + 1]
            ri = radius[i]
            # Exclude the degenerate face
            # if(area(face1Orig) < 0.000001) continue;
            # Loop through face j where j != i
            for j in range(i + 1, meshfn.numPolygons):
                cuj = center[2 * j]
                cvj = center[2 * j + 1]
                rj = radius[j]
                du = cuj - cui
                dv = cvj - cvi
                dsqr = du * du + dv * dv
                # Quick rejection if bounding circles don't overlap
                if (dsqr >= (ri + rj) * (ri + rj)): continue

                rayb2, face2Orig, face2Vec = self.create_ray_given_face(
                    meshfn, j)
                if not rayb2: continue
                # Exclude the degenerate face
                # if(area(face2Orig) < 0.000001): continue;
                if self.check_crossing_edges(face1Orig, face1Vec, face2Orig,
                                             face2Vec):
                    face1 = '%s.f[%d]' % (meshfn.name(), i)
                    face2 = '%s.f[%d]' % (meshfn.name(), j)
                    if face1 not in faces:
                        faces.append(face1)
                    if face2 not in faces:
                        faces.append(face2)
        return faces
Esempio n. 4
0
def getParent(mobject):
    """Returns the parent MFnDagNode if it has a parent else None

    :param mobject: MObject
    :return: MObject or None
    """
    if mobject.hasFn(om2.MFn.kDagNode):
        dagpath = om2.MDagPath.getAPathTo(mobject)
        if dagpath.node().apiType() == om2.MFn.kWorld:
            return None
        dagNode = om2.MFnDagNode(dagpath).parent(0)
        if dagNode.apiType() == om2.MFn.kWorld:
            return None
        return dagNode
Esempio n. 5
0
File: ipymel.py Progetto: zewt/pymel
def api_children(path):
    sel = om.MSelectionList()
    try:
        sel.add(path)
    except RuntimeError:
        return []
    if not sel.length():
        return []
    try:
        dagPath = sel.getDagPath(0)
    except TypeError:
        return []
    return [om.MFnDagNode(dagPath.child(i)).fullPathName()
            for i in range(dagPath.childCount())]
Esempio n. 6
0
    def _createInScene(self, node, name):
        if node is None:
            name = "_".join([name or self.__class__.__name__, "meta"])
            node = nodes.createDagNode(name, "camera")
        self._handle = om2.MObjectHandle(node)
        if node.hasFn(om2.MFn.kDagNode):
            self._mfn = om2.MFnDagNode(node)
        else:
            self._mfn = om2.MFnDependencyNode(node)

        if node.hasFn(om2.MFn.kTransform):
            node = list(
                nodes.iterChildren(self.mobject(), False, om2.MFn.kCamera))[0]
        self.camMfn = om2.MFnCamera(node)
    def postConstructor(self):
        this_object = self.thisMObject()
        node = OpenMaya.MFnDagNode(this_object)

        hidden_attributes = [
            u'localPosition', u'localPositionX', u'localPositionY', u'localPositionZ',
            u'localScale', u'localScaleX', u'localScaleY', u'localScaleZ'
        ]
        for attribute in hidden_attributes:
            attr_object = node.attribute(attribute)
            plug = OpenMaya.MPlug(this_object, attr_object)
            plug.isLocked = True
            plug.isChannelBox = False
            plug.isKeyable = False
Esempio n. 8
0
    def prepareForDraw(self, obj_path, camera_path, frame_context, old_data):
        """
        """
        data = old_data
        if not isinstance(data, ZShotMaskData):
            data = ZShotMaskData()

        fnDagNode = om.MFnDagNode(obj_path)

        data.camera_name = fnDagNode.findPlug("camera", False).asString()

        data.text_fields = []
        for i in range(0, len(ZShotMaskLocator.TEXT_ATTRS), 2):
            data.text_fields.append(fnDagNode.findPlug(ZShotMaskLocator.TEXT_ATTRS[i], False).asString())

        counter_padding = fnDagNode.findPlug("counterPadding", False).asInt()
        if counter_padding < 1:
            counter_padding = 1
        elif counter_padding > 6:
            counter_padding = 6

        current_time = int(cmds.currentTime(q=True))
        counter_position = fnDagNode.findPlug("counterPosition", False).asInt()
        if counter_position > 0 and counter_position <= len(ZShotMaskLocator.TEXT_ATTRS) / 2:
            data.text_fields[counter_position - 1] = "{0}".format(str(current_time).zfill(counter_padding))

        data.text_padding = fnDagNode.findPlug("textPadding", False).asInt()

        data.font_name = fnDagNode.findPlug("fontName", False).asString()

        r = fnDagNode.findPlug("fontColorR", False).asFloat()
        g = fnDagNode.findPlug("fontColorG", False).asFloat()
        b = fnDagNode.findPlug("fontColorB", False).asFloat()
        a = fnDagNode.findPlug("fontAlpha", False).asFloat()
        data.font_color = om.MColor((r, g, b, a))

        data.font_scale = fnDagNode.findPlug("fontScale", False).asFloat()

        r = fnDagNode.findPlug("borderColorR", False).asFloat()
        g = fnDagNode.findPlug("borderColorG", False).asFloat()
        b = fnDagNode.findPlug("borderColorB", False).asFloat()
        a = fnDagNode.findPlug("borderAlpha", False).asFloat()
        data.border_color = om.MColor((r, g, b, a))

        data.border_scale = fnDagNode.findPlug("borderScale", False).asFloat()

        data.top_border = fnDagNode.findPlug("topBorder", False).asBool()
        data.bottom_border = fnDagNode.findPlug("bottomBorder", False).asBool()

        return data
Esempio n. 9
0
 def Query_node_exist(self):
     # 返回指定对象是否存在
     it = om.MItDependencyNodes(om.MFn.kMesh)
     self.meshNodes = om.MObjectArray()
     self.meshObjs = []
     self.meshNames = []
     while not it.isDone():
         self.meshNodes.append(it.thisNode())
         it.next()
     for meshNode in self.meshNodes:
         self.meshObjs.append(meshNode)
         mDagNode = om.MFnDagNode(meshNode)
         meshName = mDagNode.fullPathName()
         self.meshNames.append(meshName)
Esempio n. 10
0
    def doAction(self, target, source):
        """ This method performs the override action for a given target and source. """
        # NOTE: doAction should never add commands in the undo stack

        # Make connection to new shading engine
        enginePlug = source.source()
        if not enginePlug.isNull:

            # First break the connection to old shading engine.
            # NOTE: Returning the plug and then disconnecting it didn't work.
            # The plug object was destroyed when we got outside the scope of
            # where it was created (reference count didn't work properly).
            # I think it has to do with the special nature of the shadingEngine
            # attribute (dagSetMembers) which has its array elements destroyed
            # as soon as they are disconnected.
            # A workaround for this was to add support to disconnect the
            # shading engine directly inside the method instead.
            MaterialOverride._hasShadingEngineConnection(target,
                                                         disconnect=True)

            fnShadingEngine = OpenMaya.MFnDependencyNode(enginePlug.node())
            dagSetMembersPlug = fnShadingEngine.findPlug(
                "dagSetMembers", False)

            # Get full path name to target which is needed in case of object instancing
            targetPath = OpenMaya.MFnDagNode(target.node()).fullPathName()
            targetAttr = target.partialName(includeNodeName=False,
                                            includeNonMandatoryIndices=True,
                                            includeInstancedIndices=True,
                                            useAlias=False,
                                            useFullAttributePath=True,
                                            useLongNames=True)
            targetFullAttrName = targetPath + "." + targetAttr

            # Need to use a command here to use 'nextAvailable' needed by set assignment
            with undo.SuspendUndo():
                # Turn reference edits on if restoring the original.
                with handleRestoringOriginalCtx():
                    # Guard agains the case where the connection can't be made,
                    # to make sure we don't break the system if that happens.
                    # This happens if per-face assignments are made when the
                    # override is already applied, which is not supported.
                    try:
                        # doAction should never add commands in the undo stack
                        cmds.connectAttr(targetFullAttrName,
                                         dagSetMembersPlug.name(),
                                         nextAvailable=True)
                    except:
                        OpenMaya.MGlobal.displayWarning(
                            kMaterialOverrideFailure % self.name())
Esempio n. 11
0
def getChildren(node, recursive=True):
    result = []

    dagNode = OpenMaya.MFnDagNode(node)

    for i in range(dagNode.childCount()):
        childMObject = dagNode.child(i)

        if childMObject.hasFn(OpenMaya.MFn.kTransform):
            result.append(childMObject)
            if recursive:
                result.extend(getChildren(childMObject))

    return result
Esempio n. 12
0
def getPositionAtU(jointObj,u_parameter):
    pos=om.MVector()
    jointFn=om.MFnDagNode(jointObj)
    jointName=jointFn.name()
    nextJointObj=om.MObject()
    # GET BONE DATA
    jointFn=om.MFnDagNode(jointObj)
    if jointFn.childCount()>1:
        if 'Belly' in jointName:
            for i in range(jointFn.childCount()):
                childObj=jointFn.child(i)
                childName=om.MFnDependencyNode(childObj).name()
                if 'Chest' in childName:
                    nextJointObj=childObj
        elif 'Neck' in jointName:
            for i in range(jointFn.childCount()):
                childObj=jointFn.child(i)
                childName=om.MFnDependencyNode(childObj).name()
                if 'Head' in childName:
                    nextJointObj=childObj
    elif jointFn.childCount()==1:
        nextJointObj=jointFn.child(0)
    elif jointFn.childCount()==0 and jointFn.parentCount()==1:
        nextJointObj=jointFn.parent(0)
                
    nextJointFn=om.MFnDagNode(nextJointObj)
    nextBoneName=nextJointFn.name()
    nextBoneDagPath = nextJointFn.getPath()
    
    # To avoid issues like freezeTransform, recommend rotate pivot to attain the position
    jointPosition=cmds.xform(jointName,absolute=True,query=True,worldSpace=True,rotatePivot=True)
    jointPosition=om.MVector(jointPosition[0],jointPosition[1],jointPosition[2])
    nextjointPosition=cmds.xform(nextBoneName,absolute=True,query=True,worldSpace=True,rotatePivot=True)
    nextjointPosition=om.MVector(nextjointPosition[0],nextjointPosition[1],nextjointPosition[2])
    pos=linear_interpolate_3D(jointPosition,nextjointPosition,u_parameter)
    positionAtU=om.MVector(pos[0],pos[1],pos[2])    
    return positionAtU
Esempio n. 13
0
 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
     dgIter = om.MItDependencyNodes(om.MFn.kCamera)
     while not dgIter.isDone():
         shape = om.MFnDagNode(dgIter.thisNode())
         transform = shape.parent(0)
         if transform is not None:
             self.mCameraMovedCallbackIds.append(
                 om.MNodeMessage.addAttributeChangedCallback(
                     transform, self.cameraMovedCB))
         dgIter.next()
Esempio n. 14
0
    def _getPolyCountInDagContainer(node):
        meshFn = om.MFnMesh()
        dagNodeFn = om.MFnDagNode(node)
        containerData = _createtContainerNode()
        containerData['container'] = dagNodeFn.name()
        if node.hasFn(om.MFn.kMesh):
            meshFn.setObject(node)
            if not meshFn.isIntermediateObject:
                containerData['Verts'] = meshFn.numVertices
                containerData['Edges'] = meshFn.numEdges
                containerData['Faces'] = meshFn.numPolygons
                containerData['UVs'] = meshFn.numUVs()
                containerData['Tris'] = sum(meshFn.getTriangles()[0])

        return containerData
Esempio n. 15
0
    def getSelectedVertexIDs(cls):
        '''If a face or edge, converts to a vertex.'''

        # TODO: support conversion to CVs

        sel = om.MGlobal.getActiveSelectionList()
        dag, selectedComponents = sel.getComponent(0)

        vertexConversion = set()

        if selectedComponents.apiType() == om.MFn.kMeshVertComponent:
            return dag, selectedComponents
        elif selectedComponents.apiType() == om.MFn.kMeshEdgeComponent:
            edgeIter = om.MItMeshEdge(dag, selectedComponents)
            while not edgeIter.isDone():
                vert1 = edgeIter.vertexId(0)
                vert2 = edgeIter.vertexId(1)
                vertexConversion.add(vert1)
                vertexConversion.add(vert2)
                edgeIter.next()
        elif selectedComponents.apiType() == om.MFn.kMeshPolygonComponent:
            faceIter = om.MItMeshPolygon(dag, selectedComponents)
            while not faceIter.isDone():
                connectedVertices = faceIter.getVertices()
                vertexConversion.update(connectedVertices)

                faceIter.next()
        elif selectedComponents.apiType() == om.MFn.kInvalid:
            # no selected components. A transform might only be selected
            _dag = om.MDagPath(dag)
            _dag.extendToShape(0)
            # check what the shape's type is
            _shapeMObj = _dag.node()
            if _shapeMObj.hasFn(om.MFn.kMesh):
                meshMFnDagNode = om.MFnDagNode(_shapeMObj)
                meshMFn = om.MFnMesh(_shapeMObj)
                if not meshMFnDagNode.isIntermediateObject:
                    vertexConversion.update(xrange(meshMFn.numVertices))
            else:
                return

        newSel = om.MSelectionList()
        for vertId in vertexConversion:
            newSel.add(dag.fullPathName() + '.vtx[{0}]'.format(vertId))

        dag, selectedComponents = newSel.getComponent(0)

        return dag, selectedComponents
Esempio n. 16
0
def getDagContainerStacksUsingMayaAPI():
    # TODO: om.MFn.kContainerBase indicates the object either a container or a dagContainer.
    def _getPolyCountInDagContainer(node):
        meshFn = om.MFnMesh()
        dagNodeFn = om.MFnDagNode(node)
        containerData = _createtContainerNode()
        containerData['container'] = dagNodeFn.name()
        if node.hasFn(om.MFn.kMesh):
            meshFn.setObject(node)
            if not meshFn.isIntermediateObject:
                containerData['Verts'] = meshFn.numVertices
                containerData['Edges'] = meshFn.numEdges
                containerData['Faces'] = meshFn.numPolygons
                containerData['UVs'] = meshFn.numUVs()
                containerData['Tris'] = sum(meshFn.getTriangles()[0])

        return containerData

    def _addPolyCountIntoDagContainer(meshNodeData, dagContainer):
        dagContainer['Verts'] += meshNodeData['Verts']
        dagContainer['Edges'] += meshNodeData['Edges']
        dagContainer['Faces'] += meshNodeData['Faces']
        dagContainer['Tris'] += meshNodeData['Tris']
        dagContainer['UVs'] += meshNodeData['UVs']

    # MItDependencyNodes may miss some mesh nodes in the scene.
    # meshIterator = om.MItDependencyNodes(om.MFn.kMesh)
    meshIterator = om.MItDag(om.MItDag.kDepthFirst, om.MFn.kMesh)
    dagNodeFn = om.MFnDagNode()
    dagContainerStacks = []
    while not meshIterator.isDone():
        stack = deque()
        path = dagNodeFn.setObject(meshIterator.currentItem()).getPath()
        meshNodeData = _getPolyCountInDagContainer(path.node())
        path.pop()
        while path.length():
            node = path.node()
            not node.hasFn(om.MFn.kDagContainer) or stack.append(
                _getPolyCountInDagContainer(node))
            path.pop()

        if len(stack):
            _addPolyCountIntoDagContainer(meshNodeData, stack[0])
            dagContainerStacks.append(stack)

        meshIterator.next()

    return dagContainerStacks
Esempio n. 17
0
    def getPosition(self, objPath):
        '''Get the position of the transform node

        Args:
            objPath: The DAG path for this locator
        '''

        # Get the current node and attach to a DAG node function set
        nNode = objPath.node()
        dagFn = om.MFnDagNode(nNode)
        # Get the parent (transform) node and attach to the DAG function set
        parentObj = dagFn.parent(0)
        dagFn.setObject(parentObj)
        # Get the name of the transform node and find the position attribute
        nodeName = dagFn.name()
        self.m_position = mc.getAttr(nodeName + ".translate")[0]
Esempio n. 18
0
    def testMayaShapeBBoxCacheClearing(self):
        ''' Verify that the bounding box cache gets cleared'''

        cmds.file(new=True, force=True)

        # create a Capsule via contextOps menu
        import mayaUsd_createStageWithNewLayer
        proxyShape = mayaUsd_createStageWithNewLayer.createStageWithNewLayer()
        proxyShapePath = ufe.PathString.path(proxyShape)
        proxyShapeItem = ufe.Hierarchy.createItem(proxyShapePath)
        proxyShapeContextOps = ufe.ContextOps.contextOps(proxyShapeItem)
        proxyShapeContextOps.doOp(['Add New Prim', 'Xform'])
        xformPath = ufe.PathString.path('%s,/Xform1' % proxyShape)
        xformItem = ufe.Hierarchy.createItem(xformPath)
        xformObject3d = ufe.Object3d.object3d(xformItem)
        proxyShapeContextOps = ufe.ContextOps.contextOps(xformItem)
        proxyShapeContextOps.doOp(['Add New Prim', 'Sphere'])
        proxyShapeContextOps.doOp(['Add New Prim', 'Sphere'])
        selectionList = OpenMaya.MSelectionList()
        selectionList.add(proxyShape)
        shapeNode = OpenMaya.MFnDagNode(selectionList.getDependNode(0))

        # Two spheres at origin, the bounding box is the unit cube:
        expectedBBox = ((-1.0, -1.0, -1.0), (1.0, 1.0, 1.0))
        self.assertTrue(
            almostEqualBBox(xformObject3d.boundingBox(), expectedBBox))
        # Shape BBox should be the same (and will be cached):
        self.assertTrue(almostEqualBBox(shapeNode.boundingBox, expectedBBox))

        sphere1Path = ufe.PathString.path('%s,/Xform1/Sphere1' % proxyShape)
        sphere1Item = ufe.Hierarchy.createItem(sphere1Path)
        sphere1Prim = mayaUsd.ufe.ufePathToPrim(
            ufe.PathString.string(sphere1Path))
        UsdGeom.XformCommonAPI(sphere1Prim).SetTranslate((-5, 0, 0))

        sphere2Path = ufe.PathString.path('%s,/Xform1/Sphere2' % proxyShape)
        sphere2Item = ufe.Hierarchy.createItem(sphere2Path)
        sphere2Prim = mayaUsd.ufe.ufePathToPrim(
            ufe.PathString.string(sphere2Path))
        UsdGeom.XformCommonAPI(sphere2Prim).SetTranslate((0, 5, 0))

        expectedBBox = ((-6.0, -1.0, -1.0), (1.0, 6.0, 1.0))
        self.assertTrue(
            almostEqualBBox(xformObject3d.boundingBox(), expectedBBox))
        # The next test will only work if the cache was cleared when translating
        # the spheres:
        self.assertTrue(almostEqualBBox(shapeNode.boundingBox, expectedBBox))
Esempio n. 19
0
    def getScale(self, objPath):
        '''Get the scale of the transform node.

        Args:
            objPath: The DAG path for this locator
        '''

        # Get the current node and attach to a DAG node function set
        nNode = objPath.node()
        dagFn = om.MFnDagNode(nNode)
        # Get the parent (transform) node and attach to the DAG function set
        parentObj = dagFn.parent(0)
        dagFn.setObject(parentObj)
        # Get the name of the transform node and find the scale attribute
        nodeName = dagFn.name()
        self.m_scale = mc.getAttr(nodeName + ".scale")[0]
        self.m_radius = max(self.m_scale)
 def findFromSelection(self):
     selectionList = om.MGlobal.getActiveSelectionList()
     iterator = om.MItSelectionList(selectionList, om.MFn.kDagNode)
     if iterator.isDone():
         print "Error. Nothing selected."
         return ""
     else:
         dagPath = om.MDagPath()
         dagFn = om.MFnDagNode()
         dagPath = iterator.getDagPath()
         try:
             dagPath.extendToShape()
         except:
             pass
         node = dagPath.node()
         dagFn.setObject(node)
         return dagFn.name()
Esempio n. 21
0
    def nameChanged(self, oldName):
        # Check in each render layer if a collection for this light source exists.
        # If so we need to update it to use the new name
        if renderSetup.hasInstance():
            renderLayers = renderSetup.instance().getRenderLayers()
            for renderLayer in renderLayers:
                col = LightSource._findLightCollection(renderLayer, oldName)
                if col:
                    # Rename the collection and reset its static selection to match the new name
                    newLightName = om.MFnDagNode(
                        self.mayaHandle.object()).name()
                    newCollectionName = LIGHT_COLLECTION_PREFIX + newLightName + LIGHT_COLLECTION_SUFFIX
                    col.setName(newCollectionName)
                    col.getSelector().setStaticSelection(self.getShapeName())

        # Call parent class
        super(LightSource, self).nameChanged(oldName)
Esempio n. 22
0
def getParent(node):
    """Get the first available parent transform.

    Returns:
        OpenMaya.MObject
    """
    dagNode = OpenMaya.MFnDagNode(node)

    if dagNode.parentCount() == 0:
        return

    parent = dagNode.parent(0)

    if not parent.hasFn(OpenMaya.MFn.kTransform):
        return

    return parent
Esempio n. 23
0
def cloneMeshs(meshPaths):
    cloneMeshPaths = []
    cloneGroup = cmds.group(empty=True, world=True, name='ssdsResult')
    cloneGroupSL = om.MGlobal.getSelectionListByName(cloneGroup)
    cloneGroupFn = om.MFnTransform(cloneGroupSL.getDagPath(0))
    for path in meshPaths:
        mesh = om.MFnMesh(path)
        meshName = om.MFnDagNode(mesh.parent(0)).name()
        cloneMeshName = 'ssds_' + meshName
        cmds.duplicate(mesh.name(), returnRootsOnly=True, name=cloneMeshName)
        cmds.parent(cloneMeshName, cloneGroup)
        cmds.setAttr(cloneMeshName + '.inheritsTransform', False)
        cloneMeshSL = om.MGlobal.getSelectionListByName(cloneMeshName)
        cloneMeshPath = cloneMeshSL.getDagPath(0)
        cloneMeshPath.extendToShape()
        cloneMeshPaths.append(cloneMeshPath)
    return cloneMeshPaths, cloneGroup
Esempio n. 24
0
    def instances(self):
        # type: () -> List[DagNode]
        if not self.is_instanced:
            return []

        instances = []  # type: List[DagNode]

        tmp_mfn = _om2.MFnDagNode()
        mdagpath = self.mdagpath
        for other_mdagpath in _om2.MDagPath.getAllPathsTo(self.mobject):
            if other_mdagpath == mdagpath:
                continue
            tmp_mfn.setObject(other_mdagpath.node())
            node = _graphs.to_node_instance(tmp_mfn,
                                            _om2.MDagPath(other_mdagpath))
            instances.append(node)

        return instances
Esempio n. 25
0
    def selection_animators(cls):
        """Generator for VertexColorAnimator for each selected mesh
        
        If a selected mesh does not have an animator setup for it,
        one will be created automatically and tracked. If that mesh
        has cached data associated with it, the new animator instance
        will use that cached data.

        Returns:
            VertexColorAnimator: for each mesh selected
        """
        for dag_path in selected_meshes():
            path = om.MFnDagNode(dag_path.transform()).fullPathName()
            if path not in cls.animators:
                animator = VertexColorAnimator(dag_path)
                cls.animators[path] = animator

            yield cls.animators[path]
Esempio n. 26
0
def getMatrices(node):
    nodeName = OpenMaya.MFnDagNode(node).getPath()

    r = cmds.getAttr('{0}.r'.format(nodeName))
    r = [math.radians(x) for x in r[0]]
    ra = cmds.getAttr('{0}.ra'.format(nodeName))
    ra = [math.radians(x) for x in ra[0]]
    jo = cmds.getAttr('{0}.jo'.format(nodeName))
    jo = [math.radians(x) for x in jo[0]]

    wm = OpenMaya.MMatrix(cmds.getAttr('{0}.wm'.format(nodeName)))
    pm = OpenMaya.MMatrix(cmds.getAttr('{0}.pm'.format(nodeName)))

    r = OpenMaya.MEulerRotation(*r).asMatrix() * pm
    ra = OpenMaya.MEulerRotation(*ra).asMatrix() * pm
    jo = OpenMaya.MEulerRotation(*jo).asMatrix() * pm

    return wm, r, ra, jo
Esempio n. 27
0
def getBoundingBox():
    transform = 'pCube1'

    mSel = om.MSelectionList()
    dagPath = om.MDagPath()
    mSel.add(transform)
    mSel.getDagPath(0, dagPath)

    dagFn = om.MFnDagNode(dagPath)

    # Returns the bounding box for the dag node in object space.
    boundingBox = dagFn.boundingBox()

    # There's a few useful methods available, including min and max
    # which will return the min/max values represented in the attribute editor.

    min = boundingBox.min()
    max = boundingBox.max()
Esempio n. 28
0
def getPath(mObj, returnString=True):
    if mObj.hasFn(om.MFn.kTransform) or mObj.hasFn(om.MFn.kShape):
        dagNode = om.MFnDagNode(mObj)
        dagPath = om.MDagPath()
        #dagNode.getPath(dagPath)
        dagPath = dagNode.getPath()
        objPath = dagPath.fullPathName()
        objName = objPath.rpartition('|')
        objName = objName[-1]
    else:
        depNode = om.MFnDependencyNode(mObj)
        objPath = depNode.name()
        objName = objPath

    if returnString:
        return objPath, objName
    else:
        return dagPath
Esempio n. 29
0
    def create_proxy_ac(self):
        for proxy in self.proxy_influence_pairs.keys():
            proxy_dag = self.get_object_path(proxy)
            proxy_dag_fn = om.MFnDagNode(proxy_dag)

            proxy_translation = self.get_value(proxy_dag, 't')
            proxy_rotation = self.get_value(proxy_dag, 'r')
            proxy_scale = self.get_value(proxy_dag, 's')

            x_ac = self.create_ac(proxy_dag_fn, proxy_dag, 'translateX',
                                  om.MFn.kAnimCurveTimeToDistance)
            y_ac = self.create_ac(proxy_dag_fn, proxy_dag, 'translateY',
                                  om.MFn.kAnimCurveTimeToDistance)
            z_ac = self.create_ac(proxy_dag_fn, proxy_dag, 'translateZ',
                                  om.MFn.kAnimCurveTimeToDistance)

            self.ac_translate[proxy] = [x_ac, y_ac, z_ac]

            x_ac = self.create_ac(proxy_dag_fn, proxy_dag, 'rotateX',
                                  oma.MFnAnimCurve.kAnimCurveTA)
            y_ac = self.create_ac(proxy_dag_fn, proxy_dag, 'rotateY',
                                  oma.MFnAnimCurve.kAnimCurveTA)
            z_ac = self.create_ac(proxy_dag_fn, proxy_dag, 'rotateZ',
                                  oma.MFnAnimCurve.kAnimCurveTA)

            self.ac_rotate[proxy] = [x_ac, y_ac, z_ac]

            x_ac = self.create_ac(proxy_dag_fn, proxy_dag, 'scaleX',
                                  om.MFn.kAnimCurveTimeToUnitless)
            y_ac = self.create_ac(proxy_dag_fn, proxy_dag, 'scaleY',
                                  om.MFn.kAnimCurveTimeToUnitless)
            z_ac = self.create_ac(proxy_dag_fn, proxy_dag, 'scaleZ',
                                  om.MFn.kAnimCurveTimeToUnitless)

            self.ac_scale[proxy] = [x_ac, y_ac, z_ac]

            current_time = om.MTime(0, om.MTime.kPALFrame)
            oma.MAnimControl.setCurrentTime(current_time)

            euler_rotation = self.get_angular(proxy_rotation.asEulerRotation())

            self.add_proxy_key(current_time, proxy, proxy_translation,
                               euler_rotation, proxy_scale)
Esempio n. 30
0
    def nodes(self):
        # type: () -> List[DependNode]
        nodes = self.mfn.nodes()
        if len(nodes) == 0:
            return []

        mfn = _om2.MFnDependencyNode()
        mfn_dag = _om2.MFnDagNode()

        result = []
        for node in nodes:
            mfn.setObject(node)
            mdagpath = None
            if node.hasFn(_om2.MFn.kDagNode):
                mfn_dag.setObject(node)
                mdagpath = mfn_dag.getPath()
            result.append(_graphs.to_node_instance(mfn, mdagpath))

        return result