Exemple #1
0
 def __create_joint(self):
     """ Create a joint """
     jnt = None
     if self._parent:
         sel = cmds.ls(selection=True)
         if not sel:
             jnt = cmds.joint(name=self.joint, position=self._position,
                              orientation=self._orientation,
                              radius=self._radius)
         else:
             if not cmds.nodeType(sel[0]) == 'joint':
                 jnt = cmds.joint(name=self.joint, position=self._position,
                                  orientation=self._orientation,
                                  radius=self._radius)
                 cmds.setAttr(jnt + '.t', 0, 0, 0)
                 cmds.setAttr(jnt + '.r', 0, 0, 0)
                 cmds.setAttr(jnt + '.s', 1, 1, 1)
             else:
                 jnt = cmds.joint(name=self.joint, position=self._position,
                                  orientation=self._orientation,
                                  radius=self._radius)
                 if "|" in jnt:
                     self.joint = jnt.split("|")[-1]
                 else:
                     self.joint = jnt
     else:
         jnt = cmds.joint(name=self.joint, position=self._position,
                          orientation=self._orientation, radius=self._radius)
         self.joint = jnt
         cmds.select(clear=True)
     return
Exemple #2
0
    def mirrorJoints(self, topJoint = '', prefix = ['l_', 'r_']):
        """
        mirroring joint, top node needs to contain 'l_' as prefix
        """

        lPrefix = prefix[0]
        rPrefix = prefix[1]
        
        cmds.select(cl = True)
        cmds.joint(n = 'temp_jnt')
        cmds.select(topJoint, r = True)
        cmds.select('temp_jnt', tgl = True)
        self.toggleSelect(topJoint, 'temp_jnt')
        cmds.parent()
        
        cmds.select(topJoint, r = True)
        cmds.mirrorJoint(mirrorYZ = True, mirrorBehavior  = True, myz = True, searchReplace =  prefix)
        
        rJoint = rPrefix + topJoint.split(lPrefix)[-1]
        cmds.select(topJoint, rJoint)
        cmds.parent(w = True)
        
        cmds.delete('temp_jnt')
        
        return rJoint
Exemple #3
0
    def create_twist_joints(self, start, end, name):
        """Creates the joints for the arm twist.
        @param start: the start joint
        @param end: the end joint
        @param name: the name of the twist section
        @type start: String
        @type end: String
        @type name: String

        """
        jnts = list()
        m, uv = self.c.get_vector_info(start, end)
        count = 5
        for i in range(count):
            pos = [0, 0, 0]
            pos[0] = start[0] + uv[0]*((m/(count-1))*i)
            pos[1] = start[1] + uv[1]*((m/(count-1))*i)
            pos[2] = start[2] + uv[2]*((m/(count-1))*i)
            jnt_name = '%s_%s_%s%s_%s_%s' % (self.side, name, 'seg', i,
                                             self.nc.result, self.nc.joint)
            jnt = cmds.joint(p=pos, n=jnt_name)
            jnts.append(jnt)
        # END for
        cmds.joint(jnts[0], e=True, oj='xyz', secondaryAxisOrient='ydown', ch=True, zso=True)
        self.c.reset_joint_orient(jnts[-1])
        return jnts
Exemple #4
0
    def _create_wrist(self):
        """Creates the special wrist setup for the 3 different rotation axes of
        Dave's wrist.
        @todo: change the constraining to the PLY GRP to something save

        """

        hand = '%s_hand_result_%s' % (self.side, self.nc.joint)
        hand_end = '%s_handEnd_result_%s' % (self.side, self.nc.joint)
        fore_arm = '%s_foreArm_result_%s' % (self.side, self.nc.joint)

        # joints
        cmds.select(cl=True)
        root_jnt = cmds.joint(n='%s_wristRoot_%s' % (self.side, self.nc.joint))
        end_jnt = cmds.joint(n='%s_wristEnd_%s' % (self.side, self.nc.joint))
        tmp_end_jnt = cmds.joint(n='%s_wristTmpEnd_%s' % (self.side, self.nc.joint))
        self.c.snap_a_to_b(root_jnt, hand)
        self.c.snap_a_to_b(end_jnt, hand_end)
        self.c.snap_a_to_b(tmp_end_jnt, hand_end)

        # orient joints properly
        self.orient_joint(root_jnt)
        cmds.delete(tmp_end_jnt)
        cmds.parent(end_jnt, w=True)

        # constrain joints
        cmds.parentConstraint(hand, root_jnt, mo=True)
        cmds.pointConstraint(root_jnt, end_jnt, mo=True)
        cmds.orientConstraint(root_jnt, end_jnt, mo=True)

        # constrain hand const group
        cmds.parentConstraint('%s_wristRotZ_PLY_%s' % (self.side, self.nc.group),
                              '%s_hand_const_%s' % (self.side, self.nc.group), mo=True)

        cmds.parent(root_jnt, end_jnt, '%s_hand_%s' % (self.side, self.nc.group))
Exemple #5
0
def build(numBindJoints=6, numSpans=None, name='', numSkinJoints=3, width=None):
    '''
    builds a nurbs ribbon
    If width is not specified, width will be set to numBindJoints
    If numSpans is not specified, it will be set to numBindJoints
    
    '''
    if not width:
        width = numBindJoints
    if not numSpans:
        numSpans = numBindJoints
    
    main_grp = cmds.group(empty=1, name=(name + '_grp'))
    plane = cmds.nurbsPlane(axis=(0, 1, 0), ch=0, lengthRatio=(1.0 / width), w=width, u=numSpans, name=(name + '_nurbsPlane'))[0]
    cmds.parent(plane, main_grp)
    
    # Creat Skin joints
    skinJoints = []
    skinJointPositions = common.pointsAlongVector( start=[width*.5, 0, 0], end=[width*-.5, 0, 0], divisions=(numSkinJoints-1) )
    for index in range(len(skinJointPositions)):
        cmds.select(main_grp)
        j = cmds.joint(position = skinJointPositions[index], name=(name + '_' + str(index) + '_jnt'))
        skinJoints.append(j)
        
    # Add skinning to ribbon
    cmds.skinCluster(skinJoints, plane, tsb=1, name=(plane + '_skinCluster'))
    cmds.setAttr(plane+'.inheritsTransform', 0)
    
    # Add follicles
    for index in range(numBindJoints):
        f = rivet.build( mesh=plane, paramU=(1.0 / (numBindJoints-1) * index), paramV=0.5, name=(name + '_' + str(index)))
        cmds.parent(f, main_grp)
        j = cmds.joint(name=(name + '_' + str(index) + '_bnd'))
Exemple #6
0
    def modifiy_joint_chain_axis(joint_chain, orient_chain='xyz', up_axis_chain='yup'):
        '''
        Desc:
        Modify specified joint chain orientation

        Parameter:
        joint_chain = chain to affect
        orient_chain = axis to orient
        up_axis_chain = chain up axis

        Return:
        None
        '''
        for i in range(0, len(joint_chain)):
            KstOut.debug(KstRig._debug, 'Reorient current joint:' )
            KstOut.debug(KstRig._debug, 'joint: %s' % joint_chain[i])
            try:
                cmds.joint(joint_chain[i], e=True, zso=True, oj=orient_chain, sao=up_axis_chain, ch=True)
            except:
                print('Error on reorient, check the rotations')

            # If it's the last joint reset rotation axis
            if i == len(joint_chain)-1:
                rot_axis = ['X','Y','Z']
                for axis in rot_axis:
                    cmds.setAttr(joint_chain[i]+'.jointOrient'+axis, 0)
Exemple #7
0
    def confirmJoints(self):
        """   
        draw joints in locator position
        """

        #- Getting Ball and Toe Location
        self.leftHipPos = cmds.xform('l_hip_Adjust_ctl', q = True, ws = True, t = True)
        self.leftKneePos = cmds.xform('l_knee_Adjust_ctl', q = True, ws = True, t = True)
        self.leftAnklePos = cmds.xform('l_ankle_Adjust_ctl', q = True, ws = True, t = True)
        self.leftBallPos = cmds.xform('l_ball_Adjust_ctl', q = True, ws = True, t = True)
        self.leftToePos = cmds.xform('l_toe_Adjust_ctl', q = True, ws = True, t = True)
        self.leftHeelPos = cmds.xform('l_heel_PivotPosition', q = True, ws = True, t = True)
        self.leftSideInPos = cmds.xform('l_sidein_PivotPosition', q = True, ws = True, t = True)
        self.leftSideOutPos = cmds.xform('l_sideout_PivotPosition', q = True, ws = True, t = True)
        
        #duplicate pivots
        cmds.duplicate('l_heel_PivotPosition', n = 'r_heel_PivotPosition', rr =  True)
        cmds.xform('r_heel_PivotPosition', t = [-self.leftHeelPos[0], self.leftHeelPos[1], self.leftHeelPos[2]])
        cmds.duplicate('l_sidein_PivotPosition', n = 'r_sidein_PivotPosition', rr =  True)
        cmds.xform('r_sidein_PivotPosition', t = [-self.leftSideInPos[0], self.leftSideInPos[1], self.leftSideInPos[2]])
        cmds.duplicate('l_sideout_PivotPosition', n = 'r_sideout_PivotPosition', rr =  True)
        cmds.xform('r_sideout_PivotPosition', t = [-self.leftSideOutPos[0], self.leftSideOutPos[1], self.leftSideOutPos[2]])
        
        cmds.select(cl = True)
        print 'leg Parts : ' , self.legParts
        for elem in self.legElement :
            jointPos = cmds.xform(self.left + elem + '_Adjust_ctl', t = True, q = True, ws = True)
            cmds.joint(n = '%s%s_jnt' %(self.left, elem), p = jointPos)
            
        #- orient joint
        cmds.joint(self.lHipJnt, e = True, oj = 'xzy', secondaryAxisOrient = 'yup', ch = True, zso = True)

        #- delete position locators
        cmds.delete(self.legParts)
Exemple #8
0
def create_chain(num, axis, value, description='temp'):
    joints = []
    for count, i in enumerate(range(num)):
        j = cmds.joint(name="C_%s_%s_jnt" % (description, i))
        joints.append(j)

        cmds.setAttr("%s.displayLocalAxis" % j, True)

        if count > 0:
            cmds.setAttr("%s.translate%s" % (j, axis.upper()), value)

    cmds.select(joints, r=True)
    cmds.joint(joints, e=True, oj="xyz", secondaryAxisOrient="yup", ch=True, zso=True)

    for j in joints:
        cmds.setAttr("%s.rotateY" % j, -10)
        cmds.joint(j, e=True, spa=True, ch=True)
        cmds.setAttr("%s.rotateY" % j, 0)

    # Add shapes
    for joint in joints:
        _shape = shape.add_shape(joint)
        cmds.setAttr("%s.visibility" % _shape, 0)
        
    return joints
def createJoints(prefix, lytObs, *args):
    print "CreateJoints"

    cmds.select(d=True)

    ik_joints = []

    for item in lytObs:
        """ item[0] will be the joint
            item[1] will be the position
            item[2] will be the parent        
        """
        newJointName = item[0].replace("lyt_", prefix)

        cmds.select(d=True)
        if cmds.objExists(newJointName) == True:
            cmds.delete(newJointName)
        jnt = cmds.joint(p=item[1], n=newJointName )
        ik_joints.append(jnt)


    lytLen = len(lytObs)

    for item in range(len(lytObs)):
        if item != 0:
            joint = lytObs[item][0].replace("lyt_", prefix)
            jointParent = lytObs[item][2].replace("lyt_", prefix)
            cmds.parent(joint, jointParent) 

    for jnt in ik_joints:
        cmds.joint(jnt, e=True, oj='xyz', secondaryAxisOrient='yup', ch=True, zso=True)


    return ik_joints  
Exemple #10
0
	def _createJoint(self):
		"""create joint on poistion"""
		mc.select( cl = True )
		self.parentJoint = mn.Node( mc.joint( p = self.rivet.a.translate.v[0], o = self.rivet.a.rotate.v[0], n = self.name + '_joint' ) )
		self._skinJoint = mc.joint( p = self.rivet.a.translate.v[0], o = self.rivet.a.rotate.v[0], n = self.name + '_skin' )
		if self._baseJoint != '':
			self.parentJoint.parent = self._baseJoint
Exemple #11
0
 def createGuide(self, *args):
     Base.StartClass.createGuide(self)
     # Custom GUIDE:
     cmds.addAttr(self.moduleGrp, longName="flip", attributeType='bool')
     cmds.setAttr(self.moduleGrp+".flip", 0)
     
     cmds.addAttr(self.moduleGrp, longName="indirectSkin", attributeType='bool')
     cmds.setAttr(self.moduleGrp+".indirectSkin", 0)
     
     cmds.setAttr(self.moduleGrp+".moduleNamespace", self.moduleGrp[:self.moduleGrp.rfind(":")], type='string')
     
     self.cvJointLoc, shapeSizeCH = ctrls.cvJointLoc(ctrlName=self.guideName+"_JointLoc1", r=0.3)
     self.connectShapeSize(shapeSizeCH)
     self.jGuide1 = cmds.joint(name=self.guideName+"_JGuide1", radius=0.001)
     cmds.setAttr(self.jGuide1+".template", 1)
     cmds.parent(self.jGuide1, self.moduleGrp, relative=True)
     
     self.cvEndJoint, shapeSizeCH = ctrls.cvLocator(ctrlName=self.guideName+"_JointEnd", r=0.1)
     self.connectShapeSize(shapeSizeCH)
     cmds.parent(self.cvEndJoint, self.cvJointLoc)
     cmds.setAttr(self.cvEndJoint+".tz", 1.3)
     self.jGuideEnd = cmds.joint(name=self.guideName+"_JGuideEnd", radius=0.001)
     cmds.setAttr(self.jGuideEnd+".template", 1)
     cmds.transformLimits(self.cvEndJoint, tz=(0.01, 1), etz=(True, False))
     ctrls.setLockHide([self.cvEndJoint], ['tx', 'ty', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])
     
     cmds.parent(self.cvJointLoc, self.moduleGrp)
     cmds.parent(self.jGuideEnd, self.jGuide1)
     cmds.parentConstraint(self.cvJointLoc, self.jGuide1, maintainOffset=False, name=self.jGuide1+"_ParentConstraint")
     cmds.parentConstraint(self.cvEndJoint, self.jGuideEnd, maintainOffset=False, name=self.jGuideEnd+"_ParentConstraint")
     cmds.scaleConstraint(self.cvJointLoc, self.jGuide1, maintainOffset=False, name=self.jGuide1+"_ScaleConstraint")
     cmds.scaleConstraint(self.cvEndJoint, self.jGuideEnd, maintainOffset=False, name=self.jGuideEnd+"_ScaleConstraint")
Exemple #12
0
    def create_guides(self):
        """Creates the guides.
        Re-implemented to have the fingers separated.

        """
        cmds.select(cl=True)
        grp = cmds.group(n='%s_%s_%s_%s' % (self.side, self.modulename,
                         self.nc.guide, self.nc.group), empty=True)
        for name, pos in self.guides.items():
            if 'Base' in name:
                cmds.select(grp, r=True)
            # END if
            jnt_name = '%s_%s_%s' % (self.side, name, self.nc.guide)
            jnt = cmds.joint(p=pos, n=jnt_name)
            if 'Base' in name and name != 'handBase':
                base = '%s_%s_%s' % (self.side, 'handBase', self.nc.guide)
                cmds.parent(jnt, base)
            # END if
            cmds.addAttr(jnt, ln='guideType', dt='string')
            cmds.setAttr('%s.guideType' % jnt, e=True, keyable=True)
            cmds.setAttr('%s.guideType' % jnt, 'guides', type='string')
        # END for
        cmds.select(grp, r=True)
        for name, pos in self.additional_guides.items():
            jnt_name = '%s_%s_%s' % (self.side, name, self.nc.guide)
            jnt = cmds.joint(p=pos, n=jnt_name)
            cmds.addAttr(jnt, ln='guideType', dt='string')
            cmds.setAttr('%s.guideType' % jnt, e=True, keyable=True)
            cmds.setAttr('%s.guideType' % jnt, 'additional_guides', type='string')
Exemple #13
0
def template_joints(joints=None, reorient_children=True, reset_orientation=True):
    if joints is None:
        joints = cmds.ls(sl=True, type='joint')
    if not joints:
        raise RuntimeError('No joint selected to orient.')

    if reorient_children:
        children = cmds.listRelatives(fullPath=True, allDescendents=True, type='joint')
        joints.extend(children)

    red, green, blue = create_shaders()

    orient_group = cmds.createNode('transform', name=ORIENT_GROUP)
    manips = []
    for joint in joints:
        if reset_orientation:
            cmds.makeIdentity(joint, apply=True)
            cmds.joint(joint, edit=True, orientJoint='xyz', secondaryAxisOrient='yup', children=False, zeroScaleOrient=True)
        if not cmds.listRelatives(joint, children=True):
            zero_orient([joint])
            continue
        group, manip = create_orient_manipulator(joint, blue)
        manips.append(manip)
        cmds.parent(group, orient_group)
        cmds.parentConstraint(joint, group)
        cmds.setAttr(joint + '.template', 1)
    cmds.select(manips)
Exemple #14
0
def mmInsertJoint( *args ):
    
    def normalize(vector_value):
        length = math.sqrt(vector_value[0]**2 + vector_value[1]**2 + vector_value[2]**2)
        x = vector_value[0]/length
        y = vector_value[1]/length
        z = vector_value[2]/length
        result = [x, y, z]
        return result
    
    num_joints =input(10)
    num_joints = num_joints+1
    joint_list = cmds.ls(sl=True)
    
    for r in joint_list:
    
        first_joint_trans = cmds.xform(r, q=True, ws=True, t=True)
        first_joint_ori = cmds.xform(r, q=True, ws=True, ro=True)
        end_joint = cmds.listRelatives(r, f=True, c=True)
        end_joint_rename=cmds.rename(end_joint[0], "end_to_delete______yeah")
        end_joint_trans = cmds.xform(end_joint_rename, q=True, ws=True, t=True)
        end_joint_ori = cmds.xform(end_joint_rename, q=True, ws=True, ro=True)
        
        between_vector = [-(first_joint_trans[0]-end_joint_trans[0]),-(first_joint_trans[1]-end_joint_trans[1]),-(first_joint_trans[2]-end_joint_trans[2])]
        vector_length = mel.eval(("mag(<<"+str(between_vector[0])+","+str(between_vector[1])+","+str(between_vector[2])+">>)"))
        vector_normalize = normalize(between_vector)
        
        for i in range(num_joints):
                vector_to_add = [(vector_normalize[0]*((vector_length/num_joints)*((num_joints-float(i))))),(vector_normalize[1]*((vector_length/num_joints)*((num_joints-float(i))))),(vector_normalize[2]*((vector_length/num_joints)*((num_joints-float(i)))))]
                inset_joint = cmds.insertJoint(r)
                cmds.joint(inset_joint, e=True, co=True, o=(0,0,0), p=((first_joint_trans[0]+vector_to_add[0]), (first_joint_trans[1]+vector_to_add[1]), (first_joint_trans[2]+vector_to_add[2])))
        cmds.delete(end_joint_rename)
Exemple #15
0
def createFromPointList(ptList, orient=False, side='cn', part='chain', suffix='jnt'):
    """
    Create joint chain from a list of point positions
    @param ptList: List of points to create joint chain from
    @type ptList: list
    @param orient: Orient joints
    @type orient: bool
    @param side: Joint side name prefix
    @type side: str
    @param part: Joint part name
    @type part: str
    @param suffix: Joint name suffix
    @type suffix: str
    """
    # Clear selection
    cmds.select(cl=True)

    # Create joint chain
    jntList = []
    for i in range(len(ptList)):
        jnt = cmds.joint(p=ptList[i], n=side + '_' + part + str(i + 1) + '_' + suffix)
        if i and orient: cmds.joint(jntList[-1], e=True, zso=True, oj='xyz', sao='yup')
        jntList.append(jnt)

    # Return result
    return jntList
def jointFromList(xformList=[], orient="xyz", secAxis="zup", strip="", suffix="", *args):
    """
    uses the xformlist arg (a list of transforms in scene) to create a joint chain in order.
    Arguments: xformList (a list), orient ("xyz", etc), secAxis ("xup", "zdown", etc), strip (string to strip off), suffix (string to add to the joints)
    """
    jointList = []

    #if no list is provided, get the list from selection order
    if not xformList:
        sel = getSelection()

        if sel:
            xformList = sel
        #if no list && no selection then throw error
        else:
            cmds.error("you must provide a list of transforms or have the transforms selected in order")

    #clear selection
    cmds.select(cl=True)
    #for each thing in the list create a joint at that location (they'll be parented to the previous)
    for xform in xformList:
        xformPos = cmds.xform(xform, q=True, ws=True, t=True)
        jointName = "%s%s"%(xform.rstrip(strip), suffix)
        thisJoint = cmds.joint(n=jointName, p=xformPos)
        jointList.append(thisJoint)

    #now orient the joint chain based on args and return a list of the joints
    cmds.joint(jointList[0], e=True, ch=True, oj=orient, sao=secAxis)
    return(jointList)
Exemple #17
0
def j_BodyFix():
    # Get The Goal Joint position 
    position = dict()
    dupJnt = ['ShoulderPart2_L','Elbow_L','ElbowPart1_L','HipPart2_L','Knee_L','KneePart1_L']
    for jnt in dupJnt:
        position[jnt] =mc.xform(jnt,ws=1,t=1,q=1)
        
    # Create  Joint  And Ikhandle From position
    newJnt = []
    na =1;
    for j in dupJnt: 
        if mc.objExists(('Fix'+j)):
            mc.select(('Fix'+j),r=1)
            break;
        newJnt.append(mc.joint(n=('Fix'+j),p=position[j],radius=1.75))
        if na%3==0:        
        # Create IKHandle With ikRPsolver , Then Mirror With IkHandle
            mc.joint(newJnt[0],e=1,zso=1,oj='xyz',sao='yup')
            mc.joint(newJnt[1],e=1,zso=1,oj='xyz',sao='yup')
            mc.setAttr('%s.jointOrient'%newJnt[2],0,0,0)
            ikhand = mc.ikHandle(name=('rpik_'+newJnt[1]+'01'),sj=newJnt[0],ee=newJnt[2],sol = 'ikSCsolver')
            mc.setAttr('%s.v'%ikhand[0],0)
            # mirrorJoint -mirrorYZ -mirrorBehavior -searchReplace "_L" "_R";
            mc.mirrorJoint(newJnt[0],mirrorYZ =1,mirrorBehavior =1,searchReplace=('_L','_R'))
            mc.parent(ikhand[0],j)
            mc.parent((re.sub('_L',"_R",ikhand[0])),(re.sub('_L','_R',j)))
            mc.parent(newJnt[0],dupJnt[na-3])
            mc.parent((re.sub("_L","_R",newJnt[0])),(re.sub('_L','_R',dupJnt[na-3])))
            newJnt = []       
            mc.select(clear=1)
        na=na+1; 
Exemple #18
0
 def create_guides(self):
     """Creates the guides for the given character."""
     cmds.select(cl=True)
     grp = cmds.group(n='%s_%s_%s_%s' % (self.side, self.modulename,
                      self.nc.guide, self.nc.group), empty=True)
     for name, pos in self.guides.items():
         jnt_name = '%s_%s_%s' % (self.side, name, self.nc.guide)
         jnt = cmds.joint(p=pos, n=jnt_name)
         cmds.addAttr(jnt, ln='guideType', dt='string')
         cmds.setAttr('%s.guideType' % jnt, e=True, keyable=False)
         cmds.setAttr('%s.guideType' % jnt, 'guides', type='string')
     # END for
     cmds.select(grp, r=True)
     for name, pos in self.fk_guides.items():
         jnt_name = '%s_%s_%s_%s' % (self.side, name, self.nc.fk, self.nc.guide)
         jnt = cmds.joint(p=pos, n=jnt_name)
         cmds.addAttr(jnt, ln='guideType', dt='string')
         cmds.setAttr('%s.guideType' % jnt, e=True, keyable=False)
         cmds.setAttr('%s.guideType' % jnt, 'fk_guides', type='string')
     # END for
     cmds.select(grp, r=True)
     for name, pos in self.ik_guides.items():
         jnt_name = '%s_%s_%s_%s' % (self.side, name, self.nc.ik, self.nc.guide)
         jnt = cmds.joint(p=pos, n=jnt_name)
         cmds.addAttr(jnt, ln='guideType', dt='string')
         cmds.setAttr('%s.guideType' % jnt, e=True, keyable=False)
         cmds.setAttr('%s.guideType' % jnt, 'ik_guides', type='string')
     # END for
     cmds.select(grp, r=True)
     for name, pos in self.additional_guides.items():
         jnt_name = '%s_%s_%s' % (self.side, name, self.nc.guide)
         jnt = cmds.joint(p=pos, n=jnt_name)
         cmds.addAttr(jnt, ln='guideType', dt='string')
         cmds.setAttr('%s.guideType' % jnt, e=True, keyable=False)
         cmds.setAttr('%s.guideType' % jnt, 'additional_guides', type='string')
def createWristAngleJoints( orientObject ):

    import sgBFunction_dag

    orientObjP = sgBFunction_dag.getParent( orientObject )
    orientObjectName = orientObject.split( '|' )[-1]
    
    if cmds.nodeType( orientObject ) == 'joint':
        baseJointRad = cmds.getAttr( orientObject+'.radius' )
    else:
        baseJointRad = 1
    
    cmds.select( orientObjP )
    zJoint = cmds.joint( n = orientObjectName+'_waZ', radius = baseJointRad * 1.5 )
    yJoint = cmds.joint( n = orientObjectName+'_waY', radius = baseJointRad * 2.0 )
    xJoint = cmds.joint( n = orientObjectName+'_waX', radius = baseJointRad * 2.5 )
    
    waz = cmds.createNode( 'wristAngle', n='WA_Z_' + orientObjectName )
    way = cmds.createNode( 'wristAngle', n='WA_Y_' + orientObjectName )
    wax = cmds.createNode( 'wristAngle', n='WA_X_' + orientObjectName )
    
    cmds.connectAttr( orientObject+'.m', waz+'.inputMatrix' )
    cmds.setAttr( waz+'.axis', 2 )
    cmds.connectAttr( waz+'.outAngle', zJoint+'.rotateZ' )
    
    mm = getMultMatrixAsParenting( orientObject, zJoint )
    cmds.connectAttr( mm+'.o', way+'.inputMatrix' )
    cmds.setAttr( way+'.axis', 1 )
    cmds.connectAttr( way+'.outAngle', yJoint+'.rotateY' )
    
    mm = getMultMatrixAsParenting( orientObject, yJoint )
    cmds.connectAttr( mm+'.o', wax+'.inputMatrix' )
    cmds.setAttr( wax+'.axis', 0 )
    cmds.connectAttr( wax+'.outAngle', xJoint+'.rotateX' )
	def autoRig(self,meshName):
		height = self.getSizeY(meshName)
		minPosY = height[1]
		height = height[0]
		width = self.getSizeX(meshName)
		minPosX = width[1]
		width = width[0]
		bassinPoint = (minPosX + width * 0.0,minPosY + height * 0.48,self.getZ(minPosX + width * 0.0,minPosY + height * 0.48,meshName))
		couPoint = (minPosX + width * 0.0,minPosY + height * 0.870,self.getZ(minPosX + width * 0.0,minPosY + height * 0.870,meshName))
		epaulePoint = (minPosX + width * 0.129,minPosY + height * 0.825,self.getZ(minPosX + width * 0.129,minPosY + height * 0.825,meshName))
		coudePoint = (minPosX + width * 0.315,minPosY + height * 0.825,self.getZ(minPosX + width * 0.315,minPosY + height * 0.825,meshName))
		poignetPoint = (minPosX + width * 0.461,minPosY + height * 0.825,self.getZ(minPosX + width * 0.461,minPosY + height * 0.825,meshName))
		jambePoint = (minPosX + width * 0.0955,minPosY + height * 0.4,self.getZ(minPosX + width * 0.0955,minPosY + height * 0.4,meshName))
		genouPoint = (minPosX + width * 0.1,minPosY + height * 0.285,self.getZ(minPosX + width * 0.1,minPosY + height * 0.285,meshName))
		piedPoint = (minPosX + width * 0.12,minPosY + height * 0.039 ,self.getZ(minPosX + width * 0.12,minPosY + height * 0.039,meshName))
		
		cmds.select(clear=True)
		cmds.joint(p=bassinPoint,name="bassinBase")
		cmds.select("bassinBase")
		rigList = [couPoint,epaulePoint,coudePoint,poignetPoint]
		self.createListRig(rigList,"rigTop","bassinBase")
		cmds.select("bassinBase")
		rigList2 = [jambePoint,genouPoint,piedPoint]
		self.createListRig(rigList2,"rigBot","bassinBase")
		cmds.select("rigTop1")
		cmds.mirrorJoint(mirrorYZ=True)
		cmds.select("rigBot0")
		cmds.mirrorJoint(mirrorYZ=True)
		cmds.select("bassinBase")
		cmds.select(meshName,tgl=True)
		cmds.bindSkin()
 def build(self):
     
     root  = 'root%s' % self.count
     backa = 'backA%s' % self.count
     backb = 'backB%s' % self.count
     chest = 'chest%s' % self.count
     neck  = 'neck%s' % self.count
     
     if not cmds.objExists(root): return
     
     # root
     cmds.parent(backa,w=True)
     cmds.setAttr('%s.jointOrientY' % root,0)
     cmds.parent(backa,root)
     
     # midsection
     cmds.joint(backa,e=True,oj='xyz',sao='zup',zso=True)
     cmds.joint(backb,e=True,oj='xyz',sao='zup',zso=True)
     
     # chest
     cmds.parent(neck,w=True)
     cmds.makeIdentity(chest,a=True,t=False,r=True,s=False,n=False,jo=True)    
     rx,ry,rz = cmds.xform(chest,q=True,ws=True,ro=True)
     cmds.setAttr('%s.jointOrientZ' % chest,ry)
     cmds.parent(neck,chest)
     
     grp = cmds.group(n='fit',em=True)
     cmds.parent(root,grp)
 def test_setupHeirarchy(self):
     #--- Setup the scene
     startJnt = cmds.joint(n='startJnt',p=(3, 0, 0))
     endJnt = cmds.joint(n='endJnt',p=(3, 5, -2))        
     locs = []
     locs.append(cmds.spaceLocator(n='test_topLoc_pos', p=(0, 0, 1))[0])
     locs.append(cmds.spaceLocator(n='test_midLoc_pos',p=(1, 2, 2))[0])
     locs.append(cmds.spaceLocator(n='test_btmLoc_pos',p=(2, 4, 3))[0])
     
     locGrp = cmds.group(em=True)
     fGrp = cmds.group(em=True)
     plane = cmds.nurbsPlane( w=1, lengthRatio=5, d=3, u=1, v=6, ax=[0, 0, 1])[0]
     
     for each in locs:
         cmds.parent(each,locGrp)
     
     #--- Call method, get results
     result = self.rig._setupHeirarchy(name='test', startObj=startJnt, endObj=endJnt, 
                                       locGrp=locGrp, plane=plane, follicleGrp=fGrp)
     
     #--- Check Results
     expectedTopNode = 'test_rbbnTopNode'
     self.assertEqual(result, expectedTopNode)
     self.assertTrue(cmds.objExists(expectedTopNode))
     self.assertEqual(cmds.listRelatives(fGrp,parent=True)[0], expectedTopNode) 
     self.assertEqual(cmds.listRelatives(plane,parent=True)[0], expectedTopNode) 
     self.test.assertConstrained(startJnt,locs[2],type='parent')
     self.test.assertConstrained(endJnt,locs[0],type='parent')
