def dup_morphyHeadShape(headToDup = 'UprFocus'):
    _sl = mc.ls(sl=True)
    if mc.objExists('bs_grp'):
        mGroup  = cgmMeta.cgmObject('bs_grp')
    else:
        mGroup  = cgmMeta.cgmObject()
        mGroup.addAttr('cgmName','bs')
        mGroup.addAttr('cgmType','grp')
        mGroup.doName()
    mGroup.v = 0
    result = mc.promptDialog(title='blendshape Name',
                             message='Enter Name:',
                             button=['OK', 'Cancel'],
                             defaultButton='OK',
                             cancelButton='Cancel',
                             dismissString='Cancel')
    if result:
        newName = mc.promptDialog(query=True, text=True)
        _name = newName
        if mc.objExists(_name):
            log.warning("Deleting {0}".format(_name))
            mc.delete(_name)
        log.info(_name)
        newMesh = mc.duplicate(headToDup)
        mMesh = cgmMeta.cgmObject(newMesh[0])
        attributes.doSetLockHideKeyableAttr(mMesh.mNode,False,True,True)			    
        mMesh.rename(_name)
        mMesh.parent = mGroup
        mMesh.translate = [0,0,0]
        if _sl:mc.select(_sl)
        return True
    return False
Beispiel #2
0
def createPoseBuffer(name, poseList):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns the colors used on the shapes of a curve as a list in order
    of volume used

    ARGUMENTS:
    curve(string
    
    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    returnList = []

    poseBuffer = mc.group(em=True)
    attributes.storeInfo(poseBuffer, 'cgmName', name)
    attributes.storeInfo(poseBuffer, 'cgmType', 'poseBuffer')
    poseBuffer = NameFactory.doNameObject(poseBuffer)
    returnList.append(poseBuffer)

    returnList.append(
        attributes.addFloatAttrsToObj(poseBuffer, poseList, dv=0,
                                      keyable=True))

    attributes.doSetLockHideKeyableAttr(poseBuffer, True, False, False)

    return returnList
Beispiel #3
0
def createPoseBuffer(name, poseList):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns the colors used on the shapes of a curve as a list in order
    of volume used

    ARGUMENTS:
    curve(string
    
    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    returnList = []

    poseBuffer = mc.group(em=True)
    attributes.storeInfo(poseBuffer, "cgmName", name)
    attributes.storeInfo(poseBuffer, "cgmType", "poseBuffer")
    poseBuffer = NameFactoryOld.doNameObject(poseBuffer)
    returnList.append(poseBuffer)

    returnList.append(attributes.addFloatAttrsToObj(poseBuffer, poseList, dv=0, keyable=True))

    attributes.doSetLockHideKeyableAttr(poseBuffer, True, False, False)

    return returnList
 def _lockNHide(self):	
     autoLockNHide = self.d_kws['autoLockNHide']	    
     if autoLockNHide:
         if self.mi_control.hasAttr('cgmTypeModifier'):
             if self.mi_control.cgmTypeModifier.lower() == 'fk':
                 attributes.doSetLockHideKeyableAttr(self.mi_control.mNode,channels=['tx','ty','tz','sx','sy','sz'])
         if self.mi_control.cgmName.lower() == 'cog':
             attributes.doSetLockHideKeyableAttr(self.mi_control.mNode,channels=['sx','sy','sz'])
         cgmMeta.cgmAttr(self.mi_control,'visibility',lock=True,hidden=True)   
Beispiel #5
0
 def _lockNHide(self):	
     autoLockNHide = self.d_kws['autoLockNHide']	    
     if autoLockNHide:
         if self.mi_control.hasAttr('cgmTypeModifier'):
             if self.mi_control.cgmTypeModifier.lower() == 'fk':
                 attributes.doSetLockHideKeyableAttr(self.mi_control.mNode,channels=['tx','ty','tz','sx','sy','sz'])
         if self.mi_control.cgmName.lower() == 'cog':
             attributes.doSetLockHideKeyableAttr(self.mi_control.mNode,channels=['sx','sy','sz'])
         cgmMeta.cgmAttr(self.mi_control,'visibility',lock=True,hidden=True)   
Beispiel #6
0
def createFollicleOnMesh(targetSurface, name='follicle'):
    """
    Creates named follicle node on a mesh
    
    Keywords
    mesh -- mesh to attach to
    name -- base name to use ('follicle' default)
    
    Returns
    [follicleNode,follicleTransform]
    """

    if SEARCH.is_shape(targetSurface):
        l_shapes = [targetSurface]
    else:
        l_shapes = mc.listRelatives(targetSurface, s=True, fullPath=True)
    if not l_shapes:
        raise ValueError, "Must have shapes to check."

    _shape = l_shapes[0]
    log.debug("_shape: {0}".format(_shape))
    _type = VALID.get_mayaType(_shape)

    #objType = search.returnObjectType(mesh)
    #assert objType in ['mesh','nurbsSurface'],("'%s' isn't a mesh"%mesh)

    follicleNode = create((name), 'follicle')
    """ make the closest point node """
    #closestPointNode = createNamedNode((targetObj+'_to_'+mesh),'closestPointOnMesh')
    #controlSurface = mc.listRelatives(_shape,shapes=True)[0]
    follicleTransform = mc.listRelatives(follicleNode, p=True,
                                         fullPath=True)[0]

    attributes.doConnectAttr(
        (_shape + '.worldMatrix[0]'),
        (follicleNode + '.inputWorldMatrix'))  #surface to follicle node

    if _type == 'mesh':
        attributes.doConnectAttr(
            (_shape + '.outMesh'),
            (follicleNode +
             '.inputMesh'))  #surface mesh to follicle input mesh
    else:
        attributes.doConnectAttr(
            (_shape + '.local'),
            (follicleNode +
             '.inputSurface'))  #surface mesh to follicle input mesh

    attributes.doConnectAttr((follicleNode + '.outTranslate'),
                             (follicleTransform + '.translate'))
    attributes.doConnectAttr((follicleNode + '.outRotate'),
                             (follicleTransform + '.rotate'))

    attributes.doSetLockHideKeyableAttr(follicleTransform)

    return [follicleNode, follicleTransform]
Beispiel #7
0
	def build(self):#================================================================================   	
		    
	    try:#>>>Get data
		orientation = self._go._jointOrientation or modules.returnSettingsData('jointOrientation')
		mi_moduleParent = False
		if self._go._mi_module.getMessage('moduleParent'):
		    mi_moduleParent = self._go._mi_module.moduleParent
		    
		mi_controlIK = self._go._i_rigNull.controlIK
		ml_controlsFK =  self._go._i_rigNull.msgList_get('controlsFK')    
		ml_rigJoints = self._go._i_rigNull.msgList_get('rigJoints')
		ml_blendJoints = self._go._i_rigNull.msgList_get('blendJoints')
		mi_settings = self._go._i_rigNull.settings
		
		log.info("mi_controlIK: %s"%mi_controlIK.getShortName())
		log.info("ml_controlsFK: %s"%[o.getShortName() for o in ml_controlsFK])
		log.info("mi_settings: %s"%mi_settings.getShortName())
		
		log.info("ml_rigJoints: %s"%[o.getShortName() for o in ml_rigJoints])
		log.info("ml_blendJoints: %s"%[o.getShortName() for o in ml_blendJoints])
		
		ml_segmentHandleChains = self._go._get_segmentHandleChains()
		ml_segmentChains = self._go._get_segmentChains()
		ml_influenceChains = self._go._get_influenceChains()	
		
		aimVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[0])
		upVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[1]) 
		
		#Build our contrain to pool
		l_constrainTargetJoints = []
		"""
		for ml_chain in ml_segmentChains:
		    l_constrainTargetJoints.extend([i_jnt.mNode for i_jnt in ml_chain[:-1]])
		l_constrainTargetJoints.extend([i_jnt.mNode for i_jnt in ml_blendJoints[-2:]])
		"""
		if not l_constrainTargetJoints:
		    l_constrainTargetJoints = [i_jnt.mNode for i_jnt in ml_blendJoints]
		    
		for i_jnt in ml_blendJoints:
		    attributes.doSetLockHideKeyableAttr(i_jnt.mNode,lock=True, visible=True, keyable=False)
		    i_jnt.radius = 0#This is how we can hide joints without hiding them since we have children we want to ride along
		    i_jnt.drawStyle = 2
		    
		for i_jnt in ml_controlsFK:
		    i_jnt.radius = 0#This is how we can hide joints without hiding them since we have children we want to ride along
		    i_jnt.drawStyle = 2		    
		    
		#Set group lockks
		for mCtrl in self._go._i_rigNull.msgList_get('controlsAll'):
		    try:mCtrl._setControlGroupLocks()	
		    except Exception,error:log.error("%s _setControlGroupLocks failed on object: %s"%(self._str_reportStart,mCtrl.p_nameShort))
	    	    
	    except Exception,error:
		log.error("finger.build_rig>> Gather data fail!")
		raise Exception,error
Beispiel #8
0
def set_primeScaleAxis(control=None,
                       primeAxis=None,
                       slaveOthers=False,
                       alias=None):
    """
    Set a single axis of scale for a given control. The other channels are locked and hidden.
    
    :parameters:
        control(str): Object to change
        primeAxis(str/idx): X,Y,Z or index
        slaveOthers(bool): Whether to drive the remaining attributes of the given channel
        alias(str): If given, will attempt to alias the primeAxis

    :returns
        success(bool)
    """
    _str_func = 'set_primeAxis'
    _l = ['X', 'Y', 'Z']
    _primeAxis = cgmValid.kw_fromList(primeAxis, _l)
    _idx = _l.index(_primeAxis)
    _attr_prime = 'scale{0}'.format(_primeAxis)

    _l_others = []
    for i, v in enumerate(_l):
        if i != _idx:
            _l_others.append(v)

    log.debug("{0} || control:{1}".format(_str_func, control))
    log.debug("{0} || primeAxis:{1}".format(_str_func, _primeAxis))
    log.debug("{0} || slaveOthers:{1}".format(_str_func, slaveOthers))
    log.debug("{0} || alias:{1}".format(_str_func, alias))
    log.debug("{0} || prime attr:{1}".format(_str_func, _attr_prime))
    log.debug("{0} || other attrs:{1}".format(_str_func, _l_others))

    if alias:
        coreAttr.alias_set("{0}.{1}".format(control, _attr_prime), alias)

    for attr in _l_others:
        if slaveOthers:
            try:
                attributes.doConnectAttr(
                    "{0}.{1}".format(control, _attr_prime),
                    "{0}.scale{1}".format(control, attr.capitalize()),
                    transferConnection=True)
            except:
                pass
        attributes.doSetLockHideKeyableAttr(
            control,
            lock=True,
            visible=False,
            keyable=False,
            channels=['s{0}'.format(attr.lower())])

    return True
