Example #1
0
    def postRig(self):
        '''
        clean up for the rig build.
        '''
        if common.isValid('%s.jointVis' % self.rigGrp):
            return True
        
        if cmds.ls(type = 'rig') and common.isValid(self.controlsGrp) and not common.isValid(self.rigGrp):
            return True
        
        jointVisAttr     = attribute.addAttr(self.rigGrp, 'jointVis', attrType = 'enum', defValue = 'off:on')
        scaleAttr        = attribute.addAttr(self.rigGrp, 'uniformScale', attrType = 'double', defValue = 1, min = 0)
        jointDisplayAttr = attribute.addAttr(self.rigGrp, 'displayJnts', attrType = 'enum', defValue = 'Normal:Template:Reference')
        
        cmds.setAttr(jointDisplayAttr, 2)
        
        #setup attribute for uniform scale
        attribute.connect(scaleAttr, '%s.sx' % self.rigGrp)
        attribute.connect(scaleAttr, '%s.sy' % self.rigGrp)
        attribute.connect(scaleAttr, '%s.sz' % self.rigGrp)
            
        if self.skinClusterJnts:
            for jnt in self.skinClusterJnts:
                if cmds.objExists(jnt):
                    attribute.connect(jointVisAttr , '%s.v' % jnt)
                    cmds.setAttr('%s.overrideEnabled' % jnt, 1)
                    attribute.connect(jointDisplayAttr , '%s.overrideDisplayType' % jnt)

        #set joint visibility attribute
        cmds.setAttr(jointVisAttr, 1)
        
        for grp in [self.rigGrp, self.jointsGrp, self.controlsGrp]:
            attribute.lockAndHide(['t', 'r', 's', 'v'], grp)
Example #2
0
File: arm.py Project: jonntd/japeto
	def setupRig(self):
		if super(Arm,self).setupRig():
			return True
		
		self.skinClusterJnts.remove(self.endJoint)
		self.skinClusterJnts.insert(0,self.clavicleJoint)
		
		#delete end joint and end guide
		endJntGuide = self.endJoint.replace(common.JOINT, common.GUIDES)
		if common.isValid(self.endJoint):
			cmds.delete(self.endJoint)
		if common.isValid(endJntGuide):
			cmds.delete(endJntGuide)
			

		if self._getSide() == common.LEFT:
			positions = (
				[self.position[0] + .5, self.position[1], self.position[2] + 1],
				[self.position[0] + 2, self.position[1], self.position[2]],
				[self.position[0] + 5, self.position[1], self.position[2] - 1],
				[self.position[0] + 8, self.position[1], self.position[2]]
				)
		elif self._getSide() == common.RIGHT:
			positions = (
				[self.position[0] + -.5, self.position[1], self.position[2] + 1],
				[self.position[0] - 2, self.position[1], self.position[2]],
				[self.position[0] - 5, self.position[1], self.position[2] - 1],
				[self.position[0] - 8, self.position[1], self.position[2]]
				)
		else:
			positions = (
				[self.position[0] + .5, self.position[1], self.position[2] + 1],
				[self.position[0] + 2, self.position[1], self.position[2]],
				[self.position[0] + 5, self.position[1], self.position[2] - 1],
				[self.position[0] + 8, self.position[1], self.position[2]]
				)


		#create pelvis joint and parent leg under pelvis
		if not common.isValid(self.clavicleJoint):
			joint.create(name = self.clavicleJoint, parent = self.skeletonGrp, position = positions[0])
		
		cmds.parent(self.startJoint, self.clavicleJoint)
		
		#declare guides
		clavicleJointGuide = self.setupCtrl(self.clavicleJoint.replace('_%s' % common.JOINT, ''),self.clavicleJoint)
		startJointGuide  = self.startJoint.replace(common.JOINT, common.GUIDES)
		midJointGuide    = self.midJoint.replace(common.JOINT, common.GUIDES)
		tipJointGuide    = self.tipJoint.replace(common.JOINT, common.GUIDES)
		
		#move master guide to clavicle position
		for i, guide in enumerate([clavicleJointGuide,startJointGuide,midJointGuide, tipJointGuide]):
			zeroGroup = common.getParent(guide)
			if i == 0:
				cmds.xform(common.getParent(self.masterGuide), ws = True, t = positions[i])
			cmds.xform(zeroGroup, ws = True, t = positions[i])
Example #3
0
    def postSetupRig(self):
        '''
        clean up section for the setup rig
        '''
        if common.isValid('%s.displayAxis' % self.masterGuide) or common.isValid(self.masterGuide) != True:
            return True
        #create attributes and lock/hide attrs on top nodes as well as masterGuide control
        displayAttr = attribute.addAttr(self.masterGuide, 'displayAxis', attrType = 'enum', defValue = 'off:on')
        attribute.lockAndHide(['r','t','s','v'], [self.setupRigGrp, self.skeletonGrp,self.guidesGrp, common.getParent(self.masterGuide)])
        attribute.lockAndHide('v', self.masterGuide)
        
        #resize guide controls
        for guide in self.getGuides():
            cmds.setAttr('%s.radius' % common.getShapes(guide, 0), self.controlScale * .5)
        
        #resize masterGuide control
        control.scaleShape(self.masterGuide, scale = [self.controlScale * 2, self.controlScale * 2, self.controlScale * 2])
        
        #declaring skeleton joints
        skeletonJnts = self.getSkeletonJnts()
        
        #connect joints to the attributes on the masterGuide control
        for jnt in skeletonJnts:
            if cmds.objExists(jnt):
                attribute.connect(displayAttr , '%s.displayLocalAxis' % jnt)
                common.setDisplayType(jnt, 'reference')

        #parent all constraints to guides group
        if self.setupConstraints:
            cmds.parent(self.setupConstraints, self.guidesGrp)

        #Put the build attributes onto setup rigs
        '''
        cmds.addAttr(self.setupRigGrp, ln = 'kwargs', dt = "string")
        cmds.setAttr('%s.kwargs' % self.setupRigGrp, str(self._buildAttrs), type = "string")
        '''
        attribute.copy('displayAxis', self.masterGuide, self.name(), reverseConnect = True)
        
        #parent setup under puppet node
        self._puppetNode.addChild(self.setupRigGrp)
        
        if self.parentHook:
            if cmds.objExists(self.parentHook):
                displayLine = control.displayLine(self.masterGuide, self.parentHook, name = self.masterGuide.replace('_%s' % common.GUIDES, '_%s' % common.CURVE))
                cmds.parent(displayLine, self.guidesGrp)

        #set build args on puppet node
        attrs = dict()
        for attr in self.attributes():
            attrs[attr.name()] = attr.value()
        self.puppetNode.storeArgs(**attrs)
Example #4
0
File: rig.py Project: jonntd/japeto
    def saveJoints(cls, joints, filepath):
        """
        Save the joints for the asset
        
        :param joints: joints that will be written out
        :type joints: list | str | tuple
        """
        # declare list that will be used to gather controls to save
        savedJoints = list()
        # make sure controls is a list before proceeding
        joints = common.toList(joints)

        if not isinstance(joints, list):
            raise RuntimeError("%s must be a list" % joints)
        # end if

        for jnt in joints:
            if common.isValid(jnt):
                if common.isType(jnt, "joint"):
                    savedJoints.append(jnt)
            # end if
        # end loop

        # save the controls in savedControls list
        joint.save(savedJoints, filepath=filepath)
Example #5
0
File: rig.py Project: jonntd/japeto
    def postBuild(self):
        """
        clean up rig asset
        
        .. todo: Finish complete cleanup of the rig
        """
        # create nodes on the rigGrp node
        tagControlsAttr = control.tag_as_control(self.rigGrp)
        cmds.addAttr(self.rigGrp, ln="deform_joints", at="message")
        tagJointsAttr = "%s.deform_joints" % self.rigGrp

        if self.controls:
            for ctrl in self.controls:
                attribute.connect(tagControlsAttr, "%s.%s" % (ctrl, tagControlsAttr.split(".")[1]))
            # end loop
        # end if

        if self.skinClusterJoints:
            for jnt in self.skinClusterJoints:
                if common.isValid(jnt):
                    cmds.addAttr(jnt, ln="deform_joints", at="message")
                    attribute.connect(tagJointsAttr, "%s.deform_joints" % jnt)
                # end if
            # end loop
        # end if

        # lock and hide attributes
        attribute.lockAndHide(["s", "v"], [self._shotCtrl, self._trsCtrl])
        attribute.lockAndHide(["t", "r", "s", "v"], self.rigGrp)

        # clear selection
        cmds.select(cl=True)