Exemple #23
0
def reorientJoints(_joints, _up=False, _upVec=(0, 0, 1),  _aimVec=(1, 0, 0)):
    for topJoint in _joints:
        # Clean translations
        cmds.joint(topJoint, edit=True, oj="xyz", sao="zup", ch=True, zso=True) 
        if _up:
            # Clean rotations
            reorientRecursive(topJoint, _up, _upVec, _aimVec)
Exemple #24
0
 def surfJnts(name, pairL):
     jntPairs = []
     iks = []
     j = 0
     for pair in pairL:
         jnts = []
         i = 0
         suff = ['_root', '_aim', '_up']
         for point in pair:
             cmds.select(point)
             pos = cmds.xform(point, q=True, t=True, ws=True)
             jnts.append(place.joint(0, name + str(j) + suff[i] + '_jnt', pad=2, rpQuery=False)[0])
             i = i + 1
         j = j + 1
         # parent ik joints
         cmds.parent(jnts[1], jnts[0])
         # orient ik joints
         cmds.joint(jnts[0], e=True, oj='zyx', secondaryAxisOrient='yup')
         jnt.ZeroJointOrient(jnts[1])
         # orient up vector jnt
         cmds.parent(jnts[2], jnts[0])
         jnt.ZeroJointOrient(jnts[2])
         cmds.parent(jnts[2], w=True)
         # append pairs to list
         jntPairs.append(jnts)
         # ik
         ikhndl = cmds.ikHandle(sj=jnts[0], ee=jnts[1], sol='ikRPsolver', sticky='sticky')[0]
         cmds.setAttr(ikhndl + '.visibility', False)
         cmds.poleVectorConstraint(jnts[2], ikhndl)
         iks.append(ikhndl)
         # cleanup
         place.cleanUp(jnts[0], SknJnts=True)
         place.cleanUp(jnts[2], SknJnts=True)
         place.cleanUp(ikhndl, World=True)
     return jntPairs, iks
Exemple #25
0
    def lock_joints(self, moduleInfo):
        ##  clear selection
        cmds.select(clear=True )


        joints = moduleInfo[0]
        jointPositions = moduleInfo[1]
        jointOrientations = moduleInfo[2]
        jointRotationOrders = moduleInfo[3]
        jointPreferredAngles = moduleInfo[4]
        
        cmds.delete(self.containerName)
        
        index = 0
        ##  creating joints this way because when you select a joint and create joint, it corrects orientation
        for joint in joints:
            jointName = joint
            jointPos = jointPositions[index]

            parentJoint = ''
            childJoint = ''
            
            if index > 0:
                parentJoint = self.moduleName + ":" + self.jointInfo[index-1][0]
                cmds.select(parentJoint, replace = True)
                
            newJoint = cmds.joint(name = self.moduleName + ":" + self.jointInfo[index][0], position = jointPositions[index])
  
            if index > 0:
                cmds.joint(parentJoint, edit = True, orientJoint = "xyz", secondaryAxisOrient = "yup")   
            
            cmds.joint(newJoint, edit = True, orientation = jointOrientations[index])   
            index += 1
        def _iterate_(self):	
	    self.call2_func = self.test2_func
	    _first = mc.joint(n = "first")
	    #_first = mc.createNode('transform',n = "first")
            for i in range(self.int_targetCount):
                self.progressBar_set(status = ("Pass 1: Substantiating Call %i"%i), progress = i, maxValue = self.int_targetCount)		
		mc.select(cl=True)
		string = mc.joint(n = "baseobj_{0}".format(i))
		if i:
		    for ii in (range(i)):
			string = mc.joint(n = "obj_{0}".format(i))
		#mc.parent(string,world = True)
		#string = mc.createNode('network',n = "obj_{0}".format(i))
		#string = mc.createNode('transform',n = "obj_{0}".format(i))
		#string = mc.createNode('transform',n = "sameName".format(i))
		#_group = mc.group(n = "obj_{0}".format(i), em=True)
		#string = mc.parent(string,_group)[0]
		t1 = time.clock()	
		self.test1_func(_first)              
		t2 = time.clock()
		self.l_times_1.append(t2-t1)
		
		t1 = time.clock()	
		#self.l_roots_2.extend( [self.test2_func(self._toCall)] )  
		self.call2_func(string)              
		t2 = time.clock()
		self.l_times_2.append(t2-t1)	
Exemple #27
0
def  MakeJntAndIKs(side):
    """
    选择两圈眼球上的线,生成骨骼和ik,side的值例如:R_In or R_Out
    ps: 选择骨骼链的子物体,打组,centerPivot,在原点生成一个骨点,用组约束骨点,正确命名,然后将IK组分别放到对应骨点下边。
    """    
    lx_start=mc.xform('loc_eyeCenter01',q=1,ws=1,t=1)
    lx_mouthPnt= mc.filterExpand(sm=31)
    mc.select (cl=1)
    lx_Jnts=[]
    lx_IKs = []
    for i in lx_mouthPnt :
        lx_end=mc.xform(i,q=1,ws=1,t=1)
        lx_stJnt=mc.joint (n=("Jnt_"+side+"_st"),p=(lx_start[0],lx_start[1],lx_start[2]),radius=0.1)
        lx_edJnt=mc.joint (n=("Jnt_"+side+"_ed"),p=(lx_end[0],lx_end[1],lx_end[2]),radius=0.1)        
        lx_scik =mc.ikHandle (n=("scik_"+side+str(01)),sj=lx_stJnt,ee=lx_edJnt,sol="ikSCsolver")
        #mc.setAttr((str(lx_scik[0]) +".visibility") ,0)
        mc.select(cl=1)
        lx_Jnts.append(lx_stJnt)
        lx_IKs .append(lx_scik[0])
    mc.select(lx_Jnts,r=1)
    mc.group(n=("grp_Jnts"+side))
    
    mc.select(lx_IKs,r=1)
    mc.group(n=("grp_iks"+side))
    mc.setAttr((str("grp_iks"+side) +".visibility") ,0)
    
#3.选择眼皮曲线,执行脚本,生成
    def  MakeEyeLidJnts(cuvs):
        
        
 def test_constrainLocators(self):
     #--- Setup the scene
     startJnt = cmds.joint(n='startJnt',p=(3, 0, 0))
     endJnt = cmds.joint(n='endJnt',p=(3, 5, -2))
     upObj = cmds.joint(n='upJnt',p=(4, 0, 0))
     
     #--- Create the locators... tsk, tsk, external dependency, but why repo so much code here!?
     result = self.rig._createLocators(name='test', start=startJnt, end=endJnt, startUpObj=upObj)
     
     #--- Call method, get results
     result = self.rig._constrainLocators(locators=result)
     
     #--- Check Results
     self.test.assertConstrained('test_btmLoc_pos','test_topLoc_aim',type='aim')
     self.test.assertConstrained('test_topLoc_pos','test_btmLoc_aim',type='aim')
     self.test.assertConstrained('test_topLoc_pos','test_midLoc_aim',type='aim')
     
     self.test.assertConstrained('test_topLoc_pos','test_midLoc_pos',type='point')      
     self.test.assertConstrained('test_btmLoc_pos','test_midLoc_pos',type='point')       
     
     self.test.assertConstrained('test_topLoc_up','test_midLoc_up',type='point')       
     self.test.assertConstrained('test_btmLoc_up','test_midLoc_up',type='point')
     
     btmPos = cmds.xform('test_btmLoc_up', q=1,ws=1, rp=1)
     self.test.assertFloatListAlmostEqual(btmPos,[13,0,0])
     
     # Twist the top
     cmds.rotate(0,45,0,'test_topLoc_pos')
     topPos = cmds.xform('test_topLoc_up', q=1,ws=1, rp=1)
     midPos = cmds.xform('test_midLoc_up', q=1,ws=1, rp=1)
     avgPos = [(topPos[0]+btmPos[0])/2.0, (topPos[1]+btmPos[1])/2.0, (topPos[2]+btmPos[2])/2.0]
     self.test.assertListEqual(avgPos, midPos)
def create_joints():
	'''Subelements: vertecies, faces, edges should be selected'''
	# Get selected object name
	selection_list = cmds.ls(selection=True)
	for selection in selection_list:
		selected_object = selection.split('.')[0]
		break
	old_loc_list = cmds.ls('*LOC*', flatten=True)
	#Create locators constrained to subelements
	HZrivet.UI.HZrivet_finalCC()
	current_loc_list = cmds.ls('*LOC*', flatten=True)
	#Filter created locators
	new_loc_list = [loc for loc in current_loc_list if loc not in old_loc_list]
	# Get list of locators names and apply it as a prefix to a joint name
	loc_list = [loc for loc in new_loc_list if 'Shape' not in loc]
	root_joint = 'root'
	if not cmds.objExists(root_joint):
	    cmds.select(clear=True)
	    cmds.joint(name=root_joint)
	    root_p_constraint = cmds.pointConstraint(selected_object, root_joint)
	    root_o_constraint = cmds.orientConstraint(selected_object, root_joint)
	    cmds.delete(root_p_constraint, root_o_constraint)
	for loc in loc_list:
	    joint_prefix = re.sub("\D", "", loc)
	    joint_name = 'JNT_' + joint_prefix
	    cmds.select(clear=True)
	    cmds.joint(name=joint_name)
	    cmds.pointConstraint(loc, joint_name)
	    cmds.orientConstraint(loc, joint_name)
	    cmds.parent(joint_name, 'root') 
Exemple #30
0
def lip_setup(upperLipCurve, lowerLipCurve, upperLocators, lowerLocators, lipUp):

    upperLipCtrlCurve = utils.rebuild_to_ctrlCurve(upperLipCurve, spans=5, name='upperLipRCtrlCurve')
    lowerLipCtrlCurve = utils.rebuild_to_ctrlCurve(lowerLipCurve, spans=5, name='lowerLipRCtrlCurve')

    upperWireNode, upperWire, upperWireBase = utils.wire_deformer(upperLipCtrlCurve, upperLipCurve)
    lowerWireNode, lowerWire, lowerWireBase = utils.wire_deformer(lowerLipCtrlCurve, lowerLipCurve)
    
    upperWireMaster = utils.create_wires_master([upperWire, upperWireBase], name='upperLipRWireMaster_DELETE')
    lowerWireMaster = utils.create_wires_master([lowerWire, lowerWireBase], name='lowerLipRWireMaster_DELETE')    
    
    #upperLocators = utils.create_locators_on_cv(upperLipCurve)
    for loc in upperLocators : 
        utils.revit_locator_to_curve(loc, upperLipCurve)
        cmds.tangentConstraint(upperLipCurve, loc, aimVector=[1,0,0], upVector=[0,1,0], worldUpType='object', worldUpObject=lipUp)
        cmds.select(clear=True)
        j = cmds.joint()
        g = cmds.group(j)
        pm.parentConstraint(loc, g, mo=False)        
    
    #lowerLocators = utils.create_locators_on_cv(lowerLipCurve)
    for loc in lowerLocators : 
        utils.revit_locator_to_curve(loc, lowerLipCurve)
        cmds.tangentConstraint(lowerLipCurve, loc, aimVector=[1,0,0], upVector=[0,1,0], worldUpType='object', worldUpObject=lipUp)        
        cmds.select(clear=True)
        j = cmds.joint()
        g = cmds.group(j)
        pm.parentConstraint(loc, g, mo=False)

    return upperLipCurve, lowerLipCurve, upperLipCtrlCurve, lowerLipCtrlCurve
Exemple #31
0
def buildRig(surface, uValue):
    """
    Build basic groom surface scuplting rig.
    @param surface: Surface to build joints along
    @type surface: str
    @param uValue: U isoparm to build joints along
    @type uValue: float
    """
    # ==========
    # - Checks -
    # ==========

    if not glTools.utils.surface.isSurface(surface):
        raise Exception('Object "' + surface + '" is not a valid surface!')

    # Check Domain
    if uValue > cmds.getAttr(surface + '.maxValueU'):
        raise Exception('U value "' + str(uValue) +
                        '" is outside the parameter range!')
    if uValue < cmds.getAttr(surface + '.minValueU'):
        raise Exception('U value "' + str(uValue) +
                        '" is outside the parameter range!')

    # Check SkinCluster
    skinCluster = glTools.utils.skinCluster.findRelatedSkinCluster(surface)
    if skinCluster:
        raise Exception('Surface "' + skinCluster +
                        '" is already attached to an existing skinCluster!')

    # Get Surface Info
    surfFn = glTools.utils.surface.getSurfaceFn(surface)
    cvs = surfFn.nucmdsVsInU()

    # ================
    # - Build Joints -
    # ================

    # Extract IsoParm
    crv = cmds.duplicateCurve(surface + '.u[' + str(uValue) + ']', ch=False)[0]

    # Get Curve Points
    pts = glTools.utils.base.getPointArray(crv)
    cmds.delete(crv)

    # Create Joint Chain
    jnts = []
    cmds.select(cl=True)
    for i in range(len(pts)):
        # Select Prev Joint
        if i: cmds.select(jnts[-1])
        # Get Index String
        ind = glTools.utils.stringUtils.stringIndex(i)
        # Create Joint
        jnt = cmds.joint(p=pts[i], n=surface + str(i) + '_jnt')
        # Append Return List
        jnts.append(jnt)
    for i in range(len(pts)):
        # Orient Joint
        uv = glTools.utils.surface.closestPoint(surface, pos=pts[i])
        uTangent = cmds.pointOnSurface(surface, u=uv[0], v=uv[1], ntu=True)
        glTools.utils.joint.orient(jnts[i], upVec=uTangent)

    # ======================
    # - Create SkinCluster -
    # ======================

    skinCluster = cmds.skinCluster(surface, jnts, tsb=True)[0]

    # Clear Weights
    glTools.utils.skinCluster.clearWeights(surface)
    # Set Weights
    for i in range(len(pts)):
        # Generate Weights
        wts = []
        for k in range(cvs):
            for n in range(len(pts)):
                if i == n:
                    wts.append(1.0)
                else:
                    wts.append(0.0)
        # Set Influence Weights
        glTools.utils.skinCluster.setInfluenceWeights(skinCluster,
                                                      jnts[i],
                                                      wts,
                                                      normalize=False)

    # =================
    # - Return Result -
    # =================

    return jnts
Exemple #32
0
"""
Mirrors joints regardless of their position in hierarchy
for mirrored rotation behavior
"""

from maya import cmds, mel

#Strings to search and replace for new joints' names
search = 'L_'
replace = 'R_'

sel = cmds.ls(sl=1)
cmds.select(cl=1)
mirrorJnt = cmds.joint(n='temp_mirror_JNT')

for jnt in sel:
    parJnt = 0
    if cmds.listRelatives(jnt, p=1):
        parJnt = cmds.listRelatives(jnt, p=1)

    cmds.parent(jnt, mirrorJnt)
    cmds.mirrorJoint(myz=1, mb=1, sr=(search, replace))
    cmds.parent(w=1)

    #Reparent joint to its original parent
    if parJnt:
        cmds.parent(jnt, parJnt)
    else:
        cmds.parent(jnt, w=1)

cmds.delete(mirrorJnt)
Exemple #33
0
def chain_Oncurve(name='',
                  number_joints=4,
                  suffix='jnt',
                  curva='',
                  axis='x',
                  parentTo=''):
    '''
            Method to create a number of joints on a curve
            example use:spine_joints=chain_Oncurve (
                                    name = 'spine',
                                    number_joints = 20,
                                    suffix = 'jnt',
                                    curva = 'spine',
                                    axis = 'x',
                                    parentTo = '')
            name (str) : name to joints
            number_joints (int) : number of joints you want created
            curva = name of curve to create onto
            
            '''
    if cmds.objExists(curva):
        maxV_curve = cmds.getAttr(curva + '.maxValue')
        shape_curve = cmds.listRelatives(curva, c=True, s=True)[0]
        dist_joints = maxV_curve / (number_joints - 1)
        i = 0
        chain_joints = []

        # create node to run parameter of curve
        POC = cmds.createNode('pointOnCurveInfo', n='POC_' + curva)
        cmds.connectAttr(shape_curve + '.worldSpace', POC + '.inputCurve')

        for i in range(number_joints):

            if i == 0:

                cmds.select(cl=1)
                cmds.setAttr(POC + '.parameter', 0)
                POC_jnt = 0

            else:

                POC_current = cmds.getAttr(POC + '.parameter')
                POC_jnt = POC_current + dist_joints
                cmds.setAttr(POC + '.parameter', (POC_current + dist_joints))

            cmds.select(cl=1)

            jnt = cmds.joint(name=name + str(i) + '_' + suffix)

            chain_joints.append(jnt)

            cmds.connectAttr(POC + '.position', jnt + '.translate', f=1)
            cmds.disconnectAttr(POC + '.position', jnt + '.translate')

            jnt_ant = (name + str(i - 1) + '_' + suffix)

            if cmds.objExists(jnt_ant):
                cmds.parent(jnt, jnt_ant)

        cmds.delete(POC)

        if axis == 'x':

            cmds.joint(chain_joints[0],
                       e=True,
                       oj='xyz',
                       secondaryAxisOrient='yup',
                       ch=True)

        if axis == 'y':

            cmds.joint(chain_joints[0],
                       e=True,
                       oj='yzx',
                       secondaryAxisOrient='yup',
                       ch=True)

        if axis == 'z':

            cmds.joint(chain_joints[0],
                       e=True,
                       oj='zxy',
                       secondaryAxisOrient='yup',
                       ch=True)

        if cmds.objExists(parentTo):

            cmds.parent(chain_joints[0], parentTo)

        return chain_joints
    else:
        cmds.confirmDialog(title='Warnning',
                           message='not exist a curve named' + curva,
                           button=['ok'])
Exemple #34
0
def Arm_R():
    Scale_Guide = cmds.xform('Guide_Ctrl_Master', ws=True, q=True, s=True)[0]
    #J_Clavicle_R#
    translate_Guide_Clavicle_R = cmds.xform('Loc_Guide_Clavicle_R',
                                            ws=True,
                                            q=True,
                                            t=True)
    rot_Guide_Clavicle_R = cmds.xform('Loc_Guide_Clavicle_R',
                                      ws=True,
                                      q=True,
                                      ro=True)
    J_Clavicle_R = cmds.joint(n=('J_Clavicle_R'),
                              p=translate_Guide_Clavicle_R,
                              rad=.7 * Scale_Guide)
    cmds.mirrorJoint(myz=True, mb=True)
    cmds.delete('J_Clavicle_R')
    Rename_FK = mel.eval('searchReplaceNames("_R1","_R","all")')
    cmds.select(d=True)
    Z_J_Clavicle_R = cmds.group(n=("Z_J_Clavicle_R"), em=True)
    translate_J_Clavicle_R = cmds.xform('J_Clavicle_R',
                                        ws=True,
                                        q=True,
                                        t=True)
    rot_J_Clavicle_R = cmds.xform('J_Clavicle_R', ws=True, q=True, ro=True)
    emparentarTrans_J_Clavicle_R = cmds.xform(Z_J_Clavicle_R,
                                              ws=True,
                                              t=translate_J_Clavicle_R)
    emparentarRot_J_Clavicle_R = cmds.xform(Z_J_Clavicle_R,
                                            ws=True,
                                            ro=rot_J_Clavicle_R)
    cmds.parent(J_Clavicle_R, Z_J_Clavicle_R)
    cmds.select(d=True)
    #R_Clavicle_CTL#
    translate_Clavicle_R = cmds.xform('J_Clavicle_R', ws=True, q=True, t=True)
    rot_Clavicle_R = cmds.xform('J_Clavicle_R', ws=True, q=True, ro=True)
    emparentarTrans_Clavicle_R = cmds.xform('P_R_Clavicle_CTL',
                                            ws=True,
                                            t=translate_Clavicle_R)
    emparentarRot_Clavicle_R = cmds.xform('P_R_Clavicle_CTL',
                                          ws=True,
                                          ro=rot_Clavicle_R)
    cmds.parentConstraint('R_Clavicle_CTL', 'J_Clavicle_R', mo=True)
    cmds.select(d=True)
    ##Joints Arm_R##
    #J_ARM_R#
    trans_Guide_Arm_R = cmds.xform('Loc_Guide_Arm_R', ws=True, q=True, t=True)
    translate_Guide_ForeArm_R = cmds.xform('Loc_Guide_ForeArm_R',
                                           ws=True,
                                           q=True,
                                           t=True)
    translate_Guide_Hand_R = cmds.xform('Loc_Guide_Hand_R',
                                        ws=True,
                                        q=True,
                                        t=True)
    Joint_Arm_Neutral_R = cmds.joint(n='J_Arm_Neutral_R',
                                     p=trans_Guide_Arm_R,
                                     rad=1 * Scale_Guide)
    Joint_ForeArm_Neutral_R = cmds.joint(n='J_ForeArm_Neutral_R',
                                         p=translate_Guide_ForeArm_R,
                                         rad=1 * Scale_Guide)
    Joint_Hand_Neutral_R = cmds.joint(n='J_Hand_Neutral_R',
                                      p=translate_Guide_Hand_R,
                                      rad=1 * Scale_Guide)
    OJ_Joint_Arm_Neutral_R = cmds.joint('J_Arm_Neutral_R',
                                        e=True,
                                        zso=True,
                                        oj='xzy',
                                        sao='zup')
    OJ_Joint_ForeArm_Neutral_R = cmds.joint('J_ForeArm_Neutral_R',
                                            e=True,
                                            zso=True,
                                            oj='xzy',
                                            sao='zup')
    OJ_Joint_Hand_Neutral_R = cmds.joint('J_Hand_Neutral_R',
                                         e=True,
                                         zso=True,
                                         oj='xzy',
                                         sao='zup')
    joX_Hand_R = cmds.setAttr("J_Hand_Neutral_R.jointOrientX", 0)
    joY_Hand_R = cmds.setAttr("J_Hand_Neutral_R.jointOrientY", 0)
    joZ_Hand_R = cmds.setAttr("J_Hand_Neutral_R.jointOrientZ", 0)
    cmds.select(Joint_Arm_Neutral_R)
    cmds.mirrorJoint(myz=True, mb=True)
    cmds.delete('J_Arm_Neutral_R')
    Rename_FK = mel.eval('searchReplaceNames("_R1","_R","all")')
    cmds.select(d=True)
    rot_J_Arm_Neutral_R = cmds.xform('J_Arm_Neutral_R',
                                     ws=True,
                                     q=True,
                                     ro=True)
    trans_J_Arm_Neutral_R = cmds.xform('J_Arm_Neutral_R',
                                       ws=True,
                                       q=True,
                                       t=True)
    Z_J_Arm = cmds.group(n='Z_J_Arm_Neutral_R', em=True)
    P_J_Arm = cmds.group(n='P_J_Arm_Neutral_R')
    emparentarTrans = cmds.xform('P_J_Arm_Neutral_R',
                                 ws=True,
                                 t=trans_J_Arm_Neutral_R)
    emparentarRot = cmds.xform('P_J_Arm_Neutral_R',
                               ws=True,
                               ro=rot_J_Arm_Neutral_R)
    P_J_Arm_Neutral_R_Z_J_Arm_Neutral_R = cmds.parent('J_Arm_Neutral_R',
                                                      'Z_J_Arm_Neutral_R')
    cmds.select(d=True)
    Activar_color = cmds.setAttr('P_J_Arm_Neutral_R.overrideEnabled', 1)
    Blanco = cmds.setAttr('P_J_Arm_Neutral_R.overrideColor', 16)
    #duplicate the originaR chain
    Duplicar_a_FK = cmds.duplicate(P_J_Arm, rc=True)
    Duplicar_a_IK = cmds.duplicate(P_J_Arm, rc=True)
    #rename the chain
    Rename_FK = mel.eval('searchReplaceNames("_Neutral_R1","_FK_R","all")')
    Rename_IK = mel.eval('searchReplaceNames("_Neutral_R2","_IK_R","all")')
    #Change color Herarchy FK_IK
    Activar_color = cmds.setAttr(('P_J_Arm_FK_R.overrideEnabled'), 1)
    Azul = cmds.setAttr('P_J_Arm_FK_R.overrideColor', 6)
    Activar_color = cmds.setAttr('P_J_Arm_IK_R.overrideEnabled', 1)
    Amarillo = cmds.setAttr('P_J_Arm_IK_R.overrideColor', 17)

    def J(Joints, nombre, radio):
        for Elemento in Joints:
            Change_Radius_Tip_FK = cmds.setAttr(
                Elemento + '_' + nombre + '_R' + '.radius',
                radio * Scale_Guide)

    J(['J_Arm', 'J_ForeArm', 'J_Hand'], "FK", .5)
    J(['J_Arm', 'J_ForeArm', 'J_Hand'], "IK", .3)
    #########Create_Ctrls_FK_R#############
    #Create_Ctrl_Arm_FK_R
    translate = cmds.xform('J_Arm_FK_R', ws=True, q=True, t=True)
    rot = cmds.xform('J_Arm_FK_R', ws=True, q=True, ro=True)
    #Emparentar R_FK_Arm_CTL
    emparentarTrans_R = cmds.xform('P_R_FK_Arm_CTL', ws=True, t=translate)
    emparentarRot_R = cmds.xform('P_R_FK_Arm_CTL', ws=True, ro=rot)
    cmds.parentConstraint('R_FK_Arm_CTL', 'J_Arm_FK_R', mo=True)
    #Create_Ctrl_ForeArm_FK_R
    translate = cmds.xform('J_ForeArm_FK_R', ws=True, q=True, t=True)
    rot = cmds.xform('J_ForeArm_FK_R', ws=True, q=True, ro=True)
    #Emparentar R_FK_Arm_CTL
    emparentarTrans_R = cmds.xform('P_R_FK_ForeArm_CTL', ws=True, t=translate)
    emparentarRot_R = cmds.xform('P_R_FK_ForeArm_CTL', ws=True, ro=rot)
    cmds.parentConstraint('R_FK_ForeArm_CTL', 'J_ForeArm_FK_R', mo=True)
    #Create_Ctrl_Hand_FK_R
    translate = cmds.xform('J_Hand_FK_R', ws=True, q=True, t=True)
    rot = cmds.xform('J_Hand_FK_R', ws=True, q=True, ro=True)
    #Emparentar R_FK_Arm_CTL
    emparentarTrans_R = cmds.xform('P_R_FK_Wrist_CTL', ws=True, t=translate)
    emparentarRot_R = cmds.xform('P_R_FK_Wrist_CTL', ws=True, ro=rot)
    cmds.parentConstraint('R_FK_Wrist_CTL', 'J_Hand_FK_R', mo=True)
    #Herarchy FK_Ctrls
    P_Hand_R_Ctrl_ForeArm_R = cmds.parent(
        ("P_R_FK_Wrist_CTL", "R_FK_ForeArm_CTL"))
    P_ForeArm_R_Ctrl_Arm_R = cmds.parent(
        ("P_R_FK_ForeArm_CTL", "R_FK_Arm_CTL"))
    #Create_IKHandle_Arm_R
    IK_Handle_Arm_R = cmds.ikHandle(n='Ik_Handle_arm_R',
                                    sj='J_Arm_IK_R',
                                    ee='J_Hand_IK_R')
    Hidde_IK_Handle_Arm_R = cmds.hide('Ik_Handle_arm_R')
    #Create_Ctrl_PV_ARM_R
    pos_Arm_IK_R = cmds.xform('J_Arm_IK_R', ws=True, q=True, t=True)
    pos_ForeArm_IK_R = cmds.xform('J_ForeArm_IK_R', ws=True, q=True, t=True)
    pos_Hand_IK_R = cmds.xform('J_Hand_IK_R', ws=True, q=True, t=True)
    Cv_Polevector_Arm_R = cmds.curve(n='Cv_PV_Guide_Arm_R',
                                     d=1,
                                     p=[(pos_Arm_IK_R), (pos_ForeArm_IK_R),
                                        (pos_Hand_IK_R)],
                                     k=(0, 1, 2))
    Move_Cv_Guide = cmds.moveVertexAlongDirection('Cv_PV_Guide_Arm_R.cv[1]',
                                                  n=4.8 * Scale_Guide)
    pos_Cv = cmds.pointPosition('Cv_PV_Guide_Arm_R.cv[1]')
    emparentarTrans_R_PV_Arm_R = cmds.xform('P_R_PolevectorArm_CTL',
                                            ws=True,
                                            t=pos_Cv)
    delete_Cv_Polevector_Arm_R = cmds.delete(Cv_Polevector_Arm_R)
    Cons_PV_Arm_R = cmds.poleVectorConstraint('R_PolevectorArm_CTL',
                                              'Ik_Handle_arm_R')
    #R_IK_Arm_CTL
    translate_Ctrl_IK_R = cmds.xform('J_Hand_IK_R', ws=True, q=True, t=True)
    rot_Ctrl_IK_R = cmds.xform('J_Hand_IK_R', ws=True, q=True, ro=True)
    emparentarTrans_IK_Arm_R = cmds.xform('P_R_IK_Arm_CTL',
                                          ws=True,
                                          t=translate_Ctrl_IK_R)
    emparentarRot_IK_Arm_R = cmds.xform('P_R_IK_Arm_CTL',
                                        ws=True,
                                        ro=rot_Ctrl_IK_R)
    cmds.setAttr('P_R_IK_Arm_CTL.rotateX', 0)
    #Herarchy_IkH_Ctrl_Arm_IK_R
    IkH_Arm_R_Ctrl_Arm_IK_R = cmds.parent('Ik_Handle_arm_R', 'R_IK_Arm_CTL')
    ##Herarchy_J_R
    Parent_J_Arm_Neutral_R_J_Clavicle_R = cmds.parent("P_J_Arm_Neutral_R",
                                                      "J_Clavicle_R")
    Parent_J_Arm_FK_R_J_Clavicle_R = cmds.parent("P_J_Arm_FK_R",
                                                 "J_Clavicle_R")
    Parent_J_Arm_IK_R_J_Clavicle_R = cmds.parent("P_J_Arm_IK_R",
                                                 "J_Clavicle_R")
    ##Herarchy_Ctrl_FK_Clavicle_R
    Parent_Ctrl_Arm_Neutral_R_Ctrl_Clavicle_R = cmds.parent(
        "P_R_FK_Arm_CTL", "R_Clavicle_CTL")
    #Create_Ctrl_Switch_ARM_R
    translate_Switch_ARM_R = cmds.xform('Guide_Ctrl_Switch_Arm_R',
                                        ws=True,
                                        q=True,
                                        t=True)
    rot_Switch_ARM_R = cmds.xform('Guide_Ctrl_Switch_Arm_R',
                                  ws=True,
                                  q=True,
                                  ro=True)
    emparentarTrans_R_Switch_ARM_R = cmds.xform("P_R_SwitchArm_CTL",
                                                ws=True,
                                                t=translate_Switch_ARM_R)
    emparentarRot_R_Switch_ARM_R = cmds.xform("P_R_SwitchArm_CTL",
                                              ws=True,
                                              ro=rot_Switch_ARM_R)
    #Add_Attrs_Switch_Arm_R
    Atributo_Switch = cmds.addAttr("R_SwitchArm_CTL",
                                   longName='Switch_FK_IK',
                                   attributeType='float',
                                   defaultValue=0,
                                   minValue=0,
                                   maxValue=10)
    agregarAttr = cmds.setAttr("R_SwitchArm_CTL.Switch_FK_IK", k=True)
    Atributo_Stretch = cmds.addAttr("R_SwitchArm_CTL",
                                    longName='Stretch',
                                    attributeType='float',
                                    defaultValue=1,
                                    minValue=0,
                                    maxValue=1)
    AgregarAttrStretch = cmds.setAttr("R_SwitchArm_CTL.Stretch", k=True)
    #Switch_FK_IK_Arm_R
    Select_Arm = cmds.select('J_Arm_Neutral_R', 'J_ForeArm_Neutral_R',
                             'J_Hand_Neutral_R')
    sel = cmds.ls(sl=True)

    def Clear_Select():
        cmds.select(cl=True)

    Clear_Select()
    MD_switch_fk_ik = cmds.shadingNode("multiplyDivide",
                                       asUtility=True,
                                       n="MD_Arm_Switch_FK_IK_R")
    cmds.setAttr(MD_switch_fk_ik + '.operation', 2)
    cmds.setAttr(MD_switch_fk_ik + '.input2X', 10)
    cmds.connectAttr('R_SwitchArm_CTL.Switch_FK_IK',
                     MD_switch_fk_ik + ".input1X")
    for J in sel:
        N = J.split("_Neutral_R")[0]
        print N
        New_N = N.split("J_")[1]
        BC_rotate = cmds.shadingNode("blendColors",
                                     asUtility=True,
                                     n="BC_" + New_N + "_rotate_R")
        BC_translate = cmds.shadingNode("blendColors",
                                        asUtility=True,
                                        n="BC_" + New_N + "_translate_R")
        cmds.connectAttr(BC_rotate + ".output", J + ".rotate")
        cmds.connectAttr(MD_switch_fk_ik + ".outputX", BC_rotate + ".blender")
        cmds.connectAttr(BC_translate + ".output", J + ".translate")
        cmds.connectAttr(MD_switch_fk_ik + ".outputX",
                         BC_translate + ".blender")
    j_arm_neutral = ('J_Arm_Neutral_R')
    j_forearm_neutral = ('J_ForeArm_Neutral_R')
    jnt_hand_neutral_R = ('J_Hand_Neutral_R')
    JN1 = j_arm_neutral.split("_Neutral_R")[0]
    JN2 = j_forearm_neutral.split("_Neutral_R")[0]
    JN3 = jnt_hand_neutral_R.split("_Neutral_R")[0]
    Milista = []
    list.append(Milista, JN1)
    list.append(Milista, JN2)
    list.append(Milista, JN3)

    def fun1(Var1):
        list.append(Milista, Milista[0] + Var1)
        list.append(Milista, Milista[1] + Var1)
        list.append(Milista, Milista[2] + Var1)

    fun1('_FK_R')
    fun1('_IK_R')

    def fun(Var):
        cmds.connectAttr(Milista[3] + "." + Var, "BC_Arm_" + Var + "_R.color2")
        cmds.connectAttr(Milista[6] + "." + Var, "BC_Arm_" + Var + "_R.color1")
        cmds.connectAttr(Milista[4] + "." + Var,
                         "BC_ForeArm_" + Var + "_R.color2")
        cmds.connectAttr(Milista[7] + "." + Var,
                         "BC_ForeArm_" + Var + "_R.color1")
        cmds.connectAttr(Milista[5] + "." + Var,
                         "BC_Hand_" + Var + "_R.color2")
        cmds.connectAttr(Milista[8] + "." + Var,
                         "BC_Hand_" + Var + "_R.color1")

    fun('rotate')
    fun('translate')
    #Cons_Orient_Ik_Hand_J_Hand_R
    cmds.duplicate('J_Hand_IK_R', n='Eff_J_Hand_IK_R')
    cmds.move(Scale_Guide * (-2),
              0,
              0,
              'Eff_J_Hand_IK_R',
              r=True,
              os=True,
              wd=True)
    cmds.parent('Eff_J_Hand_IK_R', 'J_Hand_IK_R')
    cmds.ikHandle(n='IkHandle_Wrist_R',
                  sj='J_Hand_IK_R',
                  ee='Eff_J_Hand_IK_R',
                  sol='ikSCsolver')
    cmds.parent('IkHandle_Wrist_R', 'R_IK_Arm_CTL')
    cmds.hide('IkHandle_Wrist_R')
    cmds.select(cl=True)
    Parent_Cons_FK_Ctrl_J_Ik_Arm = cmds.parentConstraint('R_FK_Arm_CTL',
                                                         'J_Arm_IK_R',
                                                         mo=True)
    Herarchy_Switch_Arm_R_J_Hand_Neutral_R = cmds.parent(
        'P_R_SwitchArm_CTL', 'J_Hand_Neutral_R')
    translate_J_ForeArm_Ik_R = cmds.xform('J_ForeArm_IK_R',
                                          ws=True,
                                          q=True,
                                          t=True)
    translate_Ctrl_Polevector_Arm_R = cmds.xform('R_PolevectorArm_CTL',
                                                 ws=True,
                                                 q=True,
                                                 t=True)
    #CVPv_IK_R#
    Cv_Polevector_Arm_R = cmds.curve(n='Cv_Polevector_Arm_R',
                                     d=1,
                                     p=[(translate_J_ForeArm_Ik_R),
                                        (translate_Ctrl_Polevector_Arm_R)],
                                     k=(0, 1))
    Z_Cvv_Polevector_Arm_R = cmds.group(n=("Z_Cv_Polevector_Arm_R"), em=True)
    Herarchy_CV_Grp = cmds.parent('Cv_Polevector_Arm_R',
                                  "Z_Cv_Polevector_Arm_R")
    lineWidth_Cv_Polevector_Arm_R = cmds.setAttr(
        Cv_Polevector_Arm_R + ".lineWidth", 2)
    OvE_Cv_Polevector_Arm_R = cmds.setAttr(
        Cv_Polevector_Arm_R + ".overrideEnabled", 1)
    OvDT_Cv_Polevector_Arm_R = cmds.setAttr(
        Cv_Polevector_Arm_R + ".overrideDisplayType", 2)
    cmds.select(d=True)
    J_CV_0_ARM_R = cmds.joint(p=translate_J_ForeArm_Ik_R, n="J_Cv_0_Arm_R")
    Grp_J_CV_0_ARM_R = cmds.group(n='Z_J_Cv_0_Arm_R')
    cmds.select(d=True)
    J_CV_1_ARM_R = cmds.joint(p=translate_Ctrl_Polevector_Arm_R,
                              n="J_Cv_1_Arm_R")
    Grp_J_CV_1_ARM_R = cmds.group(n='Z_J_Cv_1_Arm_R')
    cmds.select(d=True)
    Skin_J_Cvs = cmds.skinCluster('J_Cv_0_Arm_R',
                                  'J_Cv_1_Arm_R',
                                  'Cv_Polevector_Arm_R',
                                  dr=4)
    Parent_J_CV_Arm_R_J_ForeArm_IK_R = cmds.parent(Grp_J_CV_0_ARM_R,
                                                   'J_ForeArm_IK_R')
    Parent_J_CV_Arm_R_J_ForeArm_IK_R = cmds.parent(Grp_J_CV_1_ARM_R,
                                                   'R_PolevectorArm_CTL')
    cmds.select(d=True)
    #Create Node_Vis_Arm_R#
    Node_Reverse_Vis_Arm_R = cmds.shadingNode('reverse',
                                              au=True,
                                              n='R_Vis_Arm_R')
    Node_MD_Vis_Arm_R = cmds.shadingNode('multiplyDivide',
                                         au=True,
                                         n='MD_Vis_Arm_R')
    Operation_MD_Vis_Arm_R = cmds.setAttr(Node_MD_Vis_Arm_R + '.operation',
                                          2,
                                          k=True)
    Set_2X_Node_MD_Vis_Arm_R = cmds.setAttr(Node_MD_Vis_Arm_R + '.input2X',
                                            10,
                                            k=True)
    #Conect Vis_Arm_R#
    Switch_MD_Arm_R = cmds.connectAttr('R_SwitchArm_CTL.Switch_FK_IK',
                                       Node_MD_Vis_Arm_R + '.input1X')
    MD_R_Arm_R = cmds.connectAttr(Node_MD_Vis_Arm_R + '.outputX',
                                  Node_Reverse_Vis_Arm_R + '.inputX')
    R_Ctrl_FK_Arm_R = cmds.connectAttr(Node_Reverse_Vis_Arm_R + '.outputX',
                                       'P_R_FK_ForeArm_CTL.visibility')
    R_J_FK_Arm_R = cmds.connectAttr(Node_Reverse_Vis_Arm_R + '.outputX',
                                    'P_J_Arm_FK_R.visibility')
    MD_Ctrl_IK_Arm_R = cmds.connectAttr(Node_MD_Vis_Arm_R + '.outputX',
                                        'P_R_IK_Arm_CTL.visibility')
    MD_PV_IK_Arm_R = cmds.connectAttr(Node_MD_Vis_Arm_R + '.outputX',
                                      'R_PolevectorArm_CTL.visibility')
    MD_CV_PV_IK_Arm_R = cmds.connectAttr(Node_MD_Vis_Arm_R + '.outputX',
                                         'Z_Cv_Polevector_Arm_R.visibility')
    MD_J_IK_Arm_R = cmds.connectAttr(Node_MD_Vis_Arm_R + '.outputX',
                                     'P_J_Arm_IK_R.visibility')