Beispiel #9
0
def add_follicle(mesh, name='follicle'):
    """
    Creates named follicle node on a mesh
    
    :parameters:
        mesh(str): Surface to attach to
        name(str): base name for the follicle

    :returns
        [newNode, newTransform]
    """
    _str_func = "add_follicle"

    _node = create(name, 'follicle')

    if SEARCH.is_shape(mesh):
        _surface = mesh
    else:
        _surface = mc.listRelatives(mesh, shapes=True, fullPath=True)[0]
    _type = VALID.get_mayaType(_surface)
    _trans = SEARCH.get_transform(_node)

    attributes.doConnectAttr(
        (_surface + '.worldMatrix[0]'),
        (_node + '.inputWorldMatrix'))  #surface to follicle node
    if _type == 'mesh':
        attributes.doConnectAttr(
            (_surface + '.outMesh'),
            (_node + '.inputMesh'))  #surface mesh to follicle input mesh
    else:
        attributes.doConnectAttr(
            (_surface + '.local'),
            (_node + '.inputSurface'))  #surface mesh to follicle input mesh

    attributes.doConnectAttr((_node + '.outTranslate'),
                             (_trans + '.translate'))
    attributes.doConnectAttr((_node + '.outRotate'), (_trans + '.rotate'))

    #ATTR.set_message(_node,'follTrans',_trans)
    #ATTR.set_message(_trans,'follNode',_node)

    attributes.doSetLockHideKeyableAttr(_trans)

    return [_node, _trans]
    """follicleNode = createNamedNode((name),'follicle')
Beispiel #10
0
def createFollicleOnMesh(mesh, name='follicle'):
    """
    Creates named follicle node on a mesh
    
    Keywords
    mesh -- mesh to attach to
    name -- base name to use ('follicle' default)
    
    Returns
    [follicleNode,follicleTransform]
    """
    assert mc.objExists(mesh), "'%s' doesn't exist!" % mesh
    #objType = search.returnObjectType(mesh)
    #assert objType in ['mesh','nurbsSurface'],("'%s' isn't a mesh"%mesh)

    follicleNode = createNamedNode((name), 'follicle')
    """ make the closest point node """
    #closestPointNode = createNamedNode((targetObj+'_to_'+mesh),'closestPointOnMesh')
    controlSurface = mc.listRelatives(mesh, shapes=True)[0]
    follicleTransform = mc.listRelatives(follicleNode, p=True)[0]

    attributes.doConnectAttr(
        (controlSurface + '.worldMatrix[0]'),
        (follicleNode + '.inputWorldMatrix'))  #surface to follicle node
    if objType == 'mesh':
        attributes.doConnectAttr(
            (controlSurface + '.outMesh'),
            (follicleNode +
             '.inputMesh'))  #surface mesh to follicle input mesh
    else:
        attributes.doConnectAttr(
            (controlSurface + '.local'),
            (follicleNode +
             '.inputSurface'))  #surface mesh to follicle input mesh

    attributes.doConnectAttr((follicleNode + '.outTranslate'),
                             (follicleTransform + '.translate'))
    attributes.doConnectAttr((follicleNode + '.outRotate'),
                             (follicleTransform + '.rotate'))

    attributes.doSetLockHideKeyableAttr(follicleTransform)

    return [follicleNode, follicleTransform]
Beispiel #11
0
        def _buildPupilIris_(self):
            mi_go = self._go#Rig Go instance link
            str_mirrorSide = self.str_mirrorSide

            try:#>>>> Iris pupil #==================================================================	
                try:
                    _l_build = [{'tag':'iris','buildCheck':self.mi_helper.buildIris,'shape':self.md_rigList['iris_shape'],'joint':self.md_rigList['iris'],'parent':self.md_rigList['eye']},
                                {'tag':'pupil','buildCheck':self.mi_helper.buildPupil,'shape':self.md_rigList['pupil_shape'],'joint':self.md_rigList['pupil'],'parent':self.md_rigList['iris']}]
                except Exception,error:raise Exception,"[build dict]{%s}"%(error)

                for _d in _l_build:
                    try:
                        self._d_buffer = _d
                        self.log_infoNestedDict('_d_buffer')
                        _tag = _d['tag']
                        _shape = _d['shape']
                        _joint = _d['joint']
                        _b_buildCheck = _d['buildCheck']

                        if not _b_buildCheck:
                            self.log_info("Build %s toggle: off"%(_tag))
                            _shape.delete()

                        else:
                            _joint.parent =  mi_go._i_constrainNull.eyeTrackNull.mNode
                            d_buffer = mControlFactory.registerControl(_joint,useShape = _shape,
                                                                       mirrorSide = str_mirrorSide, mirrorAxis="",
                                                                       makeAimable=True,setRotateOrder ='zxy') 	    

                            mi_control = d_buffer['instance']
                            _shape.delete()

                            attributes.doSetAttr(mi_control.mNode,'overrideEnabled',0)
                            attributes.doSetAttr(mi_control.mNode,'overrideDisplayType',0)
                            cgmMeta.cgmAttr(mi_control,'radius',.0001,hidden=True)
                            mi_go._i_rigNull.connectChildNode(mi_control,'control%s'%_tag.capitalize(),"rigNull")
                            self.ml_controlsAll.append(mi_control)	
                            attributes.doSetLockHideKeyableAttr(mi_control.mNode,channels=['tx','ty','tz','rx','ry','rz','v','s%s'%mi_go._jointOrientation[0]])				
                    except Exception,error:raise Exception,"[%s]{%s}"%(_tag,error)
            except Exception,error:raise Exception,"[Build iris/pupil fail]{%s}"%(error)
Beispiel #12
0
def createFollicleOnMesh(mesh, name="follicle"):
    """
    Creates named follicle node on a mesh
    
    Keywords
    mesh -- mesh to attach to
    name -- base name to use ('follicle' default)
    
    Returns
    [follicleNode,follicleTransform]
    """
    assert mc.objExists(mesh), "'%s' doesn't exist!" % mesh
    objType = search.returnObjectType(mesh)
    assert objType in ["mesh", "nurbsSurface"], "'%s' isn't a mesh" % mesh

    follicleNode = createNamedNode((name), "follicle")

    """ make the closest point node """
    # closestPointNode = createNamedNode((targetObj+'_to_'+mesh),'closestPointOnMesh')
    controlSurface = mc.listRelatives(mesh, shapes=True)[0]
    follicleTransform = mc.listRelatives(follicleNode, p=True)[0]

    attributes.doConnectAttr(
        (controlSurface + ".worldMatrix[0]"), (follicleNode + ".inputWorldMatrix")
    )  # surface to follicle node
    if objType == "mesh":
        attributes.doConnectAttr(
            (controlSurface + ".outMesh"), (follicleNode + ".inputMesh")
        )  # surface mesh to follicle input mesh
    else:
        attributes.doConnectAttr(
            (controlSurface + ".local"), (follicleNode + ".inputSurface")
        )  # surface mesh to follicle input mesh

    attributes.doConnectAttr((follicleNode + ".outTranslate"), (follicleTransform + ".translate"))
    attributes.doConnectAttr((follicleNode + ".outRotate"), (follicleTransform + ".rotate"))

    attributes.doSetLockHideKeyableAttr(follicleTransform)

    return [follicleNode, follicleTransform]
Beispiel #13
0
def rigMasterCardCharaterOLD():
    spineChain = []
    jointChains = []
    def skinIt():
	#Skin it
	geoGroupObjects = search.returnAllChildrenObjects('geo_grp',True)
	#Get our group objects
	
	jointChains = getSkinJointChains()

	for i,g in enumerate([u'torso_geoGrp', u'armLeft_geoGrp', u'armRight_geoGrp', u'legLeft_geoGrp', u'legRight_geoGrp']):
	    geoGroupObjects = search.returnAllChildrenObjects(g,True)	
	
	    toSkin = []
	    for o in geoGroupObjects:
		if search.returnObjectType(o) in ['mesh','nurbsSurface']:
		    toSkin.append(o)
		
	    if toSkin:
		for o in toSkin:
		    toBind = jointChains[i] + [o]
		    mc.skinCluster(toBind, tsb = True, normalizeWeights = True, mi = 4, dr = 10,polySmoothness = 3)
	    else:
		print ("'%s' has nothing to skin!"%g)   
		
	
    def orientSkeletonTemplate():
	#First unparent the parts so we can orient properly
	hip = rigging.doParentToWorld('hip_l')
	heel = rigging.doParentToWorld('heel_l')
	clav = rigging.doParentToWorld('clavicle_l')
	palm = rigging.doParentToWorld('palm_l')
	
	spineChain = ['root']
	spineChain.extend(search.returnChildrenJoints('root'))
	for j in spineChain:        
	    joints.orientJoint(j,'xzy','zup')    
	
	hipChain = [hip]
	hipChain.extend(search.returnChildrenJoints(hip))
	for j in hipChain:
	    joints.orientJoint(j,'xzy','zup')
	    
	armChain = [clav]
	armChain.extend(search.returnChildrenJoints(clav))
	for j in armChain:
	    joints.orientJoint(j,'xyz','yup')  
	    
	footChain = [heel]
	footChain.extend(search.returnChildrenJoints(heel))
	for j in footChain:
	    joints.orientJoint(j,'yzx','yup')    
	
	handChain = [palm]
	handChain.extend(search.returnChildrenJoints(palm))
	for j in handChain:
	    joints.orientJoint(j,'xzy','zup') 
		
	#Fix the thumb
	thumbChain = ['thumb1_l']
	thumbChain.extend(search.returnChildrenJoints('thumb1_l'))
	for j in thumbChain:
	    #tweak - taken from Comet's orient 
	    mc.xform(j,r=True,os=True,ra= (-20,0,0))
	    mc.joint(j,e=True,zso = True)
	    mc.makeIdentity(j,apply=True)
	    
	#Fix the Head
	headChain = ['head1']
	headChain.extend(search.returnChildrenJoints('head1'))
	for j in headChain:
	    joints.orientJoint(j,'yzx','zup') 	
	    
	#Reconnect
	rigging.doParentReturnName(hip,'root')
	rigging.doParentReturnName(clav,'spine5')
	rigging.doParentReturnName(heel,'ankle_l')
	rigging.doParentReturnName(palm,'wrist_l')
	
	return spineChain
    
    def getSkinJointChains():
	leftArmChain = ['clavicle_l']
	leftArmChain.extend(search.returnChildrenJoints('clavicle_l'))
	
	rightArmChain = ['clavicle_r']
	rightArmChain.extend(search.returnChildrenJoints('clavicle_r'))	
	
	leftLegChain = ['hip_l']
	leftLegChain.extend(search.returnChildrenJoints('hip_l'))
	
	rightLegChain = ['hip_r']
	rightLegChain.extend(search.returnChildrenJoints('hip_r'))
	
	torsoChain.extend(['clavicle_l','clavicle_r'])
	
	returnList = [torsoChain,leftArmChain,rightArmChain,leftLegChain,rightLegChain]
	return returnList
    
    torsoChain = orientSkeletonTemplate()
    
    #Get ready for JTD stuff
    mel.eval('source JTDriggingUI;')
    mel.eval('source JTDarmRig;')
    mel.eval('source JTDspineRig;')
    mel.eval('source JTDneckRig;')
    mel.eval('source JTDdynParent;')
    mel.eval('source JTDfingerRig;')    
    
    mel.eval('mirrorJoint -mirrorYZ -mirrorBehavior -searchReplace "_l" "_r" "hip_l";')
    mel.eval('mirrorJoint -mirrorYZ -mirrorBehavior -searchReplace "_l" "_r" "clavicle_l";')
      
    mel.eval('JTDspineRig("%s", "spine1", "spine5", "root", %f, "%s", "");'%(baseName,spineScale,world))
    
    mel.eval('JTDneckRig("%s", "neck1", "head1", %f, "%s", "%s");'%(baseName,spineScale,world,connect))
    
    
    mel.eval('JTDarmRig("%s","clavicle_l","shoulder_l","elbow_l","wrist_l", 3, 1, %f, "%s", "%s");'%(baseName,armScale,world,connect))
    mel.eval('JTDarmRig("%s","clavicle_r","shoulder_r","elbow_r","wrist_r", 3, 2, %f, "%s", "%s");'%(baseName,armScale,world,connect))
    
    
    mel.eval('JTDlegRig("%s","hip_l","knee_l","ankle_l","heel_l","ball_l", 3, 1, %f, "%s", "%s", 2);'%(baseName,legScale,world,connect))
    mel.eval('JTDlegRig("%s","hip_r","knee_r","ankle_r","heel_r","ball_r", 3, 2, %f, "%s", "%s", 2);'%(baseName,legScale,world,connect))
    
    #Fingers Left
    mel.eval('JTDfingerRig("wrist_l","","index1_l","index2_l","index3_l", 1, 1, 1, 0, 1, "%s", %f);'%(baseName,fingerScale))
    mel.eval('JTDfingerRig("wrist_l","","fingers1_l","fingers2_l","fingers3_l", 1, 1, 4, 0, 1, "%s", %f);'%(baseName,fingerScale))
    
    mel.eval('JTDfingerRig("wrist_l","","thumb1_l","thumb2_l","thumb3_l", 1, 1, 0, 1, 1, "%s", %f);'%(baseName,fingerScale))
    
    #Fingers Right
    mel.eval('JTDfingerRig("wrist_r","","index1_r","index2_r","index3_r", 1, 1, 1, 0, 2, "%s", %f);'%(baseName,fingerScale))
    mel.eval('JTDfingerRig("wrist_r","","fingers1_r","fingers2_r","fingers3_r", 1, 1, 4, 0, 2, "%s", %f);'%(baseName,fingerScale))
    
    mel.eval('JTDfingerRig("wrist_r","","thumb1_r","thumb2_r","thumb3_r", 1, 1, 0, 1, 2, "%s", %f);'%(baseName,fingerScale))
    
    #new stuff
    #Head scale
    attributes.doSetLockHideKeyableAttr('cubey_neck_IK_Cntrl',lock = False,visible=True,keyable=True,channels = ['sx','sy','sz'])
    mc.setAttr('cubey_neck_IK_Cntrl.sx', keyable = True)
    mc.setAttr('cubey_neck_IK_Cntrl.sy', keyable = True)
    mc.setAttr('cubey_neck_IK_Cntrl.sz', keyable = True)
    
    mc.scaleConstraint('cubey_neck_IK_Cntrl','head1')
    
    #Sets and Coloring
    leftArmSetObjects = [u'rig_clavicle_l_IK_Cntrl', u'rig_shoulder_l_twist', u'rig_shoulder_l_Bendy', u'rig_elbow_l_Bendy', u'rig_clavicle_l_FK_Cntrl', u'cubey_finger_Cntrl0_l', u'rig_wrist_l_FK', u'rig_wrist_l_SW', u'rig_shoulder_l_FK', u'rig_elbow_l_FK', u'cubey_arm_IK_Cntrl_l', u'rig_wrist_l_GimbleCntrl_l', u'cubey_arm_PV_Cntrl_l'] # 
    rightArmSetObjects = [u'rig_clavicle_r_IK_Cntrl', u'rig_shoulder_r_twist', u'rig_shoulder_r_Bendy', u'rig_elbow_r_Bendy', u'rig_clavicle_r_FK_Cntrl', u'cubey_finger_Cntrl0_r', u'rig_wrist_r_FK', u'rig_wrist_r_SW', u'rig_shoulder_r_FK', u'rig_elbow_r_FK', u'cubey_arm_IK_Cntrl_r', u'rig_wrist_r_GimbleCntrl_r', u'cubey_arm_PV_Cntrl_r'] # 
    
    centerSetObjects = [u'rig_spine1_Shoulders', u'rig_spine1_Hips', u'cubey_spine_Root', u'rig_spine1FK3', u'rig_spine1FK2', u'rig_spine1FK1', u'cubey_neck_FK_Cntrl', u'cubey_neck_IK_Cntrl']
    
    leftLegSetObjects = [u'rig_ball_l_FK', u'rig_ankle_l_SW', u'rig_hip_l_Bendy', u'rig_knee_l_FK', u'rig_ankle_l_FK', u'rig_hip_l_FK', u'rig_knee_l_Bendy', u'rig_hip_l_twist', u'cubey_leg_GimbleCntrl_l', u'cubey_leg_IKleg_Cntrl_l', u'cubey_leg_PV_Cntrl_l']
    rightLegSetObjects = [u'rig_ball_r_FK', u'rig_ankle_r_SW', u'rig_hip_r_Bendy', u'rig_knee_r_FK', u'rig_ankle_r_FK', u'rig_hip_r_FK', u'rig_knee_r_Bendy', u'rig_hip_r_twist', u'cubey_leg_GimbleCntrl_r', u'cubey_leg_IKleg_Cntrl_r', u'cubey_leg_PV_Cntrl_r']
    
    lArmSet = SetFactory.SetFactory('armLeft','animation',True)
    for o in leftArmSetObjects:
	lArmSet.store(o)
	#color
	curves.setCurveColorByName(o,'blueBright')        
	
    rArmSet = SetFactory.SetFactory('armRight','animation',True)
    for o in rightArmSetObjects:
	rArmSet.store(o)
	#color
	curves.setCurveColorByName(o,'redBright')
	
    
    torsoSet = SetFactory.SetFactory('torso','animation',True)
    for o in centerSetObjects:
	torsoSet.store(o)  
	curves.setCurveColorByName(o,'yellow')
	
	
    lLegSet = SetFactory.SetFactory('legLeft','animation',True)
    for o in leftLegSetObjects:
	lLegSet.store(o)
	curves.setCurveColorByName(o,'blueBright')
	
    rLegSet = SetFactory.SetFactory('legRight','animation',True)
    for o in rightLegSetObjects:
	rLegSet.store(o)    
	curves.setCurveColorByName(o,'redBright')
    
    bindJoints = search.returnAllChildrenObjects('root')
    bindJoints.append('root')    
    skinJointsSet = SetFactory.SetFactory('skinJoints','td',True)
    for o in bindJoints:
	if mc.ls(o,type='joint'):
	    skinJointsSet.store(o)    

    #Set of all sets    
    allSet = SetFactory.SetFactory('all','animation',True)
    allSet.store(rLegSet.nameLong)
    allSet.store(lLegSet.nameLong)
    allSet.store(torsoSet.nameLong)
    allSet.store(lArmSet.nameLong)
    allSet.store(rArmSet.nameLong)
    
    
    #Skin!
    skinIt()
Beispiel #14
0
	def build(self):#================================================================================   	
	    
	    #>>>Get data
	    ml_controlsFK =  self._go._i_rigNull.msgList_get('controlsFK')   
	    ml_rigJoints = self._go._i_rigNull.msgList_get('rigJoints')
	    ml_blendJoints = self._go._i_rigNull.msgList_get('blendJoints')
	    ml_fkJoints = self._go._i_rigNull.msgList_get('fkJoints')
	    ml_ikJoints = self._go._i_rigNull.msgList_get('ikJoints')
		    
	    mi_settings = self._go._i_rigNull.settings
		
	    aimVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[0])
	    upVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[1])
	    outVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[2])
	    
	    mi_controlIK = self._go._i_rigNull.controlIK
	
	    for chain in [ml_ikJoints,ml_blendJoints]:
		chain[0].parent = self._go._i_constrainNull.mNode
		
	    self.ml_fkAttachJoints = []
	    if self._go._str_mirrorDirection == 'Right':#mirror control setup
		self.ml_fkAttachJoints = self._go._i_rigNull.msgList_get('fkAttachJoints')
		
	    #for more stable ik, we're gonna lock off the lower channels degrees of freedom
	    for chain in [ml_ikJoints]:
		for axis in self._go._jointOrientation[:2]:
		    log.info(axis)
		    for i_j in chain[1:]:
			attributes.doSetAttr(i_j.mNode,"jointType%s"%axis.upper(),1)
	    
	    #=============================================================    
	    try:#>>>Finger Root Control and root follow
		for attr in ['tx','ty','tz']:#Unlock a few things
		    i_attr = cgmMeta.cgmAttr(ml_fkJoints[0],attr)
		    i_attr.p_keyable = True
		    i_attr.p_locked = False	   	
	
		#we have to rebuild a little so that we can use our fk base control both for fk and ik
		#Create a orient group that tracks the  module constrain null
		if self._go._partType == 'finger':
		    buffer_fkGroup = ml_fkJoints[0].parent
		    i_orientGroup = cgmMeta.asMeta( ml_fkJoints[1].doGroup(True),'cgmObject',setClass=True )
		    i_orientGroup.addAttr('cgmTypeModifier','toOrient')
		    i_orientGroup.doName()
		    
		    #constrain it 
		    str_orConst = mc.orientConstraint(self._go._i_constrainNull.mNode,i_orientGroup.mNode,maintainOffset = True)[0]
		    self._go._i_constrainNull.connectChildNode(i_orientGroup,'fingerRoot','owner')#Connect
		    i_orientGroup.parent = self._go._i_constrainNull.mNode
		    
		    attributes.doSetLockHideKeyableAttr(i_orientGroup.mNode)#lockNHide
		    
		    i_parentGroup = cgmMeta.asMeta( i_orientGroup.doGroup(True),'cgmObject',setClass=True )
		    i_parentGroup.addAttr('cgmTypeModifier','toParent')
		    i_parentGroup.doName()	
		    str_prntConst = mc.parentConstraint( ml_fkJoints[0].mNode,i_parentGroup.mNode,maintainOffset = True)[0]
		    i_parentGroup.parent = buffer_fkGroup
		    
		    #attributes.doSetLockHideKeyableAttr(ml_fkJoints[0].mNode,lock = False, visible=True, keyable=True, channels=['tx','ty','tz'])
		    
		    #Constrain ik base to fk base
		    mc.orientConstraint(ml_fkJoints[0].mNode,ml_ikJoints[0].mNode,maintainOffset = True)
		    ml_fkJoints[0].parent = self._go._i_constrainNull.mNode
	
	    except Exception,error:
		raise Exception,"%s.build_FKIK>>> Finger Root Control error: %s"%(self._go._strShortName,error)
Beispiel #15
0
        def _buildPupilIris_(self):
            mi_go = self._go  #Rig Go instance link
            str_mirrorSide = self.str_mirrorSide

            try:  #>>>> Iris pupil #==================================================================
                try:
                    _l_build = [{
                        'tag': 'iris',
                        'buildCheck': self.mi_helper.buildIris,
                        'shape': self.md_rigList['iris_shape'],
                        'joint': self.md_rigList['iris'],
                        'parent': self.md_rigList['eye']
                    }, {
                        'tag': 'pupil',
                        'buildCheck': self.mi_helper.buildPupil,
                        'shape': self.md_rigList['pupil_shape'],
                        'joint': self.md_rigList['pupil'],
                        'parent': self.md_rigList['iris']
                    }]
                except Exception, error:
                    raise Exception, "[build dict]{%s}" % (error)

                for _d in _l_build:
                    try:
                        self._d_buffer = _d
                        self.log_infoNestedDict('_d_buffer')
                        _tag = _d['tag']
                        _shape = _d['shape']
                        _joint = _d['joint']
                        _b_buildCheck = _d['buildCheck']

                        if not _b_buildCheck:
                            self.log_info("Build %s toggle: off" % (_tag))
                            _shape.delete()

                        else:
                            _joint.parent = mi_go._i_constrainNull.eyeTrackNull.mNode
                            d_buffer = mControlFactory.registerControl(
                                _joint,
                                useShape=_shape,
                                mirrorSide=str_mirrorSide,
                                mirrorAxis="",
                                makeAimable=True,
                                setRotateOrder='zxy')

                            mi_control = d_buffer['instance']
                            _shape.delete()

                            attributes.doSetAttr(mi_control.mNode,
                                                 'overrideEnabled', 0)
                            attributes.doSetAttr(mi_control.mNode,
                                                 'overrideDisplayType', 0)
                            cgmMeta.cgmAttr(mi_control,
                                            'radius',
                                            .0001,
                                            hidden=True)
                            mi_go._i_rigNull.connectChildNode(
                                mi_control, 'control%s' % _tag.capitalize(),
                                "rigNull")
                            self.ml_controlsAll.append(mi_control)
                            attributes.doSetLockHideKeyableAttr(
                                mi_control.mNode,
                                channels=[
                                    'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'v',
                                    's%s' % mi_go._jointOrientation[0]
                                ])
                    except Exception, error:
                        raise Exception, "[%s]{%s}" % (_tag, error)
Beispiel #16
0
                mi_controlFK.axisAim = "%s+" % mi_go._jointOrientation[0]
                mi_controlFK.axisUp = "%s+" % mi_go._jointOrientation[1]
                mi_controlFK.axisOut = "%s+" % mi_go._jointOrientation[2]

                #We're gonna lock the aim rot
                cgmMeta.cgmAttr(mi_controlFK,
                                'r%s' % mi_go._jointOrientation[0],
                                keyable=False,
                                lock=True,
                                hidden=True)
                mi_go._i_rigNull.connectChildNode(mi_controlFK, 'controlFK',
                                                  "rigNull")
                self.ml_controlsAll.append(mi_controlFK)

                attributes.doSetLockHideKeyableAttr(
                    mi_controlFK.mNode,
                    channels=['tx', 'ty', 'tz', 'sx', 'sy', 'sz', 'v'])

            except Exception, error:
                raise Exception, "[Build fk fail]{%s}" % (error)

            try:  #>>>> IK
                #==================================================================
                mi_ikShape.parent = mi_go._i_constrainNull.controlsIKNull.mNode
                d_buffer = mControlFactory.registerControl(
                    mi_ikShape,
                    mirrorSide=str_mirrorSide,
                    mirrorAxis="",
                    typeModifier='ik',
                    addDynParentGroup=True)
                mi_ikControl = d_buffer['instance']
Beispiel #17
0
    def verify(self):
        """ 
        Verifies the various components a masterNull for a character/asset. If a piece is missing it replaces it.
        
        RETURNS:
        success(bool)
        """
        #Puppet null
        try:
            if not mc.objExists(self.nameBase):
                buffer = mc.group(empty=True)
                self.PuppetNull = ObjectFactory(buffer)
            else:
                self.PuppetNull = ObjectFactory(self.nameBase)

            self.PuppetNull.store('cgmName', self.nameBase, True)
            self.PuppetNull.store('cgmType', 'ignore')
            self.PuppetNull.store('cgmModuleType', 'master')

            if self.PuppetNull.nameShort != self.nameBase:
                self.PuppetNull.doName(False)

            attributes.doSetLockHideKeyableAttr(self.PuppetNull.nameShort,
                                                channels=[
                                                    'tx', 'ty', 'tz', 'rx',
                                                    'ry', 'rz', 'sx', 'sy',
                                                    'sz'
                                                ])
        except:
            guiFactory.warning("Puppet null failed!")

        #Checks our modules container null
        created = False
        #Initialize message attr
        self.msgModulesGroup = AttrFactory(self.PuppetNull, 'modulesGroup',
                                           'message')
        if not self.msgModulesGroup.get():
            self.ModulesGroup = ObjectFactory(mc.group(empty=True))
            self.msgModulesGroup.doStore(self.ModulesGroup.nameShort)
            created = True
        else:
            self.ModulesGroup = ObjectFactory(self.msgModulesGroup.get())

        self.ModulesGroup.store('cgmName', 'modules')
        self.ModulesGroup.store('cgmType', 'group')

        self.ModulesGroup.doParent(self.PuppetNull.nameShort)

        if created:
            self.ModulesGroup.doName(False)

        self.msgModulesGroup.updateData()

        attributes.doSetLockHideKeyableAttr(self.ModulesGroup.nameShort)

        #Checks our noTransform container null
        created = False
        self.msgNoTransformGroup = AttrFactory(self.PuppetNull,
                                               'noTransformGroup', 'message')
        if not self.msgNoTransformGroup.get():
            self.NoTransformGroup = ObjectFactory(mc.group(empty=True))
            self.msgNoTransformGroup.doStore(self.NoTransformGroup.nameShort)
            created = True
        else:
            self.NoTransformGroup = ObjectFactory(
                self.msgNoTransformGroup.get())

        self.NoTransformGroup.store('cgmName', 'noTransform')
        self.NoTransformGroup.store('cgmType', 'group')

        self.NoTransformGroup.doParent(self.PuppetNull.nameShort)

        if created:
            self.NoTransformGroup.doName(False)

        self.msgNoTransformGroup.updateData()

        attributes.doSetLockHideKeyableAttr(self.NoTransformGroup.nameShort)

        #Checks our geo container null
        created = False
        self.msgGeoGroup = AttrFactory(self.PuppetNull, 'geoGroup', 'message')
        if not self.msgGeoGroup.get():
            self.GeoGroup = ObjectFactory(mc.group(empty=True))
            self.msgGeoGroup.doStore(self.GeoGroup.nameShort)
            created = True
        else:
            self.GeoGroup = ObjectFactory(self.msgGeoGroup.get())

        self.GeoGroup.store('cgmName', 'geo')
        self.GeoGroup.store('cgmType', 'group')

        self.GeoGroup.doParent(self.msgNoTransformGroup.get())

        if created:
            self.GeoGroup.doName(False)

        self.msgGeoGroup.updateData()

        attributes.doSetLockHideKeyableAttr(self.GeoGroup.nameShort)

        #Checks master info null
        created = False
        self.msgPuppetInfo = AttrFactory(self.PuppetNull, 'info', 'message')
        if not self.msgPuppetInfo.get():
            self.PuppetInfoNull = ObjectFactory(mc.group(empty=True))
            self.msgPuppetInfo.doStore(self.PuppetInfoNull.nameShort)
            created = True
        else:
            self.PuppetInfoNull = ObjectFactory(self.msgPuppetInfo.get())

        self.PuppetInfoNull.store('cgmName', 'master')
        self.PuppetInfoNull.store('cgmType', 'info')

        self.PuppetInfoNull.doParent(self.PuppetNull.nameShort)

        if created:
            self.PuppetInfoNull.doName(False)

        self.msgPuppetInfo.updateData()

        attributes.doSetLockHideKeyableAttr(self.PuppetInfoNull.nameShort)

        #Checks modules info null
        created = False
        self.msgModuleInfo = AttrFactory(self.msgPuppetInfo.get(), 'modules',
                                         'message')
        if not self.msgModuleInfo.get():
            self.ModuleInfoNull = ObjectFactory(mc.group(empty=True))
            self.msgModuleInfo.doStore(self.ModuleInfoNull.nameShort)
            created = True
        else:
            self.ModuleInfoNull = ObjectFactory(self.msgModuleInfo.get())

        self.ModuleInfoNull.store('cgmName', 'modules')
        self.ModuleInfoNull.store('cgmType', 'info')

        self.ModuleInfoNull.doParent(self.PuppetInfoNull.nameShort)

        if created:
            self.ModuleInfoNull.doName(False)

        self.msgModuleInfo.updateData()

        attributes.doSetLockHideKeyableAttr(self.ModuleInfoNull.nameShort)

        #Initialize our modules null as a buffer
        self.ModulesBuffer = BufferFactory(self.ModuleInfoNull.nameShort)

        #Checks geo info null
        created = False
        self.msgGeoInfo = AttrFactory(self.msgPuppetInfo.get(), 'geo',
                                      'message')
        if not self.msgGeoInfo.get():
            self.GeoInfoNull = ObjectFactory(mc.group(empty=True))
            self.msgGeoInfo.doStore(self.GeoInfoNull.nameShort)
            created = True
        else:
            self.GeoInfoNull = ObjectFactory(self.msgGeoInfo.get())

        self.GeoInfoNull.store('cgmName', 'geo')
        self.GeoInfoNull.store('cgmType', 'info')

        self.GeoInfoNull.doParent(self.msgPuppetInfo.get())

        if created:
            self.GeoInfoNull.doName(False)

        self.msgGeoInfo.updateData()

        attributes.doSetLockHideKeyableAttr(self.GeoInfoNull.nameShort)

        #Checks settings info null
        created = False
        self.msgSettingsInfo = AttrFactory(self.msgPuppetInfo.get(),
                                           'settings', 'message')
        if not self.msgSettingsInfo.get():
            self.SettingsInfoNull = ObjectFactory(mc.group(empty=True))
            self.msgSettingsInfo.doStore(self.SettingsInfoNull.nameShort)
            created = True
        else:
            self.SettingsInfoNull = ObjectFactory(self.msgSettingsInfo.get())

        self.SettingsInfoNull.store('cgmName', 'settings')
        self.SettingsInfoNull.store('cgmType', 'info')
        defaultFont = modules.returnSettingsData('defaultTextFont')
        self.SettingsInfoNull.store('font', defaultFont)

        self.SettingsInfoNull.doParent(self.msgPuppetInfo.get())

        if created:
            self.SettingsInfoNull.doName(False)

        self.msgSettingsInfo.updateData()

        self.optionPuppetMode = AttrFactory(self.SettingsInfoNull,
                                            'optionPuppetTemplateMode',
                                            'int',
                                            initialValue=0)

        self.optionAimAxis = AttrFactory(self.SettingsInfoNull,
                                         'axisAim',
                                         'enum',
                                         enum='x+:y+:z+:x-:y-:z-',
                                         initialValue=2)
        self.optionUpAxis = AttrFactory(self.SettingsInfoNull,
                                        'axisUp',
                                        'enum',
                                        enum='x+:y+:z+:x-:y-:z-',
                                        initialValue=1)
        self.optionOutAxis = AttrFactory(self.SettingsInfoNull,
                                         'axisOut',
                                         'enum',
                                         enum='x+:y+:z+:x-:y-:z-',
                                         initialValue=0)

        attributes.doSetLockHideKeyableAttr(self.SettingsInfoNull.nameShort)

        return True
Beispiel #18
0
def doCreateOrientationHelpers(self):
    """ 
    """
    log.debug(">>> addOrientationHelpers")
    assert self.cls == 'TemplateFactory.go',"Not a TemlateFactory.go instance!"
    assert mc.objExists(self.m.mNode),"module no longer exists"
    #Gather limb specific data and check
    #===================================
    #'orientHelpers':'messageSimple',#Orientation helper controls
    #'orientRootHelper':'messageSimple',#Root orienation helper

    helperObjects = []
    helperObjectGroups = []
    returnBuffer = []
    root = self.i_templateNull.getMessage('root')[0]
    objects =  self.i_templateNull.getMessage('controlObjects')
    log.debug(root)
    log.debug(objects)
    log.debug(self.foundDirections)
    
    #>> Create orient root control
    #=============================     
    orientRootSize = (distance.returnBoundingBoxSizeToAverage(root,True)*2.5)    
    i_orientRootControl = cgmMeta.cgmObject( curves.createControlCurve('circleArrow1',orientRootSize) )
    i_orientRootControl.addAttr('mClass','cgmObject',lock=True)
    
    curves.setCurveColorByName(i_orientRootControl.mNode,self.moduleColors[0])
    i_orientRootControl.addAttr('cgmName',value = str(self.m.getShortName()), attrType = 'string', lock=True)#<<<<<<<<<<<FIX THIS str(call) when Mark fixes bug    
    i_orientRootControl.addAttr('cgmType',value = 'templateOrientRoot', attrType = 'string', lock=True)
    i_orientRootControl.doName()
    
    #>>> Store it
    i_orientRootControl.connectParent(self.templateNull,'orientRootHelper','owner')#Connect it to it's object      
    
    #>>> Position and set up follow groups
    position.moveParentSnap(i_orientRootControl.mNode,root)    
    i_orientRootControl.parent = root #parent it to the root
    i_orientRootControl.doGroup(maintain = True)#group while maintainting position
    
    mc.pointConstraint(objects[0],i_orientRootControl.parent,maintainOffset = False)#Point contraint orient control to the first helper object
    mc.aimConstraint(objects[-1],i_orientRootControl.parent,maintainOffset = True, weight = 1, aimVector = [1,0,0], upVector = [0,1,0], worldUpObject = root, worldUpType = 'objectRotation' )
    attributes.doSetLockHideKeyableAttr(i_orientRootControl.mNode,True,False,False,['tx','ty','tz','rx','ry','sx','sy','sz','v'])
    
    self.i_orientHelpers = []#we're gonna store the instances so we can get them all after parenting and what not
    #>> Sub controls
    #============================= 
    if len(objects) == 1:#If a single handle module
        i_obj = cgmMeta.cgmObject(objects[0])
        position.moveOrientSnap(objects[0],root)
    else:
        for i,obj in enumerate(objects):
            log.debug("on %s"%(mc.ls(obj,shortNames=True)[0]))
            #>>> Create and color      
            size = (distance.returnBoundingBoxSizeToAverage(obj,True)*2) # Get size
            i_obj = cgmMeta.cgmObject(curves.createControlCurve('circleArrow2Axis',size))#make the curve
            i_obj.addAttr('mClass','cgmObject',lock=True)
            curves.setCurveColorByName(i_obj.mNode,self.moduleColors[1])
            #>>> Tag and name
            i_obj.doCopyNameTagsFromObject(obj)
            i_obj.doStore('cgmType','templateOrientHelper',True)        
            i_obj.doName()
            
            #>>> Link it to it's object and append list for full store
            i_obj.connectParent(obj,'helper','owner')#Connect it to it's object      
            self.i_orientHelpers.append(i_obj)
            log.debug(i_obj.owner)
            #>>> initial snapping """
            position.movePointSnap(i_obj.mNode,obj)
            
            if i < len(objects)-1:#If we have a pair for it, aim at that pairs aim, otherwise, aim at the second to last object
                constBuffer = mc.aimConstraint(objects[i+1],i_obj.mNode,maintainOffset = False, weight = 1, aimVector = [0,0,1], upVector = [0,1,0], worldUpVector = self.foundDirections[1], worldUpType = 'vector' )
            else:
                constBuffer = mc.aimConstraint(objects[-2],i_obj.mNode,maintainOffset = False, weight = 1, aimVector = [0,0,-1], upVector = [0,1,0], worldUpVector = self.foundDirections[1], worldUpType = 'vector' )
    
            if constBuffer:mc.delete(constBuffer)
        
            #>>> follow groups
            i_obj.parent = obj
            i_obj.doGroup(maintain = True)
            
            if i < len(objects)-1:#If we have a pair for it, aim at that pairs aim, otherwise, aim at the second to last object
                mc.aimConstraint(objects[i+1],i_obj.parent,maintainOffset = False, weight = 1, aimVector = [0,0,1], upVector = [0,1,0], worldUpVector = [0,1,0], worldUpObject = i_orientRootControl.mNode, worldUpType = 'objectrotation' )
            else:
                constBuffer = mc.aimConstraint(objects[-2],i_obj.parent,maintainOffset = False, weight = 1, aimVector = [0,0,-1], upVector = [0,1,0], worldUpObject = i_orientRootControl.mNode, worldUpType = 'objectrotation' )
    
            #>>> ConnectVis, lock and hide
            #mc.connectAttr((visAttr),(helperObj+'.v'))
            if obj == objects[-1]:
                attributes.doSetLockHideKeyableAttr(i_obj.mNode,True,False,False,['tx','ty','tz','ry','sx','sy','sz','v'])            
            else:
                attributes.doSetLockHideKeyableAttr(i_obj.mNode,True,False,False,['tx','ty','tz','rx','ry','sx','sy','sz','v'])
    #>>> Get data ready to go forward
    bufferList = []
    for o in self.i_orientHelpers:
        bufferList.append(o.mNode)
    self.i_templateNull.orientHelpers = bufferList
    self.i_orientRootHelper = i_orientRootControl
    log.debug("orientRootHelper: [%s]"%self.i_templateNull.orientRootHelper.getShortName())   
    log.debug("orientHelpers: %s"%self.i_templateNull.getMessage('orientHelpers'))

    return True
