Ejemplo n.º 1
0
 def test_nameFromMObject(self):
     self.assertEquals(
         nodes.nameFromMObject(nodes.asMObject(self.node),
                               partialName=False), "|transform1")
     self.assertEquals(
         nodes.nameFromMObject(nodes.asMObject(self.node),
                               partialName=True), "transform1")
Ejemplo n.º 2
0
    def execute(self, arguments):
        """The execute method is called when triggering the action item. use executeUI() for a optionBox.

        :type arguments: dict
        """
        node = arguments.get("node")
        print nodes.nameFromMObject(node.object())
Ejemplo n.º 3
0
    def process(self, nodeMap):
        """
        :param nodeMap: {nodeName: om2.MObject}
        :type nodeMap: dict
        :return:
        :rtype:
        """
        self.results.update(nodeMap)
        createdNodes = []
        connections = []
        for k, n in self.items():
            # skip any currently processed nodes.

            if k not in self.results:
                parent = n.get("parent")
                parentNode = None
                # if we have a parentNode that means we're a Dag node, so try to resolve the parent,
                if parent:
                    parentNode = self.results.get(parent)
                    # if we have come across the parent before it should already have been process so skip
                    if parentNode is None and parent in self:
                        # ok in this case we have visited the parent so process it
                        parentData = self[parent]
                        parentNode, attrs = nodes.deserializeNode(
                            parentData,
                            self.results.get(self[parent]["parent"]))
                        createdNodes.append(parentNode)
                        self.results[parent] = parentNode
                        connections.extend(parentData.get("connections", []))

                newNode, attrs = nodes.deserializeNode(n, parentNode)
                if not newNode:
                    continue
                createdNodes.append(newNode)

                self.results[k] = newNode
            else:
                newNode = self.results[k]
                if not newNode:
                    continue
            # remap the connection destination and destinationPlug to be the current node plus plug
            currentConnections = n.get("connections", [])
            for conn in currentConnections:
                conn["destination"] = newNode
                conn["destinationPlug"] = ".".join(
                    [nodes.nameFromMObject(newNode), conn["destinationPlug"]])
            if not currentConnections:
                continue
            connections.extend(currentConnections)
        if connections:
            for conn in connections:
                if conn["source"] in self.results:
                    conn["source"] = self.results[conn["source"]]
                source = conn["source"]
                if isinstance(conn["source"], om2.MObject):
                    source = nodes.nameFromMObject(conn["source"])
                conn["sourcePlug"] = ".".join([source, conn["sourcePlug"]])
            self._deserializeConnections(connections)
        return createdNodes
Ejemplo n.º 4
0
    def create(self, driver, driven, skipRotate=None, skipTranslate=None, maintainOffset=False):
        driverName = nodes.nameFromMObject(driver)
        drivenName = nodes.nameFromMObject(driven)

        const = cmds.parentConstraint(driverName, drivenName, skipRotate=skipRotate or [],
                                      skipTranslate=skipTranslate or [],
                                      weight=1.0, maintainOffset=maintainOffset)
        self.node = om2.MObjectHandle(nodes.asMObject(const[0]))
        return self.node.object()
Ejemplo n.º 5
0
    def executeUI(self, arguments):
        """The executeUI method is called when the user triggering the box icon on the right handle side
        of the action item.

        For this method to be called you must specify in the UIData method "optionBox": True.

        :type arguments: dict
        """
        node = arguments.get("node")
        print nodes.nameFromMObject(node.object())
Ejemplo n.º 6
0
    def show(self, layout, menu, parent):
        """Example override creating a linear menu with passing arguments down to the MMCommands.

        :param layout: The layout instance to update.
        :type layout: :class:`menu.Layout`
        :param menu: The parent menu which items will be parented to
        :type menu: str
        :param parent: the top level parent menu or parent widget.
        :type parent: str
        """
        # grab the nodes value which comes from the marking menu executor
        selNodes = self.commandArguments.get("nodes")
        if not selNodes:
            return
        # build a dict which contains our commands
        # each command must be specfied in the format of {"type": "command", "id": "mycommandid"}
        items = []
        for i in selNodes:
            name = nodes.nameFromMObject(i.object(),
                                         partialName=False,
                                         includeNamespace=False)
            items.append({
                "type": "command",
                "id": "printNodePath",
                "arguments": {
                    "node": i,
                    "label": name
                }
            })
        # finally update the layout object
        layout.update({"items": {"generic": items}})
        # ensure the layout has been solved to contain our commands
        layout.solve()
        super(DynamicMMBySelectionExample, self).show(layout, menu, parent)