Exemple #35
0
def build(startJoint,
          endJoint,
          clavOrient='',
          ctrlRotate=(0, 0, 0),
          prefix=''):
    '''
	@param startJoint: Clavicle start joint
	@type startJoint: str
	@param endJoint: Clavicle end joint
	@type endJoint: str
	@param scaleAttr: Global character scale attribute
	@type scaleAttr: str
	@param clavOrient: Clavicle orient transform
	@type clavOrient: str
	@param clavOrient: Rotate clavicle control shape
	@type clavOrient: list or tuple
	@param prefix: Name prefix for new nodes
	@type prefix: str
	'''

    # ==========
    # - Checks -
    # ==========

    if not mc.objExists(startJoint):
        raise Exception('Start joint "' + startJoint + '" does not exist!')
    if not mc.objExists(endJoint):
        raise Exception('End joint "' + endJoint + '" does not exist!')
    if clavOrient and not mc.objExists(clavOrient):
        raise Exception('Clavicle orient transform "' + clavOrient +
                        '" does not exist!')

    # ======================
    # - Configure Clavicle -
    # ======================

    scaleAxis = 'x'

    rotateCtrlScale = 0.5
    transCtrlScale = 0.2

    blendAttr = 'stretchToControl'

    # ==========================
    # - Build Module Structure -
    # ==========================

    # Create control group
    ctrl_grp = mc.group(em=True, n=prefix + '_ctrl_grp', w=True)

    # Create rig group
    rig_grp = mc.group(em=True, n=prefix + '_rig_grp', w=True)

    # Create skel group
    skel_grp = mc.group(em=True, n=prefix + '_skel_grp', w=True)

    # Create module group
    module = mc.group(em=True, n=prefix + '_module')
    mc.parent([ctrl_grp, rig_grp, skel_grp], module)

    # - Uniform Scale -
    mc.addAttr(module, ln='uniformScale', min=0.001, dv=1.0)
    mc.connectAttr(module + '.uniformScale', ctrl_grp + '.scaleX')
    mc.connectAttr(module + '.uniformScale', ctrl_grp + '.scaleY')
    mc.connectAttr(module + '.uniformScale', ctrl_grp + '.scaleZ')
    mc.connectAttr(module + '.uniformScale', skel_grp + '.scaleX')
    mc.connectAttr(module + '.uniformScale', skel_grp + '.scaleY')
    mc.connectAttr(module + '.uniformScale', skel_grp + '.scaleZ')

    # =======================
    # - Create Attach Joint -
    # =======================

    mc.select(cl=True)

    # Attach joint
    attachJoint = mc.joint(n=prefix + '_attachA_jnt')
    attachJointGrp = glTools.utils.joint.group(attachJoint)

    # Attach joint display
    mc.setAttr(attachJoint + '.overrideEnabled', 1)
    mc.setAttr(attachJoint + '.overrideLevelOfDetail', 1)

    # Parent Attach Joint
    mc.parent(attachJointGrp, skel_grp)

    # =========================
    # - Create Clavicle Joint -
    # =========================

    # Add start joint buffer
    startJointGrp = glTools.utils.joint.group(startJoint)
    mc.delete(mc.pointConstraint(startJointGrp, attachJointGrp))
    mc.parentConstraint(attachJoint, ctrl_grp, mo=True)
    mc.parent(startJointGrp, attachJoint)

    # ===================
    # - Create Controls -
    # ===================

    # Initialize control builder
    ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder()

    # Calculate joint length
    jntLen = glTools.utils.joint.length(startJoint)

    # Rotate control
    clavRotateCtrl = mc.group(em=True, n=prefix + '_rot_ctrl')
    if clavOrient: mc.delete(mc.orientConstraint(clavOrient, clavRotateCtrl))
    clavRotateCtrlShape = glTools.tools.controlBuilder.controlShape(
        clavRotateCtrl,
        'anchor',
        rotate=ctrlRotate,
        scale=jntLen * rotateCtrlScale,
        orient=False)
    clavRotateCtrlGrp = glTools.utils.base.group(clavRotateCtrl,
                                                 name=prefix + '_rot_ctrlGrp')
    glTools.rig.utils.tagCtrl(clavRotateCtrl, 'primary')

    # Translate control
    clavTransCtrl = ctrlBuilder.create('box',
                                       prefix + '_trans_ctrl',
                                       scale=jntLen * transCtrlScale)
    clavTransCtrlGrp = glTools.utils.base.group(clavTransCtrl,
                                                name=prefix + '_trans_ctrlGrp')
    glTools.rig.utils.tagCtrl(clavTransCtrl, 'primary')

    # Position Controls
    pt = glTools.utils.base.getPosition(startJoint)
    mc.move(pt[0], pt[1], pt[2], clavRotateCtrlGrp, ws=True, a=True)
    pt = glTools.utils.base.getPosition(endJoint)
    mc.move(pt[0], pt[1], pt[2], clavTransCtrlGrp, ws=True, a=True)

    # Parent Controls
    mc.parent(clavTransCtrlGrp, clavRotateCtrl)
    mc.parent(clavRotateCtrlGrp, ctrl_grp)

    # Constrain to Control
    mc.pointConstraint(clavRotateCtrl, startJoint)

    # =====================
    # - Build Clavicle IK -
    # =====================

    # Create ikHandle
    clavIk = glTools.tools.ikHandle.build(startJoint,
                                          endJoint,
                                          solver='ikSCsolver',
                                          prefix=prefix)

    # Parent ikHandle
    clavIkGrp = glTools.utils.base.group(clavIk, name=prefix + '_ikHandle_grp')
    mc.parent(clavIkGrp, clavTransCtrl)
    mc.setAttr(clavIkGrp + '.v', 0)

    # Create stretchy IK
    clavStretch = glTools.tools.stretchyIkChain.build(
        clavIk,
        scaleAxis=scaleAxis,
        scaleAttr=module + '.uniformScale',
        blendControl=clavTransCtrl,
        blendAttr=blendAttr,
        shrink=True,
        prefix=prefix)
    mc.setAttr(clavTransCtrl + '.' + blendAttr, 0.0)

    # ======================
    # - Set Channel States -
    # ======================

    chStateUtil = glTools.utils.channelState.ChannelState()
    chStateUtil.setFlags([0, 0, 0, 0, 0, 0, 2, 2, 2, 1],
                         objectList=[clavRotateCtrl])
    chStateUtil.setFlags([0, 0, 0, 2, 2, 2, 2, 2, 2, 1],
                         objectList=[clavTransCtrl])
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=[clavRotateCtrlGrp, clavTransCtrlGrp])
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=[clavIk, clavIkGrp])
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=[endJoint, startJointGrp])
    chStateUtil.setFlags([1, 1, 1, 1, 1, 1, 1, 2, 2, 1],
                         objectList=[startJoint])
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=[attachJointGrp])
    chStateUtil.setFlags([1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                         objectList=[attachJoint])
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=[module, ctrl_grp, rig_grp, skel_grp])

    # =================
    # - Return Result -
    # =================

    # Define control list
    ctrlList = [clavRotateCtrl, clavTransCtrl]

    return [module, attachJoint]
Exemple #36
0
def Controllers():
    charName = cmds.textFieldGrp(NameInput, q=True, text=True)
    lengthY = locXYZ[1][1] - locXYZ[0][1]
    lengthZ = abs(locXYZ[0][2]) + abs(locXYZ[1][2])
    legY = locXYZ[0][1] - locXYZ[5][1]
    side = ['_L_', '_R_']
    nb = [1, -1]
    for i in range(len(side)):
        cmds.ikHandle(n=charName + '_Leg' + side[i] + 'ikHandle',
                      sj=charName + side[i] + 'thigh_Jnt_01',
                      ee=charName + side[i] + 'ankie_Jnt_01')
        cmds.spaceLocator(n=charName + '_poleVector' + side[i] + 'leg',
                          p=(nb[i] * locXYZ[4][0] - legY * 0.005,
                             locXYZ[4][1] + legY * 0.05, locXYZ[4][2]))
        cmds.xform(centerPivots=1)
        # aims the pole vector of 1 at 2.
        cmds.poleVectorConstraint(charName + '_poleVector' + side[i] + 'leg',
                                  charName + '_Leg' + side[i] + 'ikHandle')
        cmds.move(nb[i] * lengthY * 0.75,
                  -lengthY * 0.75,
                  charName + '_poleVector' + side[i] + 'leg',
                  moveXY=True)
        cmds.setAttr(charName + '_Leg' + side[i] + 'ikHandle.twist',
                     nb[i] * 90)
        cmds.ParentConstraint(charName + 'controllerfoot',
                              charName + '_poleVector' + side[i] + 'leg')
        cmds.parent(charName + '_poleVector' + side[i] + 'leg',
                    charName + '_Leg' + side[i] + 'ikHandle',
                    relative=True)
        cmds.ikHandle(n=charName + '_Foot' + side[i] + 'ball_ikHandle',
                      sj=charName + side[i] + 'ankie' + '_Jnt_01',
                      ee=charName + side[i] + 'ball' + '_Jnt_01')
        cmds.ikHandle(n=charName + '_Foot' + side[i] + 'toe_ikHandle',
                      sj=charName + side[i] + 'ball' + '_Jnt_01',
                      ee=charName + side[i] + 'toe' + '_Jnt_01')
        cmds.group(charName + '_Leg' + side[i] + 'ikHandle',
                   n=charName + '_Foot' + side[i] + 'heelPeel')
        #change pivot position
        Xpos = cmds.getAttr(charName + '_Foot' + side[i] +
                            'ball_ikHandle.translateX')
        Ypos = cmds.getAttr(charName + '_Foot' + side[i] +
                            'ball_ikHandle.translateY')
        Zpos = cmds.getAttr(charName + '_Foot' + side[i] +
                            'ball_ikHandle.translateZ')
        cmds.move(Xpos,
                  Ypos,
                  Zpos,
                  charName + '_Foot' + side[i] + 'heelPeel.scalePivot',
                  charName + '_Foot' + side[i] + 'heelPeel.rotatePivot',
                  absolute=True)
        cmds.group(charName + '_Foot' + side[i] + 'ball_ikHandle',
                   charName + '_Foot' + side[i] + 'toe_ikHandle',
                   n=charName + '_Foot' + side[i] + 'toeTap')
        cmds.move(Xpos,
                  Ypos,
                  Zpos,
                  charName + '_Foot' + side[i] + 'toeTap.scalePivot',
                  charName + '_Foot' + side[i] + 'toeTap.rotatePivot',
                  absolute=True)
        cmds.group(charName + '_Foot' + side[i] + 'ball_ikHandle',
                   charName + '_Foot' + side[i] + 'toeTap',
                   n=charName + '_Foot' + side[i] + 'TipToe')
        cmds.group(n=charName + '_Foot' + side[i] + '1', em=True)
        cmds.parent(charName + '_Foot' + side[i] + 'heelPeel',
                    charName + '_Foot' + side[i] + 'TipToe',
                    charName + '_Foot' + side[i] + '1',
                    relative=True)
        cmds.move(Xpos,
                  Ypos,
                  Zpos,
                  charName + '_Foot' + side[i] + '1.scalePivot',
                  charName + '_Foot' + side[i] + '1.rotatePivot',
                  absolute=True)
        Xpos = cmds.getAttr(charName + '_Foot' + side[i] +
                            'ball_ikHandle.translateX')
        Ypos = cmds.getAttr(charName + '_Foot' + side[i] +
                            'ball_ikHandle.translateY')
        Zpos = cmds.getAttr(charName + '_Foot' + side[i] +
                            'ball_ikHandle.translateZ')
        CreateCtr(charName + '_Foot' + side[i] + 'Crl',
                  charName + '_Foot' + side[i] + '1', (Xpos, Ypos, Zpos),
                  (lengthY / 60 * 10, lengthY / 60 * 10, lengthY / 60 * 16),
                  (0, 0, 0))
    #left Arm
    for i in range(len(side)):
        cmds.ikHandle(n=charName + '_Arm' + str(side[i]) + 'ikHandle',
                      sj=charName + str(side[i]) + 'shoulder' + '_Jnt_02',
                      ee=charName + str(side[i]) + 'wrist' + '_Jnt_01')
        cmds.CreateNURBSCircle()
        cmds.rename('nurbsCircle1', charName + '_Elbow' + str(side[i]) + 'Crl')
        cmds.move(nb[i] * locXYZ[2][0], locXYZ[2][1], locXYZ[2][2] * 30)
        cmds.scale(2, 2, 3)
        cmds.rotate(90, 0, 0)
        cmds.move(nb[i] * locXYZ[2][0],
                  locXYZ[2][1],
                  locXYZ[2][2],
                  charName + '_Elbow' + str(side[i]) + 'Crl.scalePivot',
                  charName + '_Elbow' + str(side[i]) + 'Crl.rotatePivot',
                  absolute=True)
        cmds.makeIdentity(apply=True)
        cmds.xform(centerPivots=1)
        cmds.poleVectorConstraint(
            charName + '_Elbow' + str(side[i]) + 'Crl',
            charName + '_Arm' + str(side[i]) + 'ikHandle')
        #left Arm controller
        CreateCtr(charName + '_Arm' + side[i] + 'Crl',
                  charName + '_Arm' + side[i] + 'ikHandle',
                  (nb[i] * locXYZ[3][0], locXYZ[3][1], locXYZ[3][2]),
                  (lengthY / 60 * 5, lengthY / 60 * 5, lengthY / 60 * 8),
                  (0, 0, nb[i] * 30))
    #spline
    cmds.parent(charName + '_R_shoulder_Jnt_01', w=True)
    cmds.parent(charName + '_L_shoulder_Jnt_01', w=True)
    cmds.select(d=True)
    cmds.select(charName + '_spline_Jnt_03')
    cmds.DisconnectJoint(charName + '_spline_Jnt_03')
    cmds.rename(charName + '_spline_Jnt_03', charName + '_neck_Jnt_00')
    cmds.rename('joint1', charName + '_spline_Jnt_03')
    cmds.rename(charName + '_root' + '_Jnt_01', charName + '_spline_Jnt_00')
    cmds.parent(charName + '_R_hip_Jnt_01', w=True)
    cmds.parent(charName + '_L_hip_Jnt_01', w=True)
    cmds.select(d=True)
    cmds.joint(p=(locXYZ[0][0], locXYZ[0][1], locXYZ[0][2]),
               n=charName + '_root' + '_Jnt_01')
    cmds.parent(charName + '_L_hip_Jnt_01')
    cmds.select(charName + '_root' + '_Jnt_01')
    cmds.parent(charName + '_R_hip_Jnt_01')
    cmds.curve(n=charName + '_SplineIK_Crv_01',
               p=[(locXYZ[0][0], locXYZ[0][1], locXYZ[0][2]),
                  (0.0, locXYZ[0][1] + lengthY * 0.43,
                   locXYZ[0][2] + lengthZ * 0.43),
                  (0.0, locXYZ[0][1] + lengthY * 0.8,
                   locXYZ[0][2] + lengthZ * 0.18),
                  (locXYZ[1][0], locXYZ[1][1], locXYZ[1][2])])
    cmds.ikHandle(n=charName + 'SplineIK_01',
                  sj=charName + '_spline_Jnt_00',
                  ee=charName + '_spline_Jnt_03',
                  curve=charName + '_SplineIK_Crv_01',
                  sol='ikSplineSolver',
                  createCurve=False,
                  parentCurve=False)
    for i in range(4):
        cmds.select(charName + '_SplineIK_Crv_01' + '.cv[' + str(i) + ']')
        cmds.cluster(n='cluster_' + str(i + 1))
    CreateCtr(charName + '_Spline_Ctrl_01', 'cluster_1Handle',
              (0, locXYZ[0][1] * 1.05, 0),
              (lengthY / 60 * 25, lengthY / 60 * 25, lengthY / 60 * 25),
              (0, 0, 0))
    cmds.parentConstraint(charName + '_Spline_Ctrl_01',
                          charName + '_root_Jnt_01',
                          maintainOffset=True)
    CreateCtr(charName + '_Chest_Ctrl_01', 'cluster_4Handle',
              (0, locXYZ[1][1], 0),
              (lengthY / 60 * 25, lengthY / 60 * 25, lengthY / 60 * 25),
              (0, 0, 0))
    for i in range(len(side)):
        cmds.parentConstraint(charName + '_Chest_Ctrl_01',
                              charName + side[i] + 'shoulder_Jnt_01',
                              maintainOffset=True)
        cmds.parent(charName + '_Arm' + side[i] + 'Crl_grp',
                    charName + '_Chest_Ctrl_01')
        cmds.parent(charName + '_Elbow' + side[i] + 'Crl',
                    charName + '_Chest_Ctrl_01')
    CreateCtr(charName + '_Chest_Ctrl_02', 'cluster_2Handle',
              (0, (locXYZ[0][1] + locXYZ[1][1]) / 2, 0),
              (lengthY / 60 * 20, lengthY / 60 * 20, lengthY / 60 * 20),
              (0, 0, 0))
    cmds.parentConstraint(charName + '_Chest_Ctrl_01',
                          charName + '_neck_Jnt_00',
                          maintainOffset=True,
                          w=1)
    cmds.parentConstraint(charName + '_Chest_Ctrl_01',
                          'cluster_3Handle',
                          maintainOffset=True,
                          weight=0.5)
    cmds.parentConstraint(charName + '_Chest_Ctrl_01',
                          charName + '_Chest_Ctrl_02_grp',
                          maintainOffset=True,
                          weight=0.5)
    cmds.parentConstraint(charName + '_Spline_Ctrl_01',
                          charName + '_Chest_Ctrl_02_grp',
                          maintainOffset=True,
                          weight=0.5)
    cmds.CreateNURBSCircle()
    cmds.rename('nurbsCircle1', charName + '_Hip_Ctrl_01')
    cmds.move(0, locXYZ[0][1], 0)
    cmds.scale(lengthY / 60 * 30, lengthY / 60 * 30, lengthY / 60 * 30)
    cmds.makeIdentity(apply=True)
    cmds.parentConstraint(charName + '_Hip_Ctrl_01',
                          charName + '_Spline_Ctrl_01',
                          maintainOffset=True,
                          weight=0.5)
    cmds.parentConstraint(charName + '_Hip_Ctrl_01',
                          charName + '_Chest_Ctrl_01',
                          maintainOffset=True,
                          weight=0.5)
    #clean
    for i in range(len(side)):
        cmds.parent(charName + side[i] + 'shoulder_Jnt_01',
                    charName + '_Joints_01')
        cmds.parent(charName + '_Chest_Ctrl_0' + str(i + 1) + '_grp',
                    charName + '_Controls_01')
        cmds.parent(charName + '_Foot' + side[i] + '1',
                    charName + '_Controls_01')
        cmds.parent(charName + '_Foot' + side[i] + 'Crl_grp',
                    charName + '_Controls_01')
        cmds.parent(charName + '_Arm' + side[i] + 'ikHandle',
                    charName + '_ikHandle_01')
        cmds.parent('cluster_' + str(i + 1) + 'Handle',
                    charName + '_ikHandle_01')
        cmds.parent('cluster_' + str(i + 3) + 'Handle',
                    charName + '_ikHandle_01')
    cmds.parent(charName + 'SplineIK_01', charName + '_ikHandle_01')
    cmds.parent(charName + '_SplineIK_Crv_01', charName + '_ikHandle_01')
    cmds.parent(charName + '_neck_Jnt_00', charName + '_Joints_01')
    cmds.parent(charName + '_root_Jnt_01', charName + '_Joints_01')
    cmds.parent(charName + '_spline_Jnt_00', charName + '_Joints_01')
    cmds.parent(charName + '_Spline_Ctrl_01_grp', charName + '_Controls_01')
    cmds.parent(charName + '_Hip_Ctrl_01', charName + '_Controls_01')