Beispiel #19
0
def rigArm(objectNull):
    """return variables"""
    nullBase = names.stripSuffixObj(objectNull)
    templateNull = (nullBase + '_templateNull')
    templateNullMessageData = []
    templateNullMessageData = attributes.returnMessageAttrs(templateNull)
    templateObjects = []
    coreNamesList = []
    for set in templateNullMessageData:
        templateObjects.append(set[1])
        coreNamesList.append(set[0])
    """ return rid of locators on our template objects so they don't screw up the distance locators"""
    templateObjects.remove(templateObjects[-1])
    coreNamesList.remove(coreNamesList[-1])
    for obj in templateObjects:
        if mc.objExists(obj + '_loc'):
            mc.delete(obj + '_loc')
    """make joint chains"""
    fkJoints = joints.createJointsFromObjPositions(templateObjects, 'fk')
    mc.select(cl=True)
    ikJoints = joints.createJointsFromObjPositions(templateObjects, 'ik')
    """orient joints"""
    joints.orientJointChain(fkJoints, 'xyz', 'yup')
    joints.orientJointChain(ikJoints, 'xyz', 'yup')
    """set rotation order - CHANGE to go for the names later and optional orientation schemes"""
    joints.setRotationOrderOnJoint(fkJoints[0], 'xyz')
    joints.setRotationOrderOnJoint(fkJoints[1], 'xzy')
    joints.setRotationOrderOnJoint(fkJoints[2], 'zyx')

    joints.setRotationOrderOnJoint(ikJoints[0], 'xyz')
    joints.setRotationOrderOnJoint(ikJoints[1], 'xzy')
    joints.setRotationOrderOnJoint(ikJoints[2], 'zyx')
    """ create hand_anim locs """
    hand_animRegBuffer = locators.locMeObject(ikJoints[2])
    hand_animPinnedBuffer = locators.locMeObject(ikJoints[2])

    hand_animReg = mc.rename(hand_animRegBuffer, (coreNamesList[2] + '_anim'))
    hand_animPinned = mc.rename(hand_animPinnedBuffer,
                                (coreNamesList[2] + '_elbow_anim'))
    """ creating measure stuff """
    # Had to move this up here because distanceDimension doesn't let you specify which locator to use. Need to modify script to account for that
    uprArmMeasureLocBuffer = locators.locMeObject(ikJoints[0])
    handMeasureLocBuffer = locators.locMeObject(ikJoints[2])
    elbowMeasureLocBuffer = locators.locMeObject(ikJoints[1])

    uprArmMeasureLoc = mc.rename(uprArmMeasureLocBuffer,
                                 (coreNamesList[0] + '_dist_loc'))
    handMeasureLoc = mc.rename(handMeasureLocBuffer,
                               (coreNamesList[2] + '_dist_loc'))
    elbowMeasureLoc = mc.rename(elbowMeasureLocBuffer,
                                (coreNamesList[1] + '_dist_loc'))

    measureFullLength = [uprArmMeasureLoc, handMeasureLoc]
    fullLengthMeassureObj = distance.createDistanceObjectsBetweenObjectList(
        measureFullLength)

    measureShoulderToElbow = [uprArmMeasureLoc, elbowMeasureLoc]
    uprLengthMeassureObj = distance.createDistanceObjectsBetweenObjectList(
        measureShoulderToElbow)

    measureElbowToHand = [elbowMeasureLoc, handMeasureLoc]
    lwrLengthMeassureObj = distance.createDistanceObjectsBetweenObjectList(
        measureElbowToHand)
    """>>>Set up Rotation Isolation for FK Mode
    """
    """creates our locator parent"""
    UprArmRoot = locators.locMeObject(fkJoints[0])
    """ Create 4 target locators"""
    UprArmTorsoOrientBuffer = mc.duplicate(UprArmRoot)
    UprArmBodyOrientBuffer = mc.duplicate(UprArmRoot)
    UprArmTorsoOrientDriverBuffer = mc.duplicate(UprArmRoot)
    UprArmBodyOrientDriverBuffer = mc.duplicate(UprArmRoot)
    UprArmOrientBuffer = mc.duplicate(UprArmRoot)
    """names our loctators intelligently"""
    uprArmTorsoOrient = mc.rename(UprArmTorsoOrientBuffer[0],
                                  (coreNamesList[0] + '_torso_orient'))
    uprArmBodyOrient = mc.rename(UprArmBodyOrientBuffer[0],
                                 (coreNamesList[0] + '_body_orient'))
    uprArmTorsoOrientDriver = mc.rename(
        UprArmTorsoOrientDriverBuffer[0],
        (coreNamesList[0] + '_torso_orient_driver'))
    uprArmBodyOrientDriver = mc.rename(
        UprArmBodyOrientDriverBuffer[0],
        (coreNamesList[0] + '_body_orient_driver'))
    UprArmOrient = mc.rename(UprArmOrientBuffer[0],
                             (coreNamesList[0] + '_orient_anim'))
    """orients the orient_anim control placeholder"""
    attributes.setRotationOrderObj(UprArmOrient, 'xzy')
    """parents orient control loc to top node"""
    mc.parent(UprArmOrient, UprArmRoot)
    """parents arm to top loc"""
    mc.parent(fkJoints[0], UprArmOrient)
    """parents top loc and torso orient loc to torso diver"""
    mc.parent(UprArmRoot, uprArmTorsoOrientDriver)
    mc.parent(uprArmTorsoOrient, uprArmTorsoOrientDriver)
    mc.parent(uprArmBodyOrient, uprArmBodyOrientDriver)
    """ makes orient constraint for the fk arm"""
    orConstBuffer = mc.orientConstraint([uprArmBodyOrient, uprArmTorsoOrient],
                                        UprArmRoot,
                                        mo=True,
                                        weight=1)
    orConst = mc.rename(orConstBuffer, (fkJoints[0] + '_orConst'))
    """ adds our constraint toggle """
    mc.addAttr(fkJoints[0], ln='orient', at='enum', en='torso:body:')
    mc.setAttr((fkJoints[0] + '.orient'), keyable=True)
    """ return our orient constraint channels """
    orConstAttrs = (mc.listAttr(orConst, userDefined=True))
    """ setups up toggle to change orientation """
    mc.setDrivenKeyframe((orConst + '.' + orConstAttrs[0]),
                         currentDriver=(fkJoints[0] + '.orient'),
                         driverValue=0,
                         value=0)
    mc.setDrivenKeyframe((orConst + '.' + orConstAttrs[1]),
                         currentDriver=(fkJoints[0] + '.orient'),
                         driverValue=0,
                         value=1)
    mc.setDrivenKeyframe((orConst + '.' + orConstAttrs[0]),
                         currentDriver=(fkJoints[0] + '.orient'),
                         driverValue=1,
                         value=1)
    mc.setDrivenKeyframe((orConst + '.' + orConstAttrs[1]),
                         currentDriver=(fkJoints[0] + '.orient'),
                         driverValue=1,
                         value=0)
    """ >>>Sets up fk arm scaling """
    """ adds our length attribute"""
    mc.addAttr(fkJoints[0],
               ln='length',
               at='float',
               minValue=0,
               defaultValue=1)
    mc.setAttr((fkJoints[0] + '.length'), keyable=True)
    mc.addAttr(fkJoints[1],
               ln='length',
               at='float',
               minValue=0,
               defaultValue=1)
    mc.setAttr((fkJoints[1] + '.length'), keyable=True)
    """ connects length to child joint length """
    currentLength = mc.getAttr(fkJoints[1] + '.translateX')
    mc.setDrivenKeyframe((fkJoints[1] + '.translateX'),
                         currentDriver=(fkJoints[0] + '.length'),
                         driverValue=1,
                         value=currentLength,
                         inTangentType='linear',
                         outTangentType='linear')
    mc.setDrivenKeyframe((fkJoints[1] + '.translateX'),
                         currentDriver=(fkJoints[0] + '.length'),
                         driverValue=0,
                         value=0,
                         inTangentType='linear',
                         outTangentType='linear')

    currentLength = mc.getAttr(fkJoints[2] + '.translateX')
    mc.setDrivenKeyframe((fkJoints[2] + '.translateX'),
                         currentDriver=(fkJoints[1] + '.length'),
                         driverValue=1,
                         value=currentLength,
                         inTangentType='linear',
                         outTangentType='linear')
    mc.setDrivenKeyframe((fkJoints[2] + '.translateX'),
                         currentDriver=(fkJoints[1] + '.length'),
                         driverValue=0,
                         value=0,
                         inTangentType='linear',
                         outTangentType='linear')
    """ set sdk curves to infinity """
    mc.setInfinity((fkJoints[1] + '.translateX'), pri='constant', poi='linear')
    mc.setInfinity((fkJoints[2] + '.translateX'), pri='constant', poi='linear')
    """ lockin stuff down on the fk end """
    for jnt in fkJoints:
        attributes.doSetLockHideKeyableAttr(
            jnt, True, False, False, ['ty', 'tz', 'sx', 'sy', 'sz', 'v'])
    attributes.doSetLockHideKeyableAttr(
        UprArmOrient, True, False, False,
        ['tx', 'ty', 'tz', 'sx', 'sy', 'sz', 'v'])
    attributes.doSetLockHideKeyableAttr(fkJoints[1], False, False, False,
                                        ['tx'])
    attributes.doSetLockHideKeyableAttr(fkJoints[2], False, False, False,
                                        ['tx'])
    """ >>>IK arm time!"""
    """make elbow loc and a hand loc"""
    elbowIKLoc = locators.locMeObject(ikJoints[1])
    handIKLoc = locators.locMeObject(ikJoints[2])
    """set preferred rotation channel on elbow"""
    #---------------------->>>> Need to figure out how to generate this!
    mc.setAttr((ikJoints[1] + '.ry'), -30)
    mc.joint(ikJoints[1], edit=True, setPreferredAngles=True)
    mc.setAttr((ikJoints[1] + '.ry'), 0)
    """set up the ik handle"""
    ikHandleName = (nullBase + '_ikHandle')
    mc.ikHandle(name=ikHandleName,
                startJoint=ikJoints[0],
                endEffector=ikJoints[2],
                sol='ikRPsolver',
                snapHandleFlagToggle=True)
    """Polevector constraint"""
    mc.poleVectorConstraint(elbowIKLoc,
                            ikHandleName,
                            name=(nullBase + '.pvConst'),
                            weight=1.0)
    mc.parent(ikHandleName, handIKLoc)
    """ >>> IK Stretch stuff"""
    """connecting measure stuff"""
    mc.parent(handMeasureLoc, handIKLoc)

    uprArmLength = mc.getAttr(ikJoints[1] + '.tx')
    lwrArmLength = mc.getAttr(ikJoints[2] + '.tx')
    fullLength = (uprArmLength + lwrArmLength)
    driver = (fullLengthMeassureObj[0] + 'Shape.distance')
    """sets base sdk key for length"""
    mc.setDrivenKeyframe((ikJoints[1] + '.tx'),
                         currentDriver=driver,
                         driverValue=fullLength,
                         value=uprArmLength,
                         inTangentType='linear',
                         outTangentType='linear')
    mc.setDrivenKeyframe((ikJoints[2] + '.tx'),
                         currentDriver=driver,
                         driverValue=fullLength,
                         value=lwrArmLength,
                         inTangentType='linear',
                         outTangentType='linear')
    """sets stetch sdk key for length"""
    mc.setDrivenKeyframe((ikJoints[1] + '.tx'),
                         currentDriver=driver,
                         driverValue=(fullLength * 2),
                         value=(uprArmLength * 2),
                         inTangentType='linear',
                         outTangentType='linear')
    mc.setDrivenKeyframe((ikJoints[2] + '.tx'),
                         currentDriver=driver,
                         driverValue=(fullLength * 2),
                         value=(lwrArmLength * 2),
                         inTangentType='linear',
                         outTangentType='linear')

    mc.setInfinity((ikJoints[1] + '.tx'), pri='constant', poi='linear')
    mc.setInfinity((ikJoints[2] + '.tx'), pri='constant', poi='linear')
    """ >>> Set up pinning"""
    """ creates blend node """
    """upr"""
    uprBlendNode = mc.createNode('blendTwoAttr',
                                 name='upr_Choice_blendTwoNode',
                                 skipSelect=True)
    uprSDKCurve = mc.listConnections((ikJoints[1] + '.tx'), source=True)
    mc.connectAttr((uprSDKCurve[0] + '.output'), (uprBlendNode + '.input[0]'),
                   force=True)
    mc.connectAttr((uprLengthMeassureObj[0] + 'Shape.distance'),
                   (uprBlendNode + '.input[1]'),
                   force=True)

    mc.connectAttr((uprBlendNode + '.output'), (ikJoints[1] + '.tx'),
                   force=True)
    """lwr"""
    lwrBlendNode = mc.createNode('blendTwoAttr',
                                 name='lwr_Choice_blendTwoNode',
                                 skipSelect=True)
    lwrSDKCurve = mc.listConnections((ikJoints[2] + '.tx'), source=True)
    mc.connectAttr((lwrSDKCurve[0] + '.output'), (lwrBlendNode + '.input[0]'),
                   force=True)
    mc.connectAttr((lwrLengthMeassureObj[0] + 'Shape.distance'),
                   (lwrBlendNode + '.input[1]'),
                   force=True)

    mc.connectAttr((lwrBlendNode + '.output'), (ikJoints[2] + '.tx'),
                   force=True)
    """adds stetch attrs"""
    mc.addAttr(elbowIKLoc, ln='pin', at='float', minValue=0, defaultValue=1)
    mc.setAttr((elbowIKLoc + '.pin'), keyable=True)

    mc.connectAttr((elbowIKLoc + '.pin'),
                   (uprBlendNode + '.attributesBlender'))
    mc.connectAttr((elbowIKLoc + '.pin'),
                   (lwrBlendNode + '.attributesBlender'))
    mc.setAttr((elbowIKLoc + '.pin'), 0)

    mc.parent(elbowMeasureLoc, elbowIKLoc)
    """ >>> FK lower limb control setup """
    """ creates our pinned lower limb fk joint """
    pinnedLwrLimcgmuffer = mc.duplicate(ikJoints[1], renameChildren=True)

    nonJointStuff = search.returnNonJointObjsInHeirarchy(pinnedLwrLimcgmuffer)
    for item in nonJointStuff:
        mc.delete(item)
    """ name the joint we'll be using """
    pinnedLwrLimb = mc.rename(pinnedLwrLimcgmuffer[0],
                              (coreNamesList[1] + '_pinned_fk_anim'))
    mc.parent(pinnedLwrLimb, elbowIKLoc)
    pinnedLwrLimbEndBuffer = mc.listRelatives(pinnedLwrLimb, children=True)
    mc.rename(pinnedLwrLimbEndBuffer[0], (coreNamesList[1] + '_pinned_fk_end'))
    """ make the hand anim loc """
    mc.parent(hand_animPinned, elbowIKLoc)
    ptConstBuffer = mc.pointConstraint([hand_animReg, hand_animPinned],
                                       handIKLoc,
                                       mo=False,
                                       weight=1)
    """ make the attr to drive it """
    mc.addAttr(elbowIKLoc, ln='forearm', at='enum', en='fk:ik:')
    mc.setAttr((elbowIKLoc + '.forearm'), keyable=True)
    mc.setAttr((elbowIKLoc + '.forearm'), 1)
    """ connect it """
    mc.connectAttr((elbowIKLoc + '.forearm'),
                   (ptConstBuffer[0] + '.' + hand_animReg + 'W0'))
    revNodeBuffer = mc.createNode('reverse', name='hand_revNode')

    mc.connectAttr((elbowIKLoc + '.forearm'), (revNodeBuffer + '.inputX'))
    mc.connectAttr((revNodeBuffer + '.outputX'),
                   (ptConstBuffer[0] + '.' + hand_animPinned + 'W1'))
