Python pymel.core.setAttr() Examples

The following are 30 code examples of pymel.core.setAttr(). 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 pymel.core , or try the search function .
Example #1
Source File: anim.py    From fossil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _processAttr(plug, dups, forceKeys, staticValues, start, end):
    '''
    Used by `save`
    '''

    crvs = cmds.listConnections( plug, type='animCurve' )
    
    if not crvs:
        if forceKeys:
            setKeyframe( plug, t=start )
            setKeyframe( plug, t=end )
            crvs = cmds.listConnections( plug, type='animCurve' )
        else:
            if not cmds.getAttr(plug, lock=True) and not cmds.listConnections(plug, s=True, d=False):
                staticValues[plug] = cmds.getAttr(plug)
    
    if crvs:
        dup = cmds.duplicate(crvs)[0]
        if not objExists(dup + '.' + TAGGING_ATTR):
            cmds.addAttr( dup, ln=TAGGING_ATTR, dt='string' )
        cmds.setAttr( dup + '.' + TAGGING_ATTR, plug, type='string' )
        dups.append( dup ) 
Example #2
Source File: auxiliary.py    From anima with MIT License 6 votes vote down vote up
def check_sequence_name(self):
        """checks sequence name and asks the user to set one if maya is in UI
        mode and there is no sequence name set
        """
        sequencer = pm.ls(type='sequencer')[0]
        sequence_name = sequencer.getAttr('sequence_name')
        if sequence_name == '' and not pm.general.about(batch=1) \
           and not self.batch_mode:
            result = pm.promptDialog(
                title='Please enter a Sequence Name',
                message='Sequence Name:',
                button=['OK', 'Cancel'],
                defaultButton='OK',
                cancelButton='Cancel',
                dismissString='Cancel'
            )

            if result == 'OK':
                sequencer.setAttr(
                    'sequence_name',
                    pm.promptDialog(query=True, text=True)
                ) 
Example #3
Source File: attribute.py    From mgear_core with MIT License 6 votes vote down vote up
def setInvertMirror(node, invList=None):
    """Set invert mirror pose values

    Arguments:
        node (dagNode): The object to set invert mirror Values

    """

    aDic = {"tx": "invTx",
            "ty": "invTy",
            "tz": "invTz",
            "rx": "invRx",
            "ry": "invRy",
            "rz": "invRz",
            "sx": "invSx",
            "sy": "invSy",
            "sz": "invSz"}

    for axis in invList:
        if axis not in aDic:
            mgear.log("Invalid Invert Axis : " + axis, mgear.sev_error)
            return False

        node.setAttr(aDic[axis], True) 
Example #4
Source File: attribute.py    From mgear_core with MIT License 6 votes vote down vote up
def setNotKeyableAttributes(nodes,
                            attributes=["tx", "ty", "tz",
                                        "ro", "rx", "ry", "rz",
                                        "sx", "sy", "sz",
                                        "v"]):
    """Set not keyable attributes of a node.

    By defaul will set not keyable the rotation, scale and translation.

    Arguments:
        node(dagNode): The node with the attributes to set keyable.
        attributes (list of str): The list of the attributes to set not keyable
    """

    if not isinstance(nodes, list):
        nodes = [nodes]

    for attr_name in attributes:
        for node in nodes:
            node.setAttr(attr_name, lock=False, keyable=False, cb=True) 
Example #5
Source File: fcurve.py    From mgear_core with MIT License 6 votes vote down vote up
def getFCurveValues(fcv_node, division, factor=1):
    """Get X values evenly spaced on the FCurve.

    Arguments:
        fcv_node (pyNode or str): The FCurve to evaluate.
        division (int): The number of division you want to evaluate on
            the FCurve.
        factor (float): Multiplication factor. Default = 1. (optional)

    Returns:
        list of float: The values in a list float.

    >>> self.st_value = fcu.getFCurveValues(self.settings["st_profile"],
                                            self.divisions)

    """
    incr = 1 / (division - 1.0)

    values = []
    for i in range(division):
        pm.setAttr(fcv_node + ".input", i * incr)
        values.append(pm.getAttr(fcv_node + ".output") * factor)

    return values 