Exemple #37
0
def CreateJoints():
    charName = cmds.textFieldGrp(NameInput, q=True, text=True)
    if charName == "":
        print("Write your character name")
    else:
        #Create directory
        listDirectory = [['_Joints_', '_Controls_', '_ikHandle_'],
                         '_GlobalControl_', '_Geo_']
        cmds.group(em=True, n=charName + '_Main_01')
        for i in range(len(listDirectory) - 1):
            cmds.group(em=True, n=charName + listDirectory[i + 1] + '01')
            cmds.parent(charName + listDirectory[i + 1] + '01',
                        charName + '_Main_01')
        for i in range(len(listDirectory[0])):
            cmds.group(em=True, n=charName + listDirectory[0][i] + '01')
            cmds.parent(charName + listDirectory[0][i] + '01',
                        charName + listDirectory[1] + '01')
        cmds.select(d=True)
        global locXYZ
        locXYZ = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0],
                  [0, 0, 0]]
        for i in range(len(list)):
            locXYZ[i][0] = cmds.getAttr('Loc_' + list[i] + '.translateX')
            print('translateX calcule done')
            locXYZ[i][1] = cmds.getAttr('Loc_' + list[i] + '.translateY')
            print('translateY calcule done')
            locXYZ[i][2] = cmds.getAttr('Loc_' + list[i] + '.translateZ')
            print('translateZ calcule done')
        #total length between root and neck
        lengthY = locXYZ[1][1] - locXYZ[0][1]
        lengthZ = abs(locXYZ[0][2]) + abs(locXYZ[1][2])
        #length between root and toe
        legY = locXYZ[0][1] - locXYZ[5][1]
        lengthY = locXYZ[1][1] - locXYZ[0][1]
        lengthZ = abs(locXYZ[0][2]) + abs(locXYZ[1][2])
        #length between root and toe
        legY = locXYZ[0][1] - locXYZ[5][1]
        cmds.joint(p=(locXYZ[0][0], locXYZ[0][1], locXYZ[0][2]),
                   n=charName + '_root' + '_Jnt_01')

        def PlaceJoint(OrientThisJoint, x, y, z, jointName, o):
            cmds.joint(p=(x, y, z), n=jointName)
            cmds.joint(OrientThisJoint,
                       e=True,
                       zso=True,
                       oj='xyz',
                       sao=o + 'up')

        #place spline-head joint
        PlaceJoint(charName + '_root' + '_Jnt_01', 0,
                   locXYZ[0][1] + lengthY * 0.43,
                   locXYZ[0][2] + lengthZ * 0.43,
                   charName + '_spline' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_spline' + '_Jnt_01', 0,
                   locXYZ[0][1] + lengthY * 0.8, locXYZ[0][2] + lengthZ * 0.18,
                   charName + '_spline' + '_Jnt_02', 'x')
        PlaceJoint(charName + '_spline' + '_Jnt_02', locXYZ[1][0],
                   locXYZ[1][1], locXYZ[1][2],
                   charName + '_spline' + '_Jnt_03', 'x')
        PlaceJoint(charName + '_spline' + '_Jnt_03', locXYZ[1][0],
                   locXYZ[1][1] + lengthY * 0.1, locXYZ[1][2] + lengthY * 0.05,
                   charName + '_neck' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_neck' + '_Jnt_01',
                   (locXYZ[1][0] + locXYZ[1][0]) / 2,
                   locXYZ[1][1] + lengthY / 4,
                   (locXYZ[1][2] + locXYZ[0][2] + lengthY * 0.15) / 2,
                   charName + '_jaw' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_jaw' + '_Jnt_01',
                   (locXYZ[1][0] + locXYZ[1][0]) / 4,
                   locXYZ[1][1] + lengthY / 2.8,
                   (locXYZ[1][2] + locXYZ[0][2] + lengthY * 0.15) / 2,
                   charName + '_eye' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_eye' + '_Jnt_01', 0,
                   locXYZ[1][1] + lengthY / 1.8, locXYZ[0][2] + lengthY * 0.03,
                   charName + '_head' + '_Jnt_01', 'x')
        cmds.joint(charName + '_head' + '_Jnt_01',
                   e=True,
                   oj='none',
                   ch=True,
                   zso=True)

        #place arm joint
        cmds.select(d=True)
        cmds.joint(charName + '_spline' + '_Jnt_03',
                   p=(locXYZ[0][0] + lengthY * 0.1, locXYZ[1][1],
                      locXYZ[0][2] + lengthZ * 0.1),
                   n=charName + '_L' + '_shoulder' + '_Jnt_01')
        PlaceJoint(charName + '_L' + '_shoulder' + '_Jnt_01',
                   locXYZ[0][0] + lengthY * 0.24,
                   locXYZ[1][1] - lengthY * 0.05, locXYZ[0][2] - lengthZ * 0.2,
                   charName + '_L' + '_shoulder' + '_Jnt_02', 'y')
        PlaceJoint(
            charName + '_L' + '_shoulder' + '_Jnt_02',
            (locXYZ[0][0] + lengthY * 0.24 + locXYZ[2][0] - lengthZ * 0.1) / 2,
            (locXYZ[1][1] - lengthY * 0.05 + locXYZ[2][1] + lengthZ * 0.1) / 2,
            (locXYZ[0][2] - lengthZ * 0.2 + locXYZ[2][2]) / 2,
            charName + '_L' + '_arm' + '_Jnt_01', 'y')
        PlaceJoint(charName + '_L' + '_arm' + '_Jnt_01',
                   locXYZ[2][0] - lengthZ * 0.1, locXYZ[2][1] + lengthZ * 0.1,
                   locXYZ[2][2], charName + '_L' + '_arm' + '_Jnt_02', 'y')
        PlaceJoint(charName + '_L' + '_arm' + '_Jnt_02',
                   locXYZ[2][0] + lengthZ * 0.1, locXYZ[2][1] - lengthZ * 0.1,
                   locXYZ[2][2], charName + '_L' + '_arm' + '_Jnt_03', 'y')
        PlaceJoint(charName + '_L' + '_arm' + '_Jnt_03',
                   (locXYZ[2][0] + lengthZ * 0.1 + locXYZ[3][0]) / 2,
                   (locXYZ[2][1] - lengthZ * 0.1 + locXYZ[3][1]) / 2,
                   (locXYZ[2][2] + locXYZ[3][2]) / 2,
                   charName + '_L' + '_arm' + '_Jnt_04', 'y')
        PlaceJoint(charName + '_L' + '_arm' + '_Jnt_04', locXYZ[3][0],
                   locXYZ[3][1], locXYZ[3][2],
                   charName + '_L' + '_wrist' + '_Jnt_01', 'y')
        PlaceJoint(charName + '_L' + '_wrist' + '_Jnt_01', locXYZ[3][0],
                   locXYZ[3][1] + lengthY * -0.20, locXYZ[3][2],
                   charName + '_L' + '_hand' + '_Jnt_01', 'y')
        cmds.joint(charName + '_L' + '_hand' + '_Jnt_01',
                   e=True,
                   oj='none',
                   ch=True,
                   zso=True)

        #place leg joint
        cmds.select(d=True)
        cmds.joint(charName + '_root' + '_Jnt_01',
                   p=(locXYZ[0][0] + lengthY * 0.08, locXYZ[0][1],
                      locXYZ[0][2] - lengthZ / 3.9),
                   n=charName + '_L' + '_hip' + '_Jnt_01')
        PlaceJoint(charName + '_L' + '_hip' + '_Jnt_01',
                   locXYZ[0][0] + lengthY * 0.21, locXYZ[0][1] + legY * 0.03,
                   locXYZ[0][2] - lengthZ / 1.86,
                   charName + '_L' + '_thigh' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_L' + '_thigh' + '_Jnt_01',
                   locXYZ[4][0] - legY * 0.005, locXYZ[4][1] + legY * 0.05,
                   locXYZ[4][2], charName + '_L' + '_knee' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_L' + '_knee' + '_Jnt_01',
                   locXYZ[4][0] + legY * 0.005, locXYZ[4][1] - legY * 0.05,
                   locXYZ[4][2] - legY * 0.03,
                   charName + '_L' + '_knee' + '_Jnt_02', 'x')
        PlaceJoint(
            charName + '_L' + '_knee' + '_Jnt_02',
            locXYZ[5][0] - locXYZ[4][0] * 0.3,
            locXYZ[5][1] + locXYZ[4][1] * 0.17,
            locXYZ[4][2] - legY * 0.03 - (locXYZ[5][2] - locXYZ[4][2]) / 6,
            charName + '_L' + '_ankie' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_L' + '_ankie' + '_Jnt_01',
                   (locXYZ[5][0] - locXYZ[4][0] * 0.3 + locXYZ[5][0]) / 2,
                   locXYZ[5][1], locXYZ[4][2] + locXYZ[5][2] / 1.9,
                   charName + '_L' + '_ball' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_L' + '_ball' + '_Jnt_01', locXYZ[5][0],
                   locXYZ[5][1], locXYZ[5][2],
                   charName + '_L' + '_toe' + '_Jnt_01', 'x')
        cmds.joint(charName + '_L' + '_toe' + '_Jnt_01',
                   e=True,
                   oj='none',
                   ch=True,
                   zso=True)
Exemple #38
0
def createRig(upperVertexList,
              lowerVertexList,
              prefix='L_',
              rigPartName='EyeLid',
              rigScale=1.0,
              eyeJoint='',
              numCtrl=5,
              ):

    if numCtrl < 3:
        cmds.error('numCtrl must bigger than 3!')
        return
    cmds.select(cl=1)
    # create eyeLid Module
    eyeLidRigModule = module.Module(prefix=prefix, rigPartName=rigPartName)

    # create upper eyelid Module
    upperLidRigModule = module.Module(prefix=prefix, rigPartName='upper_' + rigPartName)

    #####################
    # Upper Eyelid Part #
    #####################

    # create eyelid joint for each vertex
    upperEyeLidJointList = lib.vertex2Joints(vertexList=upperVertexList, prefix=prefix,
                                             rigPartName='upper_' + rigPartName, radius=0.05)

    # connect attr
    for joint in upperEyeLidJointList:
        if cmds.attributeQuery('slaveJoint', node=joint, exists=1):
            cmds.connectAttr(upperLidRigModule.topGrp + '.slaveJoint', joint + '.slaveJoint', f=1)

    # create eyelid parent joint for each eyelid joint
    upperEyeLidParentJntList = []
    for i in upperEyeLidJointList:
        cmds.select(cl=1)

        parentJoint = cmds.joint(n=i + '_Parent', radius=0.05)

        cmds.delete(cmds.pointConstraint(eyeJoint, parentJoint, mo=0))

        cmds.delete(cmds.aimConstraint(i, parentJoint, aimVector=(1, 0, 0), upVector=(0, -1, 0),
                                       worldUpType='scene', weight=1, offset=(0, 0, 0), mo=0))
        cmds.parent(i, parentJoint)

        cmds.joint(i, e=1, oj='none', ch=1, zso=1)

        cmds.makeIdentity(parentJoint, apply=1, t=1, r=1, s=1)

        upperEyeLidParentJntList.append(parentJoint)

    cmds.select(cl=1)

    upperEyelidLocList = []
    # create locator for each eyelid joint
    for i in upperEyeLidParentJntList:

        cmds.select(cl=1)

        eyelidJoint = cmds.listRelatives(i, c=1, type='joint', shapes=0)[0]

        ikHandle = cmds.ikHandle(n=eyelidJoint + '_IK', sj=i, ee=eyelidJoint, sol='ikSCsolver')

        eyelidLoc = cmds.spaceLocator(n=eyelidJoint + '_LOC')[0]

        cmds.delete(cmds.parentConstraint(eyelidJoint, eyelidLoc, mo=0))

        cmds.select(cl=1)

        cmds.setAttr(ikHandle[0] + '.v', 0)
        LOCShape = cmds.listRelatives(eyelidLoc, p=0, c=1, s=1)[0]
        cmds.setAttr(LOCShape + '.localScaleX', 0.1)
        cmds.setAttr(LOCShape + '.localScaleY', 0.1)
        cmds.setAttr(LOCShape + '.localScaleZ', 0.1)

        cmds.parent(ikHandle[0], eyelidLoc)

        upperEyelidLocList.append(eyelidLoc)

    cmds.select(cl=1)

    # create high definition curve
    lowerPosList = []
    for i in upperEyelidLocList:
        pos = cmds.xform(i, q=1, ws=1, t=1)
        lowerPosList.append(tuple(pos))

    upperKList = []
    for i in xrange(len(lowerPosList)):
        upperKList.append(i)

    upperHighDefCurve = cmds.curve(n=prefix + 'upper_' +rigPartName + '_HD_Crv', p=lowerPosList, k=upperKList, d=1)
    upperLowDefCurve = cmds.duplicate(upperHighDefCurve, n=prefix + 'lower_' + rigPartName + '_LD_Crv')

    upperHighDefCurveShape = cmds.listRelatives(upperHighDefCurve, p=0, c=0, s=1, path=1)[0]
    cmds.select(cl=1)

    # make each locator attach to the curve

    for i in upperEyelidLocList:
        pos = cmds.xform(i, q=1, ws=1, t=1)
        uParam = lib.getUParam(pos, upperHighDefCurveShape)

        PCI = cmds.createNode('pointOnCurveInfo', n=name.removeSuffix(i) + '_PCI')

        cmds.connectAttr(upperHighDefCurveShape + '.worldSpace', PCI + '.inputCurve', f=1)

        cmds.setAttr(PCI + '.parameter', uParam)

        cmds.connectAttr(PCI + '.position', i + '.t')

        cmds.select(cl=1)

    # make HD curve deformed by LD curve
    upperLowDefCurve = cmds.rebuildCurve(upperLowDefCurve, ch=0, rpo=1, rt=0, end=1, kr=0, kcp=0, kep=1, kt=0, s=3, d=3)
    cmds.select(cl=1)

    upperWireDefomer = cmds.wire(upperHighDefCurve, gw=0, en=1, ce=0, li=0, w=upperLowDefCurve)
    upperWireTransNode = cmds.listConnections(upperWireDefomer[0] + '.baseWire[0]', source=1, destination=0)

    cmds.select(cl=1)

    # create control joint and controls for the LD curve
    upperControlJointList = []

    eachADD = 1.0 / (numCtrl - 1)

    for i in xrange(numCtrl):
        newJnt = cmds.joint(n=prefix + 'upper_' + rigPartName + '_CtrlJnt_' + str(i), radius=0.1)
        cmds.select(cl=1)
        motionPath = cmds.pathAnimation(upperLowDefCurve, newJnt, n=prefix + rigPartName + '_MP_' + str(i), fractionMode=1,
                                        follow=1, followAxis='x', upAxis='z', worldUpType='scene',
                                        inverseUp=0, inverseFront=0, bank=0)

        cmds.cutKey(motionPath + '.u', time=())

        cmds.setAttr(motionPath + '.uValue', eachADD * float(i))

        for attr in ['t', 'r']:
            for axis in ['x', 'y', 'z']:
                cmds.delete(newJnt + '.%s%s' % (attr, axis), icn=1)

        cmds.delete(motionPath)
        cmds.select(cl=1)

        upperControlJointList.append(newJnt)

        cmds.setAttr(newJnt + '.r', 0, 0, 0)
        cmds.select(cl=1)

    # bind LD curve by control joint
    cmds.skinCluster(upperControlJointList[:], upperLowDefCurve)
    cmds.select(cl=1)

    upperJntCtrlGrpList = []
    for i in xrange(len(upperControlJointList)):
        ctrl = control.Control(prefix=upperControlJointList[i],
                               rigPartName='',
                               scale=rigScale,
                               shape='circleY',
                               translateTo=upperControlJointList[i],
                               rotateTo=upperControlJointList[i])

        cmds.pointConstraint(ctrl.C, upperControlJointList[i], mo=0)
        cmds.orientConstraint(ctrl.C, upperControlJointList[i], mo=0)

        upperJntCtrlGrpList.append(ctrl.Off)

    cmds.select(cl=1)

    # clean hierarchy
    upperParentJntGrp = cmds.group(n=prefix + 'upper_' + rigPartName + '_skinJnt_Grp', em=1)
    upperLocGrp = cmds.group(n=prefix + 'upper_' + rigPartName + '_LOC_Grp', em=1)
    upperCurveGrp = cmds.group(n=prefix + 'upper_' + rigPartName + '_Crv_Grp', em=1)
    upperCtrlJntGrp = cmds.group(n=prefix + 'upper_' + rigPartName + '_ctrlJnt_Grp', em=1)
    upperCtrlGrp = cmds.group(n=prefix + 'upper_' + rigPartName + '_CtrlGrp', em=1)

    for i in upperEyeLidParentJntList:
        cmds.parent(i, upperParentJntGrp)

    for i in upperEyelidLocList:
        cmds.parent(i, upperLocGrp)

    cmds.parent(upperLowDefCurve, upperCurveGrp)
    cmds.parent(upperHighDefCurve, upperCurveGrp)
    cmds.parent(upperWireTransNode, upperCurveGrp)

    for i in upperControlJointList:
        cmds.parent(i, upperCtrlJntGrp)

    for i in upperJntCtrlGrpList:
        cmds.parent(i, upperCtrlGrp)

    cmds.setAttr(upperLocGrp + '.v', 0)
    cmds.setAttr(upperCurveGrp + '.v', 0)
    cmds.setAttr(upperCtrlJntGrp + '.v', 0)

    cmds.parent(upperParentJntGrp, upperLidRigModule.topGrp)
    cmds.parent(upperLocGrp, upperLidRigModule.topGrp)
    cmds.parent(upperCurveGrp, upperLidRigModule.topGrp)
    cmds.parent(upperCtrlJntGrp, upperLidRigModule.topGrp)
    cmds.parent(upperCtrlGrp, upperLidRigModule.topGrp)

###################################################################################################################

    #####################
    # Lower Eyelid Part #
    #####################
    
    # create lower eyelid Module
    lowerLidRigModule = module.Module(prefix=prefix, rigPartName='lower_' + rigPartName)

    # create eyelid joint for each vertex
    lowerEyeLidJointList = lib.vertex2Joints(vertexList=lowerVertexList, prefix=prefix,
                                             rigPartName='lower_' + rigPartName, radius=0.05)

    # connect attr
    for joint in lowerEyeLidJointList:
        if cmds.attributeQuery('slaveJoint', node=joint, exists=1):
            cmds.connectAttr(lowerLidRigModule.topGrp + '.slaveJoint', joint + '.slaveJoint', f=1)

    # create eyelid parent joint for each eyelid joint
    lowerEyeLidParentJntList = []
    for i in lowerEyeLidJointList:
        cmds.select(cl=1)

        parentJoint = cmds.joint(n=i + '_Parent', radius=0.05)

        cmds.delete(cmds.pointConstraint(eyeJoint, parentJoint, mo=0))

        cmds.delete(cmds.aimConstraint(i, parentJoint, aimVector=(1, 0, 0), upVector=(0, -1, 0),
                                       worldUpType='scene', weight=1, offset=(0, 0, 0), mo=0))
        cmds.parent(i, parentJoint)

        cmds.joint(i, e=1, oj='none', ch=1, zso=1)

        cmds.makeIdentity(parentJoint, apply=1, t=1, r=1, s=1)

        lowerEyeLidParentJntList.append(parentJoint)

    cmds.select(cl=1)

    lowerEyelidLocList = []
    # create locator for each eyelid joint
    for i in lowerEyeLidParentJntList:
        cmds.select(cl=1)

        eyelidJoint = cmds.listRelatives(i, c=1, type='joint', shapes=0)[0]

        ikHandle = cmds.ikHandle(n=eyelidJoint + '_IK', sj=i, ee=eyelidJoint, sol='ikSCsolver')

        eyelidLoc = cmds.spaceLocator(n=eyelidJoint + '_LOC')[0]

        cmds.delete(cmds.parentConstraint(eyelidJoint, eyelidLoc, mo=0))

        cmds.select(cl=1)

        cmds.setAttr(ikHandle[0] + '.v', 0)
        LOCShape = cmds.listRelatives(eyelidLoc, p=0, c=1, s=1)[0]
        cmds.setAttr(LOCShape + '.localScaleX', 0.1)
        cmds.setAttr(LOCShape + '.localScaleY', 0.1)
        cmds.setAttr(LOCShape + '.localScaleZ', 0.1)

        cmds.parent(ikHandle[0], eyelidLoc)

        lowerEyelidLocList.append(eyelidLoc)

    cmds.select(cl=1)

    # create high definition curve
    lowerPosList = []
    for i in lowerEyelidLocList:
        pos = cmds.xform(i, q=1, ws=1, t=1)
        lowerPosList.append(tuple(pos))

    lowerKList = []
    for i in xrange(len(lowerPosList)):
        lowerKList.append(i)

    lowerHighDefCurve = cmds.curve(n=prefix + 'lower_' + rigPartName + '_HD_Crv', p=lowerPosList, k=lowerKList, d=1)
    lowerLowDefCurve = cmds.duplicate(lowerHighDefCurve, n=prefix + 'lower_' + rigPartName + '_LD_Crv')

    lowerHighDefCurveShape = cmds.listRelatives(lowerHighDefCurve, p=0, c=0, s=1, path=1)[0]
    cmds.select(cl=1)

    # make each locator attach to the curve

    for i in lowerEyelidLocList:
        pos = cmds.xform(i, q=1, ws=1, t=1)
        uParam = lib.getUParam(pos, lowerHighDefCurveShape)

        PCI = cmds.createNode('pointOnCurveInfo', n=name.removeSuffix(i) + '_PCI')

        cmds.connectAttr(lowerHighDefCurveShape + '.worldSpace', PCI + '.inputCurve', f=1)

        cmds.setAttr(PCI + '.parameter', uParam)

        cmds.connectAttr(PCI + '.position', i + '.t')

        cmds.select(cl=1)

    # make HD curve deformed by LD curve
    lowerLowDefCurve = cmds.rebuildCurve(lowerLowDefCurve, ch=0, rpo=1, rt=0, end=1, kr=0, kcp=0, kep=1, kt=0, s=3, d=3)
    cmds.select(cl=1)

    lowerWireDefomer = cmds.wire(lowerHighDefCurve, gw=0, en=1, ce=0, li=0, w=lowerLowDefCurve)
    lowerWireTransNode = cmds.listConnections(lowerWireDefomer[0] + '.baseWire[0]', source=1, destination=0)

    cmds.select(cl=1)

    # create control joint and controls for the LD curve
    lowerControlJointList = []

    eachADD = 1.0 / (numCtrl - 1)

    for i in xrange(numCtrl - 2):
        newJnt = cmds.joint(n=prefix + 'lower_' + rigPartName + '_CtrlJnt_' + str(i + 1), radius=0.1)
        cmds.select(cl=1)
        motionPath = cmds.pathAnimation(lowerLowDefCurve, newJnt, n=prefix + rigPartName + '_MP_' + str(i + 1),
                                        fractionMode=1,
                                        follow=1, followAxis='x', upAxis='z', worldUpType='scene',
                                        inverseUp=0, inverseFront=0, bank=0)

        cmds.cutKey(motionPath + '.u', time=())

        cmds.setAttr(motionPath + '.uValue', eachADD * float(i + 1))

        for attr in ['t', 'r']:
            for axis in ['x', 'y', 'z']:
                cmds.delete(newJnt + '.%s%s' % (attr, axis), icn=1)

        cmds.delete(motionPath)
        cmds.select(cl=1)

        lowerControlJointList.append(newJnt)

        cmds.setAttr(newJnt + '.r', 0, 0, 0)
        cmds.select(cl=1)

    lowerControlJointList.insert(0, upperControlJointList[0])
    lowerControlJointList.append(upperControlJointList[-1])

    # bind LD curve by control joint
    cmds.skinCluster(lowerControlJointList[:], lowerLowDefCurve)
    cmds.select(cl=1)

    lowerJntCtrlGrpList = []
    for i in xrange(len(lowerControlJointList[1:-1])):
        ctrl = control.Control(prefix=lowerControlJointList[i+1],
                               rigPartName='',
                               scale=rigScale,
                               shape='circleY',
                               translateTo=lowerControlJointList[i+1],
                               rotateTo=lowerControlJointList[i+1])

        cmds.pointConstraint(ctrl.C, lowerControlJointList[i+1], mo=0)
        cmds.orientConstraint(ctrl.C, lowerControlJointList[i+1], mo=0)

        lowerJntCtrlGrpList.append(ctrl.Off)

    cmds.select(cl=1)

    # clean hierarchy
    lowerParentJntGrp = cmds.group(n=prefix + 'lower_' + rigPartName + '_skinJnt_Grp', em=1)
    lowerLocGrp = cmds.group(n=prefix + 'lower_' + rigPartName + '_LOC_Grp', em=1)
    lowerCurveGrp = cmds.group(n=prefix + 'lower_' + rigPartName + '_Crv_Grp', em=1)
    lowerCtrlJntGrp = cmds.group(n=prefix + 'lower_' + rigPartName + '_ctrlJnt_Grp', em=1)
    lowerCtrlGrp = cmds.group(n=prefix + 'lower_' + rigPartName + '_CtrlGrp', em=1)

    for i in lowerEyeLidParentJntList:
        cmds.parent(i, lowerParentJntGrp)

    for i in lowerEyelidLocList:
        cmds.parent(i, lowerLocGrp)

    cmds.parent(lowerLowDefCurve, lowerCurveGrp)
    cmds.parent(lowerHighDefCurve, lowerCurveGrp)
    cmds.parent(lowerWireTransNode, lowerCurveGrp)

    for i in lowerControlJointList:
        cmds.parent(i, lowerCtrlJntGrp)

    for i in lowerJntCtrlGrpList:
        cmds.parent(i, lowerCtrlGrp)

    cmds.setAttr(lowerLocGrp + '.v', 0)
    cmds.setAttr(lowerCurveGrp + '.v', 0)
    cmds.setAttr(lowerCtrlJntGrp + '.v', 0)

    cmds.parent(lowerParentJntGrp, lowerLidRigModule.topGrp)
    cmds.parent(lowerLocGrp, lowerLidRigModule.topGrp)
    cmds.parent(lowerCurveGrp, lowerLidRigModule.topGrp)
    cmds.parent(lowerCtrlJntGrp, lowerLidRigModule.topGrp)
    cmds.parent(lowerCtrlGrp, lowerLidRigModule.topGrp)

    # final
    cmds.parent(upperLidRigModule.topGrp, eyeLidRigModule.topGrp)
    cmds.parent(lowerLidRigModule.topGrp, eyeLidRigModule.topGrp)
