Exemplo n.º 1
0
    def addAttribute(self, name, value, Type, isArray=False, lock=True):
        mfn = self._mfn
        mobj = mfn.object()
        if mfn.hasAttribute(name):
            return mfn.findPlug(name, False)
        try:
            attr = nodes.addAttribute(mobj,
                                      name,
                                      name,
                                      Type,
                                      isArray=isArray,
                                      apply=True)
        except RuntimeError:
            raise ValueError(
                "Failed to create attribute with name: {}".format(name))
        newPlug = None
        if attr is not None:
            newPlug = om2.MPlug(mobj, attr.object())

        if value is not None and newPlug is not None:
            # if mobject expect it to be a node
            if isinstance(value, om2.MObject):
                self.connectTo(name, value)
            else:
                plugs.setPlugValue(newPlug, value)
        newPlug.isLocked = lock
        return newPlug
Exemplo n.º 2
0
def createPlusMinusAverage2D(name, inputs, output=None, operation=1):
    """ Create's a plusMinusAverage node and connects the 2D inputs and outputs.

    :param name: the plus minus average node name
    :type name: str
    :param inputs: tuple of MPlugs and/or float values, each value will be applied to /
    a new Input2D element. If the value is MPlug then it will be connected
    :type inputs: iterable(plug or float)
    :param output: A tuple of downstream MPlugs to connect to.
    :type output: iterable(plug)
    :return: The plus minus average MObject
    :rtype: om2.MObject
    """
    pma = nodes.createDGNode(name, "plusMinusAverage")
    fn = om2.MFnDependencyNode(pma)
    inPlug = fn.findPlug("input2D", False)
    fn.findPlug("operation", False).setInt(operation)
    for i, p in enumerate(inputs):
        if p is None:
            continue
        child = plugs.nextAvailableElementPlug(inPlug)
        if isinstance(p, om2.MPlug):
            plugs.connectPlugs(p, child)
            continue
        plugs.setPlugValue(child, p)

    if output is not None:
        ouPlug = fn.findPlug("output2D", False)
        for index, out in enumerate(output):
            if out is None:
                continue
            plugs.connectPlugs(ouPlug, out)
    return pma
Exemplo n.º 3
0
def conditionVector(firstTerm, secondTerm, colorIfTrue, colorIfFalse,
                    operation, name):
    """
    :param firstTerm: 
    :type firstTerm: om2.MPlug or float
    :param secondTerm: 
    :type secondTerm: om2.MPlug or float 
    :param colorIfTrue: seq of MPlugs or a single MPlug(compound) 
    :type colorIfTrue: om2.MPlug or list(om2.Plug) or om2.MVector
    :param colorIfFalse: seq of MPlugs or a single MPlug(compound)
    :type colorIfFalse: om2.MPlug or list(om2.Plug) or om2.MVector 
    :param operation: the comparsion operator
    :type operation: int
    :param name: the new name for the node
    :type name: str
    :return: 
    :rtype: om2.MObject
    """
    condNode = om2.MFnDependencyNode(nodes.createDGNode(name, "condition"))
    if isinstance(firstTerm, float):
        plugs.setPlugValue(condNode.findPlug("firstTerm", False), firstTerm)
    else:
        plugs.connectPlugs(firstTerm, condNode.findPlug("firstTerm", False))
    if isinstance(operation, int):
        plugs.setPlugValue(condNode.findPlug("operation", False), operation)
    else:
        plugs.connectPlugs(operation, condNode.findPlug("operation", False))

    if isinstance(secondTerm, float):
        plugs.setPlugValue(condNode.findPlug("secondTerm", False), firstTerm)
    else:
        plugs.connectPlugs(secondTerm, condNode.findPlug("secondTerm", False))
    if isinstance(colorIfTrue, om2.MPlug):
        plugs.connectPlugs(colorIfTrue,
                           condNode.findPlug("colorIfTrue", False))
    elif isinstance(colorIfTrue, om2.MVector):
        plugs.setPlugValue(condNode.findPlug("colorIfTrue", False),
                           colorIfTrue)
    else:
        color = condNode.findPlug("colorIfTrue", False)
        # expecting seq of plugs
        for i, p in enumerate(colorIfTrue):
            child = color.child(i)
            plugs.connectPlugs(p, child)
    if isinstance(colorIfFalse, om2.MPlug):
        plugs.connectPlugs(colorIfFalse,
                           condNode.findPlug("colorIfFalse", False))
    elif isinstance(colorIfFalse, om2.MVector):
        plugs.setPlugValue(condNode.findPlug("colorIfFalse", False),
                           colorIfFalse)
    else:
        color = condNode.findPlug("colorIfFalse", False)
        # expecting seq of plugs
        for i, p in enumerate(colorIfFalse):
            child = color.child(i)
            plugs.connectPlugs(p, child)
    return condNode.object()