Beispiel #20
0
def build_rig(goInstance = None):
    class fncWrap(modUtils.rigStep):
	def __init__(self,goInstance = None):
	    super(fncWrap, self).__init__(goInstance)
	    self._str_funcName = 'build_rig(%s)'%self.d_kws['goInstance']._strShortName	
	    self.__dataBind__()
	    self.l_funcSteps = [{'step':'Build NOT BROKEN UP YET','call':self.build}]	
	    #=================================================================
	    
	def build(self):#================================================================================   	
		    
	    try:#>>>Get data
		orientation = self._go._jointOrientation or modules.returnSettingsData('jointOrientation')
		mi_moduleParent = False
		if self._go._mi_module.getMessage('moduleParent'):
		    mi_moduleParent = self._go._mi_module.moduleParent
		    
		mi_controlIK = self._go._i_rigNull.controlIK
		ml_controlsFK =  self._go._i_rigNull.msgList_get('controlsFK')    
		ml_rigJoints = self._go._i_rigNull.msgList_get('rigJoints')
		ml_blendJoints = self._go._i_rigNull.msgList_get('blendJoints')
		mi_settings = self._go._i_rigNull.settings
		
		log.info("mi_controlIK: %s"%mi_controlIK.getShortName())
		log.info("ml_controlsFK: %s"%[o.getShortName() for o in ml_controlsFK])
		log.info("mi_settings: %s"%mi_settings.getShortName())
		
		log.info("ml_rigJoints: %s"%[o.getShortName() for o in ml_rigJoints])
		log.info("ml_blendJoints: %s"%[o.getShortName() for o in ml_blendJoints])
		
		ml_segmentHandleChains = self._go._get_segmentHandleChains()
		ml_segmentChains = self._go._get_segmentChains()
		ml_influenceChains = self._go._get_influenceChains()	
		
		aimVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[0])
		upVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[1]) 
		
		#Build our contrain to pool
		l_constrainTargetJoints = []
		"""
		for ml_chain in ml_segmentChains:
		    l_constrainTargetJoints.extend([i_jnt.mNode for i_jnt in ml_chain[:-1]])
		l_constrainTargetJoints.extend([i_jnt.mNode for i_jnt in ml_blendJoints[-2:]])
		"""
		if not l_constrainTargetJoints:
		    l_constrainTargetJoints = [i_jnt.mNode for i_jnt in ml_blendJoints]
		    
		for i_jnt in ml_blendJoints:
		    attributes.doSetLockHideKeyableAttr(i_jnt.mNode,lock=True, visible=True, keyable=False)
		    i_jnt.radius = 0#This is how we can hide joints without hiding them since we have children we want to ride along
		    i_jnt.drawStyle = 2
		    
		for i_jnt in ml_controlsFK:
		    i_jnt.radius = 0#This is how we can hide joints without hiding them since we have children we want to ride along
		    i_jnt.drawStyle = 2		    
		    
		#Set group lockks
		for mCtrl in self._go._i_rigNull.msgList_get('controlsAll'):
		    try:mCtrl._setControlGroupLocks()	
		    except Exception,error:log.error("%s _setControlGroupLocks failed on object: %s"%(self._str_reportStart,mCtrl.p_nameShort))
	    	    
	    except Exception,error:
		log.error("finger.build_rig>> Gather data fail!")
		raise Exception,error
	    

	    #Dynamic parent groups
	    #====================================================================================
	    try:#>>>> IK
		ml_fingerDynParents = []
		#Build our dynamic groups
		"""
		1)wrist
		2)fk root
		3)...
		4)world
		"""
		if mi_moduleParent:
		    mi_blendEndJoint = mi_moduleParent.rigNull.msgList_get('blendJoints')[-1]	    
		    mi_parentRigNull = mi_moduleParent.rigNull
		    if mi_moduleParent:
			mi_parentRigNull = mi_moduleParent.rigNull
			buffer = mi_parentRigNull.msgList_get('moduleJoints')
			if buffer:
			    ml_fingerDynParents.append( buffer[-1])	
			
		ml_fingerDynParents.append( ml_controlsFK[0])	
			
		mi_spine = self._go._mi_module.modulePuppet.getModuleFromDict(moduleType= ['torso','spine'])
		if mi_spine:
		    log.info("spine found: %s"%mi_spine)	    
		    mi_spineRigNull = mi_spine.rigNull
		    ml_fingerDynParents.append( mi_spineRigNull.handleIK )	    
		    ml_fingerDynParents.append( mi_spineRigNull.cog )
		    ml_fingerDynParents.append( mi_spineRigNull.hips )	    
		    
		ml_fingerDynParents.append(self._go._i_masterControl)
		if mi_controlIK.getMessage('spacePivots'):
		    ml_fingerDynParents.extend(mi_controlIK.msgList_get('spacePivots',asMeta = True))	
		log.info("%s.build_rig>>> Dynamic parents to add: %s"%(self._go._strShortName,[i_obj.getShortName() for i_obj in ml_fingerDynParents]))
		
	    
		#Add our parents
		i_dynGroup = mi_controlIK.dynParentGroup
		log.info("Dyn group at setup: %s"%i_dynGroup)
		i_dynGroup.dynMode = 0
		
		for o in ml_fingerDynParents:
		    i_dynGroup.addDynParent(o)
		i_dynGroup.rebuild()
		
	    except Exception,error:
		log.error("finger.build_rig>> finger ik dynamic parent setup fail!")
		raise Exception,error
	    
            self._go.collect_worldDynDrivers()#...collect world dyn drivers
	
	    #Make some connections
	    #====================================================================================
	    
	    #Parent and constrain joints
	    #====================================================================================
	    ml_rigJoints[0].parent = self._go._i_deformNull.mNode#shoulder
	    #ml_rigJoints[-1].parent = self._go._i_deformNull.mNode#wrist
	
	    #For each of our rig joints, find the closest constraint target joint
	    log.info("targetJoints: %s"%l_constrainTargetJoints)
	    l_rigJoints = [i_jnt.mNode for i_jnt in ml_rigJoints]
	    for i,i_jnt in enumerate(ml_rigJoints):
		#Don't try scale constraints in here, they're not viable
		log.info("Checking: '%s'"%i_jnt.getShortName())
		attachJoint = distance.returnClosestObject(i_jnt.mNode,l_constrainTargetJoints)
		log.info("'%s'<< drives <<'%s'"%(i_jnt.getShortName(),cgmMeta.cgmNode(attachJoint).getShortName()))
		pntConstBuffer = mc.pointConstraint(attachJoint,i_jnt.mNode,maintainOffset=False,weight=1)
		orConstBuffer = mc.orientConstraint(attachJoint,i_jnt.mNode,maintainOffset=False,weight=1)
		mc.connectAttr((attachJoint+'.s'),(i_jnt.mNode+'.s'))
	     
	    #Setup finger scaling
	    #==================================================================================== 
	    #Parent deform Null to last blend parent
	    if mi_moduleParent:
		mi_blendEndJoint = mi_moduleParent.rigNull.msgList_get('blendJoints')[-1]
		mi_parentBlendPlug = cgmMeta.cgmAttr(mi_blendEndJoint,'scale')
		self._go._i_deformNull.parent = mi_blendEndJoint.mNode
	    
		#connect blend joint scale to the finger blend joints
		for i_jnt in ml_blendJoints:
		    mi_parentBlendPlug.doConnectOut("%s.scale"%i_jnt.mNode)
		    
		#intercept world scale on finger IK and add in the blend wrist scale
		mPlug_moduleMasterScale = cgmMeta.cgmAttr(self._go._i_rigNull,'masterScale',value = 1.0,defaultValue=1.0)
		mPlug_globalScale = cgmMeta.cgmAttr(self._go._i_masterControl.mNode,'scaleY')
		mPlug_globalScale.doConnectOut(mPlug_moduleMasterScale)
		NodeF.argsToNodes("%s = %s * %s.sy"%(mPlug_moduleMasterScale.p_combinedShortName,
			                             mPlug_globalScale.p_combinedShortName,
			                             mi_blendEndJoint.p_nameShort)).doBuild()
	    
	    try:#Vis Network, lock and hide
		#====================================================================================
		#Segment handles need to lock
		for ml_chain in ml_segmentHandleChains:
		    for i_obj in ml_chain:
			attributes.doSetLockHideKeyableAttr(i_obj.mNode,lock=True,
			                                    visible=False, keyable=False,
			                                    channels=['s%s'%orientation[1],
			                                              's%s'%orientation[2]])
			
		attributes.doSetLockHideKeyableAttr(mi_settings.mNode,lock=True,
		                                    visible=False, keyable=False)
		attributes.doSetLockHideKeyableAttr(ml_blendJoints[0].mNode,lock=True,
		                                    visible=True, keyable=False)
		
		for i,mCtrl in enumerate(ml_controlsFK):
		    l_attrs = ['sx','sy','sz','v']
		    if i != 0:
			l_attrs.extend(['tx','ty','tz'])
			
		    attributes.doSetLockHideKeyableAttr(mCtrl.mNode,channels=l_attrs,
		                                        lock=True, visible=False, keyable=False)
		    

		
		attributes.doSetLockHideKeyableAttr(mi_controlIK.mNode,channels=['sx','sy','sz','v'],
	                                            lock=True, visible=False, keyable=False)	    
	    except Exception,error:
		raise Exception,"Lock and hide fail! | {0}".format(error)	 