Ejemplo n.º 7
0
 def test_parentPath(self):
     group = nodes.toApiObject(cmds.createNode("transform"))
     self.assertIsNone(nodes.parentPath(group.getPath()))
     cmds.group(nodes.nameFromMObject(group.object()))
     parent = nodes.parentPath(group.getPath())
     self.assertIsInstance(parent, om.MDagPath)
     self.assertEquals(parent.partialPathName(), "group1")
Ejemplo n.º 8
0
def saveToLib(node, name, override=True):
    """Save's the current transform node shapes to the zoo library, used internally for zoo.

    :param node:The mobject to the transform that you want to save
    :type node: MObject
    :param name: the name of the file to create, if not specified the node name will be used
    :type name: str
    :return: The file path to the newly created shape file
    :rtype: str

    .. code-block:: python

        nurbsCurve = cmds.circle()[0]
        # requires an MObject of the shape node
        data, path = saveToLib(api.asMObject(nurbsCurve))

    """
    if name is None:
        name = nodes.nameFromMObject(node, True, False)
    if not name.endswith(".shape"):
        name = ".".join([name, "shape"])
    data = curves.serializeCurve(node)

    lib = os.path.abspath(
        os.path.join(os.path.dirname(os.path.realpath(__file__))))
    if override:
        names = [f for f in iterAvailableShapesNames()]
        if name in names:
            raise ValueError(
                "name-> {} already exists in the shape library!".format(name))
    path = os.path.join(lib, name)
    filesystem.saveJson(data, path)

    return data, path
Ejemplo n.º 9
0
def serializeSkinWeightsFromShapes(shapes):
    """Serialize's the geometry shape skinCluster weights to a dict

    :example:
        
        {my|objectName: {"points":   [[11.720806121826172,11.951449566072865,0.47714900970458984,1]],
            "skinData": [{
                "name": "roboRig:skinCluster_hand01_L",
                "maxInfluence": 5,
                "maintainMaxInfluences": true,
                "skinningMethod": 0,
                "weights": {
                    "|L_wrist": [1,0,1,0]
                    }]
                    }
        }
    
    :param shapes: The MObjects representing the shape nodes to serialize
    :type shapes: om2.MObject 
    :rtype: dict
    """

    data = {}
    for sh in shapes:
        clusters = clusterUpstreamFromNode(sh)
        if not clusters:
            continue
        fn = om2.MFnMesh(om2.MFnDagNode(sh).getPath())
        data[generic.stripNamespaceFromName(nodes.nameFromMObject(sh))] = {
            "points": map(tuple, fn.getPoints(om2.MSpace.kWorld)),
            "skinData": serializeClusters(clusters)
        }
    return data
Ejemplo n.º 10
0
def serializeIncomingConstraints(node):
    results = []
    for driver, utilties in iterIncomingConstraints(node):
        driverName = nodes.nameFromMObject(driver)
        results.append({
            "utilities": [nodes.serializeNode(i) for i in utilties],
            "driver": driverName
        })
Ejemplo n.º 11
0
    def addNodes(self, nodes):
        """Adds a list of nodes to the current node editor

        :param nodes: a list of maya mobject representing valid nodes
        :type nodes: list(:class:`om2.MObject`)
        """

        for n in nodes:
            cmds.nodeEditor(self.objectName(),
                            addNode=apiNodes.nameFromMObject(n))
Ejemplo n.º 12
0
 def serialize(self):
     data = {}
     for plug in self.iterAttributes():
         attrData = {"name": plug.name(),
                     "type": plug.attribute().apiTypeStr,
                     "value": plugs.getPlugValue(plug)}
         connections = []
         if plug.isSource:
             for connection in plug.connectedTo(False, True):
                 connections.append((nodes.nameFromMObject(connection.node()), connection.name()))
         attrData["connections"] = connections
         data.update(attrData)
     return data
Ejemplo n.º 13
0
 def findChildrenByFilter(self, filter, plugName=None, depthLimit=256):
     children = []
     for child in self.iterMetaChildren(depthLimit):
         if not plugName:
             grp = re.search(filter, nodes.nameFromMObject(child))
         else:
             try:
                 plug = child._mfn.findPlug(plugName, False)
                 grp = re.search(filter, plugs.getPlugValue(plug))
             except RuntimeError:
                 continue
         if grp:
             children.append(child)
     return children