Exemplo n.º 4
0
 def setAttribute(self, attr, value):
     if isinstance(attr, om2.MPlug):
         with plugs.setLockedContext(attr):
             plugs.setPlugValue(attr, value)
         return
     if self.hasAttribute(attr):
         plug = self._mfn.findPlug(attr, False)
         with plugs.setLockedContext(plug):
             plugs.setPlugValue(plug, value)
Exemplo n.º 5
0
def addConstraintMap(node, driven, utilities, kwargsMap=None):
    """Adds a mapping of drivers and utilities to the constraint compound array attribute

    :param node: The node to add or has the constraint map , typically this would be the driver node \
    of the constraint.
    :type node: om2.MObject
    :param driven: a list of driven transform nodes.
    :type driven: tuple(om2.MObject)
    :param utilities: a list of utilities/support nodes that make up the constraint, this could be the \
    constraint node itself or any math node etc.
    :type utilities: tuple(om2.MObject)
    """
    kwargsmap = kwargsMap or ""
    mfn = om2.MFnDependencyNode(node)
    if not mfn.hasAttribute("constraints"):
        compoundPlug = addConstraintAttribute(node)
    else:
        compoundPlug = mfn.findPlug("constraints", False)
    availPlug = plugs.nextAvailableElementPlug(compoundPlug)
    drivenPlug = availPlug.child(0)
    # lets add the driven nodes to the xth of the element compound
    for drive in iter(driven):
        if drive is None:
            continue
        drivenFn = om2.MFnDependencyNode(drive)
        if drivenFn.hasAttribute("constraint"):
            p = drivenFn.findPlug("constraint", False)
            elementP = plugs.nextAvailableElementPlug(p)
            plugs.connectPlugs(drivenPlug, elementP)
            continue
        attr = nodes.addAttribute(drive,
                                  "constraint",
                                  "constraint",
                                  attrtypes.kMFnMessageAttribute,
                                  isArray=True)
        attrP = om2.MPlug(drive, attr.object())
        plugs.connectPlugs(drivenPlug, attrP.elementByLogicalIndex(0))
    utilPlug = availPlug.child(1)
    # add all the utilities
    for i in iter(utilities):
        if i is None:
            continue
        utilFn = om2.MFnDependencyNode(i)
        if utilFn.hasAttribute("constraint"):
            p = utilFn.findPlug("constraint", False)
            if p.isDestination:
                continue
            plugs.connectPlugs(utilPlug, p)
            continue
        attr = nodes.addAttribute(i, "constraint", "constraint",
                                  attrtypes.kMFnMessageAttribute)
        plugs.connectPlugs(utilPlug, om2.MPlug(i, attr.object()))
    # set the kwargs map plug, so we know how the constraint was created
    plugs.setPlugValue(availPlug.child(2), kwargsmap)
    return compoundPlug