Example #6
Source File: joint.py    From anima with MIT License 6 votes vote down vote up
def set_zero_joint(self):

        #Removes Zero Joint from Joint Chain
        pm.joint(self.jointChain[0], e=True, zso=True, oj='xyz', sao='xup')
        self.zeroJoint = self.jointChain[0]

        self._zeroPos = pm.dt.Point(pm.getAttr(self._zeroJoint.translate))
        self.jointChain.remove(self.jointChain[0])
        self.jointPos.remove(self.jointPos[0])
        pm.joint(self.jointChain[1], e=True, zso=True, oj='xyz', sao='yup')
        for i in range(1, len(self.jointChain)):
            pm.joint(self.jointChain[i], e=True, zso=True, oj='xyz', sao='yup')
            #sets Start End Num Of Joints again
        self._numOfJoints = len(self._jointChain)
        #Orient Zero Joint
        temporalGroup = DrawNode(Shape.transform, 'temporalGroup')
        pm.parent(self.startJoint, temporalGroup.drawnNode)

        print(pm.getAttr(self.zeroJoint.jointOrient))
        pm.setAttr(self.zeroJoint.jointOrientX, 0)
        pm.parent(self.startJoint, self.zeroJoint)
        temporalGroup.delete() 
Example #7
Source File: splinerig.py    From DynRigBuilder with MIT License 6 votes vote down vote up
def _buildBaseCtrls(self):
        # create global ctrl
        self.globalCtrl = mayautils.createCtrl("{0}_all_ctrl".format(self.prefix), "crossArrow", 1, "yellow")
        globalCtrlAttr = [
            {"ln":"globalScale", "at":"float", "dv":1, "k":1},
            {"ln":self.RIG_TOP_TAG, "dt":"string"}
        ]
        mayautils.addAttributes(self.globalCtrl, globalCtrlAttr)

        # create meta ctrl
        self.metaCtrl = mayautils.createCtrl("{0}_meta_ctrl".format(self.prefix), "fatCross", 1, "yellow", None, [0,0,90])
        pm.xform(self.metaCtrl, t=self.metaPos, ws=1)
        mayautils.aimObject(self.endPos, self.metaCtrl)
        mayautils.createParentTransform("org", self.metaCtrl).setParent(self.globalCtrl)

        # build globalScale connections
        for ch in 'xyz':
            pm.connectAttr(self.globalCtrl.globalScale, "{0}.s{1}".format(self.metaCtrl.name(), ch))
            pm.setAttr("{0}.s{1}".format(self.metaCtrl.name(), ch), cb=0, keyable=0, lock=1)
            pm.setAttr("{0}.s{1}".format(self.globalCtrl.name(), ch), cb=0, keyable=0, lock=1) 
Example #8
Source File: applyop.py    From mgear_core with MIT License 6 votes vote down vote up
def gear_intmatrix_op(mA, mB, blend=0):
    """
    create mGear interpolate Matrix node.

    Arguments:
        mA (matrix): Input matrix A.
        mB (matrix): Input matrix A.
        blend (float or connection): Blending value.

    Returns:
        pyNode: Newly created mGear_intMatrix node
    """
    node = pm.createNode("mgear_intMatrix")

    pm.connectAttr(mA, node + ".matrixA")
    pm.connectAttr(mB, node + ".matrixB")

    if (isinstance(blend, str)
        or isinstance(blend, unicode)
            or isinstance(blend, pm.Attribute)):
        pm.connectAttr(blend, node + ".blend")
    else:
        pm.setAttr(node + ".blend", blend)

    return node 
Example #9
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def store_data(self, data):
        """stores the given data
        """
        if not self.light.hasAttr(self.custom_data_storage_attr_name):
            pm.addAttr(
                self.light,
                ln=self.custom_data_storage_attr_name,
                dt='string'
            )

        self.light.setAttr(self.custom_data_storage_attr_name, data) 