Example #6
0
File: rig.py Project: jonntd/japeto
    def preBuild(self):
        """
        sets up the hierachry
        """
        # if there is no puppet node in the scene, we will run the setup first
        if not cmds.ls(type="puppet"):
            self.setup()

        if common.isValid(self.rigGrp):
            return True
        # create hierachy
        cmds.createNode("rig", n=self.rigGrp)
        cmds.createNode("transform", n=self.noXformGrp)
        cmds.createNode("transform", n=self.jointsGrp)
        cmds.createNode("transform", n=self.controlsGrp)

        # create shot and trs controls
        control.create(self._shotCtrl.replace("_%s" % common.CONTROL, ""), parent=self.controlsGrp, color=common.WHITE)
        control.create(self._trsCtrl.replace("_%s" % common.CONTROL, ""), parent=self._shotCtrl, color=common.WHITE)
        # get the parents of the controls
        shotZero = common.getParent(self._shotCtrl)
        trsZero = common.getParent(self._trsCtrl)
        cmds.parent(self._shotCtrl, self.controlsGrp)
        cmds.parent(self._trsCtrl, self._shotCtrl)
        control.scaleShape(self._shotCtrl, [2, 2, 2])
        cmds.delete([shotZero, trsZero])
        # cmds.createNode('transform', n = self.modelGroup)

        cmds.parent([self.noXformGrp, self.jointsGrp, self.controlsGrp], self.rigGrp)

        # turn off inherit transforms on the noXformGrp
        cmds.setAttr("%s.inheritsTransform" % self.noXformGrp, 0)

        self.controls.extend([self._shotCtrl, self._trsCtrl])
Example #7
0
 def setupRig(self):
     if common.isValid(self.name()):
         return True
     
     self.setupConstraints = []
     #makes component a puppet node
     self.puppetNode = puppet.create(self.name())
     
     #Create master guide control and 
     control.createSetup('{0}_master'.format(self.name()), type = 'square')
     common.setColor(self.masterGuide, 'darkred')
     
     #create hierarchy
     cmds.createNode('transform', n = self.setupRigGrp)
     cmds.createNode('transform', n = self.skeletonGrp)
     cmds.createNode('transform', n = self.guidesGrp)
     
     cmds.parent(self.skeletonGrp, self.setupRigGrp)
     cmds.parent(self.guidesGrp, self.setupRigGrp)
     cmds.parent(common.getParent(self.masterGuide),self.guidesGrp)
     
     #add attributes to groups
     attribute.addAttr(self.setupRigGrp, 'tag_guides', attrType = 'message')
     masterGuideAttr = attribute.addAttr(self.setupRigGrp, 'master_guide', attrType = 'message')
     attribute.connect(masterGuideAttr, '%s.tag_controls' % self.masterGuide)
Example #8
0
File: rig.py Project: jonntd/japeto
    def saveControls(cls, controls, filepath):
        """
        Save the controls for the asset
        
        :param controls: controls that will be written out 
                        if they're nurbsCurves
        :type controls: list | str | tuple
        """
        # declare list that will be used to gather controls to save
        savedControls = list()
        # make sure controls is a list before proceeding
        controls = common.toList(controls)

        if not isinstance(controls, list):
            raise RuntimeError("%s must be a list" % controls)
        # end if

        for ctrl in controls:
            if common.isValid(ctrl):
                if common.isType(ctrl, "nurbsCurve") or common.isType(common.getShapes(ctrl, 0), "nurbsCurve"):
                    savedControls.append(ctrl)
            # end if
        # end loop

        # save the controls in savedControls list
        control.save(savedControls, filepath=filepath)
Example #9
0
File: rig.py Project: jonntd/japeto
    def getJoints(cls, asset):
        """
        Get joints based on whether or not the given asset has
        a tag_joints attribute.

        .. warning: This is probably going to change because it's unstable to change.
        
        .. todo: get this working with just an attribute connected to all the deform joints
        
        :param asset: Asset you want to get controls from
        :type asset: str
        
        :return: Returns controls on the given asset
        :rtype: list | None
        """
        # if the attribute is valid then get connections and return
        jointAttr = "%s.displayJnts" % asset
        if common.isValid(jointAttr):
            joints = attribute.getConnections(jointAttr, plugs=False)
            if joints:
                return joints
        # if there is no "displayJnts" attribute, we check for a puppet node
        # in the scene. If there is one, we will check connections to that and
        # traverse through the connections until we get to the joints
        if cmds.ls(type="puppet"):
            puppet = cmds.ls(type="puppet")
            joints = list()
            if puppet:
                for node in attribute.getConnections("%s.puppet_nodes" % puppet[0], plugs=False):
                    jointAttr = "%s.displayAxis" % node
                    # get the connections to the "displayAxis" attribute on the node
                    # and if there is a connection, it should be the "masterGuide" control.
                    if common.isValid(jointAttr):
                        masterGuides = attribute.getConnections(jointAttr, plugs=False)
                        # get the connections to the masterGuide control, which should contain the joints
                        if masterGuides:
                            for guide in masterGuides:
                                jnts = attribute.getConnections(jointAttr.replace(node, guide), plugs=False)
                                # removes the node from the jnts list, since it is
                                # connected to the "displayAxis" attribute
                                if node in jnts:
                                    jnts.pop(jnts.index(node))
                                joints.extend(jnts)
                return joints

        return None
Example #10
0
def skinTwistSurfaces(joints, surface):
    """
    adds a skinCluster to a surface based on joints

    Example:
    
    .. python::
        skinTwistSurfaces(joints = [joint1, joint2], surface = nurbsPlane1)
    
    @param joints: joints to deform surface
    @type joints: *list*
    
    @param surface: surface to be deformed by joints
    @type surface: *str*        
    """
    if not isinstance(surface, str):
        if isinstance(surface, unicode):
            surface = str(surface)
        else:
            raise TypeError("%s is not a string. Pass string into argument surface" % surface)

    if not common.isValid(surface):
        raise RuntimeError("%s is does not exist in the scene." % surface)

    for jnt in joints:
        if not common.isValid(jnt):
            raise RuntimeError("%s is does not exist in the scene." % jnt)

    # create the skinCluster based on joints and surface
    skinCluster = cmds.skinCluster(joints, surface, dr=0.1, tsb=True)

    # iterate through joints and assign values to cv's on surface so the are bound to a specific joint
    # check surface degree
    surfShape = common.getShape(surface)[0]
    degree = cmds.getAttr("%s.degreeU" % surfShape)

    for i in range(0, len(joints)):
        cmds.skinPercent(skinCluster[0], (surface + ".cv[0:%d][%d]" % (degree, i)), transformValue=[(joints[i], 1.0)])

    return skinCluster
Example #11
0
File: rig.py Project: jonntd/japeto
    def getControls(cls, asset):
        """
        Get controls based on whether or not the given asset has
        a tag_controls attribute.
        
        :param asset: Asset you want to get controls from
        :type asset: str
        
        :return: Returns controls on the given asset
        :rtype: list | None
        """
        controlAttr = "%s.tag_controls" % asset

        if common.isValid(controlAttr):
            return attribute.getConnections(controlAttr, plugs=False)
        # end if

        return None
Example #12
0
 def rig(self):
     '''
     this is the build section for the rig.
     '''
     if common.isValid(self.controlsGrp):
         return True
     
     if not self._puppetNode:
         self.runSetupRig()
     
     #resolve build arguments
     if not self.puppetNode == self.name():
         self.puppetNode = puppet.Puppet(self.name())
     
     self.puppetNode.restoreArgs(self)
     
     cmds.createNode('transform', n = self.rigGrp)
     cmds.createNode('transform', n = self.jointsGrp)
     cmds.createNode('transform', n = self.controlsGrp)
     
     cmds.parent([self.jointsGrp, self.controlsGrp], self.rigGrp)
     
     if not self.skinClusterJnts:
         self.skinClusterJnts.extend(self.getSkeletonJnts())
     
     for jnt in self.skinClusterJnts:
         if cmds.objExists(jnt):
             common.setDisplayType(jnt, 'normal')
             #get parent jnt 
             parent = cmds.listRelatives(jnt, p = True)
             if parent:
                 if parent[0] == self.skeletonGrp:
                     cmds.parent(jnt, self.jointsGrp)
     
     #delete the setup rig group
     cmds.delete(self.setupRigGrp)
     
     for jnt in self.skinClusterJnts:
         if cmds.objExists(jnt):
             #turn display axis off
             cmds.setAttr('%s.displayLocalAxis' % jnt, 0)
             #take the rotations of the joint and make the orientation
             joint.rotateToOrient(jnt)