Exemplo n.º 6
0
def addAttributesFromList(node, data):
    """Creates an attribute on the node given a list(dict) of attribute data

        :param data: The serialized form of the attribute
                    [{
                        "channelBox": true,
                        "default": 3,
                        "isDynamic": true,
                        "keyable": false,
                        "locked": false,
                        "max": 9999,
                        "min": 1,
                        "name": "jointCount",
                        "softMax": null,
                        "softMin": null,
                        "Type": 2,
                        "value": 3
                        "isArray": True
                    }]
        :type data: dict
        :return: A list of create MPlugs
        :rtype: list(om2.MPlug)
        """
    created = []
    for attrData in iter(data):
        Type = attrData["Type"]
        default = attrData["default"]
        value = attrData["value"]
        name = attrData["name"]
        if Type == attrtypes.kMFnDataString:
            default = om2.MFnStringData().create(default)
        elif Type == attrtypes.kMFnDataMatrix:
            default = om2.MFnMatrixData().create(om2.MMatrix(default))
        elif Type == attrtypes.kMFnUnitAttributeAngle:
            default = om2.MAngle(default, om2.MAngle.kDegrees)
            value = om2.MAngle(value, om2.MAngle.kDegrees)

        plug = om2.MPlug(node, addAttribute(node, name, name, Type, isArray=data.get("array", False), apply=True))
        plugs.setPlugDefault(plug, default)

        plug.isChannelBox = attrData["value"]
        plug.isKeyable = attrData["keyable"]
        plugs.setLockState(plug, attrData["locked"])
        plugs.setMin(plug, attrData["min"])
        plugs.setMax(plug, attrData["max"])
        plugs.setSoftMin(plug, attrData["softMin"])
        plugs.setSoftMax(plug, attrData["softMax"])
        if not plug.attribute().hasFn(om2.MFn.kMessageAttribute):
            plugs.setPlugValue(plug, value)
        created.append(plug)
    return created
Exemplo n.º 7
0
def createMultMatrix(name, inputs, output):
    multMatrix = nodes.createDGNode(name, "multMatrix")
    fn = om2.MFnDependencyNode(multMatrix)
    plugs.connectPlugs(fn.findPlug("matrixSum", False), output)
    compound = fn.findPlug("matrixIn", False)
    compound.evaluateNumElements()

    for i in xrange(len(inputs)):
        inp = inputs[i]
        if isinstance(inp, om2.MPlug):
            plugs.connectPlugs(inp, compound.elementByLogicalIndex(i))
            continue
        plugs.setPlugValue(compound.elementByLogicalIndex(i), inp)
    return multMatrix
Exemplo n.º 8
0
def exportContext(rootNode):
    changed = []
    for i in nodes.iterChildren(rootNode, recursive=True):
        dp = om2.MFnDependencyNode(i)
        plug = dp.findPlug("visibility", False)
        with plugs.setLockedContext(plug):
            if plug.asFloat() != 1.0:
                plugs.setPlugValue(plug, 1.0)
                changed.append(dp)
    yield
    for i in iter(changed):
        plug = i.findPlug("visibility", False)
        with plugs.setLockedContext(plug):
            plugs.setPlugValue(plug, 0.0)
Exemplo n.º 9
0
def createPlusMinusAverage3D(name, inputs, output=None, operation=1):
    """ Create's a plusMinusAverage node and connects the 3D inputs and outputs.

    :param name: the plus minus average node name.
    :type name: str
    :param inputs: tuple of MPlugs and/or float values, each value will be applied to /
    a new Input3D element. If the value is MPlug then it will be connected.
    :type inputs: iterable(plug or float)
    :param output: A tuple of downstream MPlugs to connect to.
    :type output: iterable(plug) or None
    :return: The plus minus average MObject.
    :rtype: om2.MObject

    .. code-block:: python

        one = nodes.createDagNode("one", "transform")
        two = nodes.createDagNode("two", "transform")
        end = nodes.createDagNode("end", "transform")

        oneFn = om2.MFnDagNode(one)
        twoFn = om2.MFnDagNode(two)
        endFn = om2.MFnDagNode(end)
        inputs = [oneFn.findPlug("translate", False), twoFn.findPlug("translate", False)]
        outputs = [endFn.findPlug("translate", False)]
        pma = creation.createPlusMinusAverage3D("test_pma", inputs, outputs)
        # Result: <OpenMaya.MObject object at 0x000002AECB23AE50> #
        
    """
    pma = nodes.createDGNode(name, "plusMinusAverage")
    fn = om2.MFnDependencyNode(pma)
    inPlug = fn.findPlug("input3D", False)
    fn.findPlug("operation", False).setInt(operation)
    for i, p in enumerate(inputs):
        if p is None:
            continue
        child = plugs.nextAvailableElementPlug(inPlug)
        if isinstance(p, om2.MPlug):
            plugs.connectPlugs(p, child)
            continue
        plugs.setPlugValue(child, p)

    if output is not None:
        ouPlug = fn.findPlug("output3D", False)
        for index, out in enumerate(output):
            if out is None:
                continue
            plugs.connectPlugs(ouPlug, out)
    return pma