Ejemplo n.º 14
0
    def create(self,
               driver,
               driven,
               skipRotate=None,
               skipTranslate=None,
               maintainOffset=False):
        driverName = nodes.nameFromMObject(driver)
        drivenName = nodes.nameFromMObject(driven)

        const = cmds.parentConstraint(driverName,
                                      drivenName,
                                      skipRotate=skipRotate or [],
                                      skipTranslate=skipTranslate or [],
                                      weight=1.0,
                                      maintainOffset=maintainOffset)
        self.node = om2.MObjectHandle(nodes.asMObject(const[0]))
        mapping = dict(skipRotate=skipRotate,
                       skipTranslate=skipTranslate,
                       maintainOffset=maintainOffset)
        kwargsMap = json.dumps(mapping)
        addConstraintMap(driver, (driven, ), (self.node.object(), ),
                         kwargsMap=kwargsMap)
        return self.node.object()
Ejemplo n.º 15
0
def matchCurves(driver, targets):
    """Function that matches the curves from the driver to all the targets.

    :param driver: the transform node of the shape to match
    :type driver: om2.MObject
    :param targets: A list of transform that will have the shapes replaced
    :type targets: list(om2.MObject) or tuple(om2.MObject)
    """
    driverdata = serializeCurve(driver)

    for target in targets:
        cmds.delete([
            nodes.nameFromMObject(i.node())
            for i in nodes.iterShapes(om2.MDagPath.getAPathTo(target))
        ])
        createCurveShape(target, driverdata)
Ejemplo n.º 16
0
def createAnnotation(rootObj, endObj, text=None, name=None):
    name = name or "annotation"
    rootDag = om2.MFnDagNode(rootObj)
    boundingBox = rootDag.boundingBox
    center = om2.MVector(boundingBox.center)
    transform = nodes.createDagNode("_".join([name, "loc"]),
                                    "transform",
                                    parent=rootObj)
    nodes.setTranslation(transform,
                         nodes.getTranslation(rootObj, om2.MSpace.kWorld),
                         om2.MSpace.kWorld)
    annotationNode = nodes.asMObject(
        cmds.annotate(nodes.nameFromMObject(transform), tx=text))
    annParent = nodes.getParent(annotationNode)
    nodes.rename(annParent, name)
    plugs.setPlugValue(
        om2.MFnDagNode(annotationNode).findPlug("position", False), center)
    nodes.setParent(annParent, endObj, False)
    return annotationNode, transform
Ejemplo n.º 17
0
def convertToNode(node, parent, prefix, nodeType="joint"):
    """Converts a node into a joint but does not delete the node ,
    transfers matrix over as well

    :param node: mobject, the node that will be converted
    :param parent: mobject to the transform to parent to
    :param prefix: str, the str value to give to the start of the node name
    :param nodeType: str, the node type to convert to. must be a dag type node
    :return: mObject, the mobject of the joint
    """
    mod = om2.DagModifier("createJoint")
    jnt = mod.createNode(nodeType)
    mod.doIt()
    nodes.rename(jnt, prefix + nodes.nameFromMObject(node, partialName=True))
    nodes.setParent(jnt, parent)
    plugs.setPlugValue(
        om2.MFnDagNode(jnt).findPlug("worldMatrix", False),
        nodes.getWorldMatrix(node))

    return jnt