Example #13
0
def create(name):
    '''
    Creation of a puppet node
    
    Example:
        ...python:
            puppet.create('l_leg')
            #Result: puppet.Puppet object
    
    @param name: Name of the puppet node
    @type name: *str*
    
    @return: puppet.Puppet object
    @rtype: *Puppet*
    '''
    global PUPPET, TAGNAME
    
    name = common.checkName(name)
    
    #create a transform node with the name passed
    mFnDependNode = om.MFnDependencyNode() #create MFnDependency Node object
    
    #if puppet node does not exist, create one
    if not common.isValid(PUPPET):
        puppetObject = mFnDependNode.create('puppet', PUPPET)
        cmds.addAttr(PUPPET, ln = TAGNAME, at = 'message')
    #end if

    #create
    cmds.createNode('transform', name = name) #create transform
    #mFnDependNode.setName(name) #set name
    
    #return an asset object
    newPuppetNode = Puppet(name)
    
    #parent node to puppet
    cmds.parent(newPuppetNode.fullPathName(), PUPPET)
    
    #tag puppet nodes
    newPuppetNode.tagNode()
    
    return newPuppetNode
Example #14
0
    def postRig(self):
        super(Foot, self).postRig()

        #lock bank controls
        for node in (self.__bankInCtrl,self.__bankOutCtrl, self.__heelPivotCtrl):
            if common.isValid(node):
                attribute.lockAndHide(['rx','s', 'v'], node)
            #end if
        #end loop

        #lock and hide foot control attributes
        attribute.lockAndHide(['t', 'r', 's', 'v'], self.__footCtrl)

        for handle in self.__footIkFk.getIkHandles():
            cmds.setAttr('%s.v' % handle, 0 )
        #end loop

        cmds.setAttr('%s.v' % self.__footIkFk.ikJoints[0], 0)
        cmds.setAttr('%s.v' % self.__footIkFk.fkJoints[0], 0)
        cmds.setAttr('%s.v' % self.__footIkFk.blendJoints[0], 0)
Example #15
0
File: rig.py Project: jonntd/japeto
    def build(self):
        """
        build rig hierarchy and attach components
        """
        # if there is no rig node in the scene, we will run the setup first
        if not cmds.ls(type="rig"):
            self.preBuild()
            self.run()

        for node in self.nodes():
            if not isinstance(node, component.Component):
                continue

            if not common.isValid(node.rigGrp):
                node.runRig()

            trsChildren = cmds.listRelatives(self._trsCtrl, c=True)
            if node.controlsGrp in trsChildren:
                continue
            cmds.parent(node.controlsGrp, self._trsCtrl)
            cmds.parent(node.jointsGrp, self.jointsGrp)
            for attr in ["displayJnts", "jointVis"]:
                fullAttrPath = "%s.%s" % (self.rigGrp, attr)
                componentAttr = "%s.%s" % (node.rigGrp, attr)
                if cmds.objExists(componentAttr):
                    if not cmds.objExists(fullAttrPath):
                        attribute.copy(attr, node.rigGrp, self.rigGrp, reverseConnect=False)
                    # end if

                    connectedAttrs = attribute.getConnections(attr, node.rigGrp, incoming=False)
                    if connectedAttrs:
                        for connectedAttr in connectedAttrs:
                            cmds.disconnectAttr(componentAttr, connectedAttr)
                            attribute.connect(fullAttrPath, connectedAttr)
                        # end for
                    # end if
                # end if
            # end for
            cmds.delete(node.rigGrp)
Example #16
0
def restorePuppetNodes():
    global PUPPET
    #declare empty dictionary for restored nodes
    restoredNodes = dict()
    
    #check for a PUPPET node
    if not common.isValid(PUPPET):
        raise RunTimeError('%s does not exist in your scene! You need a %s node to restore puppet nodes' % (PUPPET, PUPPET))
    #end if
    
    #get the children of PUPPET
    children = common.getChildren(PUPPET)
    
    #check to see if there are any children, if not, raise a warning and return nothing
    if not children:
        cmds.warning('%s has no child puppet nodes to restore!' % PUPPET)
        return False
    #end if
    
    #If nodes exist then place them in the restored dictionary
    for node in children:
        restoredNodes[node] = Puppet(node)
        
    return restoredNodes
Example #17
0
    def setupRig(self):
        if super(Limb,self).setupRig():
            return True

        self.skinClusterJnts = [ self.startJoint,
                                 self.midJoint,
                                 self.tipJoint,
                                 self.endJoint ]

        if self._getSide() == common.LEFT:
            positions = (
            [self.position[0] + 2, self.position[1], self.position[2]],
            [self.position[0] + 5, self.position[1], self.position[2] - 1],
            [self.position[0] + 8, self.position[1], self.position[2]],
                [self.position[0] + 9, self.position[1], self.position[2]]
            )
        elif self._getSide() == common.RIGHT:
            positions = (
            [self.position[0] - 2, self.position[1], self.position[2]],
            [self.position[0] - 5, self.position[1], self.position[2] - 1],
            [self.position[0] - 8, self.position[1], self.position[2]],
            [self.position[0] - 9, self.position[1], self.position[2]]
            )
        else:
            positions = (
            [self.position[0] - 2, self.position[1], self.position[2]],
            [self.position[0] - 5, self.position[1], self.position[2] - 1],
            [self.position[0] - 8, self.position[1], self.position[2]],
            [self.position[0] - 9, self.position[1], self.position[2]]
            )

        for i,jnt in enumerate(self.skinClusterJnts):
            if not common.isValid(jnt):
                cmds.joint(n = jnt,position = positions[i])

            if i == 0:
                cmds.parent(jnt, self.skeletonGrp)
                #place Master Guide control in the same position as the first joint
                transform.matchXform(jnt, common.getParent(self.masterGuide), type = 'position')
            else:
                cmds.parent(jnt, self.skinClusterJnts[i - 1])

            ctrl = self.setupCtrl(jnt.replace('_%s' % common.JOINT, ''),jnt)
            #create template control
            #control.createTemplate(ctrl)
            cmds.select(cl = True)


        # ----------------------------------------------------------------------
        # CREATE GUIDES
        startJointGuide = self.startJoint.replace(common.JOINT, common.GUIDES)
        midJointGuide   = self.midJoint.replace(common.JOINT, common.GUIDES)
        tipJointGuide   = self.tipJoint.replace(common.JOINT, common.GUIDES)
        endJointGuide   = self.endJoint.replace(common.JOINT, common.GUIDES)

        #templateNullGroup = cmds.createNode('transform', n = endJointGuide.replace(common.GUIDES, common.GROUP))
        #transform.matchXform(locator, endJointGuide, type = 'position')
        #cmds.pointConstraint(tipJointGuide, templateNullGroup)
        #cmds.parent(templateNullGroup, self.guidesGrp)
        #control.createTemplate(templateNullGroup, defaultType = 'implicitSphere')


        # ----------------------------------------------------------------------
        # ORIENTATION 
        #
        if self._getSide() == common.RIGHT:
            aimVectorAttr = \
                attribute.switch ('aimVector',
                    node= self.masterGuide,
                    value=4,
                    choices=['x','y','z','-x','-y','-z'],
                    outputs=[(1,0,0),(0,1,0),(0,0,1),(-1,0,0),(0,-1,0),(0,0,-1)])

            upVectorAttr  = \
                attribute.switch ('upVector',
                    node=self.masterGuide,
                    value=3,
                    choices=['x','y','z','-x','-y','-z'],
                    outputs=[(1,0,0),(0,1,0),(0,0,1),(-1,0,0),(0,-1,0),(0,0,-1)])
        else:
            aimVectorAttr = \
                attribute.switch ('aimVector',
                    node=self.masterGuide,
                    value=1,
                    choices=['x','y','z','-x','-y','-z'],
                    outputs=[(1,0,0),(0,1,0),(0,0,1),(-1,0,0),(0,-1,0),(0,0,-1)])

            upVectorAttr  = \
                attribute.switch ('upVector',
                    node=self.masterGuide,
                    value=3,
                    choices=['x','y','z','-x','-y','-z'],
                    outputs=[(1,0,0),(0,1,0),(0,0,1),(-1,0,0),(0,-1,0),(0,0,-1)])

        #Get Vectors for the cross product
        #Decompose matrix nodes 
        startJointDcm = \
            cmds.createNode('decomposeMatrix',
                name = self.startJoint.replace('%s_%s' % (common.SKINCLUSTER, common.JOINT), common.DECOMPOSEMATRIX ))

        attribute.connect('%s.worldMatrix' % startJointGuide,'%s.inputMatrix' % startJointDcm)

        midJointDcm = \
            cmds.createNode('decomposeMatrix', name = self.midJoint.replace('%s_%s' % (common.SKINCLUSTER, common.JOINT), common.DECOMPOSEMATRIX ))

        attribute.connect('%s.worldMatrix' % midJointGuide, '%s.inputMatrix' % midJointDcm)

        tipJointDcm = \
            cmds.createNode('decomposeMatrix', name = self.tipJoint.replace('%s_%s' % (common.SKINCLUSTER, common.JOINT), common.DECOMPOSEMATRIX ))
        attribute.connect('%s.worldMatrix' % tipJointGuide, '%s.inputMatrix' % tipJointDcm)

        #plus minus average nodes
        v1Node = cmds.createNode('plusMinusAverage')
        v2Node = cmds.createNode('plusMinusAverage')
        cmds.setAttr('%s.operation' % v1Node, 2)
        cmds.setAttr('%s.operation' % v2Node, 2)

        #connect Decompose Matrix and Plus Minus Average nodes
        attribute.connect('%s.outputTranslate' % tipJointDcm, '%s.input3D[0]' % v1Node)
        attribute.connect('%s.outputTranslate' % startJointDcm, '%s.input3D[1]' % v1Node)
        attribute.connect('%s.outputTranslate' % midJointDcm, '%s.input3D[0]' % v2Node)
        attribute.connect('%s.outputTranslate' % startJointDcm, '%s.input3D[1]' % v2Node)

        #Get the cross product
        crossNode = cmds.createNode('vectorProduct')
        cmds.setAttr( '%s.%s' % (crossNode,'operation') , 2 )
        attribute.connect( '%s.%s' % (v1Node,'output3D'), '%s.%s' % (crossNode,'input1') )
        attribute.connect( '%s.%s' % (v2Node,'output3D'), '%s.%s' % (crossNode,'input2') )
        crossVectorAttr = '%s.%s' % (crossNode,'output')

        #Aim start joint to the middle joint
        constraint = \
            cmds.aimConstraint(midJointGuide,
                    self.startJoint,
                    aimVector = (1,0,0),
                    upVector = (0,1,0),
                    worldUpType = 'vector',
                    worldUpVector = (0,1,0))[0]

        attribute.connect(aimVectorAttr, '%s.aimVector' % constraint)
        attribute.connect(upVectorAttr, '%s.upVector' % constraint)
        attribute.connect(crossVectorAttr, '%s.worldUpVector' % constraint)
        self.setupConstraints.append(constraint)

        #Aim middle joint to the tip joint
        constraint = \
            cmds.aimConstraint(tipJointGuide,
                    self.midJoint,
                    aimVector = (1,0,0),
                    upVector = (0,1,0),
                    worldUpType = 'vector',
                    worldUpVector = (0,1,0))[0]

        attribute.connect(aimVectorAttr, '%s.aimVector' % constraint)
        attribute.connect(upVectorAttr, '%s.upVector' % constraint)
        attribute.connect(crossVectorAttr, '%s.worldUpVector' % constraint)
        self.setupConstraints.append(constraint)

        constraint = cmds.orientConstraint(self.midJoint, self.tipJoint)[0]
        self.setupConstraints.append(constraint)

        cmds.setAttr('%s.normalizeOutput' % crossNode, True)

        self.upTwistJnts = list()
        step   = 1.0 / (self.numSegments + 1)
        parent = self.startJoint
        for i in range( 1, self.numSegments + 1 ):
            j = joint.create( name='%s' % (self.startJoint.replace('_%s' % common.SKINCLUSTER, 'Twist_%s_%s' % (common.padNumber(i,3), common.SKINCLUSTER))), parent=parent )
            transform.matchXform( self.startJoint,j, type='rotate' )
            constraint = cmds.pointConstraint( self.startJoint, self.midJoint, j )[0]
            weightAliasList = cmds.pointConstraint( constraint, q=True, weightAliasList=True )
            cmds.setAttr( '%s.%s' % (constraint, weightAliasList[0]), 1-(step*i) )
            cmds.setAttr( '%s.%s' % (constraint, weightAliasList[1]),  step*i )
            self.upTwistJnts.append(j)
            self.skinClusterJnts.append(j) #adding the joint to skincluster joints list

        # Create MiddleJoint Segments
        self.loTwistJnts = list()
        parent = self.midJoint
        for i in range( 1, self.numSegments + 1):
            j = joint.create( name='%s' % (self.midJoint.replace('_%s' % common.SKINCLUSTER, 'Twist_%s_%s' % (common.padNumber(i,3), common.SKINCLUSTER))), parent=parent )
            transform.matchXform( self.midJoint,j, type='rotate' )
            constraint = cmds.pointConstraint( self.midJoint, self.tipJoint, j )[0]
            weightAliasList = cmds.pointConstraint( constraint, q=True, weightAliasList=True )
            cmds.setAttr( '%s.%s' % (constraint, weightAliasList[0]), 1-(step*i) )
            cmds.setAttr( '%s.%s' % (constraint, weightAliasList[1]),  step*i )
            self.loTwistJnts.append(j)
            self.skinClusterJnts.append(j) #adding the joint to skincluster joints list