Exemplo n.º 10
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)
    locator = asMObject(cmds.createNode("locator"))
    locatorTransform = getParent(locator)
    rename(locatorTransform, "_".join([name, "loc"]))
    setTranslation(locatorTransform, getTranslation(rootObj, om2.MSpace.kWorld), om2.MSpace.kWorld)
    annotationNode = asMObject(cmds.annotate(nameFromMObject(locatorTransform), tx=text))
    annParent = getParent(annotationNode)
    rename(annParent, name)
    plugs.setPlugValue(om2.MFnDagNode(annotationNode).findPlug("position", False), center)
    setParent(locatorTransform, rootObj, True)
    setParent(annParent, endObj, False)
    return annotationNode, locatorTransform
Exemplo n.º 11
0
def createCurveShape(parent, data):
    """Create a specified nurbs curves based on the data

    :param parent: The transform that takes ownership of the shapes, if None is supplied then one will be created
    :type parent: MObject
    :param data: {"shapeName": {"cvs": [], "knots":[], "degree": int, "form": int, "matrix": []}}
    :type data: dict
    :return: A 2 tuple the first element is the MObject of the parent and the second is a list /
    of mobjects represents the shapes created.
    :rtype: tuple(MObject, list(MObject))
    """
    parentInverseMatrix = om2.MMatrix()
    if parent is None:
        parent = om2.MObject.kNullObj
    elif parent != om2.MObject.kNullObj:
        parentInverseMatrix = nodes.getWorldInverseMatrix(parent)

    newCurve = om2.MFnNurbsCurve()
    newShapes = []
    for shapeName, curveData in iter(data.items()):
        cvs = om2.MPointArray(
            curveData["cvs"]
        )  # om2 allows a list of lists which converts to om2.Point per element
        knots = curveData["knots"]
        degree = curveData["degree"]
        form = curveData["form"]
        enabled = curveData["overrideEnabled"]
        matrix = curveData.get("matrix")
        if matrix is not None:
            mat = om2.MMatrix(matrix)
            for i in range(len(cvs)):
                cvs[i] *= mat * parentInverseMatrix
        shape = newCurve.create(cvs, knots, degree, form, False, False, parent)
        newShapes.append(shape)
        if parent == om2.MObject.kNullObj and shape.apiType(
        ) == om2.MFn.kTransform:
            parent = shape
        if enabled:
            plugs.setPlugValue(newCurve.findPlug("overrideEnabled", False),
                               int(curveData["overrideEnabled"]))
            colours = curveData["overrideColorRGB"]
            outlinerColour = curveData.get("outlinerColor")
            nodes.setNodeColour(newCurve.object(),
                                colours,
                                outlinerColour=outlinerColour)
    return parent, newShapes
Exemplo n.º 12
0
def createCurveShape(parent, data):
    """Create a specified nurbs curves based on the data

    :param parent: The transform that takes ownership of the shapes, if None is supplied then one will be created
    :type parent: MObject
    :param data: {"shapeName": {"cvs": [], "knots":[], "degree": int, "form": int, "matrix": []}}
    :type data: dict
    :return: the parent node
    :rtype: MObject
    """
    if parent is None:
        parent = om2.MObject.kNullObj
    newCurve = om2.MFnNurbsCurve()
    cvData = []
    for shapeName, curveData in iter(data.items()):
        cvs = om2.MPointArray(
            curveData["cvs"]
        )  # om2 allows a list of lists which converts to om2.Point per element
        knots = curveData["knots"]
        degree = curveData["degree"]
        form = curveData["form"]
        enabled = curveData["overrideEnabled"]
        shape = newCurve.create(cvs, knots, degree, form, False, False, parent)
        mat = curveData.get("matrix")
        if parent == om2.MObject.kNullObj and shape.apiType(
        ) == om2.MFn.kTransform:
            parent = shape
        if enabled:
            plugs.setPlugValue(newCurve.findPlug("overrideEnabled", False),
                               int(curveData["overrideEnabled"]))
            colours = curveData["overrideColorRGB"]
            nodes.setNodeColour(newCurve.object(), colours)
        if mat:
            cvData.append((newCurve.getPath(), mat, cvs))
    # apparently must use object space to create and calling setCVPosition with the forloop causing an maya error
    # this could be because maya has yet to refresh meaning the MObject is invalid , hence the need to loop
    # back over and multiple the cvs by the worldMatrix
    for p, mat, cvs in cvData:
        mat = om2.MMatrix(mat)
        newCurve.setObject(p)
        for i in range(len(cvs)):
            cvs[i] *= mat
        newCurve.setCVPositions(cvs, om2.MSpace.kWorld)
        newCurve.updateCurve()
    return parent