Ejemplo n.º 18
0
 def addTarget(self, driver):
     """Adds the given driver transform to the constraint
     :param driver: The driver mobject transform
     :type driver: MObject
     @note having to use maya commands here due to api not able to resize the plugs array outside the datablock
     """
     driven = self.drivenObject()
     driverName = nodes.nameFromMObject(driver)  # so we have the fullPath
     driverShortName = om2.MNamespace.stripNamespaceFromName(driverName).split("|")[-1]
     nextWeightIndex = self.numTargets()  # starts at zero so the return is the next element
     drivenFn = om2.MFnDependencyNode(driven)
     offsetMatrix = om2.MTransformationMatrix(nodes.getOffsetMatrix(driver, driven))
     translation = offsetMatrix.translation(om2.MSpace.kTransform)
     rotation = generic.eulerToDegrees(
         offsetMatrix.rotation().reorder(plugs.getPlugValue(drivenFn.findPlug("rotateOrder", False))))
     # create the weight attribute
     weightName = "W".join([driverShortName, str(nextWeightIndex)])
     weightAttr = nodes.addAttribute(self.node.object(), weightName, weightName,
                                     attrType=attrtypes.kMFnNumericDouble)
     weightAttr.setMin(0.0)
     weightAttr.setMax(1.0)
     weightAttr.default = 1.0
     weightAttr.keyable = True
     driverFn = om2.MFnDependencyNode(driver)
     targetPlug = self.mfn.findPlug("target", False).elementByLogicalIndex(nextWeightIndex)
     cmds.connectAttr(driverFn.findPlug("parentMatrix", False).elementByPhysicalIndex(0).name(),
                      targetPlug.child(0).name())  # targetParentMatrix
     cmds.connectAttr(driverFn.findPlug("scale", False).name(), targetPlug.child(13).name())  # targetScale
     cmds.connectAttr(driverFn.findPlug("rotateOrder", False).name(),
                      targetPlug.child(8).name())  # targetRotateOrder
     cmds.connectAttr(driverFn.findPlug("rotate", False).name(), targetPlug.child(7).name())  # targetRotate
     cmds.connectAttr(driverFn.findPlug("rotatePivotTranslate", False).name(),
                      targetPlug.child(5).name())  # targetRotateTranslate
     cmds.connectAttr(driverFn.findPlug("rotatePivot", False).name(),
                      targetPlug.child(4).name())  # targetRotatePivot
     cmds.connectAttr(driverFn.findPlug("translate", False).name(), targetPlug.child(3).name())  # targetTranslate
     cmds.connectAttr(om2.MPlug(self.mfn.object(), weightAttr.object()).name(),
                      targetPlug.child(1).name())  # targetWeight
     # setting offset value
     plugs.setPlugValue(targetPlug.child(6), translation)  # targetOffsetTranslate
     plugs.setPlugValue(targetPlug.child(10), rotation)  # targetOffsetRotate
Ejemplo n.º 19
0
def createAnnotation(rootObj, endObj, text=None, name=None):
    newparent = nodes.createDagNode("_".join([name, "ann_hrc"]), "transform")
    name = name or "annotation"
    locator = nodes.createDagNode("_".join([name, "loc"]), "locator",
                                  newparent)

    annotationNode = nodes.asMObject(
        cmds.annotate(nodes.nameFromMObject(locator), tx=text))
    annParent = nodes.getParent(annotationNode)
    nodes.rename(annParent, name)
    nodes.setParent(annParent, newparent, False)
    extras = [newparent]
    constraint = constraints.MatrixConstraint(
        name="_".join([name, "startMtx"]))

    extras.extend(
        constraint.create(endObj, locator, (True, True, True),
                          (True, True, True), (True, True, True)))
    extras.extend(
        constraint.create(rootObj, annParent, (True, True, True),
                          (True, True, True), (True, True, True)))

    return annParent, locator, extras
Ejemplo n.º 20
0
 def __getattr__(self, item):
     for i in iter(self):
         if nodes.nameFromMObject(i, True, False) == item:
             if i.hasFn(om2.MFn.DagNode):
                 return om2.MFnDagNode(i)
             return om2.MFnDependencyNode(i)