def rigMasterCardCharaterOLD():
    spineChain = []
    jointChains = []

    def skinIt():
        #Skin it
        geoGroupObjects = search.returnAllChildrenObjects('geo_grp', True)
        #Get our group objects

        jointChains = getSkinJointChains()

        for i, g in enumerate([
                u'torso_geoGrp', u'armLeft_geoGrp', u'armRight_geoGrp',
                u'legLeft_geoGrp', u'legRight_geoGrp'
        ]):
            geoGroupObjects = search.returnAllChildrenObjects(g, True)

            toSkin = []
            for o in geoGroupObjects:
                if search.returnObjectType(o) in ['mesh', 'nurbsSurface']:
                    toSkin.append(o)

            if toSkin:
                for o in toSkin:
                    toBind = jointChains[i] + [o]
                    mc.skinCluster(toBind,
                                   tsb=True,
                                   normalizeWeights=True,
                                   mi=4,
                                   dr=10,
                                   polySmoothness=3)
            else:
                print("'%s' has nothing to skin!" % g)

    def orientSkeletonTemplate():
        #First unparent the parts so we can orient properly
        hip = rigging.doParentToWorld('hip_l')
        heel = rigging.doParentToWorld('heel_l')
        clav = rigging.doParentToWorld('clavicle_l')
        palm = rigging.doParentToWorld('palm_l')

        spineChain = ['root']
        spineChain.extend(search.returnChildrenJoints('root'))
        for j in spineChain:
            joints.orientJoint(j, 'xzy', 'zup')

        hipChain = [hip]
        hipChain.extend(search.returnChildrenJoints(hip))
        for j in hipChain:
            joints.orientJoint(j, 'xzy', 'zup')

        armChain = [clav]
        armChain.extend(search.returnChildrenJoints(clav))
        for j in armChain:
            joints.orientJoint(j, 'xyz', 'yup')

        footChain = [heel]
        footChain.extend(search.returnChildrenJoints(heel))
        for j in footChain:
            joints.orientJoint(j, 'yzx', 'yup')

        handChain = [palm]
        handChain.extend(search.returnChildrenJoints(palm))
        for j in handChain:
            joints.orientJoint(j, 'xzy', 'zup')

        #Fix the thumb
        thumbChain = ['thumb1_l']
        thumbChain.extend(search.returnChildrenJoints('thumb1_l'))
        for j in thumbChain:
            #tweak - taken from Comet's orient
            mc.xform(j, r=True, os=True, ra=(-20, 0, 0))
            mc.joint(j, e=True, zso=True)
            mc.makeIdentity(j, apply=True)

        #Fix the Head
        headChain = ['head1']
        headChain.extend(search.returnChildrenJoints('head1'))
        for j in headChain:
            joints.orientJoint(j, 'yzx', 'zup')

        #Reconnect
        rigging.doParentReturnName(hip, 'root')
        rigging.doParentReturnName(clav, 'spine5')
        rigging.doParentReturnName(heel, 'ankle_l')
        rigging.doParentReturnName(palm, 'wrist_l')

        return spineChain

    def getSkinJointChains():
        leftArmChain = ['clavicle_l']
        leftArmChain.extend(search.returnChildrenJoints('clavicle_l'))

        rightArmChain = ['clavicle_r']
        rightArmChain.extend(search.returnChildrenJoints('clavicle_r'))

        leftLegChain = ['hip_l']
        leftLegChain.extend(search.returnChildrenJoints('hip_l'))

        rightLegChain = ['hip_r']
        rightLegChain.extend(search.returnChildrenJoints('hip_r'))

        torsoChain.extend(['clavicle_l', 'clavicle_r'])

        returnList = [
            torsoChain, leftArmChain, rightArmChain, leftLegChain,
            rightLegChain
        ]
        return returnList

    torsoChain = orientSkeletonTemplate()

    #Get ready for JTD stuff
    mel.eval('source JTDriggingUI;')
    mel.eval('source JTDarmRig;')
    mel.eval('source JTDspineRig;')
    mel.eval('source JTDneckRig;')
    mel.eval('source JTDdynParent;')
    mel.eval('source JTDfingerRig;')

    mel.eval(
        'mirrorJoint -mirrorYZ -mirrorBehavior -searchReplace "_l" "_r" "hip_l";'
    )
    mel.eval(
        'mirrorJoint -mirrorYZ -mirrorBehavior -searchReplace "_l" "_r" "clavicle_l";'
    )

    mel.eval('JTDspineRig("%s", "spine1", "spine5", "root", %f, "%s", "");' %
             (baseName, spineScale, world))

    mel.eval('JTDneckRig("%s", "neck1", "head1", %f, "%s", "%s");' %
             (baseName, spineScale, world, connect))

    mel.eval(
        'JTDarmRig("%s","clavicle_l","shoulder_l","elbow_l","wrist_l", 3, 1, %f, "%s", "%s");'
        % (baseName, armScale, world, connect))
    mel.eval(
        'JTDarmRig("%s","clavicle_r","shoulder_r","elbow_r","wrist_r", 3, 2, %f, "%s", "%s");'
        % (baseName, armScale, world, connect))

    mel.eval(
        'JTDlegRig("%s","hip_l","knee_l","ankle_l","heel_l","ball_l", 3, 1, %f, "%s", "%s", 2);'
        % (baseName, legScale, world, connect))
    mel.eval(
        'JTDlegRig("%s","hip_r","knee_r","ankle_r","heel_r","ball_r", 3, 2, %f, "%s", "%s", 2);'
        % (baseName, legScale, world, connect))

    #Fingers Left
    mel.eval(
        'JTDfingerRig("wrist_l","","index1_l","index2_l","index3_l", 1, 1, 1, 0, 1, "%s", %f);'
        % (baseName, fingerScale))
    mel.eval(
        'JTDfingerRig("wrist_l","","fingers1_l","fingers2_l","fingers3_l", 1, 1, 4, 0, 1, "%s", %f);'
        % (baseName, fingerScale))

    mel.eval(
        'JTDfingerRig("wrist_l","","thumb1_l","thumb2_l","thumb3_l", 1, 1, 0, 1, 1, "%s", %f);'
        % (baseName, fingerScale))

    #Fingers Right
    mel.eval(
        'JTDfingerRig("wrist_r","","index1_r","index2_r","index3_r", 1, 1, 1, 0, 2, "%s", %f);'
        % (baseName, fingerScale))
    mel.eval(
        'JTDfingerRig("wrist_r","","fingers1_r","fingers2_r","fingers3_r", 1, 1, 4, 0, 2, "%s", %f);'
        % (baseName, fingerScale))

    mel.eval(
        'JTDfingerRig("wrist_r","","thumb1_r","thumb2_r","thumb3_r", 1, 1, 0, 1, 2, "%s", %f);'
        % (baseName, fingerScale))

    #new stuff
    #Head scale
    attributes.doSetLockHideKeyableAttr('cubey_neck_IK_Cntrl',
                                        lock=False,
                                        visible=True,
                                        keyable=True,
                                        channels=['sx', 'sy', 'sz'])
    mc.setAttr('cubey_neck_IK_Cntrl.sx', keyable=True)
    mc.setAttr('cubey_neck_IK_Cntrl.sy', keyable=True)
    mc.setAttr('cubey_neck_IK_Cntrl.sz', keyable=True)

    mc.scaleConstraint('cubey_neck_IK_Cntrl', 'head1')

    #Sets and Coloring
    leftArmSetObjects = [
        u'rig_clavicle_l_IK_Cntrl', u'rig_shoulder_l_twist',
        u'rig_shoulder_l_Bendy', u'rig_elbow_l_Bendy',
        u'rig_clavicle_l_FK_Cntrl', u'cubey_finger_Cntrl0_l',
        u'rig_wrist_l_FK', u'rig_wrist_l_SW', u'rig_shoulder_l_FK',
        u'rig_elbow_l_FK', u'cubey_arm_IK_Cntrl_l',
        u'rig_wrist_l_GimbleCntrl_l', u'cubey_arm_PV_Cntrl_l'
    ]  #
    rightArmSetObjects = [
        u'rig_clavicle_r_IK_Cntrl', u'rig_shoulder_r_twist',
        u'rig_shoulder_r_Bendy', u'rig_elbow_r_Bendy',
        u'rig_clavicle_r_FK_Cntrl', u'cubey_finger_Cntrl0_r',
        u'rig_wrist_r_FK', u'rig_wrist_r_SW', u'rig_shoulder_r_FK',
        u'rig_elbow_r_FK', u'cubey_arm_IK_Cntrl_r',
        u'rig_wrist_r_GimbleCntrl_r', u'cubey_arm_PV_Cntrl_r'
    ]  #

    centerSetObjects = [
        u'rig_spine1_Shoulders', u'rig_spine1_Hips', u'cubey_spine_Root',
        u'rig_spine1FK3', u'rig_spine1FK2', u'rig_spine1FK1',
        u'cubey_neck_FK_Cntrl', u'cubey_neck_IK_Cntrl'
    ]

    leftLegSetObjects = [
        u'rig_ball_l_FK', u'rig_ankle_l_SW', u'rig_hip_l_Bendy',
        u'rig_knee_l_FK', u'rig_ankle_l_FK', u'rig_hip_l_FK',
        u'rig_knee_l_Bendy', u'rig_hip_l_twist', u'cubey_leg_GimbleCntrl_l',
        u'cubey_leg_IKleg_Cntrl_l', u'cubey_leg_PV_Cntrl_l'
    ]
    rightLegSetObjects = [
        u'rig_ball_r_FK', u'rig_ankle_r_SW', u'rig_hip_r_Bendy',
        u'rig_knee_r_FK', u'rig_ankle_r_FK', u'rig_hip_r_FK',
        u'rig_knee_r_Bendy', u'rig_hip_r_twist', u'cubey_leg_GimbleCntrl_r',
        u'cubey_leg_IKleg_Cntrl_r', u'cubey_leg_PV_Cntrl_r'
    ]

    lArmSet = SetFactory.SetFactory('armLeft', 'animation', True)
    for o in leftArmSetObjects:
        lArmSet.store(o)
        #color
        curves.setCurveColorByName(o, 'blueBright')

    rArmSet = SetFactory.SetFactory('armRight', 'animation', True)
    for o in rightArmSetObjects:
        rArmSet.store(o)
        #color
        curves.setCurveColorByName(o, 'redBright')

    torsoSet = SetFactory.SetFactory('torso', 'animation', True)
    for o in centerSetObjects:
        torsoSet.store(o)
        curves.setCurveColorByName(o, 'yellow')

    lLegSet = SetFactory.SetFactory('legLeft', 'animation', True)
    for o in leftLegSetObjects:
        lLegSet.store(o)
        curves.setCurveColorByName(o, 'blueBright')

    rLegSet = SetFactory.SetFactory('legRight', 'animation', True)
    for o in rightLegSetObjects:
        rLegSet.store(o)
        curves.setCurveColorByName(o, 'redBright')

    bindJoints = search.returnAllChildrenObjects('root')
    bindJoints.append('root')
    skinJointsSet = SetFactory.SetFactory('skinJoints', 'td', True)
    for o in bindJoints:
        if mc.ls(o, type='joint'):
            skinJointsSet.store(o)

    #Set of all sets
    allSet = SetFactory.SetFactory('all', 'animation', True)
    allSet.store(rLegSet.nameLong)
    allSet.store(lLegSet.nameLong)
    allSet.store(torsoSet.nameLong)
    allSet.store(lArmSet.nameLong)
    allSet.store(rArmSet.nameLong)

    #Skin!
    skinIt()