Example #10
Source File: node.py    From mgear_core with MIT License 5 votes vote down vote up
def createAddNodeMulti(inputs=[]):
    """Create and connect multiple add nodes

    Arguments:
        inputs (list of attr): The list of attributes to add

    Returns:
        list: The output attributes list.

    >>> angle_outputs = nod.createAddNodeMulti(self.angles_att)

    """
    outputs = [inputs[0]]

    for i, input in enumerate(inputs[1:]):
        node_name = pm.createNode("addDoubleLinear")

        if (isinstance(outputs[-1], str)
                or isinstance(outputs[-1], unicode)
                or isinstance(outputs[-1], pm.Attribute)):
            pm.connectAttr(outputs[-1], node_name + ".input1", f=True)
        else:
            pm.setAttr(node_name + ".input1", outputs[-1])

        if (isinstance(input, str)
                or isinstance(input, unicode)
                or isinstance(input, pm.Attribute)):
            pm.connectAttr(input, node_name + ".input2", f=True)
        else:
            pm.setAttr(node_name + ".input2", input)

        outputs.append(node_name + ".output")

    return outputs 
Example #11
Source File: node.py    From mgear_core with MIT License 5 votes vote down vote up
def createMulNodeMulti(name, inputs=[]):
    """Create and connect multiple multiply nodes

    Arguments:
        name (str): The name for the new node.
        inputs (list of attr): The list of attributes to multiply

    Returns:
        list: The output attributes list.

    """
    outputs = [inputs[0]]

    for i, input in enumerate(inputs[1:]):
        real_name = name + "_" + str(i)
        node_name = pm.createNode("multiplyDivide", n=real_name)
        pm.setAttr(node_name + ".operation", 1)

        if (isinstance(outputs[-1], str)
                or isinstance(outputs[-1], unicode)
                or isinstance(outputs[-1], pm.Attribute)):
            pm.connectAttr(outputs[-1], node_name + ".input1X", f=True)
        else:
            pm.setAttr(node_name + ".input1X", outputs[-1])

        if (isinstance(input, str)
                or isinstance(input, unicode)
                or isinstance(input, pm.Attribute)):
            pm.connectAttr(input, node_name + ".input2X", f=True)
        else:
            pm.setAttr(node_name + ".input2X", input)

        outputs.append(node_name + ".output")

    return outputs 
Example #12
Source File: node.py    From mgear_core with MIT License 5 votes vote down vote up
def createDivNodeMulti(name, inputs1=[], inputs2=[]):
    """Create and connect multiple divide nodes

    Arguments:
        name (str): The name for the new node.
        inputs1 (list of attr): The list of attributes
        inputs2 (list of attr): The list of attributes

    Returns:
        list: The output attributes list.

    """
    for i, input in enumerate(pm.inputs[1:]):
        real_name = name + "_" + str(i)
        node_name = pm.createNode("multiplyDivide", n=real_name)
        pm.setAttr(node_name + ".operation", 2)

        if (isinstance(pm.outputs[-1], str)
                or isinstance(pm.outputs[-1], unicode)
                or isinstance(pm.outputs[-1], pm.Attribute)):
            pm.connectAttr(pm.outputs[-1], node_name + ".input1X", f=True)
        else:
            pm.setAttr(node_name + ".input1X", pm.outputs[-1])

        if (isinstance(input, str)
                or isinstance(input, unicode)
                or isinstance(input, pm.Attribute)):
            pm.connectAttr(input, node_name + ".input2X", f=True)
        else:
            pm.setAttr(node_name + ".input2X", input)

        pm.outputs.append(node_name + ".output")

    return pm.outputs 
Example #13
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def set_anim_curve_color(anim_curve, color):
    """sets animCurve color to color
    """
    anim_curve = get_valid_node(anim_curve)
    anim_curve.setAttr("useCurveColor", True)
    anim_curve.setAttr("curveColor", color, type="double3") 
Example #14
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def go_home(node):
    """sets all the transformations to zero
    """
    if node.attr('t').isSettable():
        node.setAttr('t', (0, 0, 0))
    if node.attr('r').isSettable():
        node.setAttr('r', (0, 0, 0))
    if node.attr('s').isSettable():
        node.setAttr('s', (1, 1, 1)) 