Example #18
0
    def rig(self):
        if not self._puppetNode:
            self.runSetupRig()
        if cmds.objExists('%s.master_guide' % self.setupRigGrp):
            self.masterGuide = attribute.getConnections('master_guide', self.setupRigGrp)[0].split('.')[0]
        if common.isValid(self.masterGuide):
            #get orientations for controls
            fkOrient  = self.__fkOrient()
            ikOrient  = self.__ikOrient()
            upVector  = self.upVector
            aimVector = self.aimVector

        #call parent class rig function
        if super(Limb, self).rig():
            return True
        
        #create ik fk switch
        ikfkDict = ikfk.create(jointChain = [self.startJoint, self.midJoint, self.tipJoint], stretch = self.stretch)
        ikfkDict['group'] = cmds.rename(ikfkDict['group'], '%s_%s' % (self.name(),ikfkDict['group']))

        #set the visibility on the ik/fk/blend joints to off
        cmds.setAttr('%s.v' % ikfkDict['fkJoints'][0], 0)
        cmds.setAttr('%s.v' % ikfkDict['ikJoints'][0], 0)
        cmds.setAttr('%s.v' % ikfkDict['blendJoints'][0], 0)

        ikfkAttr = attribute.addAttr(self.rigGrp, attr = 'ikfk', attrType = 'enum', defValue = ['off','on'],value = 0)

        cmds.connectAttr(ikfkAttr, '%s.ikfk' % ikfkDict['group'], l = True, f = True)

        #parent ikfk group under joints group
        cmds.parent(ikfkDict['group'], self.jointsGrp)

        #rename all ik and blend joints
        for i,jnt in enumerate(ikfkDict['ikJoints']):
            jnt = cmds.rename(jnt, jnt.replace('%s_%s_%s' % (common.SKINCLUSTER,common.JOINT, common.IK), '%s_%s' % (common.IK, common.JOINT)))
            ikfkDict['ikJoints'][i] = jnt

        for i,jnt in enumerate(ikfkDict['blendJoints']):
            jnt = cmds.rename(jnt, jnt.replace('%s_%s_%s' % (common.SKINCLUSTER,common.JOINT, common.BLEND), '%s_%s' % (common.BLEND, common.JOINT)))
            ikfkDict['blendJoints'][i] = jnt

        #create ik setup
        ikCtrl = control.create(name = ikfkDict['ikJoints'][2].replace('_%s' % common.JOINT, ''),type = 'cube', parent = self.controlsGrp, color = common.SIDE_COLOR[self._getSide()])
        ikCtrlZero = common.getParent(ikCtrl)
        attribute.copy('stretch', ikfkDict['group'], destination = ikCtrl, connect = True,reverseConnect = False)
        attribute.copy('stretchTop', ikfkDict['group'], destination = ikCtrl, connect = True,reverseConnect = False)
        attribute.copy('stretchBottom', ikfkDict['group'], destination = ikCtrl, connect = True,reverseConnect = False)

        if ikOrient == 'Local':
            transform.matchXform(ikfkDict['ikJoints'][2], ikCtrlZero, type = 'pose')
        else:
            transform.matchXform(ikfkDict['ikJoints'][2], ikCtrlZero, type = 'position')
            cmds.orientConstraint(ikCtrl, ikfkDict['ikJoints'][2], mo = True)
            common.setColor(ikCtrl, common.SIDE_COLOR[self._getSide()])

            #setup poleVector
            pvCtrl = control.create(name = ikfkDict['ikJoints'][2].replace('_%s' % common.JOINT, '_%s' % common.POLEVECTOR),type = 'cube', parent = self.controlsGrp, color = common.SIDE_COLOR[self._getSide()])
            #size polevector control

        for i in range(len(common.getShapes(pvCtrl))):
            control.scaleShape(pvCtrl, scale = [self.controlScale * .5, self.controlScale * .5, self.controlScale * .5], index = i)

        pvCtrlZero = common.getParent(pvCtrl)
        pvDisplayLineAttr = attribute.addAttr(pvCtrl, attr = 'pvLine', attrType = 'enum', defValue = 'off:on', value = 1)
        transform.matchXform(ikfkDict['ikJoints'][1], pvCtrlZero, type = 'position')
        #cmds.parent(ikfkDict['ikHandle'], w = True)
        pvPos = ikfk.getPoleVectorPosition(ikfkDict['ikJoints'][1], ikfkDict['ikHandle'])
        cmds.xform(pvCtrlZero, ws = True, t = pvPos)
        common.setColor(pvCtrlZero, common.SIDE_COLOR[self._getSide()])

        #create polevector constraint and parent under control
        cmds.poleVectorConstraint(pvCtrl, ikfkDict['ikHandle'])
        targetConstraint = cmds.pointConstraint(ikCtrl, ikfkDict['targetJnts'][1], mo = True) #ikhandle is under target joint
        pvDisplayLine = control.displayLine(ikfkDict['ikJoints'][0], pvCtrl, name = pvCtrl.replace(common.CONTROL, common.DISPLAYLINE), parent = self.controlsGrp)


        cmds.orientConstraint(ikCtrl,ikfkDict['ikJoints'][0], mo = True)

        #adding attribute to ik ctrl
        ikTwistAttr = attribute.addAttr(ikCtrl, attr = 'twist')
        cmds.connectAttr(ikTwistAttr, '%s.twist' % ikfkDict['ikHandle'], f = True)

        #connecting to shapes
        ikfkReverse = cmds.createNode('reverse', n = ikCtrl.replace('%s_%s' % (common.IK, common.CONTROL), '%s_%s' % (common.REVERSE, common.UTILITY)))
        attribute.connect('%s.ikfk' % ikfkDict['group'], '%s.inputX' % ikfkReverse)
        for shape in common.getShapes(ikCtrl):
            attribute.connect('%s.outputX' % ikfkReverse,'%s.v' % shape)

        for shape in common.getShapes(pvCtrl):
            attribute.connect('%s.outputX' % ikfkReverse,'%s.v' % shape)

        #connect pvDisplayLineAttr in pvDisplayLine visibility
        displayLineMultiply = cmds.createNode('multiplyDivide', n = pvDisplayLine.replace(common.DISPLAYLINE, common.MULTIPLYDIVIDE))
        attribute.connect(pvDisplayLineAttr, '%s.input1X' % displayLineMultiply)
        attribute.connect('%s.outputX' % ikfkReverse, '%s.input2X' % displayLineMultiply)
        attribute.connect('%s.outputX' % displayLineMultiply, '%s.v' % common.getChildren(pvDisplayLine)[0])

        #create fk setup
        fkCtrls = list()
        parent = self.controlsGrp
        for i,jnt in enumerate(ikfkDict['fkJoints']):
            cmds.select(cl = True)
            #rename fk joint
            jnt = cmds.rename(jnt,jnt.replace('%s_%s_%s' % (common.SKINCLUSTER,common.JOINT,common.FK), '%s_%s' % (common.FK,common.JOINT)))
            ikfkDict['fkJoints'][i] = jnt #re-assign fk joint intop ikfkDict
            #create controls, set color, and make connections
            fkCtrl = control.create(name = jnt.replace('_%s' % common.JOINT, ''),type = 'circle', parent = parent, color = common.SIDE_COLOR[self._getSide()])
            fkCtrlZero = common.getParent(fkCtrl)
            
            if fkOrient == 'Local':
                transform.matchXform(jnt, fkCtrlZero, type = 'pose')
            #end if
            else:
                transform.matchXform(jnt, fkCtrlZero, type = 'position')
            #end else
            
            cmds.connectAttr('%s.ikfk' % ikfkDict['group'], '%s.v' % common.getShapes(fkCtrl)[0], f = True)
            cmds.parentConstraint(fkCtrl, jnt, mo = True)
            attribute.lockAndHide('t', fkCtrl)
            attribute.lockAndHide('s', fkCtrl)
            attribute.lockAndHide('v', fkCtrl)
            #get joint rotate order and apply to control and parent group
            rotateOrder = attribute.getValue('rotateOrder', jnt)
            for node in [fkCtrl, fkCtrlZero]:
                cmds.setAttr('%s.rotateOrder' % node, rotateOrder)
    
                fkCtrls.append(fkCtrl)
                parent = fkCtrl
            #end loop
        #end loop

        aimAxis = transform.getAimAxis(ikfkDict['blendJoints'][0], allowNegative = False)    
        #Up Twist Joint Setup
        if self.upTwistJnts:
            noTwistJnt = common.duplicate(self.startJoint, name = self.startJoint.replace('%s' % common.SKINCLUSTER, 'NoTwist_%s' % common.SKINCLUSTER), parent = self.startJoint)

            inverseMultNode = cmds.createNode('multiplyDivide', n = noTwistJnt.replace('%s_%s' % (common.SKINCLUSTER,common.JOINT), '%s_%s' % (common.UTILITY, common.MULTIPLYDIVIDE)))
            cmds.connectAttr('%s.r%s' % (ikfkDict['blendJoints'][0], aimAxis), '%s.input1X' % inverseMultNode, f = True)
            cmds.setAttr('%s.input2X' % inverseMultNode, -1)
            cmds.connectAttr('%s.outputX' % inverseMultNode, '%s.r%s' % (noTwistJnt, aimAxis), f = True)


            step   = 1.0 / (len(self.upTwistJnts) +1)
            for i in range( 1, (len(self.upTwistJnts)+1) ):
                twsitMultNode = cmds.createNode('multiplyDivide', n = self.upTwistJnts[i - 1].replace('%s_%s' % (common.SKINCLUSTER,common.JOINT), '%s_%s' % (common.UTILITY, common.MULTIPLYDIVIDE)))
                cmds.connectAttr('%s.r%s' % (ikfkDict['blendJoints'][0], aimAxis), '%s.input1X' % twsitMultNode, f = True)
                cmds.setAttr('%s.input2X' % twsitMultNode, -(1-(step*i))  )
                cmds.connectAttr('%s.outputX' % twsitMultNode, '%s.r%s' % (self.upTwistJnts[i -1], aimAxis),f = True)
            #end loop

            self.upTwistJnts.insert(0, noTwistJnt)
        #end if

        if self.loTwistJnts:
            twistJnt = common.duplicate(self.midJoint,name = self.midJoint.replace('%s' % common.SKINCLUSTER, 'loTwist_%s' % common.SKINCLUSTER), parent = self.midJoint)
            constraint = cmds.aimConstraint(ikfkDict['blendJoints'][2],twistJnt,aimVector =  aimVector, upVector  = upVector,  worldUpType ="objectrotation", worldUpVector = upVector, worldUpObject = self.tipJoint)
            cmds.setAttr('%s.v' % twistJnt, 0)
        #end if

        step   = 1.0 / (len(self.loTwistJnts) +1)
        for i in range( 1, (len(self.loTwistJnts)+1) ):
            twsitMultNode = cmds.createNode('multiplyDivide', n = self.loTwistJnts[i - 1].replace('%s_%s' % (common.SKINCLUSTER,common.JOINT), '%s_%s' % (common.UTILITY, common.MULTIPLYDIVIDE)))
            cmds.connectAttr('%s.r%s' % (ikfkDict['blendJoints'][2], aimAxis), '%s.input1X' % twsitMultNode, f = True)
            cmds.setAttr('%s.input2X' % twsitMultNode, 1-(step*i) )
            cmds.connectAttr('%s.outputX' % twsitMultNode, '%s.r%s' % (self.loTwistJnts[i -1], aimAxis),f = True)
        #end loop

        #------------------------
        #Add to class variables
        #------------------------
        #assign joints to the joints list
        self.joints = {'ik' : ikfkDict['ikJoints'], 'fk' : ikfkDict['fkJoints'], 'blend' : ikfkDict['blendJoints'], 'target' : ikfkDict['targetJnts']}
        #assign controls to the controls list
        #assign fkCtrls into the controls dictionary 
        self.controls = {'ik' : [ikCtrl, pvCtrl],'fk' : fkCtrls }
        self.ikfkGroup = ikfkDict['group']
        #assign hooks
        self.hookRoot = [ikfkDict['ikJoints'][0], common.getParent(fkCtrls[0]), ikCtrl, ikfkDict['targetJnts'][-1]]
        self.hookPoint = [ikfkDict['blendJoints'][-1]]
        #add no twist joint to the skincluster list
        self.skinClusterJnts.append(noTwistJnt)