Beispiel #22
0
    def doTemplate(self,PuppetInstance):       
        """
        
        """
        def makeLimbTemplate (self):
            #>>>Curve degree finder
            if self.optionCurveDegree.get() == 0:
                doCurveDegree = 1
            else:
                if len(corePositionList) <= 3:
                    doCurveDegree = 1
                else:
                    doCurveDegree = len(corePositionList) - 1
                    
            #Make some storage vehicles
            self.templatePosObjectsBuffer = BufferFactory(self.infoNulls['templatePosObjects'].get())
            self.templatePosObjectsBuffer.purge()
            
            LocatorCatcher = ObjectFactory('')
            LocatorBuffer = BufferFactory(LocatorCatcher.nameLong)
            LocatorBuffer.purge()
            
            returnList = []
            self.templHandleList = []
            
            moduleColors = modules.returnModuleColors(self.ModuleNull.nameShort)
            
            #>>>Scale stuff
            moduleParent = self.msgModuleParent.get()
            
            if not moduleParent:
                length = (distance.returnDistanceBetweenPoints (corePositionList[0],corePositionList[-1]))
                size = length / self.optionHandles.get()
            else:
                #>>>>>>>>>>>>>>>>>>>>> NOT TOUCHED YET
                parentTemplatePosObjectsInfoNull = modules.returnInfoTypeNull(moduleParent,'templatePosObjects')
                parentTemplatePosObjectsInfoData = attributes.returnUserAttrsToDict (parentTemplatePosObjectsInfoNull)
                parentTemplateObjects = []
                for key in parentTemplatePosObjectsInfoData.keys():
                    if (mc.attributeQuery (key,node=parentTemplatePosObjectsInfoNull,msg=True)) == True:
                        if search.returnTagInfo((parentTemplatePosObjectsInfoData[key]),'cgmType') != 'templateCurve':
                            parentTemplateObjects.append (parentTemplatePosObjectsInfoData[key])
                createBuffer = curves.createControlCurve('sphere',1)
                pos = corePositionList[0]
                mc.move (pos[0], pos[1], pos[2], createBuffer, a=True)
                closestParentObject = distance.returnClosestObject(createBuffer,parentTemplateObjects)
                boundingBoxSize = distance.returnBoundingBoxSize (closestParentObject)
                maxSize = max(boundingBoxSize)
                size = maxSize *.25
                mc.delete(createBuffer)
                if partType == 'clavicle':
                    size = size * .5
                elif partType == 'head':
                    size = size * .75
                if (search.returnTagInfo(moduleParent,'cgmModuleType')) == 'clavicle':
                    size = size * 2
        
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            # Making the template objects
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            self.TemplateObject = {}
            
            #>>> Template objects
            for cnt,pos in enumerate(corePositionList):
                #Size multiplier based on PuppetMode, make it take into account module mode eventually
                if PuppetInstance.optionPuppetMode.get() == 0:
                    if cnt == 0:
                        sizeMultiplier = 1
                    elif cnt == len(corePositionList) -1:
                        sizeMultiplier = .8
                    else:
                        sizeMultiplier = .5
                else:
                    sizeMultiplier = 1
                    
                #make a sphere and move it
                createBuffer = curves.createControlCurve('sphere',(size * sizeMultiplier))
                self.TemplateObject[cnt] = ObjectFactory(createBuffer) # Instance the control to our module
                obj = self.TemplateObject[cnt]
                curves.setCurveColorByName(obj.nameLong,moduleColors[0])
                obj.store('cgmName',coreNames[cnt])
                
                obj.getNameTagsFromObject(self.ModuleNull.nameLong,['cgmName','cgmType'])

                obj.store('cgmType','templateObject')
                obj.doName()
                mc.move (pos[0], pos[1], pos[2], [obj.nameLong], a=True)
                            
                #adds it to the list
                self.templHandleList.append (obj.nameLong) 
                self.templatePosObjectsBuffer.store(obj.nameLong)
            
             
            #Aim the objects           
            position.aimObjects(self.templHandleList,
                                dictionary.axisDirectionsByString[ self.optionAimAxis.get() ],
                                dictionary.axisDirectionsByString[ self.optionUpAxis.get() ],
                                dictionary.axisDirectionsByString[ PuppetInstance.optionUpAxis.get() ])            
            
            #>>> Template curve
            crvName = mc.curve (d=doCurveDegree, p = corePositionList , os=True, n=('%s_%s' %(partName,(typesDictionary.get('templateCurve')))))            
            self.afTemplateCurve = AttrFactory(self.infoNulls['templatePosObjects'].get(),
                                               'curve','message', value=crvName)# connect it back to our template objects info null
            
            curve = ObjectFactory(crvName) # instance it
            curve.getNameTagsFromObject(self.ModuleNull.nameLong,['cgmType']) #get name tags from the module

            attributes.storeInfo(crvName,'cgmType','templateCurve') # store type
            curves.setCurveColorByName(crvName,moduleColors[1]) # set curve color
            
            # Make locators to connect the cv's to
            for cnt,obj in enumerate(self.templHandleList):
                pointLoc = locators.locMeObject(obj) # make the loc
                loc = ObjectFactory(pointLoc) #instance it
                mc.setAttr ((loc.nameShort+'.visibility'),0) # turn off visibility
                mc.parentConstraint ([obj],[loc.nameShort],mo=False) # parent constrain
                mc.connectAttr ( (loc.nameShort+'.translate'),
                                 ('%s.controlPoints[%i]' % (crvName, cnt)), f=True ) # connect the cv to the loc
                self.TemplateObject[cnt].store('loc',loc.nameLong)
                LocatorBuffer.store(loc.nameLong)
                
            #>>> Direction and size Stuff
            """
            # Directional data derived from joints 
            generalDirection = logic.returnHorizontalOrVertical(self.templHandleList)
            if generalDirection == 'vertical' and 'leg' not in self.afModuleType.get():
                worldUpVector = [0,0,-1]
            elif generalDirection == 'vertical' and 'leg' in self.afModuleType.get():
                worldUpVector = [0,0,1]
            else:
                worldUpVector = [0,1,0]
            """            
            
            # Create root control
            templateNull = self.msgTemplateNull.get()
            handleList = copy.copy(self.templatePosObjectsBuffer.bufferList)
            
            rootSize = (distance.returnBoundingBoxSizeToAverage(self.templHandleList[0])*1.5)
            rootCtrl = ObjectFactory(curves.createControlCurve('cube',rootSize))
            rootCtrl.getNameTagsFromObject(self.ModuleNull.nameLong)
            self.msgTemplateRoot = AttrFactory(self.infoNulls['templatePosObjects'].get(), 'root', 'message', value = rootCtrl.nameLong)
            curves.setCurveColorByName(rootCtrl.nameLong,moduleColors[0])
            
            # move the root
            if self.afModuleType.get() == 'clavicle':
                position.movePointSnap(rootCtrl.nameLong,self.templHandleList[0])
            else:
                position.movePointSnap(rootCtrl.nameLong,self.templHandleList[0])
            # aim the root
            position.aimSnap(rootCtrl.nameShort,self.templHandleList[-1],  
                            dictionary.axisDirectionsByString[ self.optionAimAxis.get() ],
                            dictionary.axisDirectionsByString[ self.optionUpAxis.get() ],
                            dictionary.axisDirectionsByString[ PuppetInstance.optionUpAxis.get() ]) 
            
            rootCtrl.store('cgmType','templateRoot')
            rootCtrl.doName()
            
            #>>> Parent the main objcts
            rootGroup = rootCtrl.doGroup()
            rootGroup = rigging.doParentReturnName(rootGroup,templateNull)
            curve.doParent(templateNull)
            
            for obj in LocatorBuffer.bufferList:
                rigging.doParentReturnName(obj,templateNull)
            mc.delete(LocatorCatcher.nameShort) # delete the locator buffer obj
            
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            #>> Orientation helpers
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
            # Make our Orientation Helpers 
            """
            orientHelpersReturn = template.addOrientationHelpers(self)
            masterOrient = orientHelpersReturn[0]
            orientObjects = orientHelpersReturn[1]
            return
            
        
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            #>> Control helpers
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
            print orientObjects
            print self.ModuleNull.nameShort
            print (templateNull+'.visControlHelpers')
            controlHelpersReturn = addControlHelpers(orientObjects,self.ModuleNull.nameShort,(templateNull+'.visControlHelpers'))"""
    
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            #>> Input the saved values if there are any
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
            # Orientation Helpers 
            """rotBuffer = coreRotationList[-1]
            #actualName = mc.spaceLocator (n= wantedName)
            rotCheck = sum(rotBuffer)
            if rotCheck != 0:
                mc.rotate(rotBuffer[0],rotBuffer[1],rotBuffer[2],masterOrient,os=True)
            
            cnt = 0
            for obj in orientObjects:
                rotBuffer = coreRotationList[cnt]
                rotCheck = sum(rotBuffer)
                if rotCheck != 0:
                    mc.rotate(rotBuffer[0],rotBuffer[1],rotBuffer[2],obj,os=True)
                cnt +=1 
                    
            # Control Helpers 
            controlHelpers = controlHelpersReturn[0]
            cnt = 0
            for obj in controlHelpers:
                posBuffer = controlPositionList[cnt]
                posCheck = sum(posBuffer)
                if posCheck != 0:
                    mc.xform(obj,t=[posBuffer[0],posBuffer[1],posBuffer[2]],ws=True)
                
                rotBuffer = controlRotationList[cnt]
                rotCheck = sum(rotBuffer)
                if rotCheck != 0:
                    mc.rotate(rotBuffer[0],rotBuffer[1],rotBuffer[2],obj,ws=True)
                
                scaleBuffer = controlScaleList[cnt]
                scaleCheck = sum(scaleBuffer)
                if scaleCheck != 0:
                    mc.scale(scaleBuffer[0],scaleBuffer[1],scaleBuffer[2],obj,absolute=True)
                cnt +=1 """
            
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            #>> Final stuff
            #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
            """
            returnList.append(templObjNameList)
            returnList.append(self.templHandleList)
            returnList.append(rootCtrl)"""
            return True	



        # Start objects stuff 
        partName = NameFactory.returnRawGeneratedName(self.ModuleNull.nameShort,ignore=['cgmType','cgmTypeModifier'])
        templateStarterDataInfoNull = self.infoNulls['templateStarterData'].value
        initialObjectsPosData = mc.listAttr(templateStarterDataInfoNull,userDefined=True)
        corePositionList = []
        coreRotationList = []
        corePositionDict = {}
        coreRotationDict = {}        
        for a in initialObjectsPosData:
            buffer = attributes.doGetAttr(templateStarterDataInfoNull,a)                            
            if 'cgm' not in a and type(buffer) is list:
                if 'pos' in a:
                    split = a.split('pos_')
                    corePositionDict[int(split[1])] =  buffer[0]
                    corePositionList.append(buffer[0])
                elif 'rot' in a:
                    split = a.split('rot_')
                    coreRotationDict[int(split[1])] =  buffer[0] 
                    coreRotationList.append(buffer[0])
   
        print corePositionList
        print coreRotationList
        
        # template control objects stuff #
        templateControlObjectsDataNull = self.infoNulls['templateControlObjects'].value
        templateControlObjectsData = mc.listAttr(templateControlObjectsDataNull,userDefined=True)
        controlPositionList = []
        controlRotationList = []
        controlScaleList = []
        controlPositionDict = {}
        controlRotationDict = {}
        controlScaleDict = {}
        
        for a in templateControlObjectsData:
            buffer = attributes.doGetAttr(templateControlObjectsDataNull,a)                            
            if 'cgm' not in a and type(buffer) is list:
                if 'pos' in a:
                    split = a.split('pos_')
                    controlPositionDict[int(split[1])] =  buffer[0] 
                    controlPositionList.append(buffer[0])                    
                elif 'rot' in a:
                    split = a.split('rot_')
                    controlRotationDict[int(split[1])] =  buffer[0] 
                    controlRotationList.append(buffer[0])
                elif 'scale' in a:
                    split = a.split('scale_')
                    controlScaleDict[int(split[1])] =  buffer[0]   
                    controlScaleList.append(buffer[0])
                    
                  
        print controlPositionList
        print controlRotationList
        print controlScaleList
        
        # Names Info #
        coreNamesInfoNull = self.infoNulls['coreNames'].value
        coreNamesBuffer = mc.listAttr(coreNamesInfoNull,userDefined=True)
        coreNames = {}
        for a in coreNamesBuffer:
            if 'cgm' not in a and 'name_' in a:
                split = a.split('name_')
                coreNames[int(split[1])] =  attributes.doGetAttr(coreNamesInfoNull,a) 
                
        print coreNames            
        print ('%s data aquired...'%self.ModuleNull.nameShort)
        
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        #>> make template objects
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
        #makes template objects#
        assert len(corePositionList) == self.optionHandles.get(),"There isn't enough data to template. Needs to be sized"
        
        templateObjects = makeLimbTemplate(self)
        guiFactory.report( 'Template Limb made....')
        
        
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        #>> Parent objects
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
        for cnt,obj in enumerate(self.templHandleList): 
            self.TemplateObject[cnt].doParent(self.msgTemplateNull.get())
    
        guiFactory.report('Template objects parented')
        
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        #>> Transform groups and Handles...handling
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        self.templatePosObjectsBuffer.updateData()
        root = self.msgTemplateRoot.get()
        handles = copy.copy( self.templatePosObjectsBuffer.bufferList )
        stiffIndex = self.optionStiffIndex.get()
        
        """ Don't remember why I did this stiff index thing....
        #>>> Break up the handles into the sets we need 
        if stiffIndex == 0:
            splitHandles = False
            handlesToSplit = handles
            handlesRemaining = [handles[0],handles[-1]]
        elif stiffIndex < 0:
            splitHandles = True
            handlesToSplit = handles[:stiffIndex]
            handlesRemaining = handles[stiffIndex:]
            handlesRemaining.append(handles[0])
        elif stiffIndex > 0:
            splitHandles = True
            handlesToSplit = handles[stiffIndex:]
            handlesRemaining = handles[:stiffIndex]
            handlesRemaining.append(handles[-1]) 
        if len(handlesToSplit)>2:"""
        
        # makes our mid transform groups#
        if len(handles)>2:
            constraintGroups = constraints.doLimbSegmentListParentConstraint(handles)
            print 'Constraint groups created...'
            for group in constraintGroups:
                mc.parent(group,root)
            
        # zero out the first and last#
        for handle in [handles[0],handles[-1]]:
            groupBuffer = (rigging.groupMeObject(handle,maintainParent=True))
            mc.parent(groupBuffer,root)
           
        #>>> Break up the handles into the sets we need 
        if stiffIndex < 0:
            for handle in handles[(stiffIndex+-1):-1]:
                groupBuffer = (rigging.groupMeObject(handle,maintainParent=True))
                mc.parent(groupBuffer,handles[-1])
        elif stiffIndex > 0:
            for handle in handles[1:(stiffIndex+1)]:
                groupBuffer = (rigging.groupMeObject(handle,maintainParent=True))
                mc.parent(groupBuffer,handles[0])
                
        print 'Constraint groups parented...'
        
        #>>> Lock off handles
        self.templatePosObjectsBuffer.updateData()
        for obj in self.templatePosObjectsBuffer.bufferList:
            attributes.doSetLockHideKeyableAttr(obj,True,False,False,['sx','sy','sz','v'])
            
        
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        # Parenting constraining parts
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        """ COME BACK AFTER DONE WITH SEGMENT
        if self.moduleParent:
            if self.afModuleType.get() == 'clavicle':
                self.moduleParent = attributes.returnMessageObject(self.moduleParent,'self.moduleParent')
            parentTemplatePosObjectsInfoNull = modules.returnInfoTypeNull(self.moduleParent,'templatePosObjects')
            parentTemplatePosObjectsInfoData = attributes.returnUserAttrsToDict (parentTemplatePosObjectsInfoNull)
            parentTemplateObjects = []
            for key in parentTemplatePosObjectsInfoData.keys():
                if (mc.attributeQuery (key,node=parentTemplatePosObjectsInfoNull,msg=True)) == True:
                    if search.returnTagInfo((parentTemplatePosObjectsInfoData[key]),'cgmType') != 'templateCurve':
                        parentTemplateObjects.append (parentTemplatePosObjectsInfoData[key])
            closestParentObject = distance.returnClosestObject(rootName,parentTemplateObjects)
            if (search.returnTagInfo(self.ModuleNull.nameShort,'cgmModuleType')) != 'foot':
                constraintGroup = rigging.groupMeObject(rootName,maintainParent=True)
                constraintGroup = NameFactory.doNameObject(constraintGroup)
                mc.pointConstraint(closestParentObject,constraintGroup, maintainOffset=True)
                mc.scaleConstraint(closestParentObject,constraintGroup, maintainOffset=True)
            else:
                constraintGroup = rigging.groupMeObject(closestParentObject,maintainParent=True)
                constraintGroup = NameFactory.doNameObject(constraintGroup)
                mc.parentConstraint(rootName,constraintGroup, maintainOffset=True)
                
        # grab the last clavicle piece if the arm has one and connect it to the arm  #
        if self.moduleParent:
            if (search.returnTagInfo(self.ModuleNull.nameShort,'cgmModuleType')) == 'arm':
                if (search.returnTagInfo(self.moduleParent,'cgmModuleType')) == 'clavicle':
                    print '>>>>>>>>>>>>>>>>>>>>> YOU FOUND ME'
                    parentTemplatePosObjectsInfoNull = modules.returnInfoTypeNull(self.moduleParent,'templatePosObjects')
                    parentTemplatePosObjectsInfoData = attributes.returnUserAttrsToDict (parentTemplatePosObjectsInfoNull)
                    parentTemplateObjects = []
                    for key in parentTemplatePosObjectsInfoData.keys():
                        if (mc.attributeQuery (key,node=parentTemplatePosObjectsInfoNull,msg=True)) == True:
                            if search.returnTagInfo((parentTemplatePosObjectsInfoData[key]),'cgmType') != 'templateCurve':
                                parentTemplateObjects.append (parentTemplatePosObjectsInfoData[key])
                    closestParentObject = distance.returnClosestObject(rootName,parentTemplateObjects)
                    endConstraintGroup = rigging.groupMeObject(closestParentObject,maintainParent=True)
                    endConstraintGroup = NameFactory.doNameObject(endConstraintGroup)
                    mc.pointConstraint(handles[0],endConstraintGroup, maintainOffset=True)
                    mc.scaleConstraint(handles[0],endConstraintGroup, maintainOffset=True)
        """    
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        #>> Final stuff
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
        
        #>>> Set our new module rig process state
        self.afTemplateState.set(1)
        print ('%s done!'%self.ModuleNull.nameShort)
        
        #>>> Tag our objects for easy deletion
        children = mc.listRelatives (self.msgTemplateNull.get(), allDescendents = True,type='transform')
        for obj in children:
            attributes.storeInfo(obj,'cgmOwnedBy',self.msgTemplateNull.get())
            
        #>>> Visibility Connection
        """
Beispiel #23
0
def bakeCombinedBlendShapeNode(sourceObject, blendShapeNode, baseNameToUse = False, directions=['left','right']):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for baking a series of blendshapes out from one object that have a split type

    ARGUMENTS:
    sourceObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseName(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    directions[list] = (['left','right'])

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []
    bakedGeo = []

    """ size """
    sizeBuffer = distance.returnBoundingBoxSize(sourceObject)
    sizeX = sizeBuffer[0]
    sizeY = sizeBuffer[1]

    """ base name """
    if baseNameToUse == False:
        baseName = ''
    else:
        baseName = baseNameToUse + '_'


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    blendShapeNodeChannels = search.returnBlendShapeAttributes(blendShapeNode)
    blendShapeShortNames = []

    """ first loop stores and sets everything to 0 """
    for shape in blendShapeNodeChannels:
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))
        """break it """
        attributes.doBreakConnection(blendShapeBuffer)
        attributes.doSetAttr(blendShapeBuffer,0)

    """ Find pairs """
    blendshapePairs = lists.returnMatchedStrippedEndList(blendShapeNodeChannels,directions)

    """ first loop stores and sets everything to 0 """
    for pair in blendshapePairs:
        blendShapeBuffer = (blendShapeNode+'.'+pair[0])
        splitBuffer = pair[0].split('_')
        nameBuffer = splitBuffer[:-1]
        pairBaseName = '_'.join(nameBuffer)

        if '_' in list(pairBaseName):
            newSplitBuffer = pair[0].split('_')
            newNameBuffer = newSplitBuffer[1:]
            blendShapeShortNames.append('_'.join(newNameBuffer))
        else:
            blendShapeShortNames.append(pairBaseName)

    t=1
    pair = 0
    for i in range (len(blendshapePairs)):
        row = i//5
        if t>5:
            t=1
        """ start extracting """
        blendShapeNodeChannelsBuffer = blendshapePairs[pair]
        shape1 = blendShapeNodeChannelsBuffer[0]
        shape2 = blendShapeNodeChannelsBuffer[1]
        blendShape1Buffer = (blendShapeNode+'.'+shape1)
        blendShape2Buffer = (blendShapeNode+'.'+shape2)
        attributes.doSetAttr(blendShape1Buffer,1)
        attributes.doSetAttr(blendShape2Buffer,1)
        dupBuffer = mc.duplicate(sourceObject)


        splitBuffer = blendShapeShortNames[pair].split('_')
        if len(splitBuffer)>1:
            nameBuffer = splitBuffer[:-1]
        else:
            nameBuffer = splitBuffer
        shortName = '_'.join(nameBuffer)

        dupBuffer = mc.rename (dupBuffer,(baseName+shortName))
        """ Unlock it """
        attributes.doSetLockHideKeyableAttr(dupBuffer,False,True,True)

        mc.xform(dupBuffer,r=True,t=[((sizeX*(t+1.2))*1.5),(sizeY*row*-1.5),0])
        bakedGeo.append(dupBuffer)

        attributes.doSetAttr(blendShape1Buffer,0)
        attributes.doSetAttr(blendShape2Buffer,0)
        pair +=1
        t+=1

    """ restore connections """
    for shape in blendShapeNodeChannels:
        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if blendShapeConnections[currentIndex] != False:
            attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ group for geo """
    meshGroup = mc.group( em=True)
    attributes.storeInfo(meshGroup,'cgmName', baseNameToUse)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    return returnList