Exemple #39
0
    def rigModule(self, *args):
        Base.StartClass.rigModule(self)
        # verify if the guide exists:
        if cmds.objExists(self.moduleGrp):
            try:
                hideJoints = cmds.checkBox('hideJointsCB', query=True, value=True)
            except:
                hideJoints = 1
            # declare lists to store names and attributes:
            self.suspensionBCtrlGrpList, self.fatherBList, self.ctrlHookGrpList = [], [], []
            # start as no having mirror:
            sideList = [""]
            # analisys the mirror module:
            self.mirrorAxis = cmds.getAttr(self.moduleGrp+".mirrorAxis")
            if self.mirrorAxis != 'off':
                # get rigs names:
                self.mirrorNames = cmds.getAttr(self.moduleGrp+".mirrorName")
                # get first and last letters to use as side initials (prefix):
                sideList = [ self.mirrorNames[0]+'_', self.mirrorNames[len(self.mirrorNames)-1]+'_' ]
                for s, side in enumerate(sideList):
                    duplicated = cmds.duplicate(self.moduleGrp, name=side+self.userGuideName+'_Guide_Base')[0]
                    allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
                    for item in allGuideList:
                        cmds.rename(item, side+self.userGuideName+"_"+item)
                    self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True)
                    cmds.parent(side+self.userGuideName+'_Guide_Base', self.mirrorGrp, absolute=True)
                    # re-rename grp:
                    cmds.rename(self.mirrorGrp, side+self.userGuideName+'_'+self.mirrorGrp)
                    # do a group mirror with negative scaling:
                    if s == 1:
                        if cmds.getAttr(self.moduleGrp+".flip") == 0:
                            for axis in self.mirrorAxis:
                                gotValue = cmds.getAttr(side+self.userGuideName+"_Guide_Base.translate"+axis)
                                flipedValue = gotValue*(-2)
                                cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.translate'+axis, flipedValue)
                        else:
                            for axis in self.mirrorAxis:
                                cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.scale'+axis, -1)
                # joint labelling:
                jointLabelAdd = 1
            else: # if not mirror:
                duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName+'_Guide_Base')[0]
                allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
                for item in allGuideList:
                    cmds.rename(item, self.userGuideName+"_"+item)
                self.mirrorGrp = cmds.group(self.userGuideName+'_Guide_Base', name="Guide_Base_Grp", relative=True)
                #for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp"
                # re-rename grp:
                cmds.rename(self.mirrorGrp, self.userGuideName+'_'+self.mirrorGrp)
                # joint labelling:
                jointLabelAdd = 0
            # store the number of this guide by module type
            dpAR_count = utils.findModuleLastNumber(CLASS_NAME, "dpAR_type") + 1
            # run for all sides
            for s, side in enumerate(sideList):
                # declare guide:
                self.base = side+self.userGuideName+'_Guide_Base'
                self.cvALoc = side+self.userGuideName+"_Guide_JointLocA"
                self.cvBLoc = side+self.userGuideName+"_Guide_JointLocB"
                self.locatorsGrp = cmds.group(name=side+self.userGuideName+"_Loc_Grp", empty=True)
                # calculate distance between guide and end:
                self.dist = self.ctrls.distanceBet(self.cvALoc, self.cvBLoc)[0] * 0.2
                self.jointList, self.mainCtrlList, self.ctrlZeroList, self.ctrlList, self.aimLocList, self.upLocList = [], [], [], [], [], []
                for p, letter in enumerate(["A", "B"]):
                    # create joints:
                    cmds.select(clear=True)
                    jnt = cmds.joint(name=side+self.userGuideName+"_"+letter+"_1_Jnt", scaleCompensate=False)
                    endJoint = cmds.joint(name=side+self.userGuideName+"_"+letter+"_JEnd", scaleCompensate=False)
                    cmds.addAttr(jnt, longName='dpAR_joint', attributeType='float', keyable=False)
                    cmds.setAttr(endJoint+".translateZ", self.dist)
                    # joint labelling:
                    utils.setJointLabel(jnt, s+jointLabelAdd, 18, self.userGuideName+"_"+letter)
                    self.jointList.append(jnt)
                    
                    # create a control:
                    mainCtrl = self.ctrls.cvControl("id_055_SuspensionMain", side+self.userGuideName+"_"+self.langDic[self.langName]["c058_main"]+"_"+letter+"_Ctrl", r=self.ctrlRadius, d=self.curveDegree)
                    ctrl = self.ctrls.cvControl("id_056_SuspensionAB", side+self.userGuideName+"_"+letter+"_Ctrl", r=self.ctrlRadius*0.5, d=self.curveDegree)
                    upLocCtrl = self.ctrls.cvControl("id_057_SuspensionUpLoc", side+self.userGuideName+"_"+letter+"_UpLoc_Ctrl", r=self.ctrlRadius*0.1, d=self.curveDegree)
                    self.ctrls.setLockHide([ctrl], ['tx', 'ty', 'tz', 'v'])
                    self.ctrls.setLockHide([upLocCtrl], ['rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'])
                    # position and orientation of joint and control:
                    cmds.parent(ctrl, upLocCtrl, mainCtrl)
                    cmds.parentConstraint(ctrl, jnt, maintainOffset=False, name=jnt+"_ParentConstraint")
                    cmds.scaleConstraint(ctrl, jnt, maintainOffset=False, name=jnt+"_ScaleConstraint")
                    self.ctrlList.append(ctrl)
                    # zeroOut controls:
                    zeroOutCtrlGrp = utils.zeroOut([mainCtrl, ctrl, upLocCtrl])
                    self.mainCtrlList.append(zeroOutCtrlGrp[0])
                    self.ctrlZeroList.append(zeroOutCtrlGrp[1])
                    cmds.setAttr(zeroOutCtrlGrp[2]+".translateX", self.dist)
                    # origined from data:
                    if p == 0:
                        utils.originedFrom(objName=mainCtrl, attrString=self.base+";"+self.cvALoc)
                        utils.originedFrom(objName=ctrl, attrString=self.base+";"+self.cvALoc)
                        cmds.delete(cmds.parentConstraint(self.cvALoc, zeroOutCtrlGrp[0], maintainOffset=False))
                    else:
                        utils.originedFrom(objName=mainCtrl, attrString=self.cvBLoc)
                        utils.originedFrom(objName=ctrl, attrString=self.cvBLoc)
                        cmds.delete(cmds.parentConstraint(self.cvBLoc, zeroOutCtrlGrp[0], maintainOffset=False))
                        # integrating data:
                        self.suspensionBCtrlGrpList.append(zeroOutCtrlGrp[0])
                    # hide visibility attribute:
                    cmds.setAttr(mainCtrl+'.visibility', keyable=False)
                    # fixing flip mirror:
                    if s == 1:
                        if cmds.getAttr(self.moduleGrp+".flip") == 1:
                            cmds.setAttr(zeroOutCtrlGrp[0]+".scaleX", -1)
                            cmds.setAttr(zeroOutCtrlGrp[0]+".scaleY", -1)
                            cmds.setAttr(zeroOutCtrlGrp[0]+".scaleZ", -1)
                    cmds.addAttr(ctrl, longName='scaleCompensate', attributeType="bool", keyable=False)
                    cmds.setAttr(ctrl+".scaleCompensate", 1, channelBox=True)
                    cmds.connectAttr(ctrl+".scaleCompensate", jnt+".segmentScaleCompensate", force=True)
                    
                    # working with aim setup:
                    cmds.addAttr(ctrl, longName="active", attributeType="bool", defaultValue=1, keyable=True)
                    aimLoc = cmds.spaceLocator(name=side+self.userGuideName+"_"+letter+"_Aim_Loc")[0]
                    upLoc = cmds.spaceLocator(name=side+self.userGuideName+"_"+letter+"_Up_Loc")[0]
                    locGrp = cmds.group(aimLoc, upLoc, name=side+self.userGuideName+"_"+letter+"_Loc_Grp")
                    cmds.parent(locGrp, self.locatorsGrp, relative=True)
                    cmds.delete(cmds.parentConstraint(ctrl, locGrp, maintainOffset=False))
                    cmds.parentConstraint(upLocCtrl, upLoc, maintainOffset=False, name=upLoc+"_ParentConstraint")
                    cmds.parentConstraint(mainCtrl, locGrp, maintainOffset=True, name=locGrp+"_ParentConstraint")
                    cmds.setAttr(locGrp+".visibility", 0)
                    self.aimLocList.append(aimLoc)
                    self.upLocList.append(upLoc)

                # aim constraints:
                # B to A:
                aAimConst = cmds.aimConstraint(self.aimLocList[1], self.ctrlZeroList[0], aimVector=(0, 0, 1), upVector=(1, 0, 0), worldUpType="object", worldUpObject=self.upLocList[0], maintainOffset=True, name=self.ctrlZeroList[0]+"_AimConstraint")[0]
                cmds.connectAttr(self.ctrlList[0]+".active", aAimConst+"."+self.aimLocList[1]+"W0", force=True)
                # A to B:
                bAimConst = cmds.aimConstraint(self.aimLocList[0], self.ctrlZeroList[1], aimVector=(0, 0, 1), upVector=(1, 0, 0), worldUpType="object", worldUpObject=self.upLocList[1], maintainOffset=True, name=self.ctrlZeroList[0]+"_AimConstraint")[0]
                cmds.connectAttr(self.ctrlList[1]+".active", bAimConst+"."+self.aimLocList[0]+"W0", force=True)
                
                # integrating data:
                self.loadedFatherB = cmds.getAttr(self.moduleGrp+".fatherB")
                if self.loadedFatherB:
                    self.fatherBList.append(self.loadedFatherB)
                else:
                    self.fatherBList.append(None)
                
                # create a masterModuleGrp to be checked if this rig exists:
                self.toCtrlHookGrp     = cmds.group(self.mainCtrlList, name=side+self.userGuideName+"_Control_Grp")
                self.toScalableHookGrp = cmds.group(self.jointList, name=side+self.userGuideName+"_Joint_Grp")
                self.toStaticHookGrp   = cmds.group(self.toCtrlHookGrp, self.toScalableHookGrp, self.locatorsGrp, name=side+self.userGuideName+"_Grp")
                # add hook attributes to be read when rigging integrated modules:
                utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
                utils.addHook(objName=self.toScalableHookGrp, hookType='scalableHook')
                utils.addHook(objName=self.toStaticHookGrp, hookType='staticHook')
                cmds.addAttr(self.toStaticHookGrp, longName="dpAR_name", dataType="string")
                cmds.addAttr(self.toStaticHookGrp, longName="dpAR_type", dataType="string")
                cmds.setAttr(self.toStaticHookGrp+".dpAR_name", self.userGuideName, type="string")
                cmds.setAttr(self.toStaticHookGrp+".dpAR_type", CLASS_NAME, type="string")
                # add module type counter value
                cmds.addAttr(self.toStaticHookGrp, longName='dpAR_count', attributeType='long', keyable=False)
                cmds.setAttr(self.toStaticHookGrp+'.dpAR_count', dpAR_count)
                self.ctrlHookGrpList.append(self.toCtrlHookGrp)
                if hideJoints:
                    cmds.setAttr(self.toScalableHookGrp+".visibility", 0)
                # delete duplicated group for side (mirror):
                cmds.delete(side+self.userGuideName+'_'+self.mirrorGrp)
            # finalize this rig:
            self.integratingInfo()
            cmds.select(clear=True)
        # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
        self.deleteModule()
Exemple #40
0
def bend_chain(crv, controller, bones_nbr):
    jnt_nbr = bones_nbr + 1
    # get shape
    crv_shape = mc.listRelatives(crv, c=True, s=True)[0]

    # calculation of the number of cv
    crv_degree = mc.getAttr(crv_shape + '.degree')
    crv_span = mc.getAttr(crv_shape + '.spans')

    cv_nbr = crv_degree + crv_span

    # place curve pivot on first cv
    crv_info = mc.createNode('curveInfo', n=crv + '_curveInfo')
    mc.connectAttr(crv_shape + '.worldSpace', crv_info + '.inputCurve')

    cv_tx = mc.getAttr(crv_info + '.controlPoints[0].xValue')
    cv_ty = mc.getAttr(crv_info + '.controlPoints[0].yValue')
    cv_tz = mc.getAttr(crv_info + '.controlPoints[0].zValue')
    mc.xform(crv, piv=(cv_tx, cv_ty, cv_tz), ws=True)

    # Stretch creation
    mult = mc.shadingNode('multiplyDivide', asUtility=True,
                          name='multiplyDivide_STRETCH_' + crv)
    mc.connectAttr('%s.arcLength' % crv_info, '%s.input1X' % mult)
    crv_length = mc.getAttr(crv_info + '.arcLength')
    mc.setAttr(mult + '.input2X', crv_length)
    mc.setAttr(mult + '.operation', 2)

    # Joint chain creation
    jnt_length = crv_length / bones_nbr
    first_jnt = mc.joint(p=(cv_tx, cv_ty, cv_tz), name='SK_' + crv + '_0')

    for i in range(1, jnt_nbr):
        i = str(i)
        current_jnt = mc.joint(p=(jnt_length, 0, 0), r=True,
                               name='SK_' + crv + '_' + i)
        mc.connectAttr(mult + '.outputX',
                       current_jnt + '.scaleX')

    # ikSpline creation
    ik = 'IKSPLINE_' + crv
    mc.ikHandle(curve=crv, ee='SK_' + crv + '_' + str(bones_nbr),
                sol='ikSplineSolver', sj=first_jnt,
                name=ik, ccv=0)
    jnt_rotation = mc.xform(first_jnt, q=True, ro=True)

    # Orig joint
    orig.orig([first_jnt], 'orig')

    # offset de l'ik
    orig.orig([ik], 'orig')

    for j in range(0, cv_nbr):
        # Creation des clusters :)

        cls_nbr = str(j)
        cv = (crv + '.cv[' + cls_nbr + ']')

        mc.select(cv)
        cluster = mc.cluster()
        mc.select(deselect=True)

        # Recuperation de la position des clusters
        cls_pos_x = mc.getAttr('%s.controlPoints[%s].xValue'
                               % (crv_info, cls_nbr))
        cls_pos_y = mc.getAttr('%s.controlPoints[%s].yValue'
                               % (crv_info, cls_nbr))
        cls_pos_z = mc.getAttr('%s.controlPoints[%s].zValue'
                               % (crv_info, cls_nbr))

        # Controllers creation
        ctrl = mc.duplicate(controller, name='%s_%s_ctrl' % (crv, cls_nbr))
        ctrl = mc.rename(ctrl, '%s_%s_ctrl' % (crv, cls_nbr))
        mc.xform(ctrl, t=(cls_pos_x, cls_pos_y, cls_pos_z), ws=True)
        mc.xform(ctrl, ro=jnt_rotation)

        # Controllers orig
        orig.orig([ctrl], 'orig')

        # Cluster hierarchy

        mc.parent(cluster, ctrl)

    mc.select('%s_*_ctrl_orig' % crv)
    mc.group(name='%s_ctrl_grp' % crv)
    mc.select(deselect=True)
Exemple #41
0
def controlFromLocator(	locList,
						ctrlType	= 'transform',
						ctrlShape	= 'box',
						ctrlScale	= 0.1,
						ctrlLod		= 'primary',
						driverType	= None,
						orient		= True,
						parentToLoc	= False ):
	'''
	Generate controls objects from a list of locators
	@param locList: List of locators to generate controls from.
	@type locList: list
	@param ctrlType: Control transform type. Accepted values include "transform" and "joint".
	@type ctrlType: str
	@param ctrlShape: Control transform type.
	@type ctrlShape: str
	@param ctrlScale: Control shape scale.
	@type ctrlScale: float
	@param ctrlLod: Control LOD type.
	@type ctrlLod: str
	@param driverType: Control driver type. If None, don't create control driver.
	@type driverType: str or None
	@param orient: Orient control to locator.
	@type orient: bool
	@param parentToLoc: Parent control group to locator.
	@type parentToLoc: bool
	'''
	# ==========
	# - Checks -
	# ==========
	
	# Check Locators
	for loc in locList:
		if not mc.objExists(loc):
			raise Exception('Locator "'+loc+'" does not exist!')
	
	# Check Control LOD
	ctrlLodList = ['primary','secondary', 'tertiary']
	if not ctrlLod in ctrlLodList:
		raise Exception('Invalid control LOD (level of detail)! ("'+ctrlLod+'")')
	
	# ===================
	# - Create Controls -
	# ===================
	
	ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder()
	
	ctrlList = []
	ctrlGrpList = []
	driverList = []
	driverGrpList = []
	for loc in locList:
		
		# Clear Selection
		mc.select(cl=True)
		
		# Generate Naming Prefix
		prefix = glTools.utils.stringUtils.stripSuffix(loc)
		
		# Create Control
		ctrl = ''
		ctrlGrp = ''
		if ctrlType == 'transform':
			ctrl = mc.createNode(ctrlType,n=prefix+'_ctrl')
			ctrlGrp = mc.group(ctrl,n=prefix+'_ctrlGrp')
		elif ctrlType == 'joint':
			ctrl = mc.joint(n=prefix+'_jnt')
			ctrlGrp = glTools.utils.joint.group(ctrl,'A')
			mc.setAttr(ctrl+'.radius',ctrlScale)
			mc.setAttr(ctrlGrp+'.radius',ctrlScale)
			glTools.utils.base.displayOverride(ctrl,overrideEnable=1,overrideLOD=1)
			glTools.utils.base.displayOverride(ctrlGrp,overrideEnable=1,overrideLOD=1)
			if not driverType: glTools.rig.utils.tagBindJoint(ctrl)
		else:
			raise Exception('Invalid control transform type "'+ctrlType+'"!')
		
		# Parent to Locator
		if parentToLoc: mc.parent(ctrlGrp,loc)
		
		# Create Control Shape
		ctrlBuilder.controlShape(ctrl,controlType=ctrlShape,scale=ctrlScale)
		
		# Tag Control
		glTools.rig.utils.tagCtrl(ctrl,ctrlLod)
			
		# Create Driver
		driver = None
		driverGrp = None
		if driverType:
			
			# Clear Selection
			mc.select(cl=True)
			
			if driverType == 'transform':
				driver = mc.createNode(ctrlType,n=prefix+'_driver')
				driverGrp = mc.group(ctrl,n=prefix+'_driverGrp')
			elif driverType == 'joint':
				driver = mc.joint(n=prefix+'_driver')
				driverGrp = glTools.utils.joint.group(driver,'A')
				mc.setAttr(driver+'.radius',ctrlScale)
				mc.setAttr(driverGrp+'.radius',ctrlScale)
				glTools.utils.base.displayOverride(driver,overrideEnable=1,overrideLOD=1)
				glTools.utils.base.displayOverride(driverGrp,overrideEnable=1,overrideLOD=1)
				glTools.rig.utils.tagBindJoint(driver)
			else:
				raise Exception('Invalid control driver type "'+driverType+'"!')
			
			# Connect Driver
			for at in 'trs':
				mc.connectAttr(ctrl+'.'+at,driver+'.'+at,f=True)
				mc.connectAttr(driverGrp+'.'+at,ctrlGrp+'.'+at,f=True)
			
			# Position Driver Group
			mc.delete(mc.pointConstraint(loc,driverGrp))
			if orient: mc.delete(mc.orientConstraint(loc,driverGrp))
			
			# Parent to Locator
			if parentToLoc: mc.parent(driverGrp,loc)
		
		else:
		
			# Position Control Group
			mc.delete(mc.pointConstraint(loc,ctrlGrp))
			if orient: mc.delete(mc.orientConstraint(loc,ctrlGrp))
		
		# Append to Return Lists
		ctrlList.append(ctrl)
		ctrlGrpList.append(ctrlGrp)
		driverList.append(driver)
		driverGrpList.append(driverGrp)
	
	# =================
	# - Return Result -
	# =================
	
	result = {}
	
	result['ctrl'] = ctrlList
	result['ctrlGrp'] = ctrlGrpList
	result['driver'] = driverList
	result['driverGrp'] = driverGrpList
	
	return result
Exemple #42
0
def importSmdAnimationAndSkeleton( smdFilepath, namespace=None, startTime=0, angles=(-90, 0, 0) ):
	'''
	imports animation from an smd file without the need for a reference skeleton - just take note
	that in general smd animation data contains a crap load of junk...  so the skeletons built by
	this procedure are a lot more verbose.  sometimes this is desireable of course...

	the top nodes that are created are returned
	'''
	smdFilepath = Path( smdFilepath )

	fHandle = open( smdFilepath )
	lineIter = iter( fHandle )

	if namespace is None:
		namespace = ''
	else:
		if not cmd.namespace( exists=namespace ):
			namespace = cmd.namespace( addNamespace=namespace )

		namespace = namespace +':'

	skelDict = {}
	prefix = ''
	try:
		while True:
			line = lineIter.next().strip()
			if line == 'nodes':
				while True:
					line = lineIter.next().strip()
					if line == 'end':
						raise BreakException

					idx, name, parentIdx = line.split( ' ' )
					idx = int( idx )
					parentIdx = int( parentIdx )
					name = name.replace( '"', '' )

					#build the actual joint and store its name in the dict - we parent them later
					cmd.select( cl=True )
					nameToks = name.split( "." )
					if len( nameToks ) > 1:
						prefix = nameToks[ 0 ]

					name = namespace + nameToks[ -1 ]
					joint = cmd.joint( name=name )

					skelDict[ idx ] = joint, parentIdx
	except StopIteration:
		melError( "EOF reached unexpectedly - attempting to build skeleton with data obtained thus far" )
	except BreakException:
		pass


	#build the skeleton
	for idx, (joint, parentIdx) in skelDict.iteritems():
		if parentIdx < 0:
			continue

		parent, grandParentIdx = skelDict[ parentIdx ]
		cmd.parent( joint, parent )


	#turn the skeleton dict into a list
	joints = []

	jointIdxs = range( len( skelDict ) )
	for idx in jointIdxs:
		joints.append( skelDict[ idx ][ 0 ] )

	times = []
	attrs = 'tx', 'ty', 'tz', 'rx', 'ry', 'rz'
	degrees = math.degrees
	try:
		while True:
			line = lineIter.next().strip()
			if line.startswith( 'skeleton' ):
				while True:
					line = lineIter.next().strip()
					while not line.startswith( 'time' ):
						line = lineIter.next().strip()

					time = int( line.split()[ -1 ] ) + startTime
					times.append( time )
					for idx in jointIdxs:
						line = lineIter.next().strip()
						toks = line.split()
						assert idx == int( toks[ 0 ] )
						toks = list( map( float, toks[ 1: ] ) )
						transRot = toks[ :3 ] + list( map( degrees, toks[ 3: ] ) )

						for attr, value in zip( attrs, transRot ):
							cmd.setKeyframe( joints[ idx ], time=time, attribute=attr, value=value )
	except StopIteration: pass
	finally:
		fHandle.close()


	#set initial time ranges
	numFrames = len( times ) - 1 + startTime
	cmd.playbackOptions( e=True, min=startTime, animationStartTime=startTime, max=numFrames, animationEndTime=numFrames )


	#get the list of joints that have no parents and perform the rotation correction
	topNodes = [ joint for idx, (joint, parentIdx) in skelDict.iteritems() if parentIdx < 0 ]
	rotCorrectionGrp = cmd.group( empty=True, name=namespace + smdFilepath.name() )
	for j in topNodes:
		cmd.parent( j, rotCorrectionGrp )

	cmd.setAttr( '%s.r' % rotCorrectionGrp, *angles )
	#for time in times:
		#cmd.currentTime( time )
		#for j in topNodes:
			#cmd.rotate( angles[ 0 ], angles[ 1 ], angles[ 2 ], j, r=True, ws=True, pivot=(0, 0, 0) )
			#cmd.setKeyframe( j, at=attrs )


	return joints
Exemple #43
0
    def build(self):
        '''
        This is where the builds will happen.
        '''
        super(Face, self).build()

        # get all of the inputs to the node.
        jawJoint = self.getAttributeByName("jawJoint").getValue()
        faceUpperJoint = self.getAttributeByName("faceUpperJoint").getValue()
        headTipJoint = self.getAttributeByName("headTipJoint").getValue()
        faceLowerJoint = self.getAttributeByName("faceLowerJoint").getValue()
        faceMidJoint = self.getAttributeByName("faceMidJoint").getValue()
        noseBridgeJoint = self.getAttributeByName("noseBridge").getValue()
        noseJoint = self.getAttributeByName("nose").getValue()
        anchor = self.getAttributeByName("anchor").getValue()
        upperTeeth = self.getAttributeByName("upperTeeth").getValue()
        lowerTeeth = self.getAttributeByName("lowerTeeth").getValue()
        geometry = self.getAttributeByName("geometry").getValue()
        teethUpperJoint = self.getAttributeByName("upperTeeth").getValue()
        teethLowerJoint = self.getAttributeByName("lowerTeeth").getValue()

        # JAW
        if mc.objExists(jawJoint):
            # create the jaw control
            jawNul, jawDefAuto, jawCtrl = control.create(
                name="jaw",
                controlType="null",
                color=common.YELLOW,
                hierarchy=['nul', 'def_auto'])

            # position the jaw control and connect the joint to the control
            mc.xform(jawNul,
                     ws=True,
                     matrix=mc.xform(jawJoint, q=True, ws=True, matrix=True))
            mc.pointConstraint(jawCtrl, jawJoint)
            mc.orientConstraint(jawCtrl, jawJoint)
            # create jaw driver, parent it to the jaw nul, then move it to the correct position
            jawDriver = mc.createNode("joint", name="jaw_driver")
            mc.parent(jawDriver, jawNul)
            mc.xform(jawDriver,
                     ws=True,
                     matrix=mc.xform(jawNul, q=True, ws=True, matrix=True))
            mc.orientConstraint(jawCtrl, jawDriver)
            # create normRX on the driver
            mc.addAttr(jawDriver, ln="normRX", at="double", keyable=True)
            multJaw = mc.createNode("multDoubleLinear",
                                    name="jaw_driver_norm_mult")
            mc.connectAttr("{}.rx".format(jawJoint),
                           "{}.input1".format(multJaw),
                           f=True)
            mc.setAttr("{}.input2".format(multJaw), .1)
            mc.connectAttr("{}.output".format(multJaw),
                           "{}.normRX".format(jawDriver),
                           f=True)
            # turn off the visibility of the driver
            mc.setAttr("{}.drawStyle".format(jawDriver), 2)

            # create the lip lower cluster
            lipLower = "lip_lower"
            cluster.create(geometry, name=lipLower, parent=jawCtrl)

            # rename the cluster and control
            mc.rename(lipLower, '{}_cluster'.format(lipLower))
            mc.rename('{}_ctrl'.format(lipLower), lipLower)
            mc.xform("{}_nul".format(lipLower),
                     ws=True,
                     matrix=mc.xform(jawCtrl, q=True, ws=True, matrix=True))
            mc.setAttr("{}.displayHandle".format(lipLower), 1)
            control.tagAsControl(lipLower)

            # Lowerteeth control
            if mc.objExists(teethLowerJoint):
                teethLowerNul, teethLowerDefAuto, teethLowerCtrl = control.create(
                    name="teeth_lower",
                    controlType="null",
                    color=common.RED,
                    hierarchy=['nul', 'def_auto'],
                    parent=jawCtrl)

                mc.xform(teethLowerNul,
                         ws=True,
                         matrix=mc.xform(teethLowerJoint,
                                         q=True,
                                         ws=True,
                                         matrix=True))
                mc.pointConstraint(teethLowerCtrl, teethLowerJoint)
                mc.orientConstraint(teethLowerCtrl, teethLowerJoint)

        # FACE LOWER
        if mc.objExists(faceLowerJoint):
            # Create the faceLower and jaw control
            faceLowerNul, faceLowerCtrl = control.create(name="face_lower",
                                                         controlType="null",
                                                         color=common.YELLOW,
                                                         hierarchy=['nul'],
                                                         parent=anchor)

            # position the faceLowerNul and connect the joint to the control
            mc.xform(faceLowerNul,
                     ws=True,
                     matrix=mc.xform(faceLowerJoint,
                                     q=True,
                                     ws=True,
                                     matrix=True))
            mc.pointConstraint(faceLowerCtrl, faceLowerJoint)
            mc.orientConstraint(faceLowerCtrl, faceLowerJoint)

            # parent the jaw to face lower control
            if mc.objExists(jawJoint):
                mc.parent(jawNul, faceLowerCtrl)

            mouthMainName = "mouthMain"
            cluster.create(geometry, name=mouthMainName, parent=faceLowerCtrl)

            # rename the cluster and control
            mc.rename(mouthMainName, '{}_cluster'.format(mouthMainName))
            mc.rename('{}_ctrl'.format(mouthMainName), mouthMainName)
            mc.xform("{}_nul".format(mouthMainName),
                     ws=True,
                     matrix=mc.xform(faceLowerCtrl,
                                     q=True,
                                     ws=True,
                                     matrix=True))
            mc.setAttr("{}.displayHandle".format(mouthMainName), 1)
            control.tagAsControl(mouthMainName)

        elif mc.objExists(jawJoint) and mc.objExists(anchor):
            mc.parent(jawNul, anchor)

        if mc.objExists(faceUpperJoint):
            # Create the faceLower and jaw control
            faceUpperNul, faceUpperCtrl = control.create(name="face_upper",
                                                         controlType="null",
                                                         color=common.YELLOW,
                                                         hierarchy=['nul'],
                                                         parent=anchor)

            # position the faceLowerNul and connect the joint to the control
            mc.xform(faceUpperNul,
                     ws=True,
                     matrix=mc.xform(faceUpperJoint,
                                     q=True,
                                     ws=True,
                                     matrix=True))
            mc.pointConstraint(faceUpperCtrl, faceUpperJoint)
            mc.orientConstraint(faceUpperCtrl, faceUpperJoint)

            # setup the jaw compression
            jawCompressionJnt = "jaw_compression_driver"
            if not mc.objExists(jawCompressionJnt):
                jawCompressionJnt = mc.joint(name="jaw_compression_driver")
                mc.xform(jawCompressionJnt,
                         ws=True,
                         q=True,
                         rotation=mc.xform(faceLowerJoint,
                                           q=True,
                                           ws=True,
                                           rotation=True))
                mc.xform(jawCompressionJnt,
                         ws=True,
                         t=rigrpeo.libs.transform.getAveragePosition(
                             [upperTeeth, lowerTeeth]))

            # create the faceDiff joint and parent it to the faceUpperCtrl
            faceDiff = mc.duplicate("jaw_compression_driver",
                                    po=True,
                                    name="face_upper_diff")[0]
            mc.parent(faceDiff, faceUpperCtrl)
            parent = self.rigGroup
            groupList = [
                "jaw_compression_grp", "jaw_compression_nul",
                "jaw_compression_cnt", "jaw_compressiong_offset"
            ]
            for group in groupList:
                mc.createNode("transform", name=group)
                mc.parent(group, parent)
                parent = group

            # position the jaw groups
            mc.parentConstraint("skull_bind", groupList[0], mo=False)
            mc.xform(groupList[1],
                     ws=True,
                     matrix=mc.xform(jawJoint, q=True, ws=True, matrix=True))
            for attr in ['t', 'r', 's']:
                mc.connectAttr("{}.{}".format(jawCtrl, attr),
                               "{}.{}".format(groupList[2], attr),
                               f=True)

            mc.xform(groupList[-1],
                     ws=True,
                     matrix=mc.xform(jawCompressionJnt,
                                     q=True,
                                     ws=True,
                                     matrix=True))
            # parent the jawCompression joint to the last of the group nodes
            mc.parent(jawCompressionJnt, groupList[-1])
            # point constrain the jawCompression joint to the faceDiff joint
            mc.pointConstraint(faceDiff, jawCompressionJnt, mo=False)

            # turn off the visibility of the joints
            for jnt in [faceDiff, jawCompressionJnt]:
                mc.setAttr("{}.v".format(jnt), 0)

            if mc.objExists(headTipJoint):
                # Create the faceLower and jaw control
                headTipNul, headTipCtrl = control.create(name="head_tip",
                                                         controlType="null",
                                                         color=common.YELLOW,
                                                         hierarchy=['nul'],
                                                         parent=faceUpperCtrl)

            # position the faceLowerNul and connect the joint to the control
            mc.xform(headTipNul,
                     ws=True,
                     matrix=mc.xform(headTipJoint,
                                     q=True,
                                     ws=True,
                                     matrix=True))
            mc.pointConstraint(headTipCtrl, headTipJoint)
            mc.orientConstraint(headTipCtrl, headTipJoint)

        if mc.objExists(noseBridgeJoint):
            # Create the faceLower and jaw control
            noseBridgeNul, noseBridgeDefAuto, noseBridgeRotDefAuto, noseBridgeCtrl = control.create(
                name="nose_bridge",
                controlType="null",
                color=common.YELLOW,
                hierarchy=['nul', 'def_auto', 'rot_def_auto'])

            if mc.objExists(faceUpperJoint):
                mc.parent(noseBridgeNul, faceUpperCtrl)
                # create the setDriven keys for the jaw control
                mc.setDrivenKeyframe("{}.rx".format(noseBridgeRotDefAuto),
                                     cd="{}.ty".format(jawCompressionJnt),
                                     v=15,
                                     dv=-0.7)
                mc.setDrivenKeyframe("{}.rx".format(noseBridgeRotDefAuto),
                                     cd="{}.ty".format(jawCompressionJnt),
                                     v=-0,
                                     dv=0)
                for attr in ['y', 'z']:
                    mc.setDrivenKeyframe("{}.t{}".format(
                        noseBridgeDefAuto, attr),
                                         cd="{}.ty".format(jawCompressionJnt),
                                         v=.01,
                                         dv=-0.7)
                    mc.setDrivenKeyframe("{}.t{}".format(
                        noseBridgeDefAuto, attr),
                                         cd="{}.ty".format(jawCompressionJnt),
                                         v=0,
                                         dv=0)
            else:
                mc.parent(noseBridgeNul, anchor)
            # position the faceLowerNul and connect the joint to the control
            mc.xform(noseBridgeNul,
                     ws=True,
                     matrix=mc.xform(noseBridgeJoint,
                                     q=True,
                                     ws=True,
                                     matrix=True))
            mc.pointConstraint(noseBridgeCtrl, noseBridgeJoint)
            mc.orientConstraint(noseBridgeCtrl, noseBridgeJoint)

        if mc.objExists(noseJoint):
            # Create the faceLower and jaw control
            noseNul, noseDefAuto, noseCtrl = control.create(
                name="nose",
                controlType="null",
                color=common.YELLOW,
                hierarchy=['nul', 'def_auto'])

            if mc.objExists(noseBridgeJoint):
                mc.parent(noseNul, noseBridgeCtrl)
            else:
                mc.parent(noseNul, anchor)

            # position the faceLowerNul and connect the joint to the control
            mc.xform(noseNul,
                     ws=True,
                     matrix=mc.xform(noseJoint, q=True, ws=True, matrix=True))
            mc.pointConstraint(noseCtrl, noseJoint)
            mc.orientConstraint(noseCtrl, noseJoint)

            # create the left sneer cluster
            sneerNameL = "sneer_l"
            cluster.create(geometry, name=sneerNameL, parent=noseCtrl)

            # rename the cluster and control
            mc.rename(sneerNameL, '{}_cluster'.format(sneerNameL))
            mc.rename('{}_ctrl'.format(sneerNameL), sneerNameL)
            mc.xform("{}_nul".format(sneerNameL),
                     ws=True,
                     matrix=mc.xform(noseCtrl, q=True, ws=True, matrix=True))
            mc.setAttr("{}.displayHandle".format(sneerNameL), 1)
            control.tagAsControl(sneerNameL)

            # create the right sneer cluster
            sneerNameR = "sneer_r"
            cluster.create(geometry, name=sneerNameR, parent=noseCtrl)

            # rename the cluster and control
            mc.rename(sneerNameR, '{}_cluster'.format(sneerNameR))
            mc.rename('{}_ctrl'.format(sneerNameR), sneerNameR)
            mc.xform("{}_nul".format(sneerNameR),
                     ws=True,
                     matrix=mc.xform(noseCtrl, q=True, ws=True, matrix=True))
            mc.setAttr("{}.displayHandle".format(sneerNameR), 1)
            control.tagAsControl(sneerNameR)

        if mc.objExists(faceMidJoint):
            parent = faceLowerCtrl
            groupList = [
                "face_mid_nul", "face_upper_driver", "face_mid_offset",
                "face_mid_ort", "face_mid_def_auto"
            ]
            for group in groupList:
                mc.createNode("transform", name=group)
                mc.parent(group, parent)
                parent = group

            # make the driver joint and parent it to the def auto and turn off visibility
            midDriver = mc.joint(name="face_mid_driver")
            mc.setAttr("{}.drawStyle".format(midDriver), 2)

            mc.xform(groupList[0],
                     ws=True,
                     matrix=mc.xform(faceUpperCtrl,
                                     q=True,
                                     ws=True,
                                     matrix=True))
            for attr in ['t', 'r', 's']:
                mc.connectAttr("{}.{}".format(faceUpperCtrl, attr),
                               "{}.{}".format(groupList[1], attr),
                               f=True)
            mc.xform(groupList[2],
                     ws=True,
                     matrix=mc.xform(faceMidJoint,
                                     q=True,
                                     ws=True,
                                     matrix=True))
            # create the set drivens
            if mc.objExists(faceUpperJoint):
                # create the setDriven keys for the jaw control
                mc.setDrivenKeyframe("{}.rx".format(groupList[-1]),
                                     cd="{}.ty".format(jawCompressionJnt),
                                     v=10,
                                     dv=-0.7)
                mc.setDrivenKeyframe("{}.rx".format(groupList[-1]),
                                     cd="{}.ty".format(jawCompressionJnt),
                                     v=-0,
                                     dv=0)
                for attr in ['y', 'z']:
                    mc.setDrivenKeyframe("{}.t{}".format(groupList[-1], attr),
                                         cd="{}.ty".format(jawCompressionJnt),
                                         v=-1,
                                         dv=-0.7)
                    mc.setDrivenKeyframe("{}.t{}".format(groupList[-1], attr),
                                         cd="{}.ty".format(jawCompressionJnt),
                                         v=0,
                                         dv=0)

            # constrain the joint to the driver
            mc.pointConstraint(midDriver, faceMidJoint, mo=False)
            mc.orientConstraint(midDriver, faceMidJoint, mo=False)
            # parent the noseBridge to the proper group
            mc.parent(noseBridgeNul, groupList[-1])

            # create the left sneer cluster
            lipUpper = "lip_upper"
            cluster.create(geometry, name=lipUpper, parent=midDriver)

            # rename the cluster and control
            mc.rename(lipUpper, '{}_cluster'.format(lipUpper))
            mc.rename('{}_ctrl'.format(lipUpper), lipUpper)
            mc.xform("{}_nul".format(lipUpper),
                     ws=True,
                     matrix=mc.xform(midDriver, q=True, ws=True, matrix=True))
            mc.setAttr("{}.displayHandle".format(lipUpper), 1)
            control.tagAsControl(lipUpper)

            # Lowerteeth control
            if mc.objExists(teethUpperJoint):
                teethUpperNul, teethUpperDefAuto, teethUpperCtrl = control.create(
                    name="teeth_upper",
                    controlType="null",
                    color=common.RED,
                    hierarchy=['nul', 'def_auto'],
                    parent=midDriver)

                mc.xform(teethUpperNul,
                         ws=True,
                         matrix=mc.xform(teethUpperJoint,
                                         q=True,
                                         ws=True,
                                         matrix=True))
                mc.pointConstraint(teethUpperCtrl, teethUpperJoint)
                mc.orientConstraint(teethUpperCtrl, teethUpperJoint)