Ejemplo n.º 21
0
def buildConstraint(source, targets, maintainOffset=False,
                    constraintType=om2.MFn.kParentConstraint, **kwargs):
    """This Function build a space switching constraint.

    Currently Supporting types of
        kParentConstraint
        kPointConstraint
        kOrientConstraint

    :param source: The transform to drive
    :param source: om2.MObject
    :param targets: A dict containing the target information(see below example)
    :param targets: dict or None
    :param: maintainOffset: whether or not the constraint should maintain offset
    :type maintainOffset: bool
    :param constraintType: The maya api kType eg. om2.MFn.kParentConstraint, defaults to kParentConstraint
    :type constraintType: om2.MFn.kType
    :param kwargs: The cmds.kconstraintType extra arguments to use
    :type kwargs: dict

    .. code-block: python

        targets = []
        for n in ("locator1", "locator2", "locator3"):
            targets.append((n, nodes.createDagNode(n, "locator")))
        spaceNode =nodes.createDagNode("control", "locator")
        drivenNode = nodes.createDagNode("driven", "locator")
        spaces = {"spaceNode": spaceNode,
                    "attributeName": "parentSpace", "targets": targets}
        constraint, conditions = build(drivenNode, targets=spaces)

        # lets add to the existing system
        spaces = {"spaceNode": spaceNode, "attributeName": "parentSpace", "targets": (
                 ("locator8", nodes.createDagNode("locator8", "locator")),)}

        constraint, conditions = build(drivenNode, targets=spaces)

      )


    """
    # make sure we support the constrainttype the user wants
    assert constraintType in APITOCMDS_CONSTRAINT_MAP, "No Constraint of type: {}, supported".format(constraintType)

    spaceNode = targets.get("spaceNode")
    attrName = targets.get("attributeName", "parent")
    targetInfo = targets["targets"]
    targetLabels, targetNodes = zip(*targetInfo)

    # first try to find an existing constraint
    existingConstraint = findConstraint(source, constraintType, includeReferenced=False)
    # if we found existing constraint then check to see if the target is already
    # constraining, if so just excluded it.
    targetList = targetNodes
    if existingConstraint:
        existingTargets = list(iterTargetsFromConstraint(existingConstraint))
        targetList = [t for t in targetNodes if t not in existingTargets]
        # in the case that all target already exist just early out
        if not targetList:
            return None, []

    # create the constraint
    constraintMap = APITOCMDS_CONSTRAINT_MAP[constraintType]
    cmdsFunc = getattr(cmds, constraintMap["type"])
    arguments = {"maintainOffset": maintainOffset}
    arguments.update(kwargs)
    constraint = cmdsFunc(map(nodes.nameFromMObject, targetList), nodes.nameFromMObject(source),
                          **arguments)[0]
    # if we have been provided a spaceNode, which will contain our switch, otherwise ignore the setup of a switch
    # and just return the constraint
    constraintMObject = nodes.asMObject(constraint)
    if spaceNode is None:
        return constraintMObject, []

    spaceFn = om2.MFnDependencyNode(spaceNode)
    if spaceFn.hasAttribute(attrName):
        spacePlug = spaceFn.findPlug(attrName, False)
        existingFieldNames = plugs.enumNames(spacePlug)
        spaceAttr = om2.MFnEnumAttribute(spacePlug.attribute())
        # add any missing fields to enumAttribute
        for field in targetLabels:
            if field not in existingFieldNames:
                spaceAttr.addField(field, len(existingFieldNames))

    else:
        spaceAttr = nodes.addAttribute(spaceNode, attrName, attrName, attrType=attrtypes.kMFnkEnumAttribute,
                                       keyable=True,
                                       channelBox=True, locked=False,
                                       enums=targetLabels)
        spacePlug = om2.MPlug(spaceNode, spaceAttr.object())

    constraintFn = om2.MFnDependencyNode(constraintMObject)
    targetArray = constraintFn.findPlug("target", False)
    sourceShortName = nodes.nameFromMObject(source, partialName=True, includeNamespace=False)
    conditions = []
    constraintTargetWeightIndex = constraintMap["targetPlugIndex"]
    # first iterate over the target array on the constraint
    for index in targetArray.getExistingArrayAttributeIndices():
        targetElement = targetArray.elementByLogicalIndex(index)
        targetElementWeight = targetElement.child(constraintTargetWeightIndex)
        targetWeightSource = targetElementWeight.source()
        # just in case the target weight plug is disconnected
        if targetWeightSource is None:
            targetWeightSource = targetElementWeight
        else:
            # lets make sure that we're not already connected to a condition node
            # if so skip
            weightSourceNode = targetWeightSource.node()
            # if we connected to the constraint i.e spaceWO1
            if weightSourceNode == constraintMObject:
                upstreamWeight = targetWeightSource.source()
                if upstreamWeight and upstreamWeight.node().apiType() == om2.MFn.kCondition:
                    continue
            else:
                if weightSourceNode.apiType() == om2.MFn.kCondition:
                    continue
        targetNode = targetElement.child(0).source().node()
        targetShortName = nodes.nameFromMObject(targetNode, partialName=True, includeNamespace=False)
        # create the condition node and do the connections
        conditionNode = creation.conditionVector(firstTerm=spacePlug, secondTerm=float(targetElement.logicalIndex()),
                                                 colorIfTrue=(1.0, 0.0, 0.0),
                                                 colorIfFalse=(0.0, 0.0, 0.0), operation=0,
                                                 name="_".join([targetShortName, sourceShortName, "space"]))
        condFn = om2.MFnDependencyNode(conditionNode)
        plugs.connectPlugs(condFn.findPlug("outColorR", False), targetWeightSource)
        conditions.append(conditionNode)

    return constraintMObject, conditions