Exemplo n.º 13
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
Exemplo n.º 14
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
Exemplo n.º 15
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
Exemplo n.º 16
0
def multiplyDivide(input1, input2, operation, name):
    """Creates a multiply divide node with the given and setups the input connections.

    List of operations::

        no operation = 0,
        multipy = 1,
        divide = 2,
        power = 3

    :param input1:the node attribute to connect to the input1 value or use int for value
    :type input1: MPlug or MVector
    :param input2:the node attribute to connect to the input2 value or use int for value
    :type input2: MPlug or MVector
    :param operation: the int value for operation
    :type operation: int
    :return, the multiplyDivide node MObject
    :rtype: MObject
    """

    mult = om2.MFnDependencyNode(nodes.createDGNode(name, "multiplyDivide"))
    # assume connection type
    if isinstance(input1, om2.MPlug):
        plugs.connectPlugs(input1, mult.findPlug("input1", False))
    # plug set
    else:
        plugs.setPlugValue(mult.findPlug("input1", False), input1)
    if isinstance(input2, om2.MPlug):
        plugs.connectPlugs(input2, mult.findPlug("input2", False))
    else:
        plugs.setPlugValue(mult.findPlug("input2", False), input1)
    plugs.setPlugValue(mult.findPlug("operation", False), operation)

    return mult.object()
Exemplo n.º 17
0
def floatMath(floatA, floatB, operation, name):
    """Creates a floatMath node from the lookdev kit builtin plugin

    :param floatA: If the type is a MPlug then the floatA plug on the new node\
    will be connected the given plug.
    :type floatA: float or om2.MPlug
    :param floatB: If the type is a MPlug then the floatB plug on the new node\
    will be connected the given plug.
    :type floatB: float or om2.MPlug
    :param operation: The operation attributes value
    :type operation: int
    :param name: The new floatMath node name.
    :type name: str
    :return: The floatMath node MObject
    :rtype: om2.MObject
    """
    floatMathFn = om2.MFnDependencyNode(nodes.createDGNode(name, "floatMath"))
    if isinstance(floatA, om2.MPlug):
        plugs.connectPlugs(floatA, floatMathFn.findPlug("floatA", False))
    else:
        plugs.setPlugValue(floatMathFn.findPlug("floatA", False), floatA)

    if isinstance(floatB, om2.MPlug):
        plugs.connectPlugs(floatB, floatMathFn.findPlug("floatB", False))
    else:
        plugs.setPlugValue(floatMathFn.findPlug("floatB", False), floatB)
    plugs.setPlugValue(floatMathFn.findPlug("operation", False), operation)
    return floatMathFn.object()
Exemplo n.º 18
0
def blendColors(color1, color2, name, blender):
    """Creates a blend colors node.

    :param color1: If the type is a MPlug then the color1 plug on the new node\
    will be connected the given plug.
    :type color1: om2.MColor or om2.MPlug
    :param color2: If the type is a MPlug then the color2 plug on the new node\
    will be connected the given plug.
    :type color2: om2.MColor or om2.MPlug
    :param name: The new floatMath node name.
    :type name: str
    :param blender: If the type is a MPlug then the blender plug on the new node\
    will be connected the given plug.
    :type blender: float or om2.MPlug
    :return: The new colorBlend node as a MObject
    :rtype: om2.MObject
    """
    blendFn = om2.MFnDependencyNode(nodes.createDGNode(name, "blendColors"))
    if isinstance(color1, om2.MPlug):
        plugs.connectPlugs(color1, blendFn.findPlug("color1", False))
    else:
        plugs.setPlugValue(blendFn.findPlug("color1", False), color1)
    if isinstance(color2, om2.MPlug):
        plugs.connectPlugs(color2, blendFn.findPlug("color2", False))
    else:
        plugs.setPlugValue(blendFn.findPlug("color2", False), color2)
    if isinstance(blender, om2.MPlug):
        plugs.connectPlugs(blender, blendFn.findPlug("blender", False))
    else:
        plugs.setPlugValue(blendFn.findPlug("blender", False), blender)
    return blendFn.object()