Example #19
0
def load( filepath, world=False ):
    '''Import joints exported with the *save* function. **python format**
    If the joint already exists it will set the transformation, if it doesn't it will create it.
    
    .. python ::

        # This command will only import the exported values into persp node, if any.
        load( '/var/tmp/attributes.pyson', 'persp' )

    :param filepath: File exported with the save function.
    :type filepath: **str**
    :param world: Import world position
    :type world: **bool**
    '''

    if not fileIO.isFile(filepath):
        raise RuntimeError, 'No valid filepath "%s"' % filepath

    # Get Data
    data = pyon.load( filepath )
    
    # Create Joints
    for joint in data.keys():
        
        parameters    = data[joint]['parameters']
        parent        = data[joint]['parent']
        
        # Create Joint
        if not common.isValid( joint ):
            joint = create( name=joint )

        # Create Parent Node
        if not common.isValid( parent ) and parent in data.keys():
            parent = create( name=parent )

        # Parent joint
        if common.isValid( parent ) and common.getParent( joint ) != parent:
            cmds.parent( joint, parent )

        # Set values
        for attr in parameters.keys():
            
            # Check if valid
            if not common.isValid('%s.%s' % (joint, attr)):
                continue

            # ------------------------------------------------------------------
            # Check if connected or locked
            locked = False
            if attribute.isConnected( attr, joint, incoming=True, outgoing=False ) or attribute.isLocked( attr, joint ):
                locked = True
            if attribute.isCompound( attr, joint ):
                attrChildren = cmds.attributeQuery( attr, node = joint, listChildren = True)
                for attrChild in attrChildren:
                    if attribute.isConnected( attrChild, joint, incoming=True, outgoing=False ) or attribute.isLocked( attrChild, joint ):
                        locked = True
            if locked:
                continue
            
            # ------------------------------------------------------------------
            # Set values
            value = parameters[attr]
            attribute.setValue( attr, joint, value )
    
    # Set world position
    if world:
        for joint in data.keys():
            worldPosition = data[joint]['worldPosition']
            cmds.move( worldPosition[0], worldPosition[1], worldPosition[2], joint, worldSpace=True, a=True, pcp=True )
    
    #logger.info( 'Joints loaded from: "%s"' % filepath)