Example #15
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def align_to_pole_vector():
    """aligns the object to the pole vector of the selected ikHandle
    """
    selection_list = pm.ls(sl=1)

    ik_handle = ""
    control_object = ""

    for obj in selection_list:
        if pm.nodeType(obj) == 'ikHandle':
            ik_handle = obj
        else:
            control_object = obj

    temp = pm.listConnections((ik_handle + '.startJoint'), s=1)
    start_joint = temp[0]
    start_joint_pos = pm.xform(start_joint, q=True, ws=True, t=True)

    temp = pm.listConnections((ik_handle + '.endEffector'), s=1)
    end_effector = temp[0]
    pm.xform(
        control_object,
        ws=True,
        t=(start_joint_pos[0], start_joint_pos[1], start_joint_pos[2])
    )

    pm.parent(control_object, end_effector)
    pm.setAttr(control_object + '.r', 0, 0, 0)

    pm.parent(control_object, w=True) 
Example #16
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def cube_from_bbox(bbox):
    """creates a polyCube from the given bbox

    :param bbox: pymel.core.dt.BoundingBox instance
    """
    cube = pm.polyCube(
        width=bbox.width(),
        height=bbox.height(),
        depth=bbox.depth(),
        ch=False
    )
    cube[0].setAttr('t', bbox.center())
    return cube[0] 
Example #17
Source File: node.py    From mgear_core with MIT License 5 votes vote down vote up
def createNegateNodeMulti(name, inputs=[]):
    """Create and connect multiple negate nodes

    Arguments:
        name (str): The name for the new node.
        inputs (list of attr): The list of attributes to negate

    Returns:
        list: The output attributes list.

    """
    s = "XYZ"
    count = 0
    i = 0
    outputs = []
    for input in inputs:
        if count == 0:
            real_name = name + "_" + str(i)
            node_name = pm.createNode("multiplyDivide", n=real_name)
            i += 1

        pm.connectAttr(input, node_name + ".input1" + s[count], f=True)
        pm.setAttr(node_name + ".input2" + s[count], -1)

        outputs.append(node_name + ".output" + s[count])
        count = (count + 1) % 3

    return outputs 
Example #18
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def restore_user_options(self):
        """restores user options
        """
        active_panel = self.get_active_panel()
        for flag, value in self.user_view_options['display_flags'].items():
            try:
                pm.modelEditor(active_panel, **{'e': 1, flag: value})
            except TypeError:
                pass

        # reassign original hud display options
        for hud, value in self.user_view_options['huds'].items():
            if pm.headsUpDisplay(hud, q=1, ex=1):
                pm.headsUpDisplay(hud, e=1, vis=value)

        # reassign original camera options
        for camera in pm.ls(type='camera'):
            camera_name = camera.name()

            try:
                camera_flags = \
                    self.user_view_options['camera_flags'][camera_name]
            except KeyError:
                continue

            for attr, value in camera_flags.items():
                try:
                    camera.setAttr(attr, value)
                except RuntimeError:
                    pass

        self.remove_hud(self.hud_name) 
Example #19
Source File: rigutils.py    From DynRigBuilder with MIT License 5 votes vote down vote up
def duplicateJointChain(rootJoint, replace=None, suffix=None):
    """
    Duplicate the given joint chain.
    :param rootJoint: `PyNode` root joint of the given joint chain
    :param replace: `tuple` or `list` (old string, new string)
                    rename the duplicated joint chain by replacing string in given joint name
    :param suffix: `string` rename the duplicated joint chain by adding suffix to the given joint name
    :return: `list` list of joints in the duplicated joint chain. ordered by hierarchy
    """
    srcJnts = getJointsInChain(rootJoint)
    dupJnts = []
    if not replace and not suffix:
        raise ValueError("Please rename the duplicated joint chain.")
    for i, srcJnt in enumerate(srcJnts):
        newName = srcJnt.name()
        if replace:
            newName = newName.replace(replace[0], replace[1])
        if suffix:
            newName = "{0}_{1}".format(newName, suffix)
        dupJnt = pm.duplicate(srcJnt, n=newName, po=1)[0]
        dupJnts.append(dupJnt)
        for attr in ['t', 'r', 's', 'jointOrient']:
            pm.setAttr("{0}.{1}".format(dupJnt.name(), attr), pm.getAttr("{0}.{1}".format(srcJnt.name(), attr)))
        if i>0:
            dupJnt.setParent(dupJnts[i-1])
    #
    # for i, srcJnt in enumerate(srcJnts):
    #     if i==0: continue
    #     srcPar = pm.listRelatives(srcJnt, p=1)
    #     if srcPar:
    #         dupJnts[i].setParent(srcPar[0].name().replace(replace[0], replace[1]))
    return dupJnts 