Exemplo n.º 19
0
    def addAttribute(self, name, value, Type, isArray=False, lock=True):
        mobj = self._handle.object()
        mfn = om2.MFnDependencyNode(mobj)
        if mfn.hasAttribute(name):
            return
        try:
            attr = nodes.addAttribute(mobj, name, name, Type)
            attr.array = isArray
        except RuntimeError:
            return
        newPlug = None
        if attr is not None:
            newPlug = om2.MPlug(mobj, attr.object())

        if value is not None and newPlug is not None:
            # if mobject expect it to be a node
            if isinstance(value, om2.MObject):
                self.connectTo(name, value)
            else:
                plugs.setPlugValue(newPlug, value)
        newPlug.isLocked = lock
        return attr
Exemplo n.º 20
0
def pairBlend(name,
              inRotateA=None,
              inRotateB=None,
              inTranslateA=None,
              inTranslateB=None,
              weight=None,
              rotInterpolation=None):
    blendPairNode = om2.MFnDependencyNode(nodes.createDGNode(
        name, "pairBlend"))
    if inRotateA is not None:
        plugs.connectPlugs(inRotateA,
                           blendPairNode.findPlug("inRotate1", False))
    if inRotateB is not None:
        plugs.connectPlugs(inRotateB,
                           blendPairNode.findPlug("inRotate2", False))
    if inTranslateA is not None:
        plugs.connectPlugs(inTranslateA,
                           blendPairNode.findPlug("inTranslate1", False))
    if inTranslateB is not None:
        plugs.connectPlugs(inTranslateB,
                           blendPairNode.findPlug("inTranslate2", False))
    if weight is not None:
        if isinstance(weight, om2.MPlug):
            plugs.connectPlugs(weight, blendPairNode.findPlug("weight", False))
        else:
            plugs.setPlugValue(blendPairNode.findPlug("weight", False), weight)
    if rotInterpolation is not None:
        if isinstance(rotInterpolation, om2.MPlug):
            plugs.connectPlugs(
                rotInterpolation,
                blendPairNode.findPlug("rotInterpolation", False))
        else:
            plugs.setPlugValue(
                blendPairNode.findPlug("rotInterpolation", False),
                rotInterpolation)
    return blendPairNode.object()
Exemplo n.º 21
0
def floatMath(floatA, floatB, operation, name):
    floatMathFn = om2.MFnDependencyNode(nodes.createDGNode(name, "floatMath"))
    if isinstance(floatA, om2.MPlug):
        plugs.connectPlugs(floatA, floatMathFn.findPlug("floatA", False))
    else:
        plugs.setPlugValue(floatMathFn.findPlug("floatA", False), floatA)

    if isinstance(floatB, om2.MPlug):
        plugs.connectPlugs(floatB, floatMathFn.findPlug("floatB", False))
    else:
        plugs.setPlugValue(floatMathFn.findPlug("floatB", False), floatB)
    plugs.setPlugValue(floatMathFn.findPlug("operation", False), operation)
    return floatMathFn.object()
Exemplo n.º 22
0
def blendColors(color1, color2, name, blender):
    blendFn = om2.MFnDependencyNode(nodes.createDGNode(name, "blendColors"))
    if isinstance(color1, om2.MPlug):
        plugs.connectPlugs(color1, blendFn.findPlug("color1", False))
    else:
        plugs.setPlugValue(blendFn.findPlug("color1", False), color1)
    if isinstance(color2, om2.MPlug):
        plugs.connectPlugs(color2, blendFn.findPlug("color2", False))
    else:
        plugs.setPlugValue(blendFn.findPlug("color2", False), color2)
    if isinstance(blender, om2.MPlug):
        plugs.connectPlugs(blender, blendFn.findPlug("blender", False))
    else:
        plugs.setPlugValue(blendFn.findPlug("blender", False), blender)
    return blendFn.object()