Example #20
0
    def setupRig(self):
        if super(Chain, self).setupRig():
            return True
        
        self.skinClusterJnts = [self.startJoint, self.endJoint]
                
        if self._getSide() == common.LEFT:
            positions = (
            [self.position[0] + 2, self.position[1], self.position[2]],
            [self.position[0] + 9, self.position[1], self.position[2]]
            )
            
            aimCtrlPosition = [positions[0][0],
                    positions[0][1] + 5,
                    positions[0][2]]
        #end if    
        elif self._getSide() == common.RIGHT:
            positions = (
            [self.position[0] - 2, self.position[1], self.position[2]],
            [self.position[0] - 9, self.position[1], self.position[2]]
            )
            
            aimCtrlPosition = [positions[0][0],
                    positions[0][1] + 5,
                    positions[0][2]]
        #end elif    
            
        else:
            positions = (
            [self.position[0], self.position[1], self.position[2]],
            [self.position[0], self.position[1] + 9, self.position[2]]
            )
            
            aimCtrlPosition = [positions[0][0],
                    positions[0][1],
                    positions[0][2] + 5]
        #end elif
        for i,jnt in enumerate(self.skinClusterJnts):
            if not common.isValid(jnt):
                cmds.joint(n = jnt,position = positions[i])
            
            if i == 0:
                cmds.parent(jnt, self.skeletonGrp)
                #place Master Guide control in the same position
                #  as the first joint
                transform.matchXform(jnt,
                        common.getParent(self.masterGuide),
                        type = 'position')
            else:
                cmds.parent(jnt, self.skinClusterJnts[i - 1])
            #end if/else
                
            ctrl = self.setupCtrl(jnt.replace('_%s' % common.JOINT, ''),jnt)
            #create template control
            #control.createTemplate(ctrl)
            cmds.select(cl = True)
        #end loop
        

        # ----------------------------------------------------------------------
        # CREATE GUIDES
        startJointGuide = self.startJoint.replace(common.JOINT, common.GUIDES)
        endJointGuide   = self.endJoint.replace(common.JOINT, common.GUIDES)



        # ----------------------------------------------------------------------
        # ORIENTATION 
        #
        if self._getSide() == common.RIGHT:
            aimVectorAttr = attribute.switch ('aimVector',
                    node= self.masterGuide,
                    value=4,
                    choices=['x','y','z','-x','-y','-z'],
                    outputs=[(1,0,0),(0,1,0),(0,0,1),(-1,0,0),(0,-1,0),(0,0,-1)])
            upVectorAttr  = attribute.switch ('upVector',
                    node=self.masterGuide,
                    value=3,
                    choices=['x','y','z','-x','-y','-z'],
                    outputs=[(1,0,0),(0,1,0),(0,0,1),(-1,0,0),(0,-1,0),(0,0,-1)])
        else:
            aimVectorAttr = attribute.switch ('aimVector',
                    node=self.masterGuide,
                    value=1,
                    choices=['x','y','z','-x','-y','-z'],
                    outputs=[(1,0,0),(0,1,0),(0,0,1),(-1,0,0),(0,-1,0),(0,0,-1)])

            upVectorAttr  = attribute.switch ('upVector',
                    node=self.masterGuide,
                    value=3,
                    choices=['x','y','z','-x','-y','-z'],
                    outputs=[(1,0,0),(0,1,0),(0,0,1),(-1,0,0),(0,-1,0),(0,0,-1)])
        
        #create in-between joints and guides and make connections 
        step   = 1.0 / (self.numJoints - 1)
        parent = self.startJoint
        for i in range( 1, self.numJoints - 1 ):
            j = '%s_%s_%s_%s_%s' % (self._getPrefix(),
                    common.getDescription(self.name()),
                    common.padNumber(i,3),
                    common.SKINCLUSTER,
                    common.JOINT)
            if not common.isValid(j):
                joint.create( name= j)

            transform.matchXform( self.startJoint,j, type='rotate' )
            ctrl = self.setupCtrl(j.replace('_%s' % common.JOINT, ''),j)
            ctrlParent = common.getParent(ctrl)
            #create point constraint and figure out percentage for position
            constraint = cmds.pointConstraint( self.startJoint,
                    endJointGuide, ctrlParent )[0]

            weightAliasList = cmds.pointConstraint( constraint,
                    q=True,
                    weightAliasList=True)

            cmds.setAttr( '%s.%s' % (constraint, weightAliasList[0]), 1-(step*i) )
            cmds.setAttr( '%s.%s' % (constraint, weightAliasList[1]),  step*i )

            #adding the joint to skincluster joints list
            self.skinClusterJnts.insert(-1, j)
            relatives = cmds.listRelatives(j, p = True)
            if not relatives:
                cmds.parent(j, parent)
            parent = j

            if i == self.numJoints - 2:
                cmds.parent(self.endJoint, j)
                constraint = cmds.orientConstraint(j, self.endJoint)[0]
                #add constraints to setup constraint list
                self._addSetupConstraints(constraint)


        #create aim control
        aimLocator = self._createAimLocator(aimCtrlPosition,
                color = common.SIDE_COLOR_SECONDARY[self._getSide()])
        
        #create aim constraints
        for i, jnt in enumerate(self.skinClusterJnts):
            if jnt == self.endJoint:
                break
            constraint = cmds.aimConstraint(
                    self.skinClusterJnts[i+1].replace('_%s' % common.JOINT, '_%s' % common.GUIDES),
                    jnt,
                    worldUpType = "object",
                    worldUpObject = aimLocator)[0]

            attribute.connect(aimVectorAttr, '%s.aimVector' % constraint)
            attribute.connect(upVectorAttr, '%s.upVector' % constraint)
            #add constraints to setup constraint list
            self._addSetupConstraints(constraint)