Example #20
Source File: sharedShape.py    From fossil with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _makeSharedShape(obj, name, shapeType):
    '''
    shapeType should be either 'sharedShape' or 'kinematicSwitch'
    
    Returns a string of the shape, ex 'Foot_L|sharedShape' (to bypass pymel warnings)
    '''
    shape = cmds.createNode( 'nurbsCurve', p=obj.longName() )
    
    # 2017 added a bunch of keyable attrs so get rid of them if possible.
    for attr in cmds.listAttr(shape, k=True):
        try:
            cmds.setAttr(shape + '.' + attr, k=False, l=True)
        except Exception as e:  # noqa
            #print( e )
            pass
        
    # Make it a valid curve so it doesn't get deleted during optimize scene
    # but lock and hide it.
    mel.eval('''setAttr "%s.cc" -type "nurbsCurve"
             1 1 0 no 3
             2 0 1
             2
             0 0 0
             0 0 0
             ;''' % shape )
    setAttr(shape + '.visibility', False, l=True)  # noqa
    addAttr(shape, ln=core.shape.sharedShapeTag, at='message')
    
    cmds.addAttr( shape, ln=shapeType, at='message' )
    cmds.rename( shape, name )
    return obj.longName() + '|' + name 
Example #21
Source File: limb.py    From anima with MIT License 5 votes vote down vote up
def unique_spine_zero_controller(self):
    # Create Root Costrain Jnt Unde Hip cotrol
        # Duplicate zero Jnt

        tempConst = pm.duplicate(self.joints.zeroJoint, po=True,
                                 name=("Const_" + self.joints.zeroJoint ))
        rootConst_jnt = tempConst[0]

        pm.parent(rootConst_jnt, self.hipCtrl.drawnNode)
        pm.pointConstraint(rootConst_jnt, self.joints.zeroJoint)
        pm.orientConstraint(rootConst_jnt, self.joints.zeroJoint)
        pm.setAttr(rootConst_jnt.visibility, 0)
        self._stuff.append(rootConst_jnt) 
Example #22
Source File: mayautils.py    From DynRigBuilder with MIT License 5 votes vote down vote up
def enableChannels(target, channels="trsv", operation="hl"):
    """
    Unhide or unlock the specified object channels.
    :param target: `PyNode` object channels
    :param channels: `string` 'trsv' translate, rotate, scale, visibility
    :param operation: `string` 'hl' unhide or unlock or both
    :return:
    """
    inChannelBox = 1 if "h" in operation else 0
    lock = 0 if "l" in operation else 1
    for channel in channels:
        attrList = [channel+x for x in "xyz"] if channel in "trs" else [channel]
        for attr in attrList:
            pm.setAttr("{0}.{1}".format(target, attr), l=lock, k=inChannelBox) 
Example #23
Source File: joint.py    From anima with MIT License 5 votes vote down vote up
def orient_joint(self, joint, aimAxis=[1, 0, 0], upAxis=[0, 0, 1],
                     worldUpType="vector",
                     worldUpVector=[0, 1, 0]):

        #joint should be pm.nt.Joint type
        if not isinstance(joint, pm.nt.Joint):
            raise TypeError("%s sholud be an instance of pm.nt.Joint Class"
                            % joint)
        jointUnder = self.jointUnder(joint)
        if jointUnder is None:
            return 0
        temporalGroup = DrawNode(Shape.transform, 'temporalGroup')
        pm.parent(jointUnder, temporalGroup.drawnNode)

        pm.setAttr(joint.jointOrient, (0, 0, 0))

        if worldUpType == "object":
            aimConst = pm.aimConstraint(jointUnder, joint, aimVector=aimAxis,
                                        upVector=upAxis,
                                        worldUpType=worldUpType,
                                        worldUpObject=worldUpVector)
        elif worldUpType == "vector":
            aimConst = pm.aimConstraint(jointUnder, joint, aimVector=aimAxis,
                                        upVector=upAxis,
                                        worldUpType=worldUpType,
                                        worldUpVector=worldUpVector)
        pm.delete(aimConst)
        pm.parent(jointUnder, joint)

        pm.setAttr(joint.jointOrient, (pm.getAttr(joint.rotate)))
        pm.setAttr((joint.rotate), [0, 0, 0])
        pm.delete(temporalGroup.drawnNode) 