Exemplo n.º 23
0
def setNodeColour(node, colour):
    """Set the given node mobject override color can be a mobject representing a transform or shape

    :param node: the node which you want to change the override colour of
    :type node: mobject
    :param colour: The RGB colour to set
    :type colour: MColor or tuple
    """
    dependNode = om2.MFnDagNode(om2.MFnDagNode(node).getPath())
    plug = dependNode.findPlug("overrideColorRGB", False)
    enabledPlug = dependNode.findPlug("overrideEnabled", False)
    overrideRGBColors = dependNode.findPlug("overrideRGBColors", False)
    if not plugs.getPlugValue(enabledPlug):
        plugs.setPlugValue(enabledPlug, True)
    if not plugs.getPlugValue(overrideRGBColors):
        plugs.setPlugValue(dependNode.findPlug("overrideRGBColors", False), True)
    plugs.setPlugValue(plug, colour)
Exemplo n.º 24
0
def createSetRange(name, value, min_, max_, oldMin, oldMax, outValue=None):
    """ Generates and connects a setRange node.

    input/output arguments take an iterable, possibles values are om2.MPlug,
     float or None.

    if a value is None it will be skipped this is useful when you want
    some not connected or set to a value but the other is left to the
    default state.
    If MPlug is passed and its a compound it'll be connected.

    :param name: the new name for the set Range node
    :type name: str
    :param value:
    :type value: iterable(om2.MPlug or float or None)
    :param min_:
    :type min_: iterable(om2.MPlug or float or None)
    :param max_:
    :type max_: iterable(om2.MPlug or float or None)
    :param oldMin:
    :type oldMin: iterable(om2.MPlug or float or None)
    :param oldMax:
    :type oldMax: iterable(om2.MPlug or float or None)
    :param outValue:
    :type outValue: iterable(om2.MPlug or float or None)
    :return: the created setRange node
    :rtype: om2.MObject

    .. code-block:: python

        one = nodes.createDagNode("one", "transform")
        two = nodes.createDagNode("two", "transform")
        end = nodes.createDagNode("end", "transform")

        oneFn = om2.MFnDagNode(one)
        twoFn = om2.MFnDagNode(two)
        endFn = om2.MFnDagNode(end)
        values = [oneFn.findPlug("translate", False)]
        min_ = [twoFn.findPlug("translate", False)]
        max_ = [twoFn.findPlug("translate", False)]
        oldMax = [0.0,180,360]
        oldMin = [-10,-720,-360]
        reload(creation)
        outValues = [endFn.findPlug("translateX", False), endFn.findPlug("translateY", False), None]
        pma = creation.createSetRange("test_pma", values, min_, max_, oldMin, oldMax, outValues)

    """
    setRange = nodes.createDGNode(name, "setRange")
    fn = om2.MFnDependencyNode(setRange)
    valuePlug = fn.findPlug("value", False)
    oldMinPlug = fn.findPlug("oldMin", False)
    oldMaxPlug = fn.findPlug("oldMax", False)
    minPlug = fn.findPlug("min", False)
    maxPlug = fn.findPlug("max", False)

    # deal with all the inputs
    # source list, destination plug
    for source, destination in ((value, valuePlug), (min_, minPlug), (max_,
                                                                      maxPlug),
                                (oldMin, oldMinPlug), (oldMax, oldMaxPlug)):
        if source is None:
            continue
        for index, inner in enumerate(source):
            if inner is None:
                continue
            elif isinstance(inner, om2.MPlug):
                if inner.isCompound:
                    plugs.connectPlugs(inner, destination)
                    break
                child = destination.child(index)
                plugs.connectPlugs(inner, child)
                continue
            child = destination.child(index)
            plugs.setPlugValue(child, inner)
    if outValue is None:
        return setRange
    outPlug = fn.findPlug("outValue", False)
    # now the outputs
    for index, out in enumerate(outValue):
        if out is None:
            continue
        if isinstance(out, om2.MPlug):
            if out.isCompound:
                plugs.connectPlugs(outPlug, out)
                break
            child = outPlug.child(index)
            plugs.connectPlugs(child, out)
            continue
        child = outPlug.child(index)
        # not a plug must be a plug value
        plugs.setPlugValue(child, out)
    return setRange