toePos = cmds.xform('toe', query=True, worldSpace=True, translation=True)

pvKneeLoc = cmds.spaceLocator(n='KneeLocTemp')
pvCtrlLoc = cmds.spaceLocator(n='pvKneeCtrlLoc')
cmds.parent(pvCtrlLoc, pvKneeLoc)

cmds.delete(cmds.pointConstraint('hip', 'ankle', pvKneeLoc))
cmds.select(pvKneeLoc, 'knee')
cmds.align(x='mid', alignToLead=True)
cmds.align(y='mid', alignToLead=True)
cmds.move(0, 0, 20, pvCtrlLoc, localSpace=True)
cmds.select(clear=True)

# make bind joints
pelvisJnt = cmds.joint(name='pelvis',
                       absolute=True,
                       radius=2,
                       position=pelvisPos)

hipJnt = cmds.joint(name=si + un + 'hip',
                    absolute=True,
                    radius=2,
                    position=hipPos)
kneeJnt = cmds.joint(name=si + un + 'knee',
                     absolute=True,
                     radius=2,
                     position=kneePos)
ankleJnt = cmds.joint(name=si + un + 'ankle',
                      absolute=True,
                      radius=2,
                      position=anklePos)
ballJnt = cmds.joint(name=si + un + 'ball',
Exemple #45
0
    def build(self):
        '''
        This will build the rig.
        '''
        super(Mouth, self).build()
        lipMainCurve = self.getAttributeByName('lipMainCurve').getValue()
        lipCurve = self.getAttributeByName('lipCurve').getValue()
        parentGroup = self.getAttributeByName('systemParent').getValue()
        geometry = self.getAttributeByName('geometry').getValue()
        headPinTrs = self.getAttributeByName('headPin').getValue()
        jawPinTrs = self.getAttributeByName('jawPin').getValue()
        orientFile = self.getAttributeByName('orientFile').getValue()

        bindmeshGeometry, follicleList, lipMainControlHieracrchyList, jointList = self.__buildCurveRig(lipMainCurve, "lip_main" , parentGroup)
        # delete the controls, tparent joint to the node above the control
        mainBaseCurveJointList = list()
        for jnt, lipMainControlList in zip(jointList, lipMainControlHieracrchyList):
            # create the joint that we will use later to deform the base wire.
            baseCurveJoint = mc.joint(name=jnt.replace("_jnt","_baseCurve_jnt"))
            mainBaseCurveJointList.append(baseCurveJoint)
            # hide the base curve joint. Then parent it under the null node
            mc.setAttr("{}.v".format(baseCurveJoint), 0)
            mc.parent(baseCurveJoint, lipMainControlList[1])
            mc.setAttr("{}.t".format(baseCurveJoint), 0, 0, 0)
            mc.parent(jnt,lipMainControlList[-2])
            mc.delete(lipMainControlList.pop(-1))

        # create a bindMesh for mouth corner controls.
        jointListPos = [mc.xform(joint, q=True, ws=True, t=True) for joint in jointList]
        jointListPosX = [round(pos[0], 3) for pos in jointListPos]
        cornerPos = [jointListPos[jointListPosX.index(max(jointListPosX))],
                     jointListPos[jointListPosX.index(min(jointListPosX))]]

        # create the bindmesh 
        bindmeshGeometry, follicleList = bindmesh.create("{}_corner".format(self.name), cornerPos)
        # set the visibility of the bindmesh
        mc.setAttr("{}.v".format(bindmeshGeometry), 0 )
        mouthCorner_l_follicle = mc.rename(follicleList[0], follicleList[0].replace('_0_','_l_'))
        mouthCorner_r_follicle = mc.rename(follicleList[1], follicleList[1].replace('_1_','_r_'))
        mc.parent([mouthCorner_l_follicle, mouthCorner_r_follicle, bindmeshGeometry], self.name)

        controlPrefix = "lip_main"
        # get the position of the controls for lip tweakers
        upperLeft = list()
        upperLeftPosXList = list()
        upperRight = list()
        upperRightPosXList = list()
        lowerLeft = list()
        lowerLeftPosXList = list()
        lowerRight = list()
        lowerRightPosXList = list()
        mouthCornerLeftPosY = round(mc.xform(mouthCorner_l_follicle, q=True, ws=True, t=True)[1], 3)
        mouthCornerRightPosY = round(mc.xform(mouthCorner_r_follicle, q=True, ws=True, t=True)[1], 3)
        for controlHieracrchy in lipMainControlHieracrchyList:
            #position of control
            controlPosition = mc.xform(controlHieracrchy[0], q=True, ws=True, t=True)
            posX = round(controlPosition[0], 3)
            posY = round(controlPosition[1], 3)
            if posX > .001:
                if round(abs(posY-mouthCornerLeftPosY),3) <.003:
                    lipMainControlHieracrchyList[lipMainControlHieracrchyList.index(controlHieracrchy)] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lipMain_corner_l")) for ctrl in controlHieracrchy]
                elif posY > mouthCornerLeftPosY:
                    upperLeft.append(controlHieracrchy)
                    upperLeftPosXList.append(posY)
                elif posY < mouthCornerLeftPosY:
                    lowerLeft.append(controlHieracrchy)
                    lowerLeftPosXList.append(posY)

            elif posX < -.001:
                if round(abs(posY-mouthCornerLeftPosY),3) <.003:
                    lipMainControlHieracrchyList[lipMainControlHieracrchyList.index(controlHieracrchy)] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lipMain_corner_r")) for ctrl in controlHieracrchy]
                elif posY > mouthCornerRightPosY:
                    upperRight.append(controlHieracrchy)
                    upperRightPosXList.append(posY)
                elif posY < mouthCornerRightPosY:
                    lowerRight.append(controlHieracrchy)
                    lowerRightPosXList.append(posY)
            else:
                if posY > mouthCornerLeftPosY:
                    lipMainControlHieracrchyList[lipMainControlHieracrchyList.index(controlHieracrchy)] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lipMain_center_up")) for ctrl in controlHieracrchy]
                elif posY < mouthCornerLeftPosY:
                    lipMainControlHieracrchyList[lipMainControlHieracrchyList.index(controlHieracrchy)] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lipMain_center_low")) for ctrl in controlHieracrchy]
        # reorder controls
        upperLeftPosXListCopy = list(upperLeftPosXList)
        upperLeftPosXList.sort()
        # rename the controls for left and right.
        for i, pos in enumerate(upperLeftPosXListCopy):
            # rename the center controls.
            lipMainControlHieracrchyList[lipMainControlHieracrchyList.index(upperLeft[i])] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lipMain_up_{}_l".format(upperLeftPosXList.index(pos)))) for ctrl in upperLeft[i]]

        # reorder controls
        upperRightPosXListCopy = list(upperRightPosXList)
        upperRightPosXList.sort()
        # rename the controls for left and right.
        for i, pos in enumerate(upperRightPosXListCopy):
            # rename the center controls.
           lipMainControlHieracrchyList[lipMainControlHieracrchyList.index(upperRight[i])] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lipMain_up_{}_r".format(upperRightPosXList.index(pos)))) for ctrl in upperRight[i]]

        # reorder controls
        lowerLeftPosXListCopy = list(lowerLeftPosXList)
        lowerLeftPosXList.sort()
        lowerLeftPosXList.reverse()
        # rename the controls for left and right.
        for i, pos in enumerate(lowerLeftPosXListCopy):
            # rename the center controls.
            lipMainControlHieracrchyList[lipMainControlHieracrchyList.index(lowerLeft[i])] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lipMain_low_{}_l".format(lowerLeftPosXList.index(pos)))) for ctrl in lowerLeft[i]]

        # reorder controls
        lowerRightPosXListCopy = list(lowerRightPosXList)
        lowerRightPosXList.sort()
        lowerRightPosXList.reverse()
        # rename the controls for left and right.
        for i, pos in enumerate(lowerRightPosXListCopy):
            # rename the center controls.
            lipMainControlHieracrchyList[lipMainControlHieracrchyList.index(lowerRight[i])] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lipMain_low_{}_r".format(lowerRightPosXList.index(pos)))) for ctrl in lowerRight[i]]


        # create the controls
        # If there is a hierarchy argument passed in. We will loop through and create the hiearchy.
        # move the orients
        nodeDataObj = None
        if os.path.isfile(orientFile):
            nodeDataObj = node_data.NodeData()
            nodeDataObj.read(orientFile)

        driverMouthCorners = []
        animMouthCorners = []
        cornerControlHierarchyList = []
        jawPins = []
        headPins = []
        for follicle in (mouthCorner_l_follicle, mouthCorner_r_follicle):
            parent = follicle
            controlName = follicle.split("_follicle")[0]
            # Main mouth corner control
            # create the control with a large enough hierarchy to create proper SDK's
            ctrlHierarchy = control.create(name=controlName, 
                controlType="square", 
                hierarchy=['nul','ort', 'auto'], 
                color=common.BLACK,
                parent=parent,
                type='face')
            attribute.lockAndHide(ctrlHierarchy[-1], ['r', 'rx', 'ry', 'rz', 's', 'sx', 'sy', 'sz'])
            cornerControlHierarchyList.append(ctrlHierarchy)
            animMouthCorners.append(controlName)
            driverMouthCorner = mc.createNode("joint", name="{}_driver".format(controlName))
            driverMouthCorners.append(driverMouthCorner)
            # mover the driver to the orient and parent it under the orient
            mc.parent(driverMouthCorner, ctrlHierarchy[1])
            #mc.xform(driverMouthCorner, ws=True, matrix=mc.xform(ctrlHierarchy[1], q=True, ws=True, matrix=True))
            
            # turn off the visibility of the driver
            mc.setAttr("{}.drawStyle".format(driverMouthCorner), 2)
            # turn on the handle for the mouth corner control and move it 
            mc.setAttr("{}.displayHandle".format(ctrlHierarchy[-1]), 1)
            mc.setAttr("{}.selectHandleX".format(ctrlHierarchy[-1]) ,0.2)
            # zero out the mouth corner hierarchy so it's in the correct position.
            mc.setAttr("{}.translate".format(ctrlHierarchy[0]), 0,0,0)
            #mc.setAttr("{}.rotate".format(ctrlHierarchy[0]), 0,0,0)
            mc.delete(mc.listRelatives(ctrlHierarchy[-1], c=True, shapes=True)[0])

            # create the drivers for the lip_L/R
            neutral = mc.createNode("transform", name="{}_neutral".format(controlName), parent=ctrlHierarchy[1])
            headPin = mc.createNode("transform", name="{}_headPin".format(controlName), parent=ctrlHierarchy[1])
            jawPin = mc.createNode("transform", name="{}_jawPin".format(controlName), parent=ctrlHierarchy[1])
            # Store for constraining later
            headPins.append(headPin)
            jawPins.append(jawPin)

            for pinGrp in [neutral, headPin, jawPin]:
                cst = mc.parentConstraint(pinGrp, ctrlHierarchy[2])[0]
                mc.setAttr(cst+'.interpType', 2)

            # constrain the driver to the control
            mc.pointConstraint(ctrlHierarchy[-1], driverMouthCorner, mo=True)

            if nodeDataObj:
                nodeDataObj.applyData([ctrlHierarchy[1]])

            # create the head and jaw pinning.
            mc.addAttr(controlName, ln="pinning", nn="----------", at="enum", enumName="Pinning", keyable=True)
            attribute.lock(controlName, "pinning")
            mc.addAttr(controlName, ln="pin", at="double", min=-10, max=10, dv=0, keyable=True)
            mc.setDrivenKeyframe("{}.{}W0".format(cst,neutral), 
                cd="{}.pin".format(controlName), v=1, dv=0)
            mc.setDrivenKeyframe("{}.{}W1".format(cst,headPin), 
                cd="{}.pin".format(controlName), v=0, dv=0)
            mc.setDrivenKeyframe("{}.{}W2".format(cst,jawPin), 
                cd="{}.pin".format(controlName), v=0, dv=0)
            mc.setDrivenKeyframe("{}.{}W0".format(cst,neutral), 
                cd="{}.pin".format(controlName), v=0, dv=-10)
            mc.setDrivenKeyframe("{}.{}W1".format(cst,headPin), 
                cd="{}.pin".format(controlName), v=0, dv=-10)
            mc.setDrivenKeyframe("{}.{}W2".format(cst,jawPin), 
                cd="{}.pin".format(controlName), v=1, dv=-10)
            mc.setDrivenKeyframe("{}.{}W0".format(cst,neutral), 
                cd="{}.pin".format(controlName), v=0, dv=10)
            mc.setDrivenKeyframe("{}.{}W1".format(cst,headPin), 
                cd="{}.pin".format(controlName), v=1, dv=10)
            mc.setDrivenKeyframe("{}.{}W2".format(cst,jawPin), 
                cd="{}.pin".format(controlName), v=0, dv=10)

            # create the set driven keyframes
            ty_tz_dkeys = []
            for attr in ['x','y','z']:
                for lipMainControl in lipMainControlHieracrchyList:

                    # Translates
                    if "_l_" in lipMainControl[3] and follicle == mouthCorner_l_follicle:
                        mc.setDrivenKeyframe("{}.t{}".format(lipMainControl[3],attr), 
                            cd="{}.t{}".format(driverMouthCorner,attr), v=0, dv=0)
                        mc.setDrivenKeyframe("{}.t{}".format(lipMainControl[3],attr), 
                            cd="{}.t{}".format(driverMouthCorner,attr), v=1, dv=1)
                        mc.setDrivenKeyframe("{}.t{}".format(lipMainControl[3],attr), 
                            cd="{}.t{}".format(driverMouthCorner,attr), v=-1, dv=-1)

                        dkey = mc.listConnections("{}.t{}".format(driverMouthCorner,attr), type='animCurveUL')[-1]
                        dkey = mc.rename(dkey, lipMainControl[3]+'_translate'+attr.upper())

                        # RY Rotation driven by TX
                        if attr == "x":
                            mc.setDrivenKeyframe("{}.ry".format(lipMainControl[2]), 
                                cd="{}.t{}".format(driverMouthCorner,attr), v=0, dv=0)
                            mc.setDrivenKeyframe("{}.ry".format(lipMainControl[2]), 
                                cd="{}.t{}".format(driverMouthCorner,attr), v=10, dv=1)
                            mc.setDrivenKeyframe("{}.ry".format(lipMainControl[2]), 
                                cd="{}.t{}".format(driverMouthCorner,attr), v=-10, dv=-1)

                        # TY driving TZ
                        if attr == "y":
                            mc.setDrivenKeyframe("{}.tz".format(lipMainControl[3]),
                                                 cd="{}.t{}".format(driverMouthCorner,attr), v=0, dv=0)
                            mc.setDrivenKeyframe("{}.tz".format(lipMainControl[3]),
                                                 cd="{}.t{}".format(driverMouthCorner,attr), v=0, dv=1)
                            mc.setDrivenKeyframe("{}.tz".format(lipMainControl[3]),
                                                 cd="{}.t{}".format(driverMouthCorner,attr), v=0, dv=-1)

                            dkey = mc.listConnections("{}.t{}".format(driverMouthCorner,attr), type='animCurveUL')[-1]
                            dkey = mc.rename(dkey, driverMouthCorner+'_TY__'+lipMainControl[3]+'_TZ')
                            ty_tz_dkeys.append(dkey)


                    elif  "_r_" in lipMainControl[3] and follicle == mouthCorner_r_follicle:

                        # Translates
                        mc.setDrivenKeyframe("{}.t{}".format(lipMainControl[3],attr), 
                            cd="{}.t{}".format(driverMouthCorner,attr), v=0, dv=0)
                        mc.setDrivenKeyframe("{}.t{}".format(lipMainControl[3],attr), 
                            cd="{}.t{}".format(driverMouthCorner,attr), v=1, dv=1)
                        mc.setDrivenKeyframe("{}.t{}".format(lipMainControl[3],attr), 
                            cd="{}.t{}".format(driverMouthCorner,attr), v=-1, dv=-1)

                        dkey = mc.listConnections("{}.t{}".format(driverMouthCorner,attr), type='animCurveUL')[-1]
                        dkey = mc.rename(dkey, lipMainControl[3]+'_translate'+attr.upper())

                        # RY Rotation driven by TX
                        if attr == "x":
                            mc.setDrivenKeyframe("{}.ry".format(lipMainControl[2]), 
                                cd="{}.t{}".format(driverMouthCorner,attr), v=0, dv=0)
                            mc.setDrivenKeyframe("{}.ry".format(lipMainControl[2]), 
                                cd="{}.t{}".format(driverMouthCorner,attr), v=10, dv=1)
                            mc.setDrivenKeyframe("{}.ry".format(lipMainControl[2]), 
                                cd="{}.t{}".format(driverMouthCorner,attr), v=-10, dv=-1)

                        # TY driving TZ
                        if attr == "y":
                            mc.setDrivenKeyframe("{}.tz".format(lipMainControl[3]),
                                                 cd="{}.t{}".format(driverMouthCorner,attr), v=0, dv=0)
                            mc.setDrivenKeyframe("{}.tz".format(lipMainControl[3]),
                                                 cd="{}.t{}".format(driverMouthCorner,attr), v=0, dv=1)
                            mc.setDrivenKeyframe("{}.tz".format(lipMainControl[3]),
                                                 cd="{}.t{}".format(driverMouthCorner,attr), v=0, dv=-1)

                            dkey = mc.listConnections("{}.t{}".format(driverMouthCorner,attr), type='animCurveUL')[-1]
                            dkey = mc.rename(dkey, driverMouthCorner+'_TY__'+lipMainControl[3]+'_TZ')
                            ty_tz_dkeys.append(dkey)

        # Set driven keys to be post and pre infinity
        driven_keys = mc.listConnections(driverMouthCorners[0], type='animCurveUL')
        driven_keys += mc.listConnections(driverMouthCorners[1], type='animCurveUL')
        driven_keys += mc.ls('lipMain_*_rot_def_auto*', type='animCurveUA')
        for x in driven_keys:
            mc.setAttr(x + '.preInfinity', 1)
            mc.setAttr(x + '.postInfinity', 1)
            mc.keyTangent(x, index=(0, 0), inTangentType='spline')
            mc.keyTangent(x, index=(0, 0), outTangentType='spline')
            mc.keyTangent(x, index=(2, 2), inTangentType='spline')
            mc.keyTangent(x, index=(2, 2), outTangentType='spline')

        # control prefix for the lips
        controlPrefix = "lip"
        bindmeshGeometry, follicleList, controlHieracrchyList, jointList = self.__buildCurveRig(lipCurve, controlPrefix , parentGroup)

        # get the position of the controls for lip tweakers
        upperLeft = list()
        upperLeftPosXList = list()
        upperRight = list()
        upperRightPosXList = list()
        lowerLeft = list()
        lowerLeftPosXList = list()
        lowerRight = list()
        lowerRightPosXList = list()
        mouthCornerLeftPosY = round(mc.xform(mouthCorner_l_follicle, q=True, ws=True, t=True)[1], 3)
        mouthCornerRightPosY = round(mc.xform(mouthCorner_r_follicle, q=True, ws=True, t=True)[1], 3)
        for controlHieracrchy in controlHieracrchyList:
            # create the joint that we will use later to deform the base wire.
            baseCurveJoint = mc.joint(name=jointList[controlHieracrchyList.index(controlHieracrchy)].replace("_jnt","_baseCurve_jnt"))
            # hide the base curve joint. Then parent it under the null node
            mc.setAttr("{}.v".format(baseCurveJoint), 0)
            mc.parent(baseCurveJoint, controlHieracrchy[0])
            #position of control
            controlPosition = mc.xform(controlHieracrchy[0], q=True, ws=True, t=True)
            posX = round(controlPosition[0], 3)
            posY = round(controlPosition[1], 3)
            if posX > .001:
                if round(abs(posY-mouthCornerLeftPosY),3) <.003:
                    controlHieracrchyList[controlHieracrchyList.index(controlHieracrchy)] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lip_corner_l")) for ctrl in controlHieracrchy]
                elif posY > mouthCornerLeftPosY:
                    upperLeft.append(controlHieracrchy)
                    upperLeftPosXList.append(posY)
                elif posY < mouthCornerLeftPosY:
                    lowerLeft.append(controlHieracrchy)
                    lowerLeftPosXList.append(posY)

            elif posX < -.001:
                if round(abs(posY-mouthCornerLeftPosY),3) <.003:
                    controlHieracrchyList[controlHieracrchyList.index(controlHieracrchy)] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lip_corner_r")) for ctrl in controlHieracrchy]
                elif posY > mouthCornerRightPosY:
                    upperRight.append(controlHieracrchy)
                    upperRightPosXList.append(posY)
                elif posY < mouthCornerRightPosY:
                    lowerRight.append(controlHieracrchy)
                    lowerRightPosXList.append(posY)
            else:
                if posY > mouthCornerLeftPosY:
                    controlHieracrchyList[controlHieracrchyList.index(controlHieracrchy)] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lip_center_up")) for ctrl in controlHieracrchy]
                elif posY < mouthCornerLeftPosY:
                    controlHieracrchyList[controlHieracrchyList.index(controlHieracrchy)] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lip_center_low")) for ctrl in controlHieracrchy]
        # reorder controls
        upperLeftPosXListCopy = list(upperLeftPosXList)
        upperLeftPosXList.sort()
        # rename the controls for left and right.
        for i, pos in enumerate(upperLeftPosXListCopy):
            # rename the center controls.
            controlHieracrchyList[controlHieracrchyList.index(upperLeft[i])] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lip_up_{}_l".format(upperLeftPosXList.index(pos)))) for ctrl in upperLeft[i]]

        # reorder controls
        upperRightPosXListCopy = list(upperRightPosXList)
        upperRightPosXList.sort()
        # rename the controls for left and right.
        for i, pos in enumerate(upperRightPosXListCopy):
            # rename the center controls.
           controlHieracrchyList[controlHieracrchyList.index(upperRight[i])] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lip_up_{}_r".format(upperRightPosXList.index(pos)))) for ctrl in upperRight[i]]

        # reorder controls
        lowerLeftPosXListCopy = list(lowerLeftPosXList)
        lowerLeftPosXList.sort()
        lowerLeftPosXList.reverse()
        # rename the controls for left and right.
        for i, pos in enumerate(lowerLeftPosXListCopy):
            # rename the center controls.
            controlHieracrchyList[controlHieracrchyList.index(lowerLeft[i])] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lip_low_{}_l".format(lowerLeftPosXList.index(pos)))) for ctrl in lowerLeft[i]]

        # reorder controls
        lowerRightPosXListCopy = list(lowerRightPosXList)
        lowerRightPosXList.sort()
        lowerRightPosXList.reverse()
        # rename the controls for left and right.
        for i, pos in enumerate(lowerRightPosXListCopy):
            # rename the center controls.
            controlHieracrchyList[controlHieracrchyList.index(lowerRight[i])] = [mc.rename(ctrl, "_".join([name for name in ctrl.split("_") if not name.isdigit()]).replace(controlPrefix, "lip_low_{}_r".format(lowerRightPosXList.index(pos)))) for ctrl in lowerRight[i]]


        # parent the curves to their respective systems
        mc.parent(lipMainCurve, "lip_main")
        mc.parent(lipCurve, "lip")

        #deform the lip bindmesh with the lip_main curve using a wire deformer.
        wireDeformer = mc.wire(bindmeshGeometry, gw=False, en=1.00, ce=0.00, li=0.00,
                w=lipMainCurve, name="{}_wire".format(lipMainCurve))[0]
        # set the default values for the wire deformer
        mc.setAttr("{}.rotation".format(wireDeformer), 0)
        mc.setAttr("{}.dropoffDistance[0]".format(wireDeformer), 100)

        # create skinCluster for the base wire
        baseCurve = "{}BaseWire".format(lipMainCurve)
        lipMainBaseCurveSkin = mc.skinCluster(*mainBaseCurveJointList+mc.ls(baseCurve),
                                    n="{}_skinCluster".format(baseCurve),
                                    tsb=True)[0]
        # set the weights to have proper weighting
        wtObj = rigrepo.libs.weights.getWeights(lipMainBaseCurveSkin)
        weightList = list()
        for i, inf in enumerate(wtObj):
            array = numpy.zeros_like(wtObj.getWeights(inf))[0]
            array[i] = 1
            weightList.append(array)
        wtObj.setWeights(weightList)
        rigrepo.libs.weights.setWeights(lipMainBaseCurveSkin, wtObj)

        # create all of the lip clusters
        lipControls = list(set(mc.ls("lip_*.__control__", o=True)).difference(set(mc.ls(["lip_upper", "lip_lower", "lip_upper_?", "lip_lower_?"]))))
        for node in lipControls:
            rigrepo.libs.cluster.create(geometry, 
                                        "{}_cluster".format(node), 
                                        contraintTypes=["orient","scale"], 
                                        parent="{}_def_auto".format(node), 
                                        parallel=False)
            nul = "{}_cluster_nul".format(node)
            mc.xform(nul, ws=True, matrix=mc.xform(node, q=True, ws=True, matrix=True))
            mc.connectAttr("{}.t".format(node), "{}_cluster_auto.t".format(node), f=True)
            mc.connectAttr("{}.r".format(node), "{}_cluster_ctrl.r".format(node), f=True)
            mc.connectAttr("{}.s".format(node), "{}_cluster_ctrl.s".format(node), f=True)

        # Set the right side nuls to be mirrored
        for ctrls in controlHieracrchyList + \
                     lipMainControlHieracrchyList + \
                     cornerControlHierarchyList:
            nul = ctrls[0]
            if nul.endswith('_r_nul'):
                mc.setAttr(nul+'.ry', -180)
                mc.setAttr(nul+'.sz', -1)

        # constrain the head and jaw pinning. Needs to be done after nul's are mirrored
        for jawPin in jawPins:
            mc.parentConstraint(jawPinTrs, jawPin, mo=True)
        for headPin in headPins:
            mc.parentConstraint(headPinTrs, headPin, mo=True)

        # Rig Sets
        #
        rigSets = 'RigSets'
        if not mc.objExists(rigSets):
            mc.sets(n=rigSets, empty=1)
        mouthSet = mc.sets(n='Mouth', empty=1)
        mc.sets(mouthSet, e=1, add=rigSets)
        # Curves
        mc.sets( ['lip_bindmesh', 'lip_main_bindmesh',
                 lipCurve, lipMainCurve], e=1, add=mouthSet)

        # Orient Sets
        #
        corner_set = mc.sets([x[1] for x in cornerControlHierarchyList], n='orients_MouthCorner')
        main_set = mc.sets([x[1] for x in lipMainControlHieracrchyList], n='orients_lipMain')
        tweak_set = mc.sets([x[1] for x in controlHieracrchyList], n='orients_lipTweakers')

        mc.sets([main_set, tweak_set, corner_set], e=1, add=mouthSet)
        # Driven Keys
        #
        #
        for driver_axis in ['x', 'y', 'z']:
            driven_keys = mc.listConnections(driverMouthCorners[0]+'.t'+driver_axis, type='animCurveUL')
            driven_keys += mc.listConnections(driverMouthCorners[1]+'.t'+driver_axis, type='animCurveUL')
            for slave_axis in ['X', 'Y', 'Z']:
                d_keys = [n for n in driven_keys if 'translate' + slave_axis in n]
                if not d_keys:
                    d_keys = [n for n in driven_keys if '_T' + slave_axis in n]
                if d_keys:
                    d_set = mc.sets(d_keys, n='dkeys_T'+driver_axis.upper()+'_T'+slave_axis)
                    mc.sets(d_set, e=1, add=mouthSet)

        # Rot Driven Keys
        #
        rot_def_auto = [x[2] for x in lipMainControlHieracrchyList]
        ry_d_keys = []
        rx_d_keys = []
        for rot in rot_def_auto:
            driven_keys = mc.listConnections(rot, type='animCurveUA')
            if driven_keys:
                for dkey in driven_keys:
                    if 'rotateY' in dkey:
                        ry_d_keys.append(dkey)
                    if 'rotateX' in dkey:
                        rx_d_keys.append(dkey)
        ry_d_keys_set = mc.sets(ry_d_keys, n='dkeys_RY')
        mc.sets([ry_d_keys_set], e=1, add=mouthSet)

        # Anim controls
        #
        animCtrls = animMouthCorners + [x[4] for x in controlHieracrchyList]
        tweak_ctrl = mc.sets(animCtrls, n='anim')
        mc.sets(tweak_ctrl, e=1, add=mouthSet)
Exemple #46
0
import maya.cmds as cmds
import maya.mel as mel

ctrlScaleMult = 1.5
sel = cmds.ls(sl=True)
rootName = 'joint'
cmds.select(cl=True)
cmds.joint(n=rootName)
for i in sel:
	cmds.select(i, r=True)
	loc = cmds.xform(q=True, piv=True)
	objBB = cmds.xform(q=True, bb=True)
	# xmin ymin zmin xmax ymax zmax.
	ctrlScale = ((abs(objBB[0]) + abs(objBB[3])) + (abs(objBB[1]) + abs(objBB[4])) / 2)
	ctrlScale *= ctrlScaleMult

	jntName = '{}_jnt'.format(i)
	cmds.joint(n=jntName)
	cmds.move(loc[0], loc[1], loc[2])
	cmds.skinCluster( jntName, i)
	cmds.parent(jntName, rootName)

	ctrlName = '{}_ctrl'.format(i)
	cmds.circle(n=ctrlName)
	cmds.move(loc[0], loc[1], loc[2])
	cmds.rotate( '90deg', 0, 0,)
	cmds.scale(ctrlScale, ctrlScale, ctrlScale)
	mel.eval('performFreezeTransformations(0)')

	cmds.parentConstraint(ctrlName, jntName, mo=True)
	cmds.scaleConstraint(ctrlName, jntName)
Exemple #47
0
def CreateWrists():
    sides = ['L', 'R']

    for side in sides:
        ctrl1 = base.circle(nr=(0, 1, 0),
                            c=(0, 0, 0),
                            radius=1,
                            degree=1,
                            s=16,
                            name="CTRL_" + side + "_Wrist0")
        ctrl2 = base.circle(nr=(0, 1, 0),
                            c=(0, 0, 0),
                            radius=1,
                            degree=1,
                            s=16,
                            name="CTRL_" + side + "_Wrist1")
        ctrl3 = base.circle(nr=(0, 1, 0),
                            c=(0, 0, 0),
                            radius=1,
                            degree=1,
                            s=16,
                            name="CTRL_" + side + "_Wrist2")

        wrist_ctrl = base.group(em=True, name="CTRL_" + side + "_Wrist")
        curves = [ctrl1, ctrl2, ctrl3]
        for cv in curves:
            crvShape = base.listRelatives(cv, shapes=True)
            base.parent(crvShape, wrist_ctrl, s=True, r=True)
            base.delete(cv)
        base.select("CTRL_" + side + "_Wrist")
        base.addAttr(shortName="PV",
                     longName="Elbow_PV",
                     attributeType='double',
                     defaultValue=0,
                     minValue=-100,
                     maxValue=100,
                     keyable=True)
        base.scale(0.07, 0.07, 0.07, wrist_ctrl)

        wristPos = base.xform(base.ls("RIG_" + side + "_Wrist"),
                              q=True,
                              t=True,
                              ws=True)
        wristRot = base.joint(base.ls("RIG_" + side + "_Wrist"),
                              q=True,
                              o=True)
        if base.objExists("RIG_L_ArmTwist_*"):
            armTwists = base.ls("RIG_L_ArmTwist_*")
            print base.xform(base.ls("RIG_" + side + "_ArmTwist_" +
                                     str(len(armTwists) - 1)),
                             q=True,
                             ws=True,
                             ro=True)
            wristRotation = base.xform(base.ls("RIG_" + side + "_ArmTwist_" +
                                               str(len(armTwists) - 1)),
                                       q=True,
                                       ws=True,
                                       ro=True)
        else:
            wristRotation = base.xform(base.ls("RIG_" + side + "_Elbow"),
                                       q=True,
                                       ws=True,
                                       ro=True)
        base.move(wristPos[0], wristPos[1], wristPos[2], wrist_ctrl)
        wristGrp = base.group(em=True, name='CTRL_GRP_' + side + '_Wrist')
        base.move(wristPos[0], wristPos[1], wristPos[2], wristGrp)
        base.parent(wrist_ctrl, wristGrp)
        # base.parent(wrist_ctrl, world = True)

        base.rotate(0, 0, -wristRotation[2], wristGrp)
        base.parent(wristGrp, "MASTER_CONTROLLER")
Exemple #48
0
    def __buildCurveRig(self, curve, name='lip', parent=None):
        '''
        This will build a rig setup based on the curve that is passed in.

        :param curve: NurbsCurve name you want to build the rig on.
        :type curve: str

        :param name: This will be used to name the control hierachy and joints in the rig.
        :type name: str

        :return: This method will return the data needed to make adjustments to rig.
        :rtype: tuple
        '''
        # Do some check
        if not mc.objExists(curve):
            raise RuntimeError("{} doesn't exist in the current Maya session.".format(curve))
        # If the name passed in doesn't exist, we will create a transform as the parent group
        # for the rig.
        if not mc.objExists(name):
            mc.createNode("transform", n=name)
        # create the bindmesh 
        #
        # follicleList = (follicle transform, follicle shape) 
        # bindmeshGeometry = geometry name of bindmesh
        #
        bindmeshGeometry, follicleList = bindmesh.createFromCurve(name, curve)
        # emptry list to append controls to in the loop
        controlHieracrchyList = list()
        jointList = list()

        # loop through and create controls on the follicles so we have controls to deform the wire.
        for follicle in follicleList:
            # get the follicle transform so we can use it to parent the control to it.
            follicleIndex = follicleList.index(follicle)
            # create the control with a large enough hierarchy to create proper SDK's
            ctrlHierarchy = control.create(name="{}_{}".format(name, follicleIndex), 
                controlType="square", 
                hierarchy=['nul','ort','rot_def_auto','def_auto'], 
                parent=follicle,
                type='face')

            # create the joint that will drive the curve.
            jnt = mc.joint(n="{}_{}_jnt".format(name, follicleIndex))
            # make sure the joint is in the correct space
            mc.setAttr("{}.translate".format(jnt), 0,0,0)
            mc.setAttr("{}.rotate".format(jnt), 0,0,0)
            mc.setAttr("{}.drawStyle".format(jnt),2)
            mc.setAttr("{}.displayHandle".format(ctrlHierarchy[-1]), 1)
            mc.delete(mc.listRelatives(ctrlHierarchy[-1], c=True, shapes=True)[0])

            # zero out the nul for the control hierarchy so it's in the correct position.
            mc.setAttr("{}.translate".format(ctrlHierarchy[0]), 0,0,0)
            #mc.setAttr("{}.rotate".format(ctrlHierarchy[0]), 0,0,0)
            # set the visibility of the shape node for the follicle to be off.
            # append the control and the follicle transform to their lists
            controlHieracrchyList.append(ctrlHierarchy)
            jointList.append(jnt)

        # This will parent all of the data for the rig to the system group "name"
        for data in (bindmeshGeometry, follicleList):
            mc.parent(data, name)

        # If parent the parent is passed in we will parent the system to the parent.
        if parent:
            if not mc.objExists(parent):
                mc.warning('Created the system but the current parent "{}" does not exist in the \
                    current Maya session.'.format(parent))
            else:
                mc.parent(name, parent)

        # create the skinCluster for the lipMainCurve
        mc.skinCluster(*jointList + [curve], tsb=True, name="{}_skinCluster".format(curve))

        # set the visibility of the bindmesh.
        mc.setAttr("{}.v".format(bindmeshGeometry), 0 )
        mc.setAttr("{}.v".format(curve), 0 )
        return bindmeshGeometry, follicleList, controlHieracrchyList, jointList
Exemple #49
0
    def ArmatureArm(self, side):
        sign = 1
        sideindex = 0
        if side == "L":
            sign = 1
            sideindex = 0
        else:
            sign = -1
            sideindex = 1
        # ClavicleJoint
        cmds.select(self.SpineTopJoint)
        ClavicleJoint = self.Joint_Clavicles[sideindex]
        cmds.joint(n=ClavicleJoint)
        Pcon = cmds.parentConstraint(self.Proxy_Clavicle[sideindex],
                                     ClavicleJoint)
        cmds.delete(Pcon)
        Acon = cmds.aimConstraint(self.Proxy_Shoulder[sideindex],
                                  ClavicleJoint,
                                  aimVector=[1 * sign, 0, 0],
                                  upVector=[0, 1 * sign, 0],
                                  worldUpType="objectrotation",
                                  worldUpVector=[0, 1, 0],
                                  worldUpObject=self.Proxy_Clavicle[sideindex])
        cmds.delete(Acon)
        cmds.makeIdentity(ClavicleJoint, apply=True, r=1)

        # ShoulderJoint
        cmds.select(ClavicleJoint)
        ShoulderJoint = self.Joint_Shoulders[sideindex]
        cmds.joint(n=ShoulderJoint)
        Pcon = cmds.parentConstraint(self.Proxy_Shoulder[sideindex],
                                     ShoulderJoint)
        cmds.delete(Pcon)
        Acon = cmds.aimConstraint(self.Proxy_Elbow[sideindex],
                                  ShoulderJoint,
                                  aimVector=[1 * sign, 0, 0],
                                  upVector=[0, 1 * sign, 0],
                                  worldUpType="objectrotation",
                                  worldUpVector=[0, 1, 0],
                                  worldUpObject=self.Proxy_Shoulder[sideindex])
        cmds.delete(Acon)
        cmds.makeIdentity(ClavicleJoint, apply=True, r=1)

        # ElbowJoint
        cmds.select(ShoulderJoint)
        ElbowJoint = self.Joint_Elbows[sideindex]
        cmds.joint(n=ElbowJoint)
        Pcon = cmds.parentConstraint(self.Proxy_Elbow[sideindex], ElbowJoint)
        cmds.delete(Pcon)
        Acon = cmds.aimConstraint(self.Proxy_Wrist[sideindex],
                                  ElbowJoint,
                                  aimVector=[1 * sign, 0, 0],
                                  upVector=[0, 1 * sign, 0],
                                  worldUpType="objectrotation",
                                  worldUpVector=[0, 1, 0],
                                  worldUpObject=self.Proxy_Elbow[sideindex])
        cmds.delete(Acon)
        cmds.makeIdentity(ClavicleJoint, apply=True, r=1)

        # WristJoint
        cmds.select(ElbowJoint)
        WristJoint = self.Joint_Wrists[sideindex]
        cmds.joint(n=WristJoint)
        Pcon = cmds.parentConstraint(self.Proxy_Wrist[sideindex], WristJoint)
        cmds.delete(Pcon)
        cmds.select(ElbowJoint)
        WristDummyJoint = self.Joint_WristDummys[sideindex]
        cmds.joint(n=WristDummyJoint)
        Pcon = cmds.parentConstraint(self.Proxy_Wrist[sideindex],
                                     WristDummyJoint)
        cmds.delete(Pcon)
        if side == "R":
            cmds.rotate(180,
                        0,
                        0,
                        WristJoint,
                        WristDummyJoint,
                        r=True,
                        os=True)
        cmds.makeIdentity(WristJoint, WristDummyJoint, apply=True, r=1)

        # Thumb
        cmds.select(cl=True)
        cmds.select("Proxies_" + side + "_Thumb??")
        ThumbList = cmds.ls(sl=True, objectsOnly=True)
        count = len(ThumbList)
        tips = "Proxies_" + side + "_ThumbJTip"
        ThumbList.append(tips)
        ThumbJNT_list = []
        cmds.select(cl=True)
        for i in range(0, count + 1):
            if i > 0:
                cmds.select(ThumbJNT_list[i - 1])
            namesp = ThumbList[i].split("_")
            newName = self.name + "_" + side + "_" + namesp[2] + "_JNT"
            cmds.joint(n=newName)
            ThumbJNT_list.append(newName)
            Pcon = cmds.parentConstraint(ThumbList[i], newName)
            cmds.delete(Pcon)
        cmds.parent(ThumbJNT_list[0], WristJoint)
        cmds.parent(WristJoint, w=True)

        # Hand
        cmds.select(cl=True)
        cmds.select("Proxies_" + side + "_Finger_*_J1")
        FingerList = cmds.ls(sl=True, objectsOnly=True)
        FingersFirstJointList = []
        for Finger in FingerList:
            cmds.select(Finger)
            name = Finger[0:-1]
            cmds.select(name + "?")
            jointlist = cmds.ls(sl=True)
            tip = name + "Tip"
            jointlist.append(tip)
            cmds.select(WristJoint)
            i = 0
            FinList = []
            for jo in jointlist:
                namesp = jo.split("_")  # Proxies_L_Finger_1_J1
                newName = self.name + "_" + side + "_" + namesp[2] + namesp[
                    3] + namesp[4] + "_JNT"
                if i > 0:
                    cmds.select(FinList[i - 1])
                else:
                    FingersFirstJointList.append(newName)
                cmds.joint(n=newName)
                Pcon = cmds.parentConstraint(jointlist[i], newName)
                cmds.delete(Pcon)
                FinList.append(newName)
                i += 1

        # Palm
        cmds.select(WristJoint)
        Palm = self.Joint_Palms[sideindex]
        cmds.joint(n=Palm)
        Pcon = cmds.parentConstraint(self.Proxy_Palm[sideindex], Palm)
        cmds.delete(Pcon)
        if side == "R":
            cmds.rotate(180, 0, 0, Palm, r=True, os=True)
        cmds.makeIdentity(Palm, apply=True, r=1)
        for Finger in FingersFirstJointList:
            cmds.parent(Finger, Palm)

        # Forearm
        cmds.select(cl=True)
        Forearm = self.Joint_Forearms[sideindex]
        cmds.joint(n=Forearm)
        Pcon = cmds.parentConstraint(WristJoint, ElbowJoint, Forearm)
        cmds.delete(Pcon)
        cmds.parent(Forearm, ElbowJoint)
        if side == "R":
            cmds.rotate(180, 0, 0, Forearm, r=True, os=True)
        cmds.makeIdentity(Forearm, apply=True, r=1)
        pass
Exemple #50
0
    def mirrorControl(self):
        self.mirrorJointList = []
        self.mirrorJointList_add = []
        self.parentGroupList = []
        sel_re = []
        sel = cmds.ls(sl=True)
        for k in sel:
            tempParentGroupList = cmds.listRelatives(k, allParents=True)
            self.parentGroupList.append(tempParentGroupList)
        for i in sel:
            cmds.select(cl=True)
            cmds.select(i, r=True)
            tempMirrorJoint = cmds.joint(n='%s_temp_JNT' % i)
            cmds.parent(tempMirrorJoint, w=True)
            cmds.parent(i, tempMirrorJoint)
            self.mirrorJointList.append(tempMirrorJoint)
        #  미러조인트 방법이랑 방향 가져와서 세팅
        buttonXYZ = self.sender()
        btn = buttonXYZ.objectName()
        btn_XYZ = btn.split('_')

        for i in self.mirrorJointList:
            if self.ui.mirrorCON_world_RDB.isChecked() == True:
                if btn_XYZ[1] == 'X':
                    tempMirrorJoint2 = cmds.mirrorJoint(i,
                                                        mxy=True,
                                                        mirrorBehavior=False,
                                                        searchReplace=('L_',
                                                                       'R_'))
                    self.mirrorJointList_add.append(tempMirrorJoint2[0])
                elif btn_XYZ[1] == 'Y':
                    tempMirrorJoint2 = cmds.mirrorJoint(i,
                                                        myz=True,
                                                        mirrorBehavior=False,
                                                        searchReplace=('L_',
                                                                       'R_'))
                    self.mirrorJointList_add.append(tempMirrorJoint2[0])
                elif btn_XYZ[1] == 'Z':
                    tempMirrorJoint2 = cmds.mirrorJoint(i,
                                                        mxz=True,
                                                        mirrorBehavior=False,
                                                        searchReplace=('L_',
                                                                       'R_'))
                    self.mirrorJointList_add.append(tempMirrorJoint2[0])
            if self.ui.mirrorCON_behavior_RDB.isChecked() == True:
                if btn_XYZ[1] == 'X':
                    tempMirrorJoint2 = cmds.mirrorJoint(i,
                                                        mxy=True,
                                                        mirrorBehavior=True,
                                                        searchReplace=('L_',
                                                                       'R_'))
                    self.mirrorJointList_add.append(tempMirrorJoint2[0])
                elif btn_XYZ[1] == 'Y':
                    tempMirrorJoint2 = cmds.mirrorJoint(i,
                                                        myz=True,
                                                        mirrorBehavior=True,
                                                        searchReplace=('L_',
                                                                       'R_'))
                    self.mirrorJointList_add.append(tempMirrorJoint2[0])
                elif btn_XYZ[1] == 'Z':
                    tempMirrorJoint2 = cmds.mirrorJoint(i,
                                                        mxz=True,
                                                        mirrorBehavior=True,
                                                        searchReplace=('L_',
                                                                       'R_'))
                    self.mirrorJointList_add.append(tempMirrorJoint2[0])
        cmds.ungroup(self.mirrorJointList_add)
        cmds.ungroup(self.mirrorJointList)
Exemple #51
0
def CreateJoint():
    sels = cmds.ls(selection=True)
    cmds.select(cl=True)

    for sel in sels:
        cmds.matchTransform(cmds.joint(), sel)
Exemple #52
0
    def OrientJoints(self, side):
        sign = 1
        sideindex = 0
        if side == "L":
            sign = 1
            sideindex = 0
        else:
            sign = -1
            sideindex = 1

        HipJoint = self.Joint_Hips[sideindex]
        KneeJoint = self.Joint_Knees[sideindex]
        AnkleJoint = self.Joint_Ankles[sideindex]
        ForearmJoint = self.Joint_Forearms[sideindex]
        WristJoint = self.Joint_Wrists[sideindex]
        WristDummyJoint = self.Joint_WristDummys[sideindex]
        ToeJoint = self.Joint_Toes[sideindex]
        Clavicle = self.Joint_Clavicles[sideindex]

        # HipJoint
        cmds.parent(KneeJoint, w=True)
        Acon = cmds.aimConstraint(self.Proxy_Knee[sideindex],
                                  HipJoint,
                                  aimVector=[1, 0, 0],
                                  upVector=[0, 1, 0],
                                  worldUpType="objectrotation",
                                  worldUpVector=[0, 0, 1],
                                  worldUpObject=self.Proxy_Knee[sideindex])
        cmds.delete(Acon)
        cmds.makeIdentity(HipJoint, apply=True, r=1)
        cmds.parent(KneeJoint, HipJoint)

        KneeLength = cmds.xform(KneeJoint, q=True, t=True)
        AnkleLength = cmds.xform(AnkleJoint, q=True, t=True)
        cmds.select(AnkleJoint)
        cmds.joint(e=True,
                   oj="xyz",
                   secondaryAxisOrient="yup",
                   ch=True,
                   zso=True)

        # FOREARM
        cmds.setAttr("%s.jointOrient" % ForearmJoint, 0, 0, 0)

        # Thumb
        cmds.select("Mic_" + side + "_ThumbJ?_JNT")
        ThumbJNT_list = cmds.ls(sl=True)
        for thumb in ThumbJNT_list:
            cmds.select(thumb)
            cmds.joint(e=True,
                       oj="xzy",
                       secondaryAxisOrient="xdown",
                       ch=True,
                       zso=True)

        # FIX WRIST ORIENTATIONS
        Ocon = cmds.orientConstraint(WristJoint, WristDummyJoint)
        cmds.delete(Ocon)
        cmds.makeIdentity(WristDummyJoint, apply=True, t=1, r=1, s=1)

        # Toe
        cmds.select(ToeJoint)
        cmds.joint(e=True, oj="none", ch=True, zso=True)
        cmds.rotate(0, 90, 0, ToeJoint)
        cmds.makeIdentity(HipJoint, apply=True, r=1)
        cmds.select(cl=True)

        # Fix right side
        if side == "R":
            Clavicle_R_Orient = cmds.getAttr("%s.jointOrient" % Clavicle)
            Hip_R_Orient = cmds.getAttr("%s.jointOrient" % HipJoint)
            cmds.setAttr("%s.jointOrientX" % HipJoint, Hip_R_Orient[0][0] * -1)
            cmds.setAttr("%s.jointOrientY" % HipJoint, Hip_R_Orient[0][1] * -1)
            cmds.setAttr("%s.jointOrientZ" % HipJoint,
                         Hip_R_Orient[0][2] + 180)

            cmds.select(KneeJoint, hi=True)
            reOrientJoints = cmds.ls(sl=True)
            for currentJoint in reOrientJoints:
                currentOrient = cmds.getAttr(currentJoint + ".jointOrient")
                currentPos = cmds.getAttr(currentJoint + ".tx")
                cmds.setAttr("%s.jointOrientX" % currentJoint,
                             currentOrient[0][0] * -1)
                cmds.setAttr("%s.jointOrientY" % currentJoint,
                             currentOrient[0][1] * -1)
                cmds.setAttr("%s.tx" % currentJoint, currentPos * -1)

        pass
Exemple #53
0
def jnt(item, name_):
    jnt_ = cmds.joint(n='{}_{}'.format(name_, 'JNT'))
    xform_(item, jnt_)
    return jnt_
Exemple #54
0
    def MainProcessing(self):
        # Create torso Joints Chain
        cmds.select(cl=True)
        cmds.joint(n=self.RootJoint)
        self.AlignPointPos(self.Creator.Proxies_Root, self.RootJoint)
        cmds.select(self.RootJoint)
        cmds.joint(n=self.RootJointTemp)
        self.AlignPointPos(self.Creator.Proxies_SpineList[0],
                           self.RootJointTemp)
        self.SpineJointList = [self.RootJointTemp]
        Proxy_spineJoints = self.Creator.Proxies_SpineList
        i = 1
        while i < len(Proxy_spineJoints):
            cmds.select(self.SpineJointList[i - 1])
            SpineTemp = "_SpineTemp0"
            JointSuffix = "_JNT"
            spineName = self.name + SpineTemp + str(i + 1) + JointSuffix
            cmds.joint(n=spineName)
            self.AlignPointPos(Proxy_spineJoints[i], spineName)
            cmds.select(spineName)
            self.SpineJointList.append(spineName)
            i += 1
        cmds.select(self.SpineJointList[-1])
        cmds.joint(n=self.SpineTopJoint)
        # cmds.pointConstraint(self.Creator.Proxies_SpineTop, self.SpineTopJoint)
        self.AlignPointPos(self.Creator.Proxies_SpineTop, self.SpineTopJoint)

        # Create Neck Joints Chain
        # todo : only once neck
        cmds.select(self.SpineTopJoint)
        cmds.joint(n=self.NeckJointTemp)
        self.AlignPointPos(self.Creator.Proxies_NeckList[0],
                           self.NeckJointTemp)

        # Head
        cmds.select(self.NeckJointTemp)
        cmds.joint(n=self.HeadJoint)
        self.AlignPointPos(self.Creator.Proxies_Head, self.HeadJoint)
        # _HeadTip

        cmds.select(self.HeadJoint)
        cmds.joint(n=self.HeadTipJoint)
        self.AlignPointPos(self.Creator.Proxies_HeadTip, self.HeadTipJoint)
        # Jaw
        cmds.select(self.HeadJoint)
        cmds.joint(n=self.JawJoint)
        self.AlignPointPos(self.Creator.Proxies_Jaw, self.JawJoint)
        # JawTip
        cmds.select(self.HeadJoint)
        cmds.joint(n=self.JawTipJoint)
        self.AlignPointPos(self.Creator.Proxies_JawTip, self.JawTipJoint)

        # other
        self.ArmatueSide("L")
        self.ArmatueSide("R")

        # Orient
        cmds.joint(self.RootJoint,
                   e=True,
                   oj="none",
                   secondaryAxisOrient="yup",
                   zso=True)
        cmds.joint(self.SpineJointList,
                   e=True,
                   oj="xyz",
                   secondaryAxisOrient="zdown",
                   zso=True)
        cmds.joint(self.SpineTopJoint,
                   e=True,
                   oj="xyz",
                   secondaryAxisOrient="zdown",
                   zso=True)
        cmds.joint(self.NeckJointTemp,
                   e=True,
                   oj="xyz",
                   secondaryAxisOrient="zdown",
                   zso=True)
        cmds.joint(self.HeadJoint,
                   e=True,
                   oj="xyz",
                   secondaryAxisOrient="zdown",
                   zso=True)
        cmds.joint(self.HeadTipJoint,
                   e=True,
                   oj="none",
                   secondaryAxisOrient="yup",
                   zso=True)
        self.OrientJoints("L")
        self.OrientJoints("R")
        pass
Exemple #55
0
    def PutMeOn(Side, PlaneName, *args):

        cmds.select(cl=1)
        UpJoint1 = cmds.joint(n=Side + '_' + PlaneName + '_Up_Bind01')
        cmds.select(cl=1)
        UpJoint2 = cmds.joint(n=Side + '_' + PlaneName + '_Up_Bind02')
        cmds.select(cl=1)
        UpJoint3 = cmds.joint(n=Side + '_' + PlaneName + '_Up_Bind03')
        cmds.select(cl=1)
        UpJoint4 = cmds.joint(n=Side + '_' + PlaneName + '_Up_Bind01')
        cmds.select(cl=1)
        UpJoint5 = cmds.joint(n=Side + '_' + PlaneName + '_Up_Bind02')

        POSI1 = cmds.shadingNode('pointOnSurfaceInfo',
                                 asUtility=True,
                                 name=Side + '_' + PlaneName +
                                 '_PointOnSurface_01')
        cmds.setAttr(str(POSI1) + '.parameterV', 0.5)
        cmds.setAttr(str(POSI1) + '.parameterU', 0)
        cmds.connectAttr(str(Side) + '_' + str(PlaneName) + '.worldSpace[0]',
                         (POSI1) + '.inputSurface',
                         f=1)
        cmds.connectAttr(str(POSI1) + '.position',
                         str(UpJoint1) + '.translate',
                         f=1)

        POSI2 = cmds.shadingNode('pointOnSurfaceInfo',
                                 asUtility=True,
                                 name=Side + '_' + PlaneName +
                                 '_PointOnSurface_02')
        cmds.setAttr(str(POSI2) + '.parameterV', 0.5)
        cmds.setAttr(str(POSI2) + '.parameterU', 0.25)
        cmds.connectAttr(str(Side) + '_' + str(PlaneName) + '.worldSpace[0]',
                         (POSI2) + '.inputSurface',
                         f=1)
        cmds.connectAttr(str(POSI2) + '.position',
                         str(UpJoint2) + '.translate',
                         f=1)

        POSI3 = cmds.shadingNode('pointOnSurfaceInfo',
                                 asUtility=True,
                                 name=Side + '_' + PlaneName +
                                 '_PointOnSurface_03')
        cmds.setAttr(str(POSI3) + '.parameterV', 0.5)
        cmds.setAttr(str(POSI3) + '.parameterU', 0.5)
        cmds.connectAttr(str(Side) + '_' + str(PlaneName) + '.worldSpace[0]',
                         (POSI3) + '.inputSurface',
                         f=1)
        cmds.connectAttr(str(POSI3) + '.position',
                         str(UpJoint3) + '.translate',
                         f=1)

        POSI4 = cmds.shadingNode('pointOnSurfaceInfo',
                                 asUtility=True,
                                 name=Side + '_' + PlaneName +
                                 '_PointOnSurface_04')
        cmds.setAttr(str(POSI4) + '.parameterV', 0.5)
        cmds.setAttr(str(POSI4) + '.parameterU', 0.75)
        cmds.connectAttr(str(Side) + '_' + str(PlaneName) + '.worldSpace[0]',
                         (POSI4) + '.inputSurface',
                         f=1)
        cmds.connectAttr(str(POSI4) + '.position',
                         str(UpJoint4) + '.translate',
                         f=1)

        POSI5 = cmds.shadingNode('pointOnSurfaceInfo',
                                 asUtility=True,
                                 name=Side + '_' + PlaneName +
                                 '_PointOnSurface_05')
        cmds.setAttr(str(POSI5) + '.parameterV', 0.5)
        cmds.setAttr(str(POSI5) + '.parameterU', 1)
        cmds.connectAttr(str(Side) + '_' + str(PlaneName) + '.worldSpace[0]',
                         (POSI5) + '.inputSurface',
                         f=1)
        cmds.connectAttr(str(POSI5) + '.position',
                         str(UpJoint5) + '.translate',
                         f=1)
Exemple #56
0
 def create_joint(self, jntinfo):
     for item in jntinfo:
         cmds.joint(n='L_' + item[0], p=item[1], radius=1)
Exemple #57
0
    def leg(self):

        cmds.select(cl=True)
        tmp = cmds.joint(n='L_template_leg', p=(1, 11, 0))
        leg = setUniqueName(tmp, 'JNT')

        tmp = cmds.joint(n='L_template_lowLeg', p=(1, 6, 0))
        lowLeg = setUniqueName(tmp, 'JNT')
        cmds.joint(leg, e=True, zso=True, oj='xyz', sao='yup')

        tmp = cmds.joint(n='L_template_foot', p=(1, 1, 0))
        foot = setUniqueName(tmp, 'JNT')
        cmds.joint(lowLeg, e=True, zso=True, oj='xyz', sao='yup')

        tmp = cmds.joint(n='L_template_ball', p=(1, 0, 1))
        ball = setUniqueName(tmp, 'JNT')
        cmds.joint(foot, e=True, zso=True, oj='xyz', sao='yup')

        tmp = cmds.joint(n='L_template_toe', p=(1, 0, 2))
        toe = setUniqueName(tmp, 'JNT')
        cmds.joint(ball, e=True, zso=True, oj='xyz', sao='yup')

        cmds.setAttr(leg + '.rx', -10)
        cmds.setAttr(lowLeg + '.rx', 20)
        cmds.setAttr(foot + '.rx', -10)
        cmds.mirrorJoint(leg,
                         mirrorYZ=True,
                         mirrorBehavior=True,
                         searchReplace=('L_', 'R_'))

        return
Exemple #58
0
def load_data(data, threed):
    suffix = "threed" if threed else "twod"
    # jnts to ignore
    to_pass = [5, 4, 9, 10, 12] if threed else []
    # locator driver grp
    if not cmds.objExists("drivers_{0}".format(suffix)):
        cmds.group(n="drivers_{0}".format(suffix), em=True)
    for frame, jnt in data.iteritems():
        if not cmds.objExists("anim_joint"):
            cmds.group(n="anim_joint", em=True)
            anim_grp_prj = cmds.group(n="anim_joint_2d", em=True)
            cmds.parent(anim_grp_prj, "anim_joint")
        for jnt_id, trans in jnt.iteritems():
            if not int(jnt_id) in to_pass:
                if not cmds.objExists("anim_jnt_driver_{0}_{1}".format(
                        jnt_id, suffix)):
                    cmds.select(clear=True)
                    jnt = cmds.joint(n="jnt_{0}_{1}".format(jnt_id, suffix),
                                     relative=True)
                    cmds.setAttr("{0}.radius".format(jnt), 10)
                    cmds.setAttr("{0}.displayLocalAxis".format(jnt), 1)
                    # match same pos for first frame
                    if threed:
                        cmds.move(trans["translate"][0], trans["translate"][1],
                                  trans["translate"][2], jnt)
                    else:
                        cmds.move(trans["translate"][0], trans["translate"][1],
                                  jnt)
                    anim_grp_child = cmds.listRelatives("anim_joint",
                                                        children=True) or []
                    if not jnt in anim_grp_child:
                        cmds.parent(jnt, "anim_joint")

                    if threed:
                        #create 2d projection
                        jnt_proj = cmds.duplicate(
                            jnt, n="jnt_prj_{0}".format(jnt_id))
                        cmds.pointConstraint(jnt, jnt_proj, mo=False, skip="z")
                        cmds.setAttr("{0}.translateZ".format(jnt_proj[0]), 0)
                        cmds.parent(jnt_proj, "anim_joint_2d")

                    # driver locator
                    driver = cmds.spaceLocator(
                        n="anim_jnt_driver_{0}_{1}".format(jnt_id, suffix))
                    # drive jnt with animated locator frim frame 0
                    cmds.pointConstraint(driver, jnt)
                    #if not driver in cmds.listRelatives("drivers_{0}".format(suffix), children=True) or []:
                    cmds.parent(driver, "drivers_{0}".format(suffix))
                # add trans anim values to driver locator
                cmds.setKeyframe("anim_jnt_driver_{0}_{1}".format(
                    jnt_id, suffix),
                                 t=frame,
                                 v=trans["translate"][0],
                                 at='translateX')
                cmds.setKeyframe("anim_jnt_driver_{0}_{1}".format(
                    jnt_id, suffix),
                                 t=frame,
                                 v=trans["translate"][1],
                                 at='translateY')
                if threed:
                    cmds.setKeyframe("anim_jnt_driver_{0}_{1}".format(
                        jnt_id, suffix),
                                     t=frame,
                                     v=trans["translate"][2],
                                     at='translateZ')
    # hacking 3d-pose-baseline coord. to maya
    cmds.setAttr("drivers_{0}.rotateX".format(suffix),
                 -110 if threed else -180)
Exemple #59
0
    def build(
            self,
            spineJoints = [],
            rootJoint = '',
            rigScale = 1.0,
            createFKSystem = True,
            createCircleFkControl = True,
            createCircleIkControl = False,
            surroundingMeshes = []
            ):

        # Create upper body control.
        upperBodyCtrl = SERigControl.RigArrowCrossControl(
                                rigSide = SERigEnum.eRigSide.RS_Center,
                                rigType = SERigEnum.eRigType.RT_SpineUpperBody,
                                prefix = self.Prefix + 'UpperBody', 
                                translateTo = spineJoints[0],
                                scale = rigScale*20,
                                scaleX = 5,
                                scaleZ = 5,
                                parent = self.ControlsGrp,
                                fitToSurroundingMeshes = True,
                                surroundingMeshes = surroundingMeshes,
                                postFitScale = 1.75,
                                overrideFitRayDirection = True, 
                                fitRayDirection = (-1, 0, 0)
                                )
        SERigObjectTypeHelper.linkRigObjects(self.TopGrp, upperBodyCtrl.ControlGroup, 'UpperBodyCtrl', 'ControlOwner')
        self.UpperBodyCtrl = upperBodyCtrl

        # Create pelvis and chest proxy joints.
        pelvisProxyJoint = cmds.duplicate(spineJoints[0], n = spineJoints[0] + SERigNaming.s_Proxy, parentOnly = True)[0]
        chestBeginProxyJoint = cmds.duplicate(spineJoints[-1], n = spineJoints[-1] + SERigNaming.s_Proxy, parentOnly = True)[0]
        cmds.hide(pelvisProxyJoint, chestBeginProxyJoint)

        # Create IK controls.
        chestBeginCtrl = None
        if createCircleIkControl:
            chestBeginCtrl = SERigControl.RigCircleControl(
                                        rigSide = SERigEnum.eRigSide.RS_Center,
                                        rigType = SERigEnum.eRigType.RT_SpineChest,
                                        prefix = self.Prefix + 'Chest', 
                                        translateTo = chestBeginProxyJoint,
                                        rotateTo = chestBeginProxyJoint,
                                        scale = rigScale*22,
                                        parent = upperBodyCtrl.ControlObject,
                                        fitToSurroundingMeshes = True,
                                        surroundingMeshes = surroundingMeshes,
                                        postFitScale = 1.6
                                        )
        else:
            chestBeginCtrl = SERigControl.RigCubeControl(
                                    rigSide = SERigEnum.eRigSide.RS_Center,
                                    rigType = SERigEnum.eRigType.RT_SpineChest,
                                    prefix = self.Prefix + 'Chest', 
                                    translateTo = chestBeginProxyJoint,
                                    rotateTo = chestBeginProxyJoint,
                                    scale = rigScale*22,
                                    parent = upperBodyCtrl.ControlObject,
                                    cubeScaleX = 4.0,
                                    cubeScaleY = 35.0,
                                    cubeScaleZ = 35.0,
                                    transparency = 0.75,
                                    fitToSurroundingMeshes = True,
                                    surroundingMeshes = surroundingMeshes,
                                    postFitScale = 1.25
                                    )
        SERigObjectTypeHelper.linkRigObjects(self.TopGrp, chestBeginCtrl.ControlGroup, 'ChestBeginCtrl', 'ControlOwner')
        self.ChestBeginCtrl = chestBeginCtrl

        pelvisCtrl = None
        if createCircleIkControl:
            pelvisCtrl = SERigControl.RigCircleControl(
                                    rigSide = SERigEnum.eRigSide.RS_Center,
                                    rigType = SERigEnum.eRigType.RT_SpinePelvis,
                                    prefix = self.Prefix + 'Pelvis', 
                                    translateTo = pelvisProxyJoint,
                                    rotateTo = pelvisProxyJoint,
                                    scale = rigScale*26,
                                    parent = upperBodyCtrl.ControlObject,
                                    fitToSurroundingMeshes = True,
                                    surroundingMeshes = surroundingMeshes,
                                    postFitScale = 1.3
                                    )
        else:
            pelvisCtrl = SERigControl.RigCubeControl(
                                    rigSide = SERigEnum.eRigSide.RS_Center,
                                    rigType = SERigEnum.eRigType.RT_SpinePelvis,
                                    prefix = self.Prefix + 'Pelvis', 
                                    translateTo = pelvisProxyJoint,
                                    rotateTo = pelvisProxyJoint,
                                    scale = rigScale*26,
                                    parent = upperBodyCtrl.ControlObject,
                                    cubeScaleX = 4.0,
                                    cubeScaleY = 35.0,
                                    cubeScaleZ = 35.0,
                                    transparency = 0.75,
                                    fitToSurroundingMeshes = True,
                                    surroundingMeshes = surroundingMeshes,
                                    postFitScale = 1.2
                                    )
        SERigObjectTypeHelper.linkRigObjects(self.TopGrp, pelvisCtrl.ControlGroup, 'PelvisCtrl', 'ControlOwner')
        self.PelvisCtrl = pelvisCtrl

        pelvisLocalCtrl = SERigControl.RigCircleControl(
                                rigSide = SERigEnum.eRigSide.RS_Center,
                                rigType = SERigEnum.eRigType.RT_SpinePelvisLocal,
                                prefix = self.Prefix + 'PelvisLocal', 
                                translateTo = pelvisProxyJoint,
                                rotateTo = pelvisProxyJoint,
                                scale = rigScale*22,
                                parent = upperBodyCtrl.ControlObject,
                                lockChannels = ['s', 't', 'v'],
                                fitToSurroundingMeshes = True,
                                surroundingMeshes = surroundingMeshes,
                                postFitScale = 1.35
                                )
        SERigObjectTypeHelper.linkRigObjects(self.TopGrp, pelvisLocalCtrl.ControlGroup, 'PelvisLocalCtrl', 'ControlOwner')
        self.PelvisLocalCtrl = pelvisLocalCtrl

        chestBeginLocalCtrl = SERigControl.RigCircleControl(
                                rigSide = SERigEnum.eRigSide.RS_Center,
                                rigType = SERigEnum.eRigType.RT_SpineChestLocal,
                                prefix = self.Prefix + 'ChestLocal', 
                                translateTo = chestBeginProxyJoint,
                                rotateTo = chestBeginProxyJoint,
                                scale = rigScale*22,
                                parent = upperBodyCtrl.ControlObject,
                                lockChannels = ['s', 't', 'v'],
                                fitToSurroundingMeshes = True,
                                surroundingMeshes = surroundingMeshes,
                                postFitScale = 1.35
                                )
        SERigObjectTypeHelper.linkRigObjects(self.TopGrp, chestBeginLocalCtrl.ControlGroup, 'ChestBeginLocalCtrl', 'ControlOwner')
        self.ChestBeginLocalCtrl = chestBeginLocalCtrl

        cmds.parent(pelvisProxyJoint, chestBeginProxyJoint, self.JointsGrp)

        cmds.parentConstraint(chestBeginCtrl.ControlObject, chestBeginProxyJoint)
        cmds.parentConstraint(chestBeginCtrl.ControlObject, chestBeginLocalCtrl.ControlGroup)
        cmds.parentConstraint(pelvisCtrl.ControlObject, pelvisProxyJoint)
        cmds.parentConstraint(pelvisCtrl.ControlObject, pelvisLocalCtrl.ControlGroup)

        # Insert two new parents for the spine end joints.
        chestBeginNewParent = SEJointHelper.createNewParentJoint(spineJoints[-1])
        spine0NewParent = SEJointHelper.createNewParentJoint(spineJoints[1], True)

        # Get spine joints on which IK joints shall be created.
        cmds.parent(spineJoints[-1], w = 1)
        newSpineJoints = SEJointHelper.listHierarchy(spine0NewParent)
        cmds.parent(spineJoints[-1], chestBeginNewParent)
        
        # Create IK spine joints.
        ikSpineJoints = []
        preParent = None
        for joint in newSpineJoints:
            ikSpineJoint = cmds.createNode('joint', n = SERigNaming.sIKPrefix + joint)
            cmds.delete(cmds.parentConstraint(joint, ikSpineJoint))
            
            if preParent:
                cmds.parent(ikSpineJoint, preParent)

            preParent = ikSpineJoint
            ikSpineJoints.append(ikSpineJoint)

        # Move IK spine joints to component's joint group.
        cmds.parent(ikSpineJoints[0], self.JointsGrp)
        cmds.makeIdentity(ikSpineJoints[0], apply = True, t = 1, r = 1, s = 1, n = 0,  pn = 1)
        cmds.hide(ikSpineJoints[0])

        # Create IK handle on IK spine joints.
        resList = cmds.ikHandle(n = self.Prefix + SERigNaming.s_SplineIKHandle, 
                                sol = 'ikSplineSolver', sj = ikSpineJoints[0], ee = ikSpineJoints[-1], ccv = 1, parentCurve = 0, numSpans = 4)
        spineIK = resList[0]
        spineCurve = resList[2]

        spineCurveNewName = self.Prefix + SERigNaming.s_Curve
        cmds.rename(spineCurve, spineCurveNewName)
                                                
        cmds.hide(spineIK)
        cmds.hide(spineCurveNewName)
        cmds.parent(spineIK, spineCurveNewName, self.RigPartsFixedGrp)

        cmds.select(pelvisProxyJoint, chestBeginProxyJoint, spineCurveNewName)
        cmds.skinCluster(toSelectedBones = 1, bindMethod = 0, nw = 1, wd = 0, mi = 5, omi = True, dr = 4, rui = True)

        # Make spine twistable.
        cmds.setAttr(spineIK + '.dTwistControlEnable', 1)
        cmds.setAttr(spineIK + '.dWorldUpType', 4)
        cmds.connectAttr(pelvisCtrl.ControlObject + '.worldMatrix[0]', spineIK + '.dWorldUpMatrix')
        cmds.connectAttr(chestBeginCtrl.ControlObject + '.worldMatrix[0]', spineIK + '.dWorldUpMatrixEnd')

        # Control original spine in-between joints via IK spine joints.
        for ikSpineJoint, spineJoint in zip(ikSpineJoints, newSpineJoints):
            cmds.orientConstraint(ikSpineJoint, spineJoint, mo = 1)
            cmds.pointConstraint(ikSpineJoint, spineJoint, mo = 1)

        # Control original chest begin joint via chest begin local control.
        cmds.orientConstraint(chestBeginLocalCtrl.ControlObject, spineJoints[-1], mo = 1)
        cmds.pointConstraint(chestBeginLocalCtrl.ControlObject, spineJoints[-1], mo = 1)

        # Control original pelvis joint via pelvis local control.
        cmds.orientConstraint(pelvisLocalCtrl.ControlObject, spineJoints[0], mo = 1)
        cmds.pointConstraint(pelvisLocalCtrl.ControlObject, spineJoints[0], mo = 1)

        # Create stretching spine.
        curveInfoNode = cmds.arclen(spineCurveNewName, ch = 1)
        curveLen = cmds.getAttr(curveInfoNode + '.arcLength')

        globalScaleAttr = None
        if self.BaseRig:
            globalScaleAttr = self.BaseRig.getGlobalScaleAttrName()

        mulNode = cmds.createNode('multiplyDivide')
        cmds.setAttr(mulNode + '.operation', 1)
        cmds.setAttr(mulNode + '.input1X', curveLen)
        cmds.setAttr(mulNode + '.i1', l = 1)

        if globalScaleAttr:
            cmds.connectAttr(globalScaleAttr, mulNode + '.input2X', f = 1)

        divNode = cmds.createNode('multiplyDivide')
        cmds.setAttr(divNode + '.operation', 2)
        cmds.connectAttr(curveInfoNode + '.arcLength', divNode + '.input1X', f = 1)
        cmds.connectAttr(mulNode + '.outputX', divNode + '.input2X', f = 1)

        blender = cmds.createNode('blendColors')
        cmds.connectAttr(divNode + '.outputX', blender + '.color1R', f = 1)
        cmds.setAttr(blender + '.color2R', 1.0)

        if self.BaseRig:
            stretchSpineAttr = self.BaseRig.addStretchSpineAttr()
            mainControlObj = self.BaseRig.getMainControlObject()

            if mainControlObj and stretchSpineAttr:
                cmds.connectAttr(mainControlObj + '.' + stretchSpineAttr, blender + '.blender')

                for i in range(len(ikSpineJoints) - 1):
                    curIKSpineJoint = ikSpineJoints[i + 1]
                    curDefaultTransX = cmds.getAttr(curIKSpineJoint + '.translateX')
                    curMulNode = cmds.createNode('multiplyDivide')
                    cmds.setAttr(curMulNode + '.input2X', curDefaultTransX)
                    cmds.setAttr(curMulNode + '.i2', l = 1)
                    cmds.connectAttr(blender + '.outputR', curMulNode + '.input1X', f = 1)
                    cmds.connectAttr(curMulNode + '.outputX', curIKSpineJoint + '.translateX', f = 1)
            else:
                cmds.warning('Failed creating stretching spine attribute for the main control.')

        if createFKSystem:
            # Create FK joints.
            resCurve = cmds.rebuildCurve(spineCurveNewName, ch = 0, rpo = 0, rt = 0, end = 1, kr = 0, kcp = 0, kep = 1, kt = 0, s = 3, d = 1, tol = 0.00393701)[0]

            cmds.select(cl=1)
            jnt0 = cmds.joint(n = SERigNaming.sFKPrefix + spineJoints[0])
            cmds.delete(cmds.pointConstraint(spineJoints[0], jnt0))

            cmds.select(cl=1)
            jnt1 = cmds.joint(n = SERigNaming.sFKPrefix + 'C_Spine_0')
            cmds.select(resCurve + '.cv[1]')
            res = cmds.pointPosition()
            cmds.move(res[0], res[1], res[2], jnt1, rpr = 1)

            cmds.select(cl=1)
            jnt2 = cmds.joint(n = SERigNaming.sFKPrefix + 'C_Spine_1')
            cmds.select(resCurve + '.cv[2]')
            res = cmds.pointPosition()
            cmds.move(res[0], res[1], res[2], jnt2, rpr = 1)

            cmds.select(cl=1)
            jnt3 = cmds.joint(n = SERigNaming.sFKPrefix + spineJoints[-1])
            cmds.delete(cmds.pointConstraint(spineJoints[-1], jnt3))

            RefJnt = cmds.duplicate(jnt2, n =  'Ref_jnt', parentOnly = True)[0]
            cmds.move(0, 0, -10, RefJnt, r = 1, os = 1)

            cmds.delete(cmds.aimConstraint(jnt1, jnt0, offset = [0, 0, 0], w = 1, aim = [1, 0, 0], u = [0, 1, 0], worldUpType = 'object', worldUpObject = RefJnt))
            cmds.delete(cmds.aimConstraint(jnt2, jnt1, offset = [0, 0, 0], w = 1, aim = [1, 0, 0], u = [0, 1, 0], worldUpType = 'object', worldUpObject = RefJnt))
            cmds.delete(cmds.aimConstraint(jnt3, jnt2, offset = [0, 0, 0], w = 1, aim = [1, 0, 0], u = [0, 1, 0], worldUpType = 'object', worldUpObject = RefJnt))

            cmds.delete(cmds.orientConstraint(spineJoints[-1], jnt3))

            cmds.parent(jnt3, jnt2)
            cmds.parent(jnt2, jnt1)
            cmds.parent(jnt1, jnt0)
            cmds.parent(jnt0, self.JointsGrp)

            cmds.makeIdentity(jnt0, apply = True, t = 1, r = 1, s = 1, n = 0,  pn = 1)

            cmds.delete(RefJnt)
            cmds.delete(resCurve)

            # Attach FK root joint to upper body control.
            cmds.parentConstraint(upperBodyCtrl.ControlObject, jnt0, mo = 1)        

            # Create FK spine_0 control.
            FKSpine0Ctrl = None
            if createCircleFkControl:
                FKSpine0Ctrl = SERigControl.RigCircleControl(
                                        rigSide = SERigEnum.eRigSide.RS_Center,
                                        rigType = SERigEnum.eRigType.RT_SpineFK,
                                        rigControlIndex = 0,
                                        prefix = SERigNaming.sFKPrefix + self.Prefix + '_0', 
                                        translateTo = jnt1,
                                        rotateTo = jnt1,
                                        scale = rigScale*20,
                                        parent = upperBodyCtrl.ControlObject,
                                        lockChannels = ['t', 's', 'v'],
                                        overrideControlColor = True, 
                                        controlColor = (0.4, 0.9, 0.9),
                                        fitToSurroundingMeshes = True,
                                        surroundingMeshes = surroundingMeshes,
                                        postFitScale = 1.45
                                        )
            else:
                FKSpine0Ctrl = SERigControl.RigCubeControl(
                                        rigSide = SERigEnum.eRigSide.RS_Center,
                                        rigType = SERigEnum.eRigType.RT_SpineFK,
                                        rigControlIndex = 0,
                                        prefix = SERigNaming.sFKPrefix + self.Prefix + '_0', 
                                        translateTo = jnt1,
                                        rotateTo = jnt1,
                                        scale = rigScale*20,
                                        parent = upperBodyCtrl.ControlObject,
                                        lockChannels = ['t', 's', 'v'],
                                        cubeScaleX = 4.0,
                                        cubeScaleY = 35.0,
                                        cubeScaleZ = 35.0,
                                        transparency = 0.75,
                                        overrideControlColor = True, 
                                        controlColor = (0.4, 0.9, 0.9),
                                        fitToSurroundingMeshes = True,
                                        surroundingMeshes = surroundingMeshes,
                                        postFitScale = 1.1
                                        )
            SERigObjectTypeHelper.linkRigObjects(self.TopGrp, FKSpine0Ctrl.ControlGroup, 'FKSpine0Ctrl', 'ControlOwner')
            self.FKSpine0Ctrl = FKSpine0Ctrl

            cmds.orientConstraint(FKSpine0Ctrl.ControlObject, jnt1)

            # Create FK spine_1 control.
            FKSpine1Ctrl = None
            if createCircleFkControl:
                FKSpine1Ctrl = SERigControl.RigCircleControl(
                                        rigSide = SERigEnum.eRigSide.RS_Center,
                                        rigType = SERigEnum.eRigType.RT_SpineFK,
                                        rigControlIndex = 1,
                                        prefix = SERigNaming.sFKPrefix + self.Prefix + '_1', 
                                        translateTo = jnt2,
                                        rotateTo = jnt2,
                                        scale = rigScale*20,
                                        parent = FKSpine0Ctrl.ControlObject,
                                        lockChannels = ['t', 's', 'v'],
                                        overrideControlColor = True, 
                                        controlColor = (0.4, 0.9, 0.9),
                                        fitToSurroundingMeshes = True,
                                        surroundingMeshes = surroundingMeshes,
                                        postFitScale = 1.45
                                        )
            else:
                FKSpine1Ctrl = SERigControl.RigCubeControl(
                                        rigSide = SERigEnum.eRigSide.RS_Center,
                                        rigType = SERigEnum.eRigType.RT_SpineFK,
                                        rigControlIndex = 1,
                                        prefix = SERigNaming.sFKPrefix + self.Prefix + '_1', 
                                        translateTo = jnt2,
                                        rotateTo = jnt2,
                                        scale = rigScale*20,
                                        parent = FKSpine0Ctrl.ControlObject,
                                        lockChannels = ['t', 's', 'v'],
                                        cubeScaleX = 4.0,
                                        cubeScaleY = 30.0,
                                        cubeScaleZ = 30.0,
                                        transparency = 0.75,
                                        overrideControlColor = True, 
                                        controlColor = (0.4, 0.9, 0.9),
                                        fitToSurroundingMeshes = True,
                                        surroundingMeshes = surroundingMeshes,
                                        postFitScale = 1.1
                                        )
            SERigObjectTypeHelper.linkRigObjects(self.TopGrp, FKSpine1Ctrl.ControlGroup, 'FKSpine1Ctrl', 'ControlOwner')
            self.FKSpine1Ctrl = FKSpine1Ctrl

            cmds.orientConstraint(FKSpine1Ctrl.ControlObject, jnt2)

            # Attach ChestBegin controls to FK spine_1 control.
            cmds.parent(chestBeginCtrl.ControlGroup, FKSpine1Ctrl.ControlObject)
            cmds.parent(chestBeginLocalCtrl.ControlGroup, FKSpine1Ctrl.ControlObject)

            cmds.hide(jnt0)

        # Create controls visibility expression.
        mainControl = SERigNaming.sMainControlPrefix + SERigNaming.sControl
        controlsVisEN = SERigNaming.sExpressionPrefix + self.Prefix + 'ControlsVis'
        controlsVisES = ''
        tempExpressionTail = mainControl + '.' + SERigNaming.sBodyControlsVisibilityAttr + ';'

        if self.UpperBodyCtrl:
            controlsVisES += self.UpperBodyCtrl.ControlGroup + '.visibility = ' + tempExpressionTail

        if self.ChestBeginCtrl:
            controlsVisES += '\n'
            controlsVisES += self.ChestBeginCtrl.ControlGroup + '.visibility = ' + tempExpressionTail

        if self.PelvisCtrl:
            controlsVisES += '\n'
            controlsVisES += self.PelvisCtrl.ControlGroup + '.visibility = ' + tempExpressionTail

        if self.PelvisLocalCtrl:
            controlsVisES += '\n'
            controlsVisES += self.PelvisLocalCtrl.ControlGroup + '.visibility = ' + tempExpressionTail

        if self.FKSpine0Ctrl:
            controlsVisES += '\n'
            controlsVisES += self.FKSpine0Ctrl.ControlGroup + '.visibility = ' + tempExpressionTail

        if self.FKSpine1Ctrl:
            controlsVisES += '\n'
            controlsVisES += self.FKSpine1Ctrl.ControlGroup + '.visibility = ' + tempExpressionTail

        cmds.expression(n = controlsVisEN, s = controlsVisES, ae = 1)
Exemple #60
0
    def finger(self):
        #thumb
        cmds.select(cl=True)
        tmp = cmds.joint(n='L_template_thumb1', p=(0.1, 0, 0))
        thumb1 = setUniqueName(tmp, 'JNT')

        tmp = cmds.joint(n='L_template_thumb2', p=(0.45, 0, 0))
        thumb2 = setUniqueName(tmp, 'JNT')
        cmds.joint(thumb1, e=True, zso=True, oj='xyz', sao='yup')

        tmp = cmds.joint(n='L_template_thumb3', p=(0.75, 0, 0))
        thumb3 = setUniqueName(tmp, 'JNT')
        cmds.joint(thumb2, e=True, zso=True, oj='xyz', sao='yup')
        tmp = cmds.joint(n='L_template_thumb4', p=(1.05, 0, 0))
        thumb4 = setUniqueName(tmp, 'JNT')
        cmds.joint(thumb3, e=True, zso=True, oj='xyz', sao='yup')

        cmds.setAttr(thumb1 + '.t', 10, 10, 0.5)
        cmds.setAttr(thumb1 + '.jointOrient', 80, -10, -30)

        cmds.mirrorJoint(thumb1,
                         mirrorYZ=True,
                         mirrorBehavior=True,
                         searchReplace=('L_', 'R_'))

        #index~pinky
        name = ['index', 'middle', 'ring', 'pinky']
        num = ['Palm', '1', '2', '3', '4']
        buffer = []
        cmds.select(cl=True)
        for i in range(len(name)):
            for n in range(len(num)):
                tmp = cmds.joint(n='L_template_' + name[i] + num[n],
                                 p=(0.35, 0, 0),
                                 r=True)
                fin = setUniqueName(tmp, 'JNT')
                buffer.append(fin)

            cmds.setAttr(buffer[0] + '.t', 10, 10, i * -0.2)
            cmds.mirrorJoint(buffer[0],
                             mirrorYZ=True,
                             mirrorBehavior=True,
                             searchReplace=('L_', 'R_'))
            cmds.select(cl=True)
            buffer = []

        return