Example #21
0
    def setupRig(self):
        if super(Hand, self).setupRig():
            return True
        

        if self._getSide() == common.LEFT:
        #move master  guide into position
            cmds.xform(common.getParent(self.masterGuide), ws = True,
                       t = self.handPosition)

            for i,obj in enumerate(self.fingers):
                self.__fingers[obj] = finger.Finger('%s_%s' % (self._getPrefix(),
                                                               obj))
                self.__fingers[obj].initialize(numJoints = self.numJoints,
                                               position=[self.position[0] + 10,
                                                 self.position[1],
                                                 (self.position[2] + 2 )- i],
                                               parent = self.parent)
                self.__fingers[obj].setupRig()

                cmds.parentConstraint(self.masterGuide,
                            common.getParent(self.__fingers[obj].masterGuide),
                            mo = True)
                for guide in self.__fingers[obj].getGuides():
                    #tag the guide control with a tag_guides attribute
                    tagAttr = attribute.addAttr(guide, 'hand_guides',
                                                attrType = 'message')
                    attribute.connect('%s.tag_guides' % self.setupRigGrp,
                                      tagAttr)
                #end loop
            #end loop
        #end if

        elif self._getSide() == common.RIGHT:
        #move master  guide into position
            cmds.xform(common.getParent(self.masterGuide), ws = True, t = self.handPosition)

            for i,obj in enumerate(self.fingers):
                self.__fingers[obj] = finger.Finger('%s_%s' % (self._getPrefix(), obj))
                self.__fingers[obj].initialize(numJoints = self.numJoints, position = [self.position[0] - 10, self.position[1], (self.position[2] + 2 ) - i], parent = self.parent)
                self.__fingers[obj].setupRig()
            
                cmds.parentConstraint(self.masterGuide, common.getParent(self.__fingers[obj].masterGuide), mo = True)
        
                for guide in self.__fingers[obj].getGuides():
                    #tag the guide control with a tag_guides attribute
                    tagAttr = attribute.addAttr(guide, 'hand_guides', attrType = 'message')
                    attribute.connect('%s.tag_guides' % self.setupRigGrp, tagAttr)
                #end loop
            #end loop
        #end elif
        else:
        #move master  guide into position
            cmds.xform(common.getParent(self.masterGuide), ws = True, t = self.handPosition)

            for i,obj in enumerate(self.fingers):
                self.__fingers[obj] = finger.Finger('%s_%s' % (self._getPrefix(), obj))
                self.__fingers[obj].initialize(numJoints = self.numJoints, position = [self.position[0] - 10, self.position[1], (self.position[2] + 2 ) - i], parent = self.parent)
                self.__fingers[obj].setupRig()
            
                cmds.parentConstraint(self.masterGuide, common.getParent(self.__fingers[obj].masterGuide), mo = True)
        
                for guide in self.__fingers[obj].getGuides():
                    #tag the guide control with a tag_guides attribute
                    tagAttr = attribute.addAttr(guide, 'hand_guides', attrType = 'message')
                    attribute.connect('%s.tag_guides' % self.setupRigGrp, tagAttr)
                #end loop
            #end loop
        #end elif
        
        
        #create joint and guide
        if not common.isValid(self.handJoint):
            joint.create(self.handJoint, self.skeletonGrp, self.handPosition)
        if not common.isValid(self.handJoint.replace(common.JOINT,common.CONTROL)):
            self.setupCtrl(self.handGuide,self.handJoint, common.SIDE_COLOR[self._getSide()])