Example #24
Source File: joint.py    From anima with MIT License 5 votes vote down vote up
def jointUnder(self, joint):
        jointUnder = pm.listRelatives(joint, c=1, type="joint")
        if not len(jointUnder):
            pm.setAttr(joint.jointOrient, (0, 0, 0))
            return None
        return jointUnder 
Example #25
Source File: mayautils.py    From DynRigBuilder with MIT License 5 votes vote down vote up
def disableChannels(target, channels="trsv", operation="hl"):
    """
    Hide or lock the specified object channels.
    :param target: `PyNode` object channels
    :param channels: `string` 'trsv' translate, rotate, scale, visibility
    :param operation: `string` 'hl' hide or lock or both
    :return:
    """
    inChannelBox = 0 if "h" in operation else 1
    lock = 1 if "l" in operation else 0
    for channel in channels:
        attrList = [channel+x for x in "xyz"] if channel in "trs" else [channel]
        for attr in attrList:
            pm.setAttr("{0}.{1}".format(target, attr), l=lock, cb=inChannelBox, k=inChannelBox) 
Example #26
Source File: mayautils.py    From DynRigBuilder with MIT License 5 votes vote down vote up
def addAttributes(target, attrList):
    """
    Add attributes to target.
    :param target: `PyNode` target node
    :param attrList: `list` list of dictionaries defining attribute properties
                    [{ "ln": `string`    - name of the attribtue,
                       "at": `string`   - type of the attribute,
                       ... - other pm.addAttr funtion flags,
                       "cb": `bool` - display in channelBox
                    },
                    {
                    }
                    ...
                    ]
    :return:
    """
    if not isinstance(attrList, list):
        attrList = [attrList]
    for attrDict in attrList:
        paramDict = attrDict.copy()
        cb = 0
        if "cb" in attrDict.keys():
            cb = attrDict["cb"]
            del paramDict["cb"]
        pm.addAttr(target, **paramDict)
        if "cb" in attrDict.keys():
            pm.setAttr("{0}.{1}".format(target.name(), attrDict["ln"]), cb=cb) 
Example #27
Source File: applyop.py    From mgear_core with MIT License 5 votes vote down vote up
def gear_spring_op(in_obj, goal=False):
    """Apply mGear spring node.

    Arguments:
        in_obj (dagNode): Constrained object.
        goal (dagNode): By default is False.

    Returns:
        pyNode: Newly created node
    """
    if not goal:
        goal = in_obj

    node = pm.createNode("mgear_springNode")

    pm.connectAttr("time1.outTime", node + ".time")
    dm_node = pm.createNode("decomposeMatrix")
    pm.connectAttr(goal + ".parentMatrix", dm_node + ".inputMatrix")
    pm.connectAttr(dm_node + ".outputTranslate", node + ".goal")

    cm_node = pm.createNode("composeMatrix")
    pm.connectAttr(node + ".output", cm_node + ".inputTranslate")

    mm_node = pm.createNode("mgear_mulMatrix")

    pm.connectAttr(cm_node + ".outputMatrix", mm_node + ".matrixA")
    pm.connectAttr(in_obj + ".parentInverseMatrix", mm_node + ".matrixB")

    dm_node2 = pm.createNode("decomposeMatrix")
    pm.connectAttr(mm_node + ".output", dm_node2 + ".inputMatrix")
    pm.connectAttr(dm_node2 + ".outputTranslate", in_obj + ".translate")

    pm.setAttr(node + ".stiffness", 0.5)
    pm.setAttr(node + ".damping", 0.5)

    return node 