Beispiel #24
0
def bakeBlendShapes(sourceObject, targetObject, blendShapeNode, baseNameToUse = False, stripPrefix = False, ignoreInbetweens = False, ignoreTargets = False):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for exporting an objects blendshapes

    ARGUMENTS:
    targetObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseName(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    stripPrefix(bool) - whether to strip the first '_' segment
    ignoreInbetweens(bool) - whether to include inbetween targets or not
    ignoreTargets(list) - targets you want ignored during processing

    RETURNS:
    bakedGeo(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    targetDict = returnBlendShapeTargetsAndWeights(sourceObject,blendShapeNode)

    """ size """
    sizeBuffer = distance.returnBoundingBoxSize(targetObject)
    sizeX = sizeBuffer[0]
    sizeY = sizeBuffer[1]

    #  base name
    if baseNameToUse == False:
        baseName = ''
    else:
        baseName = baseNameToUse + '_'

    t=1
    i=0
    bakedGeo = []
    for key in targetDict.keys():

        targetSetBuffer = targetDict.get(key)

        if ignoreInbetweens == False:
            targetSetProcessSet = targetSetBuffer
        else:
            targetSetProcessSet = targetSetBuffer[-1:]

        if len(targetSetProcessSet) > 1:
            isInbetween = True
            targetSetProcessSet.reverse()
        else:
            isInbetween = False

        cnt = 0
        for targetSet in targetSetProcessSet:
            row = i//5
            if t>5:
                t=1

            # Check for it being an ignore target
            nameBuffer = targetSet[0]
            keepGoing = True

            if ignoreTargets != False:
                if nameBuffer in ignoreTargets:
                    keepGoing = False
                else:
                    keepGoing = True

            if keepGoing:
                #process the name
                if '_' in list(nameBuffer) and stripPrefix == True:
                    splitBuffer = nameBuffer.split('_')
                    newNameBuffer = splitBuffer[1:]
                    newName = ('_'.join(newNameBuffer))
                else:
                    newName = nameBuffer

                #>>> Start extracting
                #set our values
                mc.blendShape(blendShapeNode, edit = True, weight = [key,targetSet[1]])
                dupBuffer = mc.duplicate(targetObject)
                dupBuffer = mc.rename (dupBuffer,(baseName+newName))

                # Take care of inbetween tagging
                if isInbetween == True:
                    if cnt == 0:
                        rootTarget = dupBuffer
                    else:
                        attributes.storeInfo(dupBuffer,'cgmBlendShapeTargetParent',rootTarget)
                        attributes.storeInfo(dupBuffer,'cgmBlendShapeInbetweenWeight',targetSet[1])

                # Unlock it
                attributes.doSetLockHideKeyableAttr(dupBuffer,False,True,True)
                mc.xform(dupBuffer,r=True,t=[((sizeX*(t+1.2))*1.5),(sizeY*row*-1.5),0])
                bakedGeo.append(dupBuffer)

                # Iterate
                i+=1
                t+=1
                cnt+=1

        if keepGoing == True:
            mc.blendShape(blendShapeNode, edit = True, weight = [key,0])

    return bakedGeo
Beispiel #25
0
        def _buildControls_(self):
            mi_go = self._go#Rig Go instance link

            try:#Query ====================================================================================
                ml_rigJoints = self.ml_rigJoints

                mi_fkShape = self.md_rigList['fk_shape']
                mi_ikShape = self.md_rigList['ik_shape']
                mi_settingsShape = self.md_rigList['settings_shape']
                mi_eyeMoveShape = self.md_rigList['eyeMove_shape']
                str_mirrorSide = self.str_mirrorSide
            except Exception,error:raise Exception,"[Query]{%s}"%error	


            try:#>>>> FK #==================================================================	
                mi_fkShape.parent = mi_go._i_constrainNull.controlsFKNull.mNode
                i_obj = mi_fkShape
                d_buffer = mControlFactory.registerControl(i_obj,copyTransform = ml_rigJoints[0],
                                                           mirrorSide = str_mirrorSide, mirrorAxis="rotateY,rotateZ",
                                                           makeAimable=True,setRotateOrder ='zxy',typeModifier='fk') 	    
                mi_controlFK = d_buffer['instance']
                mi_controlFK.axisAim = "%s+"%mi_go._jointOrientation[0]
                mi_controlFK.axisUp= "%s+"%mi_go._jointOrientation[1]	
                mi_controlFK.axisOut= "%s+"%mi_go._jointOrientation[2]

                #We're gonna lock the aim rot
                cgmMeta.cgmAttr(mi_controlFK,'r%s'%mi_go._jointOrientation[0], keyable = False, lock=True,hidden=True)
                mi_go._i_rigNull.connectChildNode(mi_controlFK,'controlFK',"rigNull")
                self.ml_controlsAll.append(mi_controlFK)	

                attributes.doSetLockHideKeyableAttr(mi_controlFK.mNode,channels=['tx','ty','tz','sx','sy','sz','v'])				

            except Exception,error:raise Exception,"[Build fk fail]{%s}"%(error)

            try:#>>>> IK 
                #==================================================================	
                mi_ikShape.parent = mi_go._i_constrainNull.controlsIKNull.mNode	
                d_buffer = mControlFactory.registerControl(mi_ikShape,
                                                           mirrorSide = str_mirrorSide, mirrorAxis="",		                                           
                                                           typeModifier='ik',addDynParentGroup=True) 	    
                mi_ikControl = d_buffer['instance']	

                mi_go._i_rigNull.connectChildNode(mi_ikControl,'controlIK',"rigNull")
                self.ml_controlsAll.append(mi_ikControl)
                attributes.doSetLockHideKeyableAttr(mi_ikControl.mNode,channels=['sx','sy','sz','v'])				

            except Exception,error:raise Exception,"[Build ik fail]{%s}"%(error)


            try:#>>>> Settings
                #==================================================================	
                mi_settingsShape.parent = mi_go._i_constrainNull.mNode

                try:#Register the control
                    d_buffer = mControlFactory.registerControl(mi_settingsShape,
                                                               mirrorSide = str_mirrorSide, mirrorAxis="",		                                           		                                               
                                                               makeAimable=False,typeModifier='settings') 
                    mi_settings = d_buffer['instance']
                    mi_go._i_rigNull.connectChildNode(mi_settings,'settings','rigNull')
                    self.ml_controlsAll.append(mi_settings)

                    #>>> Verify out vis controls	    
                    self.mPlug_result_moduleFaceSubDriver = mi_go.build_visSubFace()		    

                except Exception,error:raise StandardError,"registration | %s"%error	

                try:#Set up some attributes
                    attributes.doSetLockHideKeyableAttr(mi_settings.mNode)
                    mPlug_FKIK = cgmMeta.cgmAttr(mi_settings.mNode,'blend_FKIK',attrType='float',lock=False,keyable=True,
                                                 minValue=0,maxValue=1.0)
                except Exception,error:raise StandardError,"attribute setup | %s"%error	

            except Exception,error:raise Exception,"[Build Settings fail]{%s}"%(error)

            try:#>>>> eyeMove #==================================================================	
                mi_eyeMoveShape.parent = mi_go._i_constrainNull.mNode

                try:#Register the control
                    d_buffer = mControlFactory.registerControl(mi_eyeMoveShape,
                                                               addMirrorAttributeBridges = [["mirrorIn","t%s"%mi_go._jointOrientation[2]],
                                                                                            ["mirrorBank","r%s"%mi_go._jointOrientation[0]]],
                                                               mirrorSide = str_mirrorSide, mirrorAxis="",		                                               
                                                               makeAimable=False,typeModifier='eyeMove') 
                    mObj = d_buffer['instance']
                    mi_go._i_rigNull.connectChildNode(mObj,'eyeMove','rigNull')
                    self.ml_controlsAll.append(mObj)
                except Exception,error:raise Exception,"[registration]{%s}"%(error)

                try:#Set up some attributes
                    attributes.doSetLockHideKeyableAttr(mObj.mNode,channels = ["r%s"%mi_go._jointOrientation[1],"r%s"%mi_go._jointOrientation[2],'v'])
                except Exception,error:raise Exception,"[Attribute setup]{%s}"%(error)

                try:#Vis Connect
                    for shp in mObj.getShapes():
                        mShp = cgmMeta.cgmNode(shp)
                        mShp.overrideEnabled = 1    
                        self.mPlug_result_moduleFaceSubDriver.doConnectOut("%s.overrideVisibility"%mShp.mNode)
                except Exception,error:raise Exception,"[subVisConnect]{%s}"%(error)


            except Exception,error:raise Exception,"[Build Settings fail]{%s}"%(error)
Beispiel #26
0
def addOrientationHelpers(self):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Adds orientation helpers to a template chain
    
    ARGUMENTS:
    objects(list)
    root(string) - root control of the limb chain
    moduleType(string)
    
    RETURNS:
    returnList(list) = [rootHelper(string),helperObjects(list),helperObjectGroups(list)]
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    moduleColors = modules.returnModuleColors(self.ModuleNull.nameLong)
    helperObjects = []
    helperObjectGroups = []
    returnBuffer = []
    root = self.msgTemplateRoot.getMessage()
    visAttr = "%s.visOrientHelpers" % self.infoNulls['visibilityOptions'].get()
    objects = self.templatePosObjectsBuffer.bufferList

    #>>> Direction and size Stuff
    """ Directional data derived from joints """
    generalDirection = logic.returnHorizontalOrVertical(objects)

    if generalDirection == 'vertical' and 'leg' not in self.afModuleType.get():
        worldUpVector = [0, 0, -1]
    elif generalDirection == 'vertical' and 'leg' in self.afModuleType.get():
        worldUpVector = [0, 0, 1]
    else:
        worldUpVector = [0, 1, 0]

    #Get Size
    size = (distance.returnBoundingBoxSizeToAverage(objects[0]) * 2)

    #>>> Master Orient helper
    createBuffer = curves.createControlCurve('circleArrow1', (size * 2),
                                             'z+')  # make the curve
    curves.setCurveColorByName(createBuffer, moduleColors[0])

    attributes.storeInfo(createBuffer, 'cgmType',
                         'templateOrientRoot')  #copy the name attr
    mainOrientHelperObj = NameFactory.doNameObject(createBuffer)

    attributes.storeObjectToMessage(
        mainOrientHelperObj, self.msgTemplateRoot.get(),
        'orientHelper')  #store the object to it's respective  object
    returnBuffer.append(mainOrientHelperObj)

    # Snapping
    position.movePointSnap(mainOrientHelperObj, root)
    constBuffer = mc.aimConstraint(objects[1],
                                   mainOrientHelperObj,
                                   maintainOffset=False,
                                   weight=1,
                                   aimVector=[1, 0, 0],
                                   upVector=[0, 1, 0],
                                   worldUpVector=worldUpVector,
                                   worldUpType='vector')
    mc.delete(constBuffer[0])

    # Follow Groups
    mainOrientHelperGroupBuffer = rigging.groupMeObject(mainOrientHelperObj)
    mainOrientHelperGroupBuffer = NameFactory.doNameObject(
        mainOrientHelperGroupBuffer)
    mainOrientHelperGroup = rigging.doParentReturnName(
        mainOrientHelperGroupBuffer, root)
    mc.pointConstraint(objects[0],
                       mainOrientHelperGroupBuffer,
                       maintainOffset=False)
    helperObjectGroups.append(mainOrientHelperGroup)

    # set up constraints
    mc.aimConstraint(objects[-1],
                     mainOrientHelperGroup,
                     maintainOffset=True,
                     weight=1,
                     aimVector=[1, 0, 0],
                     upVector=[0, 1, 0],
                     worldUpObject=root,
                     worldUpType='objectRotation')
    # lock and hide stuff
    attributes.doSetLockHideKeyableAttr(
        mainOrientHelperObj, True, False, False,
        ['tx', 'ty', 'tz', 'rz', 'ry', 'sx', 'sy', 'sz', 'v'])

    #>>> The sub helpers
    """ make our pair lists """
    pairList = lists.parseListToPairs(objects)
    """ make our controls """
    helperObjects = []
    for pair in pairList:
        """ Get Size """
        size = (distance.returnBoundingBoxSizeToAverage(pair[0]) * 2)
        """ make the curve"""
        createBuffer = curves.createControlCurve('circleArrow2Axis', size,
                                                 'y-')
        curves.setCurveColorByName(createBuffer, moduleColors[1])
        """ copy the name attr"""
        attributes.copyUserAttrs(pair[0], createBuffer, ['cgmName'])
        attributes.storeInfo(createBuffer, 'cgmType', 'templateOrientObject')
        helperObj = NameFactory.doNameObject(createBuffer)
        """ store the object to it's respective  object and to an object list """
        attributes.storeObjectToMessage(helperObj, pair[0], 'orientHelper')
        helperObjects.append(helperObj)
        """ initial snapping """
        position.movePointSnap(helperObj, pair[0])
        constBuffer = mc.aimConstraint(pair[1],
                                       helperObj,
                                       maintainOffset=False,
                                       weight=1,
                                       aimVector=[1, 0, 0],
                                       upVector=[0, 1, 0],
                                       worldUpVector=worldUpVector,
                                       worldUpType='vector')
        mc.delete(constBuffer[0])
        """ follow groups """
        helperGroupBuffer = rigging.groupMeObject(helperObj)
        helperGroup = NameFactory.doNameObject(helperGroupBuffer)
        helperGroup = rigging.doParentReturnName(helperGroup, pair[0])
        helperObjectGroups.append(helperGroup)
        """ set up constraints """
        mc.aimConstraint(pair[1],
                         helperGroup,
                         maintainOffset=False,
                         weight=1,
                         aimVector=[1, 0, 0],
                         upVector=[0, 1, 0],
                         worldUpVector=[0, 1, 0],
                         worldUpObject=mainOrientHelperObj,
                         worldUpType='objectrotation')
        """ lock and hide stuff """
        helperObj = attributes.returnMessageObject(pair[0], 'orientHelper')
        mc.connectAttr((visAttr), (helperObj + '.v'))
        attributes.doSetLockHideKeyableAttr(
            helperObj, True, False, False,
            ['tx', 'ty', 'tz', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'])

    #>>> For the last object in the chain
    for obj in objects[-1:]:
        """ Get Size """
        size = (distance.returnBoundingBoxSizeToAverage(obj) * 2)
        """ make the curve"""
        createBuffer = curves.createControlCurve('circleArrow2Axis', size,
                                                 'y-')
        curves.setCurveColorByName(createBuffer, moduleColors[1])
        """ copy the name attr"""
        attributes.copyUserAttrs(obj, createBuffer, ['cgmName'])
        attributes.storeInfo(createBuffer, 'cgmType', 'templateOrientObject')
        helperObj = NameFactory.doNameObject(createBuffer)
        """ store the object to it's respective  object """
        attributes.storeObjectToMessage(helperObj, obj, 'orientHelper')
        """ initial snapping """
        position.movePointSnap(helperObj, obj)
        constBuffer = mc.aimConstraint(objects[-2],
                                       helperObj,
                                       maintainOffset=False,
                                       weight=1,
                                       aimVector=[1, 0, 0],
                                       upVector=[0, 1, 0],
                                       worldUpVector=worldUpVector,
                                       worldUpType='vector')
        mc.delete(constBuffer[0])
        """ follow groups """
        helperGroupBuffer = rigging.groupMeObject(helperObj)
        helperGroup = NameFactory.doNameObject(helperGroupBuffer)
        helperGroup = rigging.doParentReturnName(helperGroup, obj)
        helperObjectGroups.append(helperGroup)
        """ set up constraints """
        secondToLastHelperObject = attributes.returnMessageObject(
            objects[-2], 'orientHelper')
        mc.orientConstraint(secondToLastHelperObject,
                            helperGroup,
                            maintainOffset=False,
                            weight=1)
        """ lock and hide stuff """
        helperObj = attributes.returnMessageObject(obj, 'orientHelper')
        mc.connectAttr((visAttr), (helperObj + '.v'))
        attributes.doSetLockHideKeyableAttr(
            helperObj, True, False, False,
            ['tx', 'ty', 'tz', 'sx', 'sy', 'sz', 'v'])
        helperObjects.append(helperObj)

    returnBuffer.append(helperObjects)
    returnBuffer.append(helperObjectGroups)
    return returnBuffer