Example #22
0
    def rig(self):
        if not self._puppetNode:
            self.runSetupRig()
        
        if common.isValid('%s_%s%s' % (self.name(), common.IK, common.FK)):
            return True
        
        cmds.parent([self.__bankInPivot,
                self.__bankOutPivot,
                self.__heelPivot],
                w = True)

        if super(Foot,self).rig():
            return True

        #create foot ik/fk chain and parent group to joints group
        self.__footIkFk = \
                ikfk.IkFkFoot(self.ankleJoint,
                        self.toeJoint,
                        name = self.name())

        #list the groups for the foot ik setup
        self.__footRollGroups.insert(0, 'anklePivot')
        footRollGrpList = self.__footRollGroups

        #create foot setup
        self.__footIkFk.create(searchReplace = '%s' % common.SKINCLUSTER,
                footRollGrpList = footRollGrpList)

        #parent to joints group
        cmds.parent(self.__footIkFk.group, self.jointsGrp)

        #get position of joints
        anklePosition    = \
            cmds.xform(self.ankleJoint, q = True, ws = True, rp = True)

        ballPosition     = \
            cmds.xform(self.ballJoint, q = True, ws = True, rp = True)

        toePosition      = \
            cmds.xform(self.toeJoint, q = True, ws = True, rp = True)

        bankInPosition   = \
            cmds.xform(self.__bankInPivot, q = True, ws = True, rp = True)

        bankOutPosition  = \
            cmds.xform(self.__bankOutPivot, q = True, ws = True, rp = True)

        heelPosition     = \
            cmds.xform(self.__heelPivot, q = True, ws = True, rp = True)

        #delete pivot joints
        for jnt in (self.__heelPivot,self.__bankOutPivot, self.__bankInPivot):
            cmds.delete(jnt)
        #end loop

        #get foot roll groups
        footRollGroups = self.__footIkFk.getFootRolls()
        handles = self.__footIkFk.getIkHandles()

        #position foot roll groups
        for grp in footRollGroups:
            if grp in ['ballRoll', 'toeBend']:
                cmds.xform(footRollGroups[grp], ws = True, rp = ballPosition)
            elif grp in ['heelRoll', 'heelPivot']:
                if grp == self.__heelPivotName:
                    cmds.setAttr('%s.rotateOrder' % footRollGroups[grp], 2)
                cmds.xform(footRollGroups[grp], ws = True, rp = heelPosition)
            elif grp in ['toeRoll', 'toePivot']: 
                cmds.xform(footRollGroups[grp], ws = True, rp = toePosition)
            elif grp in ['bankIn', self.__bankInZero]: 
                cmds.xform(footRollGroups[grp], ws = True, rp = bankInPosition)
            elif grp in ['bankOut', self.__bankOutZero]: 
                cmds.xform(footRollGroups[grp], ws = True, rp = bankOutPosition)
                cmds.setAttr('%s.rotateOrder' % footRollGroups[grp], 2)
            elif grp in ['anklePivot']: 
                cmds.xform(footRollGroups[grp], ws = True, rp = anklePosition)
        #end loop


        #create controls
        self.__footCtrl      = \
            control.create(name= self.name(),
                    type = 'implicitSphere',
                    parent = self.controlsGrp,
                    color = common.SIDE_COLOR[self._getSide()])

        self.__bankInCtrl    = \
            control.create(name= footRollGroups[self.__bankIn] ,
                    type = 'implicitSphere',
                    parent = self.controlsGrp,
                    color = common.SIDE_COLOR_SECONDARY[self._getSide()])

        self.__bankOutCtrl   = \
            control.create(name= footRollGroups[self.__bankOut] ,
                    type = 'implicitSphere',
                    parent = self.controlsGrp,
                    color = common.SIDE_COLOR_SECONDARY[self._getSide()])

        self.__heelPivotCtrl = \
            control.create(name= footRollGroups[self.__heelPivotName] ,
                    type = 'implicitSphere',
                    parent = self.controlsGrp,
                    color = common.SIDE_COLOR_SECONDARY[self._getSide()])

        #parent of controls
        parentBankOutCtrl   = common.getParent(self.__bankOutCtrl)
        parentBankInCtrl    = common.getParent(self.__bankInCtrl)
        parentHeelPivotCtrl = common.getParent(self.__heelPivotCtrl)

        #scale controls
        for ctrl in [self.__footCtrl,self.__bankOutCtrl, self.__bankInCtrl, self.__heelPivotCtrl]:
            for i in range(len(common.getShapes(ctrl))):
                control.scaleShape (ctrl, scale = [.3, .3, .3], index = i)


        #place controls in correct positions
        transform.matchXform(self.ankleJoint,
                common.getParent(self.__footCtrl),
                type = 'pose')

        cmds.xform(common.getParent(self.__footCtrl),
                ws = True,
                r = True,
                t = [0,0,-2])

        cmds.delete(cmds.parentConstraint(footRollGroups['bankIn'],
                parentBankInCtrl))

        cmds.delete(cmds.parentConstraint(footRollGroups['bankOut'],
                parentBankOutCtrl))

        cmds.delete(cmds.parentConstraint(footRollGroups['heelPivot'],
                parentHeelPivotCtrl))

        #Decompose matrix nodes for pivots and connect the controls to them
        for ctrl, grp in zip([self.__bankInCtrl, self.__bankOutCtrl, self.__heelPivotCtrl] , [footRollGroups['bankIn'], footRollGroups['bankOut'], footRollGroups[self.__heelRoll]]):
            grpZero = common.getChildren(grp)[0]

            dcm = cmds.createNode('decomposeMatrix',
                    n = '%s_%s' % (grp, common.DECOMPOSEMATRIX))

            mdn = cmds.createNode('multiplyDivide',
                    n = '%s_%s' % (grp, common.MULTIPLYDIVIDE))

            attribute.connect('%s.worldMatrix[0]' % ctrl, '%s.inputMatrix' % dcm)

            #connect controls to pivots
            attribute.connect('%s.outputTranslate' % dcm, '%s.rotatePivot' % grp)
            attribute.connect('%s.outputTranslate' % dcm, '%s.rotatePivot' % grpZero)
            #Change attributes on Multiply divide node and make connections
            cmds.setAttr('%s.input2Y' % mdn, -1)
            attribute.connect('%s.ry' % ctrl, '%s.input1Y' % mdn)
            attribute.connect('%s.outputY' % mdn, '%s.ry' % grpZero)
            attribute.connect('%s.ry' % ctrl, '%s.ry' % grp)


        #parent constrain the foot control to the ankle joint
        for node in [self.__footCtrl,parentBankOutCtrl,  parentBankInCtrl, parentHeelPivotCtrl]:
            cmds.parentConstraint(footRollGroups['anklePivot'], node, mo = True)


        #add attributes to the foot control and connect them to the pivots
        ikfkAttr      = \
            attribute.addAttr(self.__footCtrl,
                    'ikfk' ,
                    attrType = 'enum',
                    defValue = ['off', 'on'],
                    value = 0)

        bankAttr      = \
            attribute.addAttr(self.__footCtrl,
                    'bank' ,
                    attrType = 'double',
                    defValue = 0,
                    min = -10,
                    max = 10)

        ballRollAttr  = \
            attribute.addAttr(self.__footCtrl,
                    self.__ballRoll ,
                    attrType = 'double',
                    defValue = 0,
                    min = 0,
                    max = 10)

        toeRollAttr   = \
            attribute.addAttr(self.__footCtrl,
                    self.__toeRoll ,
                    attrType = 'double',
                    defValue = 0,
                    min = 0,
                    max = 10)

        toePivotAttr  = \
            attribute.addAttr(self.__footCtrl,
                    self.__toePivot ,
                    attrType = 'double',
                    defValue = 0,
                    min = -10,
                    max = 10)

        toeBendAttr   = \
            attribute.addAttr(self.__footCtrl,
                    self.__toeBend ,
                    attrType = 'double',
                    defValue = 0,
                    min = -10,
                    max = 10)

        heelRollAttr  = \
            attribute.addAttr(self.__footCtrl,
                    self.__heelRoll ,
                    attrType = 'double',
                    defValue = 0,
                    min = -10,
                    max = 0)

        heelPivotAttr = \
            attribute.addAttr(self.__footCtrl,
                    self.__heelPivotName ,
                    attrType = 'double',
                    defValue = 0,
                    min = -10,
                    max = 10)

        self.__footRollAttrs.extend([ikfkAttr,
                bankAttr,
                ballRollAttr,
                toeRollAttr ,
                toePivotAttr,
                toeBendAttr,
                heelRollAttr,
                heelPivotAttr])

        #create remap dictionary to place remap nodes in based on foot roll group names
        ramapNodes = dict()

        #create remap nodes and connect them to foot roll groups
        for attr in [bankAttr,toePivotAttr,toeBendAttr,heelPivotAttr]:
            node, attrName = attr.split('.')
            ramapNodes[attrName] = \
                cmds.createNode('remapValue',
                        n = '%s_%s_%s' % (node, attrName, common.REMAP))

            attribute.connect(attr, '%s.inputValue' % ramapNodes[attrName])
            cmds.setAttr('%s.outputMax' % ramapNodes[attrName], 100)
            cmds.setAttr('%s.outputMin' % ramapNodes[attrName], -100)
            cmds.setAttr('%s.inputMax' % ramapNodes[attrName], 10)
            cmds.setAttr('%s.inputMin' % ramapNodes[attrName], -10)
        #end loop

        for attr in [ballRollAttr,toeRollAttr, heelRollAttr]:
            node, attrName = attr.split('.')
            ramapNodes[attrName] = \
                cmds.createNode('remapValue',
                        n = '%s_%s_%s' % (node, attrName, common.REMAP))
            attribute.connect(attr, '%s.inputValue' % ramapNodes[attrName])
            cmds.setAttr('%s.outputMax' % ramapNodes[attrName], 100)
            cmds.setAttr('%s.outputMin' % ramapNodes[attrName], 0)
            cmds.setAttr('%s.inputMax' % ramapNodes[attrName], 10)
            cmds.setAttr('%s.inputMin' % ramapNodes[attrName], 0)

            if attr == heelRollAttr:
                cmds.setAttr('%s.outputMax' % ramapNodes[attrName], 0)
                cmds.setAttr('%s.outputMin' % ramapNodes[attrName], -100)
                cmds.setAttr('%s.inputMax' % ramapNodes[attrName], 0)
                cmds.setAttr('%s.inputMin' % ramapNodes[attrName], -10)
            #end if
        #end loop

        #connect remap nodes to roll groups    
        #---Bank In/Out---
        if self._getSide() == common.LEFT:
            attribute.connect('%s.outValue' % ramapNodes['bank'],
                              '%s.rz' % footRollGroups[self.__bankIn])

            attribute.connect('%s.outValue' % ramapNodes['bank'],
                              '%s.rz' % footRollGroups[self.__bankOut])

            cmds.transformLimits(footRollGroups[self.__bankIn],
                    rz =[0, 100],
                    erz = [1, 1])

            cmds.transformLimits(footRollGroups[self.__bankOut],
                    rz =[-100, 0],
                    erz = [1, 1])
        elif self._getSide() == common.RIGHT:
            invertMDN = \
                cmds.createNode('multiplyDivide',
                        n = '%s_bankInvert_%s' % (self._getSide(),
                        common.MULTIPLYDIVIDE))

            cmds.setAttr('%s.input2X' % invertMDN, -1)
            attribute.connect('%s.outValue' % ramapNodes['bank'],
                    '%s.input1X' % invertMDN)

            attribute.connect('%s.outputX' % invertMDN,
                    '%s.rz' % footRollGroups[self.__bankIn])

            attribute.connect('%s.outputX' % invertMDN,
                    '%s.rz' % footRollGroups[self.__bankOut])

            cmds.transformLimits(footRollGroups[self.__bankIn],
                    rz =[-100, 0],
                    erz = [1, 1])

            cmds.transformLimits(footRollGroups[self.__bankOut],
                    rz =[0, 100],
                    erz = [1, 1])

        #---Ball Roll---
        attribute.connect('%s.outValue' % ramapNodes[self.__ballRoll],
                '%s.rx' % footRollGroups[self.__ballRoll])
        #---Toe Roll---
        attribute.connect('%s.outValue' % ramapNodes[self.__toeRoll],
                '%s.rx' % footRollGroups[self.__toeRoll])
        #---Toe Pivot---
        attribute.connect('%s.outValue' % ramapNodes[self.__toePivot],
                '%s.ry' % footRollGroups[self.__toePivot])
        #---Heel Roll---
        attribute.connect('%s.outValue' % ramapNodes[self.__heelRoll],
                '%s.rx' % footRollGroups[self.__heelRoll])
        #---Heel Pivot---
        attribute.connect('%s.outValue' % ramapNodes[self.__heelPivotName],
                '%s.ry' % footRollGroups[self.__heelPivotName])
        #---IK/FK---
        attribute.connect(ikfkAttr,
                '%s.ikfk' % self.__footIkFk.group)
        #---Ball Roll---
        attribute.connect('%s.outValue' % ramapNodes[self.__toeBend],
                '%s.rx' % footRollGroups[self.__toeBend])

        #connect fk joints to the ankle pivot
        #cmds.parentConstraint(footRollGroups['anklePivot'], self.__footIkFk.fkJoints[0], mo = True)

        #connecting visibility of control shapes to the controls
        ikfkReverse = \
            cmds.createNode('reverse', n = '%s_%s' % (self.name(),common.REVERSE))

        attribute.connect(ikfkAttr, '%s.inputX' % ikfkReverse)

        for ikCtrl in [self.__bankInCtrl,self.__bankOutCtrl,self.__heelPivotCtrl]:
            cmds.setAttr('%s.rotateOrder' % ikCtrl, 2)
            for shape in common.getShapes(ikCtrl):
                if shape:
                    attribute.connect('%s.outputX' % ikfkReverse, '%s.v' % shape)

        #----FK Setup---
        fkCtrls = list()
        parent = self.controlsGrp
        for jnt in self.__footIkFk.fkJoints:
            if jnt == self.__footIkFk.fkJoints[-1]:
                continue
            #end if

            ctrl = \
                control.create(name= jnt.split('_%s' % common.JOINT)[0],
                        type = 'circle',
                        parent = parent,
                        color = common.SIDE_COLOR[self._getSide()])

            ctrlParent = common.getParent(ctrl)
            transform.matchXform(jnt, ctrlParent, type = 'pose')
            cmds.parentConstraint(ctrl, jnt, mo = True) #----> might change this to connect rotations and not use translation
            if jnt == self.__footIkFk.fkJoints[0]:
                cmds.parentConstraint(footRollGroups['anklePivot'],
                    ctrlParent,
                    mo = True)
            #end if

            #connect visibility of shapes to foot control
            for shape in common.getShapes(ctrl):
                attribute.connect(ikfkAttr, '%s.v' % shape)
            #end for    
            parent = ctrl
            fkCtrls.append(ctrl)

        #assign hooks
        self.hookRoot.extend([footRollGroups['anklePivot'], common.getParent(fkCtrls[0])])
        self.hookPoint.extend([footRollGroups['ballRoll']])