Example #28
Source File: applyop.py    From mgear_core with MIT License 5 votes vote down vote up
def gear_spinePointAtOp(cns, startobj, endobj, blend=.5, axis="-Z"):
    """
    Apply a SpinePointAt operator

    Arguments:
        cns (Constraint): The constraint to apply the operator on (must be a
            curve, path or direction constraint).
        startobj (dagNode): Start Reference.
        endobj (dagNode): End Reference.
        blend (float): Blend influence value from 0 to 1.
        axis (string): Axis direction.

    Returns:
        pyNode: The newly created operator.
    """
    node = pm.createNode("mgear_spinePointAt")

    # Inputs
    pm.setAttr(node + ".blend", blend)
    pm.setAttr(node + ".axe", ["X", "Y", "Z", "-X", "-Y", "-Z"].index(axis))

    pm.connectAttr(startobj + ".rotate", node + ".rotA")
    pm.connectAttr(endobj + ".rotate", node + ".rotB")

    # Outputs
    pm.setAttr(cns + ".worldUpType", 3)

    pm.connectAttr(node + ".pointAt", cns + ".worldUpVector")

    return node 
Example #29
Source File: applyop.py    From mgear_core with MIT License 5 votes vote down vote up
def gear_spinePointAtOpWM(cns, startobj, endobj, blend=.5, axis="-Z"):
    """
    Apply a SpinePointAt operator using world matrix

    Arguments:
        cns Constraint: The constraint to apply the operator on (must be a
            curve, path or direction constraint).
        startobj (dagNode): Start Reference.
        endobj (dagNode): End Reference.
        blend (float): Blend influence value from 0 to 1.
        axis (str): Axis direction.

    Returns:
        pyNode: The newly created operator.
    """
    node = pm.createNode("mgear_spinePointAt")

    # Inputs
    pm.setAttr(node + ".blend", blend)
    pm.setAttr(node + ".axe", ["X", "Y", "Z", "-X", "-Y", "-Z"].index(axis))

    dem_node1 = pm.createNode("decomposeMatrix")
    dem_node2 = pm.createNode("decomposeMatrix")
    pm.connectAttr(startobj + ".worldMatrix", dem_node1 + ".inputMatrix")
    pm.connectAttr(endobj + ".worldMatrix", dem_node2 + ".inputMatrix")

    pm.connectAttr(dem_node1 + ".outputRotate", node + ".rotA")
    pm.connectAttr(dem_node2 + ".outputRotate", node + ".rotB")

    # Outputs
    pm.setAttr(cns + ".worldUpType", 3)

    pm.connectAttr(node + ".pointAt", cns + ".worldUpVector")

    return node 
Example #30
Source File: applyop.py    From mgear_core with MIT License 5 votes vote down vote up
def gear_rollsplinekine_op(out, controlers=[], u=.5, subdiv=10):
    """Apply a sn_rollsplinekine_op operator

    Arguments:
        out (dagNode): onstrained Object.
        controlers (list of dagNodes): Objects that will act as controler of
            the bezier curve. Objects must have a parent that will be used as
            an input for the operator.
        u (float): Position of the object on the bezier curve (from 0 to 1).
        subdiv (int): spline subdivision precision.

    Returns:
        pyNode: The newly created operator.
    """
    node = pm.createNode("mgear_rollSplineKine")

    # Inputs
    pm.setAttr(node + ".u", u)
    pm.setAttr(node + ".subdiv", subdiv)

    dm_node = pm.createNode("decomposeMatrix")

    pm.connectAttr(node + ".output", dm_node + ".inputMatrix")
    pm.connectAttr(dm_node + ".outputTranslate", out + ".translate")
    pm.connectAttr(dm_node + ".outputRotate", out + ".rotate")
    # connectAttr(dm_node+".outputScale", out+".scale")

    pm.connectAttr(out + ".parentMatrix", node + ".outputParent")

    for i, obj in enumerate(controlers):
        pm.connectAttr(obj + ".parentMatrix", node + ".ctlParent[%s]" % i)

        pm.connectAttr(obj + ".worldMatrix", node + ".inputs[%s]" % i)
        pm.connectAttr(obj + ".rx", node + ".inputsRoll[%s]" % i)

    return node