Example #1
0
 def createGuide(self, *args):
     Base.StartClass.createGuide(self)
     # Custom GUIDE:
     cmds.addAttr(self.moduleGrp, longName="flip", attributeType='bool')
     cmds.setAttr(self.moduleGrp+".flip", 0)
     
     cmds.addAttr(self.moduleGrp, longName="indirectSkin", attributeType='bool')
     cmds.setAttr(self.moduleGrp+".indirectSkin", 0)
     
     cmds.setAttr(self.moduleGrp+".moduleNamespace", self.moduleGrp[:self.moduleGrp.rfind(":")], type='string')
     
     self.cvJointLoc, shapeSizeCH = ctrls.cvJointLoc(ctrlName=self.guideName+"_JointLoc1", r=0.3)
     self.connectShapeSize(shapeSizeCH)
     self.jGuide1 = cmds.joint(name=self.guideName+"_JGuide1", radius=0.001)
     cmds.setAttr(self.jGuide1+".template", 1)
     cmds.parent(self.jGuide1, self.moduleGrp, relative=True)
     
     self.cvEndJoint, shapeSizeCH = ctrls.cvLocator(ctrlName=self.guideName+"_JointEnd", r=0.1)
     self.connectShapeSize(shapeSizeCH)
     cmds.parent(self.cvEndJoint, self.cvJointLoc)
     cmds.setAttr(self.cvEndJoint+".tz", 1.3)
     self.jGuideEnd = cmds.joint(name=self.guideName+"_JGuideEnd", radius=0.001)
     cmds.setAttr(self.jGuideEnd+".template", 1)
     cmds.transformLimits(self.cvEndJoint, tz=(0.01, 1), etz=(True, False))
     ctrls.setLockHide([self.cvEndJoint], ['tx', 'ty', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])
     
     cmds.parent(self.cvJointLoc, self.moduleGrp)
     cmds.parent(self.jGuideEnd, self.jGuide1)
     cmds.parentConstraint(self.cvJointLoc, self.jGuide1, maintainOffset=False, name=self.jGuide1+"_ParentConstraint")
     cmds.parentConstraint(self.cvEndJoint, self.jGuideEnd, maintainOffset=False, name=self.jGuideEnd+"_ParentConstraint")
     cmds.scaleConstraint(self.cvJointLoc, self.jGuide1, maintainOffset=False, name=self.jGuide1+"_ScaleConstraint")
     cmds.scaleConstraint(self.cvEndJoint, self.jGuideEnd, maintainOffset=False, name=self.jGuideEnd+"_ScaleConstraint")
def rigFace() : 
    jntGrp = 'facialJnt_grp'

    if not mc.objExists(jntGrp) : 
        mc.group(em = True, n = jntGrp)

    facePolyMap = {'L_brow_ply': 'L_brow_ctrl',
                     'L_baseEye_ply': 'L_baseEye_ctrl', 
                     'L_eye_ply': 'L_eye_ctrl',
                     'R_brow_ply': 'R_brow_ctrl', 
                     'R_baseEye_ply': 'R_baseEye_ctrl', 
                     'R_eye_ply': 'R_eye_ctrl', 
                     'nose_ply': 'noseface_ctrl', 
                     'mouth_ply': 'mount_ctrl'
                     }

    for each in facePolyMap : 
        poly = each
        ctrl = facePolyMap[poly]

        if mc.objExists(poly) : 

            movePivot(ctrl, poly)

            joint = mc.createNode('joint', n = poly.replace('_ply', '_jnt'))
            mc.delete(mc.pointConstraint(poly, joint))
            mc.skinCluster(poly, joint, tsb = True)
            mc.parentConstraint(ctrl, joint)
            mc.scaleConstraint(ctrl, joint)

            mc.parent(joint, jntGrp)
Example #3
0
def createControl( si, shape = 'circleX', childsAlso = True, par = None, lastAlso = False, constraint = True, connect = False, offsetGroup = True ):
	if not lastAlso and not si.children:
		return
	if shape == 'joint':
		mc.select( cl = True )
		curv = mn.Node( mc.joint( n = si.name + "_jnt" ) )
	elif shape == 'locator':
		curv = mn.Node( mc.spaceLocator( n = si.name + '_loc' )[0] )
	else:
		curv = crv.Curve( si.name + "_ctl" )
		curv = curv.create( shape )
	if offsetGroup:
		grp = mn.createNode( "transform", ss = True )
		grp.name = si.name + "_grp"
		trf.snap( si, grp )
		curv.parent = grp
		curv.a.t.v  = [0]*3
		curv.a.r.v  = [0]*3
		if par:
			grp.parent = par
	else:
		trf.snap( si, curv )
		curv.freeze()
	if constraint:
		mc.parentConstraint( curv, si, mo = True )
		mc.scaleConstraint( curv, si, mo = True )
	if connect:
		curv.a.t >> si.a.t
		curv.a.r >> si.a.r
		curv.a.s >> si.a.s
	if childsAlso and si.children:
		for c in si.children:
			c = mn.Node( c.name.split( '|' )[-1] )
			createControl( c, shape, True, curv, lastAlso, constraint, connect, offsetGroup )
	def attachGeoToBlueprint_parenting(self,blueprintJoint,geometry):
		jointName = utils.stripAllNamespaces(blueprintJoint)[1]
		parentGroup = cmds.group(empty=True,n=jointName + '_geoAttach_parentGrp#')
		
		if len(geometry) == 1:
			geoParent = cmds.listRelatives(geometry,parent=True)
			if geoParent != None:
				cmds.parent(parentGroup, geoParent)
				
		cmds.parentConstraint(blueprintJoint,parentGroup, maintainOffset=False,n=parentGroup+'_parentConstraint')
		cmds.scaleConstraint(blueprintJoint,parentGroup, maintainOffset=False,n=parentGroup+'_scaleConstraint')
		
		geoParent = parentGroup
		
		children = cmds.listRelatives(blueprintJoint, children=True)
		children = cmds.ls(children,type='joint')
		
		if len(children) != 0:
			childJoint = children[0]
			
			scaleGroup = cmds.group(empty=True, n=jointName+'_geoAttach_scaleGrp#')
			cmds.parent(scaleGroup,parentGroup,relative=True)
			
			geoParent = scaleGroup
			
			originalTxValue = cmds.getAttr(childJoint + '.translateX')
			scaleFactor = cmds.shadingNode('multiplyDivide', asUtility=True, n=scaleGroup+'_scaleFactor')
			cmds.setAttr(scaleFactor+'.operation',2)#divide
			cmds.connectAttr(childJoint+'.translateX',scaleFactor+'.input1X')
			cmds.setAttr(scaleFactor+'.input2X', originalTxValue)
			
			cmds.connectAttr(scaleFactor+'.outputX',scaleGroup+'.scaleX')
			
		for geo in geometry:
			cmds.parent(geo,geoParent,absolute=True)
Example #5
0
 def __init__(self, _sceneData, _parent1, _parent2, _name, _baseName, _numCtrls, _numJoints = 5):
     self.m_sceneData = _sceneData
     self.m_parent1 = _parent1
     self.m_parent2 = _parent2
     self.m_name = _name
     self.m_baseName = _baseName
     self.m_group = cmds.group(em=1, n=_name+"_GRP")
     self.m_numCtrls = _numCtrls
     self.m_numJoints = _numJoints
     self.m_isParentBend = True
     self.m_blendControl = False
     self.m_blendAttrName = "autoBend"
     self.m_squetchAttrName = "squetchiness"
     self.m_squetchBoolAttrName = "squetchOnOff"
     self.m_attrHeading = "Heading"
     self.m_isMirrored = False
     self.m_twistAxis = "y"
     self.m_userJoints = False
     self.m_isAutoBend = True
     self.m_isParentTwist = True
     self.m_allControls = {}
     
     #create null for scale fixing
     self.m_scaleNull = cmds.group(em=1, n=_name+"_NULL", w=True)
     cmds.setAttr(self.m_scaleNull+".inheritsTransform", 0)
     cmds.parent(self.m_scaleNull, self.m_group)
     cmds.scaleConstraint(self.m_group, self.m_scaleNull) 
Example #6
0
def create_spine_rig(base_curve, rig_region_name, pelvis, cog, spine_1, spine_2, spine_3, spine_4, neck):

    # create group to contain all rigging nodes
    cmds.select(cl=True)
    spine_group = cmds.group(em=True, n=rig_region_name + '_group')
    cmds.select(spine_group, base_curve, r=True)
    cmds.parent()

    # add the arm group node to the base curve rig nodes attr
    add_node_to_rig_nodes(base_curve, rig_region_name, spine_group)

    cog_curve, cog_curve_group = jt_ctl_curve.create(cog, 'star_5', lock_unused=False)
    cmds.setAttr(cog_curve + '.scale', 3,3,3)
    cmds.select(cog_curve, r=True)
    cmds.makeIdentity(apply=True, t=0, r=0, s=1, n=0)

    cmds.select(cog_curve, cog, r=True)
    cmds.parentConstraint(mo=True, weight=1)
    cmds.scaleConstraint(mo=True, weight=1)

    cmds.select(cog_curve_group, base_curve, r=True)
    cmds.parent()

    pelvis_curve, pelvis_curve_group = jt_ctl_curve.create(pelvis, 'waist', True, True, True, True)
    spine_1_curve, spine_1_curve_group = jt_ctl_curve.create(spine_1, 'circle', True, True, True, True)
    spine_2_curve, spine_2_curve_group = jt_ctl_curve.create(spine_2, 'circle', True, True, True, True)
    spine_3_curve, spine_3_curve_group = jt_ctl_curve.create(spine_3, 'circle', True, True, True, True)
    spine_4_curve, spine_4_curve_group = jt_ctl_curve.create(spine_4, 'circle', True, True, True, True)
    neck_curve, neck_curve_group = jt_ctl_curve.create(neck, 'circle', True, True, True, True)

    # parent fk controlls to spine group
    cmds.select(cog_curve_group, pelvis_curve_group, spine_1_curve_group, spine_2_curve_group, spine_3_curve_group, spine_4_curve_group, neck_curve_group, spine_group, r=True)
    cmds.parent()
Example #7
0
def makeGlobalControl():
    utils.debbug.DebbugMessage(message="Creating global control")

    parent = nameLib.groupNames.modulesGroup["name"]
    constraintTo = [nameLib.groupNames.jointsGroup["name"]]

    globalControlData = {"name":nameLib.prefixNames.globalControl,
                         "style":"circle",
                         "size":(30,30,30),
                         "orient":(0,1,0),
                         "color":16,
                         "attributes":False}


    globalControl = utils.makeControl.MakeControl(name=globalControlData["name"],
                                                  style=globalControlData["style"],
                                                  orient=globalControlData["orient"],
                                                  size=globalControlData["size"],
                                                  color=globalControlData["color"],
                                                  parentUnder=parent,
                                                  lockChannels = ["v"])

    # constraint to joints group
    mc.parentConstraint(globalControl.controller, constraintTo[0], name="globalParent_constraint")
    mc.scaleConstraint(globalControl.controller, constraintTo[0], name="globalScale_constraint")

    # add to character set
    utils.characterSet.characterSet(globalControl.controller, channelsToRemove = [".v"])
Example #8
0
def rigExtrudePlane() : 
	mc.select(cl = True)
	lf_leg = ['lf_upLeg_nrJnt', 'L_leg_profileCrv']
	rt_leg = ['rt_upLeg_nrJnt', 'R_leg_profileCrv']
	lf_arm = ['lf_upArm_nrJnt', 'L_arm_profileCrv']
	rt_arm = ['rt_upArm_nrJnt', 'R_arm_profileCrv']
	set1 = [lf_leg, rt_leg, lf_arm, rt_arm]

	for each in set1 : 
		# constraint nonRoll to profile curve
		mc.orientConstraint(each[0], each[1], mo = True)
		print each[0], each[1]

	mc.select(cl = True)

	naming1 = ['L_arm_pathCrv', 'L_arm_profileCrv', 'R_arm_pathCrv', 'R_arm_profileCrv']
	naming2 = ['L_leg_pathCrv', 'L_leg_profileCrv', 'R_leg_pathCrv', 'R_leg_profileCrv']
	mc.select(naming1, naming2)
	mm.eval('tazGrp;')
	mc.select(cl = True)

	grp = ['L_armProfileCrv_zGrp', 'R_armProfileCrv_zGrp', 'L_legProfileCrv_zGrp', 'R_legProfileCrv_zGrp']

	for each in grp : 
		mc.scaleConstraint('placement_ctrl', each)

	# mc.select(cl = True)
	# # bind skin
	# mc.skinCluster('lf_upArm_jnt', 'lf_loArm_jnt', 'lf_wrist_jnt', 'L_arm_pathCrv', tsb = True)
	# mc.skinCluster('lf_upArm_jnt', 'lf_loArm_jnt', 'lf_wrist_jnt', 'L_arm_pathCrv', tsb = True)
	# mc.skinCluster('rt_upLeg_jnt', 'rt_loLeg_jnt', 'rt_ankle_jnt', 'R_leg_pathCrv', tsb = True)
	# mc.skinCluster('rt_upArm_jnt', 'rt_loArm_jnt', 'rt_wrist_jnt', 'Larm_pathCrv', tsb = True)

			
	# print 'Done'
 def setCST(self, constrainttype = 'parent', source = '', weight = 1, mo = True, remove = False, skip = "none"):
     """This can be used instead of the constraint class to constrain the current superObject to something quickly.
     @param type: the type of constraint,valid options are point, parent, aim, scale, orient.
     @param source: what you want to constrain to. single source only
     @param weight: the weight of the constraint
     @param mo: maintain offset
     @param remove: remove from constraint
     @type type: string
     @type target: string
     @type weight: int
     @type mo: boolean
     @type remove: boolean
     """
     self.cstName = self.name + constrainttype + '_Constraint'
     self.cstType = constrainttype
     self.source = source
     cstTypes = ['point', 'orient', 'aim', 'parent', 'scale']
     if self.cstType not in cstTypes:
         print 'Invalid constraint type called for superObject %s, try again' % self.name
     elif self.cstType == 'point':
         cmds.pointConstraint(self.source, self.name, weight = weight, mo = mo, rm = remove, n = self.cstName, skip = skip)
     elif self.cstType == 'parent':
         cmds.parentConstraint(self.source, self.name, weight = weight, mo = mo, rm = remove, n = self.cstName)
     elif self.cstType == 'aim':
         cmds.aimConstraint(self.source, self.name, weight = weight, mo = mo, rm = remove, n = self.cstName)
     elif self.cstType == 'scale':
         cmds.scaleConstraint(self.source, self.name, weight = weight, mo = mo, rm = remove, n = self.cstName)
     elif self.cstType == 'orient':
         cmds.orientConstraint(self.source, self.name, weight = weight, mo = mo, rm = remove, n = self.cstName)
def claw(ref):
    # duplicate geo
    selection = cmds.ls(sl=True)
    for locator in selection:
        split = locator.split("section_")
        name = "%sclaw_%s" % (split[0], split[1].replace("locator", "C"))
        bind = "bind_%s" % name

        old_name = "old_%s" % name
        old_bind = "old_%s" % bind

        cmds.rename(name, old_name)
        cmds.rename(bind, old_bind)

        cmds.duplicate(ref, rr=True, un=True, name=bind)
        cmds.duplicate(bind, name=name)

        shape = cmds.listRelatives(bind, s=True)[0]
        claw_bs = cmds.listConnections(shape, type="blendShape", s=True)[0]
        cmds.connectAttr(locator + ".parameter", claw_bs + ".tentacle_claw")

        cmds.scaleConstraint(locator, bind, maintainOffset=False)
        cmds.parentConstraint(locator, bind, maintainOffset=False)

        bs = cmds.blendShape(bind, name, origin="world")
        cmds.setAttr(bs[0] + ".w[0]", 1)

        cmds.parent(name, cmds.listRelatives(old_name, p=True)[0])
        cmds.parent(bind, cmds.listRelatives(old_bind, p=True)[0])

        cmds.delete(old_name, old_bind)
Example #11
0
def friendsBeachRig() :
	
	for each in mc.ls( sl=True ) :
    
		currName = each.split( '_' )[0]
		
		ctrl = pc.Control( 'circle' )
		ctrl.name = '%s_ctrl' % currName
		ctrl.color = 'red'
		ctrl.attr( 'v' ).lock = True
		ctrl.attr( 'v' ).hide = True
		ctrl.scaleShape( 7 )
		grp = pc.group( ctrl )
		grp.snap( each )
		grp.name = '%sCtrlZro_grp' % currName
		
		geoZro = mc.listRelatives( each , p=True )[0]
		geoGrp = mc.listRelatives( geoZro , p=True )[0]
		rigGrp = geoGrp.replace( 'Geo_' , 'Rig_' )
		
		if not mc.objExists( rigGrp ) :
			mc.group( em=True , n=rigGrp )
		
		mc.parentConstraint( ctrl , geoZro , mo=True)
		mc.scaleConstraint( ctrl , geoZro , mo=True )
		mc.parent( grp , rigGrp )
Example #12
0
def scaleConstraintCmd(maintainOffset):
    # Get selection Objects
    selection = cmds.ls (sl = True)

    # Error Checking
    if len(selection) != 2:
        raise Warning ("Please Select 2 Objects")
        return
        
    cmds.scaleConstraint(selection[0], selection[1], maintainOffset=maintainOffset)
Example #13
0
def rigScale():
    placementControl = nameLib.prefixNames.globalControl + nameLib.prefixNames.controlSuffix

    groups = [nameLib.groupNames.leftLegRigGroup["name"],
              nameLib.groupNames.rightLegRigGroup["name"],
              nameLib.groupNames.leftArmRigGroup["name"],
              nameLib.groupNames.rightArmRigGroup["name"],]

    for i in groups:
        mc.scaleConstraint(placementControl, i)
Example #14
0
	def scale(self):
		"""make a scale constraint between lists"""
		fromItems, toItems = self._getItemsInLists()
		maintainOffset = self.maintainOffset_chb.isChecked()
		if len( fromItems ) == 1:
			for toNode in toItems:
				mc.scaleConstraint( fromItems[0].name, toNode.name, mo = maintainOffset )
		else:
			for fromNode,toNode in zip( fromItems, toItems ):
				mc.scaleConstraint( fromNode.name, toNode.name, mo = maintainOffset )
Example #15
0
def create(geo,prefix=''):
	'''
	'''
	# Check prefix
	if not prefix: prefix = geo
	
	# Create Deformer
	sMod = mc.softMod(geo,n=prefix+'_softMod')
	sModHandle = sMod[1]
	sMod = sMod[0]
	sModBase = mc.duplicate(sModHandle,po=True,n=prefix+'_softModBase')[0]
	
	# Get Handle pivot
	piv = mc.xform(sModHandle,q=True,ws=True,rp=True)
	
	# Initiate Control Builder
	ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder()
	
	# Create Base control
	base_grp = mc.createNode('transform',n=prefix+'_softModBase_grp')
	base_ctrl = mc.createNode('transform',n=prefix+'_softModBase_ctrl',p=base_grp)
	base_ctrlShape = ctrlBuilder.controlShape(base_ctrl,'box',scale=2)
	
	# Create Offset control
	offset_grp = mc.createNode('transform',n=prefix+'_softModOffset_grp',p=base_ctrl)
	offset_ctrl = mc.createNode('transform',n=prefix+'_softModOffset_ctrl',p=offset_grp)
	offset_ctrlShape = ctrlBuilder.controlShape(offset_ctrl,'sphere',scale=0.25)
	
	# Create Falloff control
	falloff_grp = mc.createNode('transform',n=prefix+'_softModFalloff_grp',p=base_ctrl)
	falloff_ctrl = mc.createNode('transform',n=prefix+'_softModFalloff_ctrl',p=falloff_grp)
	falloff_ctrlShape = ctrlBuilder.controlShape(falloff_ctrl,'circle',scale=1)
	falloff_loc = mc.spaceLocator(n=prefix+'_softModFalloff_loc')[0]
	mc.parent(falloff_loc,falloff_ctrl)
	mc.addAttr(falloff_ctrl,ln='radius',min=0.001,dv=1,k=True)
	mc.setAttr(falloff_loc+'.v',0)
	
	# Move hierarchy into place
	mc.move(piv[0],piv[1],piv[2],base_grp,a=True)
	
	# Connect to deformer
	mc.connectAttr(falloff_loc+'.worldPosition[0]',sMod+'.falloffCenter',f=True)
	mc.connectAttr(falloff_ctrl+'.radius',sMod+'.falloffRadius',f=True)
	mc.connectAttr(sModBase+'.worldInverseMatrix[0]',sMod+'.bindPreMatrix',f=True)
	
	# Parent and constrain softMod elements
	mc.parentConstraint(offset_ctrl,sModHandle,mo=True)
	mc.scaleConstraint(offset_ctrl,sModHandle,mo=True)
	mc.parentConstraint(base_ctrl,sModBase,mo=True)
	mc.scaleConstraint(base_ctrl,sModBase,mo=True)
	mc.parent(sModHandle,sModBase)
	mc.parent(sModBase,base_grp)
	
	# Return result
	return sMod
Example #16
0
def create(geo, prefix=""):
    """
	"""
    # Check prefix
    if not prefix:
        prefix = geo

    # Create Deformer
    sMod = mc.softMod(geo, n=prefix + "_softMod")
    sModHandle = sMod[1]
    sMod = sMod[0]
    sModBase = mc.duplicate(sModHandle, po=True, n=prefix + "_softModBase")[0]

    # Get Handle pivot
    piv = mc.xform(sModHandle, q=True, ws=True, rp=True)

    # Create Base control
    base_grp = mc.createNode("transform", n=prefix + "_softModBase_grp")
    base_ctrl = mc.createNode("transform", n=prefix + "_softModBase_ctrl", p=base_grp)
    base_ctrlShape = glTools.tools.controlBuilder.controlShape(base_ctrl, "box", scale=2)

    # Create Offset control
    offset_grp = mc.createNode("transform", n=prefix + "_softModOffset_grp", p=base_ctrl)
    offset_ctrl = mc.createNode("transform", n=prefix + "_softModOffset_ctrl", p=offset_grp)
    offset_ctrlShape = glTools.tools.controlBuilder.controlShape(offset_ctrl, "sphere", scale=0.25)

    # Create Falloff control
    falloff_grp = mc.createNode("transform", n=prefix + "_softModFalloff_grp", p=base_ctrl)
    falloff_ctrl = mc.createNode("transform", n=prefix + "_softModFalloff_ctrl", p=falloff_grp)
    falloff_ctrlShape = glTools.tools.controlBuilder.controlShape(falloff_ctrl, "circle", scale=1)
    falloff_loc = mc.spaceLocator(n=prefix + "_softModFalloff_loc")[0]
    mc.parent(falloff_loc, falloff_ctrl)
    mc.addAttr(falloff_ctrl, ln="radius", min=0.001, dv=1, k=True)
    mc.setAttr(falloff_loc + ".v", 0)

    # Move hierarchy into place
    mc.move(piv[0], piv[1], piv[2], base_grp, a=True)

    # Connect to deformer
    mc.connectAttr(falloff_loc + ".worldPosition[0]", sMod + ".falloffCenter", f=True)
    mc.connectAttr(falloff_ctrl + ".radius", sMod + ".falloffRadius", f=True)
    mc.connectAttr(sModBase + ".worldInverseMatrix[0]", sMod + ".bindPreMatrix", f=True)

    # Parent and constrain softMod elements
    mc.parentConstraint(offset_ctrl, sModHandle, mo=True)
    mc.scaleConstraint(offset_ctrl, sModHandle, mo=True)
    mc.parentConstraint(base_ctrl, sModBase, mo=True)
    mc.scaleConstraint(base_ctrl, sModBase, mo=True)
    mc.parent(sModHandle, sModBase)
    mc.parent(sModBase, base_grp)

    # Return result
    return sMod
Example #17
0
		def createConnection(self, inputModule, connectionKey):
			"""
				Connect objects based on connection data
			"""
			inputModule = self.Modules[inputModule]
			# Check connection exists
			if not inputModule.connections.has_key(connectionKey):
				cmds.error("Connection data not found")
			inputPlug = inputModule.connections[connectionKey]["input"]
			outputPlug = inputModule.connections[connectionKey]["output"]
			connectionAttr = inputModule.connections[connectionKey]["connectAttr"]
			connectionDataAttr = (connectionAttr + "_data")
			
			inputModule = inputPlug.split(".")[0]
			outputModule = outputPlug.split(".")[0]
			
			inputKey = Util.getSuffix( inputPlug.split(".")[1] )
			outputey = Util.getSuffix( outputPlug.split(".")[1] )
			
			input = self.getInput(inputModule, inputKey)
			output = self.getOutput(outputModule, outputey)
			
			# Get connection data
			connectionData = cmds.getAttr( (inputModule + "_CNT." + connectionDataAttr) )
			AttributeName = connectionData[3]
			type = AttributeName = connectionData[1]
			
			if type == "trans":
				cmds.parentConstraint(output,input, mo= False)
			elif type == "transMo":
				cmds.parentConstraint(output,input, mo= True)
			elif type == "pos":
				cmds.pointConstraint(output,input, mo= False)
			elif type == "posMo":
				cmds.pointConstraint(output,input, mo= True)
			elif type == "rot":
				cmds.orientConstraint(output,input, mo= False)
			elif type == "rotMo":
				cmds.orientConstraint(output,input, mo= True)
			elif type == "scale":
				cmds.scaleConstraint(output,input)
			elif type == "matrix":
				Util.matrixConstraint(output, input, 0, {})
			elif type == "matrixMo":
				Util.matrixConstraint(output, input, 1, {})
			elif type == "Attribute":
				cmds.connectAttr(output, input, f= True)
			else:
				cmds.error( ("Connection type not found on connectionAttr: " + connectionAttr) )
Example #18
0
def scaleConstrain():
    sel = [
        'splineFK_Ct__tentacle_L1',
        'splineFK_Ct__tentacle_L2',
        'splineFK_Ct__tentacle_L3',
        'splineFK_Ct__tentacle_L4',
        'splineFK_Ct__tentacle_L5',
        'splineFK_Ct__tentacle_R1',
        'splineFK_Ct__tentacle_R2',
        'splineFK_Ct__tentacle_R3',
        'splineFK_Ct__tentacle_R4',
        'splineFK_Ct__tentacle_R5'
    ]
    for s in sel:
        cmds.scaleConstraint('CNTRL_God', s, mo=True)
Example #19
0
    def install_custom(self, joints, moduleGrp, moduleContainer):
        joint = joints[1]
        name = "globalControl"
        
        controlObjectInstance = controlObject.ControlObject()
        globalControlInfo = controlObjectInstance.create(name, "cubeLocator.ma", self, lod=1, translation=True, rotation=True, globalScale=True, spaceSwitching=True)
        globalControl = globalControlInfo[0]
        globalControl_rootParent = globalControlInfo[1]
        
        # Position and orient control object
        pos = cmds.xform(joint, q=True, worldSpace=True, translation=True)
        orient = cmds.xform(joint, q=True, worldSpace=True, rotation=True)
        
        cmds.xform(globalControl, worldSpace=True, absolute=True, translation=pos)
        cmds.xform(globalControl, worldSpace=True, absolute=True, rotation=orient)
        """ Try freezing transforms """
        #cmds.makeIdentity(globalControl, apply=True, t=True, r=False, s=False)
        
        cmds.parent(globalControl_rootParent, moduleGrp, absolute=True)
        
        cmds.connectAttr(joint+".rotateOrder", globalControl+".rotateOrder")
        
        parentConstraint = cmds.parentConstraint(globalControl, joint, maintainOffset=False, n=joint+"_parentConstraint")[0]
        scaleConstraint = cmds.scaleConstraint(globalControl, joint, maintainOffset=False, n=joint+"_scaleConstraint")[0]

        utils.addNodeToContainer(moduleContainer, [parentConstraint, scaleConstraint])
Example #20
0
def scale_and_parent(maintain_offset=False):
    '''
    do both
    '''
    first, second = cmds.ls(sl=True)[0:2]
    prntConstraint = cmds.parentConstraint( first,second, maintainOffset=maintain_offset)
    sclConstraint = cmds.scaleConstraint( first,second)
Example #21
0
    def setParent(self, parent, **keywords):

        rel = False

        for k in keywords:
            if k == "r" or k == "relative":
                rel = keywords[k]

        wsm = mc.xform(self.child, q=True, ws=True, m=True)
        piv = mc.xform(self.child, q=True, ws=True, rp=True)

        self.parentConstraint = pc = mc.parentConstraint(self[0], q=True)
        pcTargets = mc.parentConstraint(pc, q=True, tl=True)
        pcAliasList = mc.parentConstraint(pc, q=True, wal=True)

        self.scaleConstraint = sc = mc.scaleConstraint(self[0], q=True)

        for i in range(0, len(pcTargets)):
            if mc.ls(parent)[0] == mc.ls(pcTargets[i])[0]:
                cond = mc.listConnections(pc + "." + pcAliasList[i], s=True, d=False)[0]
                mc.setAttr(self.child + ".parentTo", mc.getAttr(cond + ".st"))
                mc.setAttr(self.child + ".zenPrevParentNum", mc.getAttr(cond + ".st"))
                break

        mc.xform(self.child, a=True, ws=True, m=wsm)
        mc.xform(self.child, ws=True, piv=piv)
Example #22
0
 def test_assertConstrained(self):
     a = cmds.polySphere()[0]
     b = cmds.polySphere()[0]
     
     temp = cmds.parentConstraint(a,b)
     self.assertTrue( self.lib.assertConstrained(a, b, type='parent') )
     cmds.delete(temp)
     
     temp = cmds.aimConstraint(a,b)
     self.assertTrue( self.lib.assertConstrained(a, b, type='aim') )
     cmds.delete(temp)        
     
     temp = cmds.pointConstraint(a,b)
     self.assertTrue( self.lib.assertConstrained(a, b, type='point') )
     cmds.delete(temp)  
     
     temp = cmds.orientConstraint(a,b)
     self.assertTrue( self.lib.assertConstrained(a,b,type='orient') )
     cmds.delete(temp)      
     
     temp = cmds.scaleConstraint(a,b)
     self.assertTrue( self.lib.assertConstrained(a,b,type='scale') )
     cmds.delete(temp)    
     
     temp = cmds.geometryConstraint(a,b)
     self.assertTrue( self.lib.assertConstrained(a,b,type='geometry') )
     cmds.delete(temp)       
     
     try:
         self.lib.assertConstrained(a,b,type='parent')
     except AssertionError:
         pass
Example #23
0
def targetAliasList(constraint):
	'''
	Return a list of targets (drivers) attribute aliases for the specified constraint node
	@param constraint: The constraint node whose targets will be returned
	@type constraint: str
	'''
	# Check Constraint
	if not isConstraint(constraint):
		raise Exception('Constraint "'+constraint+'" does not exist!!')
	
	# Get Target List
	targetList = []
	constraintType = mc.objectType(constraint)
	if constraintType == 'aimConstraint': targetList = mc.aimConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'geometryConstraint': targetList = mc.geometryConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'normalConstraint': targetList = mc.normalConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'orientConstraint': targetList = mc.orientConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'parentConstraint': targetList = mc.parentConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'pointConstraint': targetList = mc.pointConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'poleVectorConstraint': targetList = mc.poleVectorConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'scaleConstraint': targetList = mc.scaleConstraint(constraint,q=True,weightAliasList=True)
	elif constraintType == 'tangentConstraint': targetList = mc.tangentConstraint(constraint,q=True,weightAliasList=True)
	
	# Check Target List
	if not targetList: targetList = []
	
	# Return Result
	return targetList
Example #24
0
 def parentGameToBlueprint(self, characterName, characterNamespace):
     # Define the file name and path        
     reader = self.initCsvReader(characterName)
     
     gameJoints = []
     parentJoints = []
     numRows = []
     parentConstraints = []
     
     for row in reader:
         numRows.append(row)   
         gjntData = list(row)
         gameJoints.append(gjntData[0])
         parentJoints.append(gjntData[6])
     for index in range(len(gameJoints)):
         bpJoint = (characterNamespace + ":" + parentJoints[index])
         if cmds.objExists(gameJoints[index]):
             parentConstraint = cmds.parentConstraint(bpJoint, gameJoints[index], mo=True)
             scaleConstraint = cmds.scaleConstraint(bpJoint, gameJoints[index])
             parentConstraints.append(parentConstraint)
             parentConstraints.append(scaleConstraint)
         else:
             print (gameJoints[index] + 'is missing')
         
     return parentConstraints
Example #25
0
	def create_stretchy_obj(self,obj_relative_filepath,obj_container_name,obj_name,parent_joint,child_joint):

		obj_file = os.environ["mlrig_tool"]+obj_relative_filepath
		cmds.file(obj_file, i=True)

		obj_container = cmds.rename(obj_container_name, parent_joint+"_"+obj_container_name)

		for node in cmds.container(obj_container, q=True, nodeList=True):
			cmds.rename(node, parent_joint+"_"+node, ignoreShape=True)

		obj = parent_joint+"_"+obj_name

		con_grp = cmds.group(empty=True, name=obj+"_parentConstraint_grp")
		cmds.parent(obj, con_grp, absolute=True)

		parent_con = cmds.parentConstraint(parent_joint, con_grp, maintainOffset=False)[0]

		cmds.connectAttr(child_joint+".translateX", con_grp+".scaleX")

		scale_con = cmds.scaleConstraint(self.module_trans, con_grp, skip=["x"], maintainOffset=0)[0]

		utils.add_node_to_container(obj_container, [con_grp, parent_con, scale_con], ihb=True)
		utils.add_node_to_container(self.container_name, obj_container)

		return(obj_container, obj, con_grp)
Example #26
0
def do(selection=None):
    """
    Snaps second object to first.
    @param selection: List of 2 objects (optional).
    """
    if not selection:
        selection = cmds.ls(selection=True, long=True)

    if not len(selection) == 2:
        confirm = cmds.confirmDialog(
            title="Warning",
            messageAlign="center",
            message="Select exactly two objects to snap the second to the first.",
            button=["Ok"],
            defaultButton="Ok",
            cancelButton="Ok",
            dismissString="Ok",
        )
        if confirm == "Ok":
            return

    source = selection[0]
    target = selection[1]

    try:
        cmds.delete(cmds.parentConstraint(source, target, mo=False))
        cmds.delete(cmds.scaleConstraint(source, target, mo=False))
    except:
        sys.stdout.write("Unable to snap %s to %s. \n" % (target, source))
Example #27
0
	def lock_phase3(self, hook_obj):

		module_container = self.module_namespace+":module_container"

		if hook_obj != None:
			hook_obj_module_node = utils.strip_leading_namespace(hook_obj)
			hook_obj_module = hook_obj_module_node[0]
			hook_obj_joint = hook_obj_module_node[1].split("_translation_control")[0]

			hook_obj = hook_obj_module+":blueprint_"+hook_obj_joint

			parent_con = cmds.parentConstraint(
													hook_obj,
													self.module_namespace+":HOOK_IN",
													maintainOffset=True,
													name=self.module_namespace+":hook_parent_constraint"
												)[0]

			scale_con = cmds.scaleConstraint(
												hook_obj,
												self.module_namespace+":HOOK_IN",
												maintainOffset=True,
												name=self.module_namespace+":hook_scale_constraint"
											)[0]

			module_container = self.module_namespace+":module_container"
			utils.add_node_to_container(module_container, [parent_con, scale_con])

		cmds.lockNode(module_container, lock=True, lockUnpublished=True)
	def createPreferredAngleRepresentation(self,joint,scaleTarget, childOfOrientationControl=False):
		paRepresentationFile = os.environ['RIGGING_TOOL_ROOT'] + '/ControlObjects/Blueprint/preferredAngle_representation.ma'
		cmds.file(paRepresentationFile, i=True)
		
		container = cmds.rename('preferredAngle_representation_container', joint + '_preferredAngle_representation_container')
		utils.addNodeToContainer(self.containerName, container)
		
		for node in cmds.container(container, q=True, nodeList=True):
			cmds.rename(node, joint + '_' + node, ignoreShape=True)
			
		control = joint + '_preferredAngle_representation'
		controlName = utils.stripAllNamespaces(control)[1]
		cmds.container(self.containerName,edit=True, publishAndBind=[container + '.axis' , controlName + '_axis'])
		
		controlGroup = cmds.group(control, n=joint + '_preferredAngle_parentConstraintGrp',absolute=True)
		containedNodes = [controlGroup]
		
		cmds.parent(controlGroup, self.preferredAngleRepresentationGrp, absolute=True)
		
		containedNodes.append(cmds.parentConstraint(joint, controlGroup, maintainOffset=False)[0])
		
		if childOfOrientationControl:
			rotateXGrp = cmds.group(control, n=control + '_rotateX_grp', absolute=True)
			orientationControl = self.getOrientationControl(joint)
			cmds.connectAttr(orientationControl + '.rotateX', rotateXGrp + '.rotateX')
			
			containedNodes.append(rotateXGrp)
			
		containedNodes.append(cmds.scaleConstraint(scaleTarget, controlGroup, maintainOffset=False)[0])
		
		utils.addNodeToContainer(container, containedNodes)
		
		return control
Example #29
0
 def rigShoulder(self):
    try:
        # --- Shoulder --- #
        #Create shoulder controls
        gimbalCtrls = rc.makeGimbalCTRL(
             self.m_joints.m_shoulder, 
             False, 
             True
             )
        self.m_shoulderGBLCtrl = gimbalCtrls[0]
        self.m_shoulderCtrl = gimbalCtrls[1]    
        # Add to controls
        rc.addToControlDict(self.m_allControls, "%s_FKShoulder" %(self.m_baseName), self.m_shoulderCtrl)
        rc.addToControlDict(
           self.m_allControls,
           "%s_FKShoulderGBL" %(self.m_baseName),
           self.m_shoulderGBLCtrl
           )
        rc.addToLayer(self.m_sceneData, "mainCtrl", gimbalCtrls)      
        self.m_isShoulder = True
        cmds.parent(self.m_shoulderCtrl+"_0", self.m_group, r=1)
        cmds.pointConstraint(
             self.m_shoulderGBLCtrl, 
             self.m_joints.m_shoulder
             )
        #Sort out scaling
        cmds.scaleConstraint(
             self.m_shoulderGBLCtrl, 
             self.m_joints.m_shoulder
             )
         
        #Lock unused attributes
        rc.lockAttrs(
             self.m_shoulderCtrl,
             ["translate", "scale"],
             True,
             False
             )
        rc.lockAttrs(
             self.m_shoulderGBLCtrl,
             ["translate", "scale"],
             True,
             False
             )
    except:
        print "WARNING: FK Shoulder setup was unsuccessful!"
        self.m_isShoulder = False
Example #30
0
def doAddCtrl( shape='circle' ) :
	
	jnts = mc.ls( sl=True , l=True )
	ctrls = []
	gmbls = []
	zgrps = []
	
	for jnt in jnts :
		jntName = ''
		if ':' in jnt :
			jntName = jnt.split( ':' )[-1].split( '|' )[-1]
		else :
			jntName = jnt.split( '|' )[-1]
		
		currName = ''
		currSide = '_'
		
		sides = ( 'LFT' , 'RGT' )
		for side in sides :
			if side in jntName :
				currSide = '%s_' % side
		
		currName = jntName.split( currSide )[0]
		
		ctrl = pc.Control( shape )
		ctrl.lockHideAttrs( 'v' )
		ctrl.color = 'blue'
		ctrl.name = '%s%sctrl' % ( currName , currSide )
		
		mc.select( ctrl , r=True )
		zgrp = doZeroGroup()[0]
		
		mc.select( ctrl , r=True )
		gmbl = doAddGimbal()[0]

		conCtrl = pc.addConCtrl( ctrl )
		conCtrl.name = '%sCon%sctrl' % ( currName , currSide )
		
		zgrp.snap( jnt )
		mc.parentConstraint( gmbl , jnt )
		mc.scaleConstraint( gmbl , jnt )

		ctrls.append( ctrl )
		gmbls.append( gmbl )
		zgrps.append( zgrp )

	return ctrls , gmbls , zgrps
Example #31
0
def connectTargets(parentCtrl):
    '''
	Add all constraint targets to constraint transforms connected to the specified constraint target control parent transform
	@param parentCtrl: Parent constraint target control to create connections for
	@type parentCtrl: str
	'''
    # ==========
    # - Checks -
    # ==========

    # Check Parent Control
    if not mc.objExists(parentCtrl + '.constraintTarget'):
        raise Exception(
            'Object "' + parentCtrl +
            '" is not a valid constraint target control parent transform!')

    # =============================================
    # - Get Constraint Transform and Target Lists -
    # =============================================

    constraintTransformList = getConstraintTransforms(parentCtrl)
    constraintTargetList = getConstraintTargets(parentCtrl)

    if not constraintTransformList:
        raise Exception(
            'No valid constraint transforms connected to parent control "' +
            parentCtrl + '"!')
    if not constraintTargetList:
        raise Exception(
            'No valid constraint targets connected to parent control "' +
            parentCtrl + '"!')

    # ======================
    # - Create Constraints -
    # ======================

    for constraintTransform in constraintTransformList:

        # Check existing constraint node
        pTargetList = []
        sTargetList = []
        pConstraintNode = ''
        sConstraintNode = ''
        existingParentConstraint = mc.listConnections(constraintTransform +
                                                      '.t',
                                                      s=True,
                                                      d=False,
                                                      type='parentConstraint')
        existingScaleConstraint = mc.listConnections(constraintTransform +
                                                     '.s',
                                                     s=True,
                                                     d=False,
                                                     type='scaleConstraint')

        # Get Existing Constraint Target Lists
        if existingParentConstraint:
            pConstraintNode = existingParentConstraint[0]
            pTargetList = glTools.utils.constraint.targetList(pConstraintNode)
        if existingScaleConstraint:
            sConstraintNode = existingScaleConstraint[0]
            sTargetList = glTools.utils.constraint.targetList(sConstraintNode)

        # For Each Constraint Target
        for constraintTarget in constraintTargetList:

            # Check Target Label Attribute
            if not mc.objExists(constraintTarget + '.targetLabel'):
                raise Exception(
                    'Constraint target "' + constraintTarget +
                    '" has no "targetLabel" attribute! Unable to determine associated target label transform.'
                )

            # Check Target Label Connection
            targetCon = mc.listConnections(constraintTarget + '.targetLabel',
                                           s=True,
                                           d=False)
            if not targetCon:
                raise Exception(
                    'Constraint target "' + constraintTarget +
                    '" has no "targetLabel" connection! Unable to determine associated target label transform.'
                )
            target = targetCon[0]

            # Check existing Constraint Target
            if pTargetList.count(target):
                raise Exception(
                    'Constraint target "' + target +
                    '" is already a target transform for constraint node "' +
                    pConstraintNode + '"!')
            if sTargetList.count(target):
                raise Exception(
                    'Constraint target "' + target +
                    '" is already a target transform for constraint node "' +
                    sConstraintNode + '"!')

            # Get Target Label
            if not mc.objExists(target + '.label'):
                raise Exception(
                    'Constraint target "' + target +
                    '" has no "label" attribute! Unable to determine label string.'
                )
            label = mc.getAttr(target + '.label')

            # Attach as Constraint Target
            pConstraintNode = mc.parentConstraint(target,
                                                  constraintTransform,
                                                  mo=False)[0]
            pConstraintTargetAlias = glTools.utils.constraint.targetAlias(
                pConstraintNode, target)
            sConstraintNode = mc.scaleConstraint(target,
                                                 constraintTransform,
                                                 mo=False)[0]
            sConstraintTargetAlias = glTools.utils.constraint.targetAlias(
                sConstraintNode, target)

            # Connect To Constraint Target Weight
            if not mc.objExists(constraintTransform + '.' + label):
                mc.addAttr(constraintTransform,
                           ln=label,
                           min=0,
                           max=1,
                           dv=0,
                           k=True)
            mc.connectAttr(constraintTransform + '.' + label,
                           pConstraintNode + '.' + pConstraintTargetAlias,
                           f=True)
            mc.connectAttr(constraintTransform + '.' + label,
                           sConstraintNode + '.' + sConstraintTargetAlias,
                           f=True)

            # Set Constraint Rest Values
            mc.setAttr(pConstraintNode + '.restTranslate', 0, 0, 0)
            mc.setAttr(pConstraintNode + '.restRotate', 0, 0, 0)

            # Connect Interpolation Type
            pConstraintInterpCon = mc.listConnections(pConstraintNode +
                                                      '.interpType',
                                                      s=True,
                                                      d=False,
                                                      p=True)
            if not pConstraintInterpCon: pConstraintInterpCon = []
            if not pConstraintInterpCon.count(constraintTransform +
                                              '.interpType'):
                try:
                    mc.connectAttr(constraintTransform + '.interpType',
                                   pConstraintNode + '.interpType',
                                   f=True)
                except:
                    pass
Example #32
0
    def rigModule(self, *args):
        Base.StartClass.rigModule(self)
        # verify if the guide exists:
        if cmds.objExists(self.moduleGrp):
            try:
                hideJoints = cmds.checkBox('hideJointsCB',
                                           query=True,
                                           value=True)
            except:
                hideJoints = 1
            self.currentStyle = cmds.getAttr(self.moduleGrp + ".style")
            # start as no having mirror:
            sideList = [""]
            # analisys the mirror module:
            self.mirrorAxis = cmds.getAttr(self.moduleGrp + ".mirrorAxis")
            if self.mirrorAxis != 'off':
                # get rigs names:
                self.mirrorNames = cmds.getAttr(self.moduleGrp + ".mirrorName")
                # get first and last letters to use as side initials (prefix):
                sideList = [
                    self.mirrorNames[0] + '_',
                    self.mirrorNames[len(self.mirrorNames) - 1] + '_'
                ]
                for s, side in enumerate(sideList):
                    duplicated = cmds.duplicate(
                        self.moduleGrp,
                        name=side + self.userGuideName + '_Guide_Base')[0]
                    allGuideList = cmds.listRelatives(duplicated,
                                                      allDescendents=True)
                    for item in allGuideList:
                        cmds.rename(item,
                                    side + self.userGuideName + "_" + item)
                    self.mirrorGrp = cmds.group(name="Guide_Base_Grp",
                                                empty=True)
                    cmds.parent(side + self.userGuideName + '_Guide_Base',
                                self.mirrorGrp,
                                absolute=True)
                    # re-rename grp:
                    cmds.rename(
                        self.mirrorGrp,
                        side + self.userGuideName + '_' + self.mirrorGrp)
                    # do a group mirror with negative scaling:
                    if s == 1:
                        for axis in self.mirrorAxis:
                            cmds.setAttr(
                                side + self.userGuideName + '_' +
                                self.mirrorGrp + '.scale' + axis, -1)
            else:  # if not mirror:
                duplicated = cmds.duplicate(self.moduleGrp,
                                            name=self.userGuideName +
                                            '_Guide_Base')[0]
                allGuideList = cmds.listRelatives(duplicated,
                                                  allDescendents=True)
                for item in allGuideList:
                    cmds.rename(item, self.userGuideName + "_" + item)
                self.mirrorGrp = cmds.group(self.userGuideName + '_Guide_Base',
                                            name="Guide_Base_Grp",
                                            relative=True)
                # re-rename grp:
                cmds.rename(self.mirrorGrp,
                            self.userGuideName + '_' + self.mirrorGrp)
            # store the number of this guide by module type
            dpAR_count = utils.findModuleLastNumber(CLASS_NAME,
                                                    "dpAR_type") + 1
            # run for all sides
            for s, side in enumerate(sideList):
                self.base = side + self.userGuideName + '_Guide_Base'
                # get the number of joints to be created:
                self.nJoints = cmds.getAttr(self.base + ".nJoints")
                # create controls:
                self.hipsA = ctrls.cvBox(
                    ctrlName=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c_hips'] + "A_Ctrl",
                    r=self.ctrlRadius,
                    h=(self.ctrlRadius * 0.25))
                self.hipsB = \
                cmds.circle(name=side + self.userGuideName + "_" + self.langDic[self.langName]['c_hips'] + "B_Ctrl",
                            ch=False, o=True, nr=(0, 1, 0), d=1, s=8, radius=self.ctrlRadius)[0]
                self.chestA = ctrls.cvBox(
                    ctrlName=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c_chest'] + "A_Ctrl",
                    r=self.ctrlRadius,
                    h=(self.ctrlRadius * 0.25))
                self.chestB = \
                cmds.circle(name=side + self.userGuideName + "_" + self.langDic[self.langName]['c_chest'] + "B_Ctrl",
                            ch=False, o=True, nr=(0, 1, 0), d=1, s=8, radius=self.ctrlRadius)[0]
                cmds.addAttr(self.hipsA,
                             longName=side + self.userGuideName + '_' +
                             self.langDic[self.langName]['c_volumeVariation'],
                             attributeType="float",
                             defaultValue=1,
                             keyable=True)
                cmds.addAttr(self.hipsA,
                             longName=side + self.userGuideName + '_active_' +
                             self.langDic[self.langName]['c_volumeVariation'],
                             attributeType="float",
                             defaultValue=1,
                             keyable=True)
                cmds.addAttr(self.hipsA,
                             longName=side + self.userGuideName +
                             '_masterScale_' +
                             self.langDic[self.langName]['c_volumeVariation'],
                             attributeType="float",
                             defaultValue=1,
                             keyable=True)
                ctrls.setLockHide(
                    [self.hipsA, self.hipsB, self.chestA, self.chestB], ['v'],
                    l=False)
                self.aHipsAList.append(self.hipsA)
                self.aChestAList.append(self.chestA)
                self.aVolVariationAttrList.append(
                    side + self.userGuideName + '_' +
                    self.langDic[self.langName]['c_volumeVariation'])
                self.aActVolVariationAttrList.append(
                    side + self.userGuideName + '_active_' +
                    self.langDic[self.langName]['c_volumeVariation'])
                self.aMScaleVolVariationAttrList.append(
                    side + self.userGuideName + '_masterScale_' +
                    self.langDic[self.langName]['c_volumeVariation'])

                # Setup axis order
                if self.rigType == Base.RigType.quadruped:
                    cmds.setAttr(self.hipsA + ".rotateOrder", 1)
                    cmds.setAttr(self.hipsB + ".rotateOrder", 1)
                    cmds.setAttr(self.chestA + ".rotateOrder", 1)
                    cmds.setAttr(self.chestB + ".rotateOrder", 1)
                else:
                    cmds.setAttr(self.hipsA + ".rotateOrder", 3)
                    cmds.setAttr(self.hipsB + ".rotateOrder", 3)
                    cmds.setAttr(self.chestA + ".rotateOrder", 3)
                    cmds.setAttr(self.chestB + ".rotateOrder", 3)

                # Keep a list of ctrls we want to colorize a certain way
                self.aFkCtrl.append([self.hipsB, self.chestB])
                self.aIkCtrl.append([self.hipsA, self.chestA])

                # organize hierarchy:
                cmds.parent(self.hipsB, self.hipsA)
                cmds.parent(self.chestB, self.chestA)
                if self.currentStyle == 0:  #default
                    cmds.rotate(-90, 0, 0, self.hipsA, self.chestA)
                    cmds.makeIdentity(self.hipsA,
                                      self.chestA,
                                      apply=True,
                                      rotate=True)
                # position of controls:
                bottomLocGuide = side + self.userGuideName + "_Guide_JointLoc1"
                topLocGuide = side + self.userGuideName + "_Guide_JointLoc" + str(
                    self.nJoints)
                # snap controls to guideLocators:
                cmds.delete(
                    cmds.parentConstraint(bottomLocGuide,
                                          self.hipsA,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(topLocGuide,
                                          self.chestA,
                                          maintainOffset=False))

                # change axis orientation for biped stype
                if self.currentStyle == 1:  #biped
                    cmds.rotate(0, 0, 0, self.hipsA, self.chestA)
                    cmds.makeIdentity(self.hipsA,
                                      self.chestA,
                                      apply=True,
                                      rotate=True)
                cmds.parent(self.chestA, self.hipsA)

                # zeroOut transformations:
                utils.zeroOut([self.hipsA, self.chestA])
                # modify the pivots of chest controls:
                upPivotPos = cmds.xform(side + self.userGuideName +
                                        "_Guide_JointLoc" +
                                        str(self.nJoints - 1),
                                        query=True,
                                        worldSpace=True,
                                        translation=True)
                cmds.move(
                    upPivotPos[0], upPivotPos[1], upPivotPos[2],
                    self.chestA + ".scalePivot", self.chestA + ".rotatePivot"
                )  # , self.chestB+".scalePivot", self.chestB+".rotatePivot")
                # add originedFrom attributes to hipsA, hipsB and chestB:
                utils.originedFrom(objName=self.hipsA, attrString=self.base)
                utils.originedFrom(objName=self.hipsB,
                                   attrString=bottomLocGuide)
                utils.originedFrom(objName=self.chestB, attrString=topLocGuide)
                # create a simple spine ribbon:
                returnedRibbonList = ctrls.createSimpleRibbon(
                    name=side + self.userGuideName,
                    totalJoints=(self.nJoints - 1))
                rbnNurbsPlane = returnedRibbonList[0]
                rbnNurbsPlaneShape = returnedRibbonList[1]
                rbnJointGrpList = returnedRibbonList[2]
                self.aRbnJointList = returnedRibbonList[3]
                # position of ribbon nurbs plane:
                cmds.setAttr(rbnNurbsPlane + ".tz", -4)
                cmds.move(0, 0, 0, rbnNurbsPlane + ".scalePivot",
                          rbnNurbsPlane + ".rotatePivot")
                cmds.rotate(90, 90, 0, rbnNurbsPlane)
                cmds.makeIdentity(rbnNurbsPlane,
                                  apply=True,
                                  translate=True,
                                  rotate=True)
                downLocPos = cmds.xform(side + self.userGuideName +
                                        "_Guide_JointLoc1",
                                        query=True,
                                        worldSpace=True,
                                        translation=True)
                upLocPos = cmds.xform(side + self.userGuideName +
                                      "_Guide_JointLoc" + str(self.nJoints),
                                      query=True,
                                      worldSpace=True,
                                      translation=True)
                cmds.move(downLocPos[0], downLocPos[1], downLocPos[2],
                          rbnNurbsPlane)
                # create up and down clusters:
                downCluster = \
                cmds.cluster(rbnNurbsPlane + ".cv[0:3][0:1]", name=side + self.userGuideName + '_Down_Cls')[1]
                upCluster = \
                cmds.cluster(rbnNurbsPlane + ".cv[0:3][" + str(self.nJoints) + ":" + str(self.nJoints + 1) + "]",
                             name=side + self.userGuideName + '_Up_Cls')[1]
                # get positions of joints from ribbon nurbs plane:
                startRbnJointPos = cmds.xform(side + self.userGuideName +
                                              "_00_Jnt",
                                              query=True,
                                              worldSpace=True,
                                              translation=True)
                endRbnJointPos = cmds.xform(side + self.userGuideName +
                                            "_%02d_Jnt" % (self.nJoints - 1),
                                            query=True,
                                            worldSpace=True,
                                            translation=True)
                # move pivots of clusters to start and end positions:
                cmds.move(startRbnJointPos[0], startRbnJointPos[1],
                          startRbnJointPos[2], downCluster + ".scalePivot",
                          downCluster + ".rotatePivot")
                cmds.move(endRbnJointPos[0], endRbnJointPos[1],
                          endRbnJointPos[2], upCluster + ".scalePivot",
                          upCluster + ".rotatePivot")
                # snap clusters to guideLocators:
                tempDel = cmds.parentConstraint(bottomLocGuide,
                                                downCluster,
                                                maintainOffset=False)
                cmds.delete(tempDel)
                tempDel = cmds.parentConstraint(topLocGuide,
                                                upCluster,
                                                maintainOffset=False)
                cmds.delete(tempDel)
                # rotate clusters to compensate guide:
                upClusterRot = cmds.xform(upCluster,
                                          query=True,
                                          worldSpace=True,
                                          rotation=True)
                downClusterRot = cmds.xform(downCluster,
                                            query=True,
                                            worldSpace=True,
                                            rotation=True)
                cmds.xform(upCluster,
                           worldSpace=True,
                           rotation=(upClusterRot[0] + 90, upClusterRot[1],
                                     upClusterRot[2]))
                cmds.xform(downCluster,
                           worldSpace=True,
                           rotation=(downClusterRot[0] + 90, downClusterRot[1],
                                     downClusterRot[2]))
                # scaleY of the clusters in order to avoid great extremity deforms:
                rbnHeight = ctrls.distanceBet(
                    side + self.userGuideName + "_Guide_JointLoc" +
                    str(self.nJoints),
                    side + self.userGuideName + "_Guide_JointLoc1",
                    keep=False)[0]
                cmds.setAttr(upCluster + ".sy", rbnHeight / 10)
                cmds.setAttr(downCluster + ".sy", rbnHeight / 10)
                # parent clusters in controls (up and down):
                cmds.parentConstraint(self.hipsB,
                                      downCluster,
                                      maintainOffset=True,
                                      name=downCluster + "_ParentConstraint")
                cmds.parentConstraint(self.chestB,
                                      upCluster,
                                      maintainOffset=True,
                                      name=upCluster + "_ParentConstraint")
                # organize a group of clusters:
                clustersGrp = cmds.group(name=side + self.userGuideName +
                                         "_Rbn_Clusters_Grp",
                                         empty=True)
                self.aClusterGrp.append(clustersGrp)
                if hideJoints:
                    cmds.setAttr(clustersGrp + ".visibility", 0)
                cmds.parent(downCluster, upCluster, clustersGrp, relative=True)
                # make ribbon joints groups scalable:
                for r, rbnJntGrp in enumerate(rbnJointGrpList):
                    if ((r > 0) and (r < (len(rbnJointGrpList) - 1))):
                        scaleGrp = cmds.group(rbnJntGrp,
                                              name=rbnJntGrp.replace(
                                                  "_Grp", "_Scale_Grp"))
                        ctrls.directConnect(scaleGrp, rbnJntGrp, ['sx', 'sz'])
                        cmds.scaleConstraint(clustersGrp,
                                             scaleGrp,
                                             maintainOffset=True,
                                             name=rbnJntGrp + "_Scale")
                    else:
                        cmds.scaleConstraint(clustersGrp,
                                             rbnJntGrp,
                                             maintainOffset=True,
                                             name=rbnJntGrp + "_Scale")
                # calculate the distance to volumeVariation:
                arcLenShape = cmds.createNode('arcLengthDimension',
                                              name=side + self.userGuideName +
                                              "_Rbn_ArcLenShape")
                arcLenFather = cmds.listRelatives(arcLenShape, parent=True)[0]
                arcLen = cmds.rename(arcLenFather,
                                     side + self.userGuideName + "_Rbn_ArcLen")
                arcLenShape = cmds.listRelatives(arcLen,
                                                 children=True,
                                                 shapes=True)[0]
                cmds.setAttr(arcLen + '.visibility', 0)
                # connect nurbsPlaneShape to arcLength node:
                cmds.connectAttr(rbnNurbsPlaneShape + '.worldSpace[0]',
                                 arcLenShape + '.nurbsGeometry')
                cmds.setAttr(arcLenShape + '.vParamValue', 1)
                # avoid undesired squash if rotateZ the nurbsPlane:
                cmds.setAttr(arcLenShape + '.uParamValue', 0.5)
                arcLenValue = cmds.getAttr(arcLenShape + '.arcLengthInV')
                # create a multiplyDivide to output the squashStretch values:
                rbnMD = cmds.createNode('multiplyDivide',
                                        name=side + self.userGuideName +
                                        "_Rbn_MD")
                cmds.connectAttr(arcLenShape + '.arcLengthInV',
                                 rbnMD + '.input2X')
                cmds.setAttr(rbnMD + '.input1X', arcLenValue)
                cmds.setAttr(rbnMD + '.operation', 2)
                # create a blendColor, a condition and a multiplyDivide in order to get the correct result value of volumeVariation:
                rbnBlendColors = cmds.createNode(
                    'blendColors',
                    name=side + self.userGuideName + "_Rbn_BlendColor")
                cmds.connectAttr(
                    self.hipsA + '.' + side + self.userGuideName + '_' +
                    self.langDic[self.langName]['c_volumeVariation'],
                    rbnBlendColors + '.blender')
                rbnCond = cmds.createNode('condition',
                                          name=side + self.userGuideName +
                                          '_Rbn_Cond')
                cmds.connectAttr(
                    self.hipsA + '.' + side + self.userGuideName + '_active_' +
                    self.langDic[self.langName]['c_volumeVariation'],
                    rbnCond + '.firstTerm')
                cmds.connectAttr(rbnBlendColors + '.outputR',
                                 rbnCond + '.colorIfTrueR')
                cmds.connectAttr(rbnMD + '.outputX',
                                 rbnBlendColors + '.color1R')
                rbnVVMD = cmds.createNode('multiplyDivide',
                                          name=side + self.userGuideName +
                                          "_Rbn_VV_MD")
                cmds.connectAttr(
                    self.hipsA + '.' + side + self.userGuideName +
                    '_masterScale_' +
                    self.langDic[self.langName]['c_volumeVariation'],
                    rbnVVMD + '.input2X')
                cmds.connectAttr(rbnVVMD + '.outputX',
                                 rbnCond + '.colorIfFalseR')
                cmds.setAttr(rbnVVMD + '.operation', 2)
                cmds.setAttr(rbnBlendColors + '.color2R', 1)
                cmds.setAttr(rbnCond + ".secondTerm", 1)
                # middle ribbon setup:
                for n in range(1, self.nJoints - 1):
                    if self.currentStyle == 0:  #default
                        self.middle = cmds.circle(
                            name=side + self.userGuideName + "_" +
                            self.langDic[self.langName]['c_middle'] + str(n) +
                            "_Ctrl",
                            ch=False,
                            o=True,
                            nr=(0, 0, 1),
                            d=3,
                            s=8,
                            radius=self.ctrlRadius)[0]
                        cmds.setAttr(self.middle + ".rotateOrder", 4)
                    else:  #biped
                        self.middle = cmds.circle(
                            name=side + self.userGuideName + "_" +
                            self.langDic[self.langName]['c_middle'] + str(n) +
                            "_Ctrl",
                            ch=False,
                            o=True,
                            nr=(0, 1, 0),
                            d=3,
                            s=8,
                            radius=self.ctrlRadius)[0]
                        cmds.setAttr(self.middle + ".rotateOrder", 3)
                    self.aFkCtrl[s].append(self.middle)
                    ctrls.setLockHide([self.middle], ['sx', 'sy', 'sz'])
                    cmds.setAttr(self.middle + '.visibility', keyable=False)
                    cmds.parent(self.middle, self.hipsA)
                    middleLocGuide = side + self.userGuideName + "_Guide_JointLoc" + str(
                        n + 1)
                    cmds.delete(
                        cmds.parentConstraint(middleLocGuide,
                                              self.middle,
                                              maintainOffset=False))
                    if self.currentStyle == 1:  #biped
                        cmds.rotate(0, 0, 0, self.middle)
                    utils.zeroOut([self.middle])
                    middleCluster = cmds.cluster(
                        rbnNurbsPlane + ".cv[0:3][" + str(n + 1) + "]",
                        name=side + self.userGuideName + '_Middle_Cls')[1]
                    middleLocPos = cmds.xform(side + self.userGuideName +
                                              "_Guide_JointLoc" + str(n),
                                              query=True,
                                              worldSpace=True,
                                              translation=True)
                    tempDel = cmds.parentConstraint(middleLocGuide,
                                                    middleCluster,
                                                    maintainOffset=False)
                    cmds.delete(tempDel)
                    middleClusterRot = cmds.xform(middleCluster,
                                                  query=True,
                                                  worldSpace=True,
                                                  rotation=True)
                    cmds.xform(middleCluster,
                               worldSpace=True,
                               rotation=(middleClusterRot[0] + 90,
                                         middleClusterRot[1],
                                         middleClusterRot[2]))
                    cmds.parentConstraint(self.middle,
                                          middleCluster,
                                          maintainOffset=True,
                                          name=middleCluster +
                                          "_ParentConstraint")
                    # parenting constraints like guide locators:
                    self.parentConst = cmds.parentConstraint(
                        self.hipsB,
                        self.chestB,
                        self.middle + "_Zero",
                        name=self.middle + "_ParentConstraint",
                        maintainOffset=True)[0]
                    nParentValue = (n) / float(self.nJoints - 1)
                    cmds.setAttr(self.parentConst + "." + self.hipsB + "W0",
                                 1 - nParentValue)
                    cmds.setAttr(self.parentConst + "." + self.chestB + "W1",
                                 nParentValue)
                    cmds.parent(middleCluster, clustersGrp, relative=True)
                    # add originedFrom attribute to this middle ctrl:
                    utils.originedFrom(objName=self.middle,
                                       attrString=middleLocGuide)
                    # apply volumeVariation to joints in the middle ribbon setup:
                    cmds.connectAttr(rbnCond + '.outColorR',
                                     self.aRbnJointList[n] + '.scaleX')
                    cmds.connectAttr(rbnCond + '.outColorR',
                                     self.aRbnJointList[n] + '.scaleZ')
                # update spine volume variation setup
                currentVV = cmds.getAttr(rbnMD + '.outputX')
                cmds.setAttr(rbnVVMD + '.input1X', currentVV)
                # organize groups:
                self.rbnRigGrp = cmds.group(name=side + self.userGuideName +
                                            "_Grp",
                                            empty=True)
                self.rbnControlGrp = cmds.group(
                    name=side + self.userGuideName + "_Control_Grp",
                    empty=True)
                cmds.parent(self.hipsA + "_Zero",
                            self.rbnControlGrp,
                            relative=True)
                cmds.parent(clustersGrp,
                            side + self.userGuideName + "_Rbn_RibbonJoint_Grp",
                            self.rbnControlGrp,
                            arcLen,
                            self.rbnRigGrp,
                            relative=True)
                if hideJoints:
                    cmds.setAttr(
                        side + self.userGuideName +
                        "_Rbn_RibbonJoint_Grp.visibility", 0)
                # add hook attributes to be read when rigging integrated modules:
                utils.addHook(objName=self.rbnControlGrp, hookType='ctrlHook')
                utils.addHook(objName=clustersGrp, hookType='scalableHook')
                utils.addHook(objName=self.rbnRigGrp, hookType='staticHook')
                cmds.addAttr(self.rbnRigGrp,
                             longName="dpAR_name",
                             dataType="string")
                cmds.addAttr(self.rbnRigGrp,
                             longName="dpAR_type",
                             dataType="string")
                cmds.setAttr(self.rbnRigGrp + ".dpAR_name",
                             self.userGuideName,
                             type="string")
                cmds.setAttr(self.rbnRigGrp + ".dpAR_type",
                             CLASS_NAME,
                             type="string")
                # add module type counter value
                cmds.addAttr(self.rbnRigGrp,
                             longName='dpAR_count',
                             attributeType='long',
                             keyable=False)
                cmds.setAttr(self.rbnRigGrp + '.dpAR_count', dpAR_count)
                # lockHide scale of up and down controls:
                ctrls.setLockHide(
                    [self.hipsA, self.hipsB, self.chestA, self.chestB],
                    ['sx', 'sy', 'sz'])
                # delete duplicated group for side (mirror):
                cmds.delete(side + self.userGuideName + '_' + self.mirrorGrp)
            # finalize this rig:
            self.integratingInfo()
            cmds.select(clear=True)
        # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
        self.deleteModule()
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()
Example #34
0
import maya.mel as mel

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

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

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

	cmds.parentConstraint(ctrlName, jntName, mo=True)
	cmds.scaleConstraint(ctrlName, jntName)
Example #35
0
def link(src_root, dst_root):

    srcs = collect_by_name(src_root, type='mesh')
    dsts = collect_by_name(dst_root, type='mesh')

    for name, src_node in sorted(srcs.iteritems()):

        dst_node = dsts.get(name)
        if not dst_node:
            continue

        # Only bother transferring attributes on meshes that have a connection
        # to an alembic node. This isn't a very strong connection, but it
        # seems to work for us.
        is_deformed = False
        for node in cmds.listHistory(src_node) or ():
            type_ = cmds.nodeType(node)
            if type_ == 'AlembicNode':
                is_deformed = True
                break
        if not is_deformed:
            continue

        print 'mesh {}: {} -> {}'.format(name, src_node, dst_node)

        src_transform = cmds.listRelatives(src_node, parent=True, path=True)[0]
        dst_transform = cmds.listRelatives(dst_node, parent=True, path=True)[0]

        transfer = cmds.transferAttributes(
            src_transform,
            dst_transform,
            afterReference=1,  # To play nice with references.
            transferPositions=1,
            transferNormals=1,
            sampleSpace=4,  # 4 == components
        )[0]

        print '    transferAttributes:', transfer

    srcs = collect_by_name(src_root, type='transform')
    dsts = collect_by_name(dst_root, type='transform')

    for name, src_node in sorted(srcs.iteritems()):

        dst_node = dsts.get(name)
        if not dst_node:
            continue

        print 'transform {}: {} -> {}'.format(name, src_node, dst_node)

        is_alembiced = False
        if True:
            for node in cmds.listConnections(src_node,
                                             skipConversionNodes=True,
                                             source=True,
                                             destination=False) or ():
                if cmds.nodeType(node) == 'AlembicNode':
                    is_alembiced = True
                    print '    is alembiced:', node
                    break

        is_animated = False
        if True:
            for attr in ('tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'):
                connections = cmds.listConnections('{}.{}'.format(
                    src_node, attr),
                                                   source=True,
                                                   destination=False)
                if connections:
                    is_animated = True
                    print '    is animated: {} is connected'.format(attr)
                    break

        is_transformed = False
        if True:
            for attr in ('tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'):
                src_value = cmds.getAttr('{}.{}'.format(src_node, attr))
                dst_value = cmds.getAttr('{}.{}'.format(dst_node, attr))
                if src_value != dst_value:
                    if abs(src_value - dst_value) > 1e-12:
                        is_transformed = True
                        print '    is transformed: src {} {} != dst {}'.format(
                            attr, src_value, dst_value)
                    else:
                        print '    has minor transform: src {} {} != dst {}'.format(
                            attr, src_value, dst_value)
                    break

        is_group = False
        has_shapes = False
        if True:
            children = cmds.listRelatives(src_node)
            child_shapes = cmds.listRelatives(src_node, shapes=True)

            has_shapes = bool(child_shapes)
            is_group = bool(children and not has_shapes)

            if is_group:
                print '    is group: {} children with no shapes'.format(
                    len(children))
            elif has_shapes:
                print '    has shapes: {} children with {} shapes'.format(
                    len(children), len(child_shapes))

        # Kevin asked to never constrain things which have shapes.
        do_constraint = (is_alembiced or is_animated
                         or is_transformed) and not has_shapes

        if do_constraint:

            # Bulk of transform is handled by a parent constraint...
            constraint = cmds.parentConstraint(src_node,
                                               dst_node,
                                               name='abc_link_parent_' +
                                               name)[0]
            print '    parentConstraint:', constraint
            constraint = cmds.scaleConstraint(src_node,
                                              dst_node,
                                              name='abc_link_scale_' + name)[0]
            print '    scaleConstraint:', constraint

        # We really do want to connect all the visibility regardless of animation.
        if name != 'hi':
            # ... and other attributed are done directly.
            for attr_name in ('visibility', ):
                cmds.connectAttr(src_node + '.' + attr_name,
                                 dst_node + '.' + attr_name,
                                 force=True)
                print '    {}: {} -> {}'.format(attr_name, src_node, dst_node)
Example #36
0
class ART_BakeOffsets():
    """
    This clas builds a UI that allows the rigger to select modules to bake offset mover values up to the global mover
    controls, making the offset movers no longer offset from their global mover parents. It can be found on the rig
    creator toolbar with the following icon:
        .. image:: /images/bakeOffsetsButton.png

    The full interface looks like this, listing found modules in the scene to select and bake offsets down to.
        .. image:: /images/bakeOffsets.png

    """
    def __init__(self, mainUI):
        """
        Instantiates the class, getting the QSettings and then calling on ART_BakeOffsetsUI.buildBakeOffsetsUI to
        create the interface.

        :param mainUI: The instance of the Rig Creator UI where this class was called from.

        .. seealso:: ART_BakeOffsetsUI.buildBakeOffsetsUI

        """

        # get the directory path of the tools
        settings = QtCore.QSettings("Epic Games", "ARTv2")
        self.toolsPath = settings.value("toolsPath")
        self.iconsPath = settings.value("iconPath")
        self.mainUI = mainUI

        # build the UI
        self.buildBakeOffsetsUI()

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    def buildBakeOffsetsUI(self):
        """
        Builds the interface, finding all modules and listing them for selection.

        """

        if cmds.window("ART_BakeOffsetsWin", exists=True):
            cmds.deleteUI("ART_BakeOffsetsWin", wnd=True)

        # launch a UI to get the name information
        self.bakeOffsetsWin = QtWidgets.QMainWindow(self.mainUI)

        # load stylesheet
        styleSheetFile = utils.returnNicePath(
            self.toolsPath,
            "Core/Scripts/Interfaces/StyleSheets/mainScheme.qss")
        f = open(styleSheetFile, "r")
        self.style = f.read()
        f.close()

        self.bakeOffsetsWin.setStyleSheet(self.style)

        # size policies
        mainSizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                               QtWidgets.QSizePolicy.Fixed)

        # create the main widget
        self.bakeOffsetsWin_mainWidget = QtWidgets.QWidget()
        self.bakeOffsetsWin.setCentralWidget(self.bakeOffsetsWin_mainWidget)

        # set qt object name
        self.bakeOffsetsWin.setObjectName("ART_BakeOffsetsWin")
        self.bakeOffsetsWin.setWindowTitle("Bake Offsets")

        # create the mainLayout for the rig creator UI
        self.bakeOffsetsWin_mainLayout = QtWidgets.QVBoxLayout(
            self.bakeOffsetsWin_mainWidget)
        self.bakeOffsetsWin_mainLayout.setContentsMargins(0, 0, 0, 0)

        self.bakeOffsetsWin.resize(400, 250)
        self.bakeOffsetsWin.setSizePolicy(mainSizePolicy)
        self.bakeOffsetsWin.setMinimumSize(QtCore.QSize(400, 250))
        self.bakeOffsetsWin.setMaximumSize(QtCore.QSize(400, 250))

        # create the background
        self.bakeOffsetsWin_frame = QtWidgets.QFrame()
        self.bakeOffsetsWin_mainLayout.addWidget(self.bakeOffsetsWin_frame)

        # create the layout for the widgets
        self.bakeOffsetsWin_widgetLayout = QtWidgets.QHBoxLayout(
            self.bakeOffsetsWin_frame)
        self.bakeOffsetsWin_widgetLayout.setContentsMargins(5, 5, 5, 5)

        # add the QListWidget Frame
        self.bakeOffsetsWin_moduleListFrame = QtWidgets.QFrame()
        self.bakeOffsetsWin_moduleListFrame.setMinimumSize(
            QtCore.QSize(265, 200))
        self.bakeOffsetsWin_moduleListFrame.setMaximumSize(
            QtCore.QSize(265, 200))
        self.bakeOffsetsWin_moduleListFrame.setContentsMargins(20, 0, 20, 0)

        # create the list widget
        self.bakeOffsetsWin_moduleList = QtWidgets.QListWidget(
            self.bakeOffsetsWin_moduleListFrame)
        self.bakeOffsetsWin_widgetLayout.addWidget(
            self.bakeOffsetsWin_moduleListFrame)
        self.bakeOffsetsWin_moduleList.setMinimumSize(QtCore.QSize(265, 200))
        self.bakeOffsetsWin_moduleList.setMaximumSize(QtCore.QSize(265, 200))
        self.bakeOffsetsWin_moduleList.setSelectionMode(
            QtWidgets.QAbstractItemView.MultiSelection)
        self.bakeOffsetsWin_moduleList.setSpacing(3)

        # add the layout for the buttons
        self.bakeOffsetsWin_buttonLayoutAll = QtWidgets.QVBoxLayout()
        self.bakeOffsetsWin_widgetLayout.addLayout(
            self.bakeOffsetsWin_buttonLayoutAll)
        self.bakeOffsetsWin_buttonLayoutAll.setContentsMargins(5, 20, 5, 20)

        # add the selection buttons
        self.bakeOffsetsWin_selectionButtonLayout = QtWidgets.QVBoxLayout()
        self.bakeOffsetsWin_buttonLayoutAll.addLayout(
            self.bakeOffsetsWin_selectionButtonLayout)
        self.bakeOffsetsWin_selectAllButton = QtWidgets.QPushButton(
            "Select All")
        self.bakeOffsetsWin_selectAllButton.setMinimumSize(
            QtCore.QSize(115, 25))
        self.bakeOffsetsWin_selectAllButton.setMaximumSize(
            QtCore.QSize(115, 25))
        self.bakeOffsetsWin_selectionButtonLayout.addWidget(
            self.bakeOffsetsWin_selectAllButton)
        self.bakeOffsetsWin_selectAllButton.clicked.connect(
            self.bakeOffsetsWin_moduleList.selectAll)
        self.bakeOffsetsWin_selectAllButton.setObjectName("blueButton")

        self.bakeOffsetsWin_selectNoneButton = QtWidgets.QPushButton(
            "Clear Selection")
        self.bakeOffsetsWin_selectNoneButton.setMinimumSize(
            QtCore.QSize(115, 25))
        self.bakeOffsetsWin_selectNoneButton.setMaximumSize(
            QtCore.QSize(115, 25))
        self.bakeOffsetsWin_selectionButtonLayout.addWidget(
            self.bakeOffsetsWin_selectNoneButton)
        self.bakeOffsetsWin_selectNoneButton.clicked.connect(
            self.bakeOffsetsWin_moduleList.clearSelection)
        self.bakeOffsetsWin_selectNoneButton.setObjectName("blueButton")

        # spacer
        spacerItem = QtWidgets.QSpacerItem(20, 80,
                                           QtWidgets.QSizePolicy.Minimum,
                                           QtWidgets.QSizePolicy.Expanding)
        self.bakeOffsetsWin_selectionButtonLayout.addItem(spacerItem)

        # add the buttons for reset settings and reset transforms
        self.bakeOffsetsWin_bakeOFfsetsBtn = QtWidgets.QPushButton(
            "Bake Offsets")
        self.bakeOffsetsWin_bakeOFfsetsBtn.setMinimumSize(QtCore.QSize(
            115, 25))
        self.bakeOffsetsWin_bakeOFfsetsBtn.setMaximumSize(QtCore.QSize(
            115, 25))
        self.bakeOffsetsWin_selectionButtonLayout.addWidget(
            self.bakeOffsetsWin_bakeOFfsetsBtn)
        self.bakeOffsetsWin_bakeOFfsetsBtn.setToolTip(
            "Turn on Aim Mode for selected modules.")
        self.bakeOffsetsWin_bakeOFfsetsBtn.clicked.connect(
            partial(self.bakeOffsets))
        self.bakeOffsetsWin_bakeOFfsetsBtn.setObjectName("blueButton")

        # populate the list widget
        modules = utils.returnRigModules()
        for module in modules:
            # get module name
            moduleName = cmds.getAttr(module + ".moduleName")
            if moduleName != "root":
                self.bakeOffsetsWin_moduleList.addItem(moduleName)

        # show the window
        self.bakeOffsetsWin.show()

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    def bakeOffsets(self):
        """
        Tales selected modules listed in the QListWidget and bakes the offset mover values up to the global mover
        parent. This is achieved by creating a locator in the space of the offset mover, zeroing the offset mover
        out, and constraining the global mover to the constraint. Finally, the constraints are removed and the
        locators deleted.

        """

        selected = self.bakeOffsetsWin_moduleList.selectedItems()
        items = []
        for each in selected:
            items.append(each.text())

        constraints = []
        locators = []

        # go through each module and create the locators for the offset movers
        for each in self.mainUI.moduleInstances:
            name = each.name
            if name in items:

                # get movers
                jointMovers = each.returnJointMovers

                # separate mover lists
                globalMovers = jointMovers[0]
                offsetMovers = jointMovers[1]

                # create locators for the offsetMovers, then zero out offset mover
                for mover in offsetMovers:
                    locatorName = mover.partition("_offset")[0] + "_loc"
                    loc = cmds.spaceLocator(name=locatorName)[0]

                    # constrain locator
                    constraint = cmds.parentConstraint(mover, loc)[0]
                    cmds.delete(constraint)

                    # parent locator under a copy of the locatorName
                    parentLoc = cmds.duplicate(loc)[0]
                    cmds.parent(loc, parentLoc)
                    locators.append(parentLoc)

                for mover in offsetMovers:
                    for attr in [".tx", ".ty", ".tz", ".rx", ".ry", ".rz"]:
                        try:
                            cmds.setAttr(mover + attr, 0)
                        except:
                            pass

        # now, for each global mover, find child groups that are constrained to them
        for each in self.mainUI.moduleInstances:
            name = each.name
            if name in items:
                # get movers
                jointMovers = each.returnJointMovers

                # separate mover lists
                globalMovers = jointMovers[0]
                offsetMovers = jointMovers[1]

                childGrps = []

                for mover in globalMovers:
                    try:

                        # find the mover group constrained to this mover (if any)
                        connection = cmds.listConnections(
                            mover, type="parentConstraint")[0]
                        grp = cmds.listConnections(connection +
                                                   ".constraintRotateX")[0]
                        if grp.find("_mover_grp") != -1:
                            childGrps.append([mover, grp])

                        # now take this group and delete the constraints
                        cmds.select(grp)
                        cmds.delete(constraints=True)

                    except Exception, e:
                        print e

        # now snap global movers to offset movers
        for each in self.mainUI.moduleInstances:
            name = each.name
            if name in items:
                # get movers
                jointMovers = each.returnJointMovers

                # separate mover lists
                globalMovers = jointMovers[0]
                offsetMovers = jointMovers[1]

                for mover in globalMovers:
                    if cmds.objExists(mover + "_loc"):
                        constraint = cmds.parentConstraint(
                            mover + "_loc", mover)[0]
                        constraints.append(constraint)

        # now remove all locs
        for const in constraints:
            cmds.delete(const)

        for loc in locators:
            cmds.delete(loc)

        # finally, reconstrain mover_grps to their movers
        cmds.refresh(force=True)
        for group in childGrps:
            cmds.parentConstraint(group[0], group[1], mo=True)
            cmds.scaleConstraint(group[0], group[1])

        cmds.select(clear=True)
Example #37
0
    def dpMatchMesh(self, *args):
        """ Get selection and transfere vertice information.
        """
        # declaring variables
        fromTransformDic, toTransformDic = {}, {}
        attrList = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz']

        # get a list of selected items
        selList = cmds.ls(selection=True)

        if (len(selList) <= 1):
            cmds.warning(
                "Select the FROM mesh first and the TO mesh after to transfer vertice data."
            )
        else:
            # declaring current variables
            fromFather = None
            fromTransform = selList[0]
            toTransform = selList[1]
            fromMesh = selList[0]
            toMesh = selList[1]
            gotMeshes = True

            # getting transforms
            if cmds.objectType(selList[0]) != "transform":
                parentList = cmds.listRelatives(selList[0],
                                                allParents=True,
                                                type="transform")
                if parentList:
                    fromTransform = parentList[0]
            if cmds.objectType(selList[1]) != "transform":
                parentList = cmds.listRelatives(selList[1],
                                                allParents=True,
                                                type="transform")
                if parentList:
                    toTransform = parentList

            # getting fromTransform father
            fromFatherList = cmds.listRelatives(fromTransform,
                                                allParents=True,
                                                type="transform")
            if fromFatherList:
                fromFather = fromFatherList[0]

            # getting meshes
            if cmds.objectType(selList[0]) != "mesh":
                childrenList = cmds.listRelatives(selList[0],
                                                  children=True,
                                                  type="mesh")
                if childrenList:
                    fromMesh = childrenList[0]
                else:
                    gotMeshes = False
            if cmds.objectType(selList[1]) != "mesh":
                childrenList = cmds.listRelatives(selList[1],
                                                  children=True,
                                                  type="mesh")
                if childrenList:
                    toMesh = childrenList[0]
                else:
                    gotMeshes = False

            if gotMeshes:
                # storing transformation data
                for attr in attrList:
                    fromTransformDic[attr] = cmds.getAttr(fromTransform + "." +
                                                          attr)
                    toTransformDic[attr] = cmds.getAttr(toTransform + "." +
                                                        attr)

                # get list of mesh vertice proccess
                # selecting meshes
                cmds.select([fromMesh, toMesh])
                meshList = om.MSelectionList()
                om.MGlobal_getActiveSelectionList(meshList)

                # declaring from and to objects, dagPaths and vertice lists
                fromObject = om.MObject()
                fromDagPath = om.MDagPath()
                toObject = om.MObject()
                toDagPath = om.MDagPath()
                fromVerticeList = om.MPointArray()
                toVerticeList = om.MPointArray()

                # getting dagPaths
                meshList.getDagPath(0, fromDagPath, fromObject)
                meshList.getDagPath(1, toDagPath, toObject)
                # getting open maya API mesh
                fromMeshFn = om.MFnMesh(fromDagPath)
                toMeshFn = om.MFnMesh(toDagPath)

                # verify the same number of vertices
                if fromMeshFn.numVertices() == toMeshFn.numVertices():
                    # put fromTransform in the same location then toTransform
                    if fromFather != None:
                        cmds.parent(fromTransform, world=True)
                    for attr in attrList:
                        if not "s" in attr:
                            cmds.setAttr(fromTransform + "." + attr, 0)
                            cmds.setAttr(toTransform + "." + attr, 0)
                        else:
                            cmds.setAttr(fromTransform + "." + attr, 1)
                            cmds.setAttr(toTransform + "." + attr, 1)
                    tempToDeleteA = cmds.parentConstraint(fromTransform,
                                                          toTransform,
                                                          maintainOffset=False)
                    tempToDeleteB = cmds.scaleConstraint(fromTransform,
                                                         toTransform,
                                                         maintainOffset=False)
                    cmds.delete(tempToDeleteA, tempToDeleteB)

                    # getting vertices as points
                    fromMeshFn.getPoints(fromVerticeList)
                    toMeshFn.getPoints(toVerticeList)

                    # progress window
                    progressAmount = 0
                    cmds.progressWindow(title='Match Mesh Data',
                                        progress=progressAmount,
                                        status='Tranfering: 0%',
                                        isInterruptable=True)
                    cancelled = False

                    # transfer vetex position from FROM mesh to TO mesh selected
                    nbVertice = fromVerticeList.length()
                    for i in range(0, fromVerticeList.length()):
                        # update progress window
                        progressAmount += 1
                        # check if the dialog has been cancelled
                        if cmds.progressWindow(query=True, isCancelled=True):
                            cancelled = True
                            break
                        cmds.progressWindow(
                            edit=True,
                            maxValue=nbVertice,
                            progress=progressAmount,
                            status=('Transfering: ' + ` progressAmount ` +
                                    ' vertex'))

                        # transfer data
                        cmds.move(fromVerticeList[i].x,
                                  fromVerticeList[i].y,
                                  fromVerticeList[i].z,
                                  toMesh + ".vtx[" + str(i) + "]",
                                  absolute=True)

                    cmds.progressWindow(endProgress=True)

                    if fromFather != None:
                        cmds.parent(fromTransform, fromFather)
                    # restore transformation data
                    for attr in attrList:
                        cmds.setAttr(fromTransform + "." + attr,
                                     fromTransformDic[attr])
                        cmds.setAttr(toTransform + "." + attr,
                                     toTransformDic[attr])

                    if not cancelled:
                        print self.langDic[
                            self.langName]['i035_transfData'], self.langDic[
                                self.langName]['i036_from'].upper(
                                ), ":", fromMesh, ",", self.langDic[
                                    self.langName]['i037_to'].upper(
                                    ), ":", toMesh
                    else:
                        print self.langDic[self.langName]['i038_canceled']

                else:
                    mel.eval("warning \"" +
                             self.langDic[self.langName]['i039_notMatchDif'] +
                             "\";")
                cmds.select(selList)

            else:
                mel.eval("warning \"" +
                         self.langDic[self.langName]['i040_notMatchSel'] +
                         "\";")
Example #38
0
def bind_skeletons(source,
                   dest,
                   method='connect',
                   scales=False,
                   verbose=False):
    '''
    From 2 given root joints search through each hierarchy for child joints, match
    them based on node name, then connect their trans/rots directly, or
    parentConstrain them. Again cmds for speed

    :param source: the root node of the driving skeleton
    :param dest: the root node of the driven skeleton
    :param method: the method used for the connection, either 'connect' or 'constrain'
    :param scale: do we bind the scales of the destination skel to the source??
    '''

    sourceJoints = cmds.listRelatives(source, ad=True, f=True, type='joint')
    destJoints = cmds.listRelatives(dest, ad=True, f=True, type='joint')

    if verbose:
        result = cmds.confirmDialog(
            title='Bind Skeletons SCALES',
            message=
            ("Would you also like to process the SCALE channels within the bind?"
             ),
            button=['Yes', 'No'],
            messageAlign='center',
            icon='question',
            dismissString='Cancel')
        if result == 'Yes':
            scales = True
        else:
            scales = False

    # parent constrain the root nodes regardless of bindType, fixes issues where
    # we have additional rotated parent groups on the source
    cmds.parentConstraint(source, dest)
    if scales:
        cmds.scaleConstraint(source, dest, mo=True)

    attrs = [
        'rotateX', 'rotateY', 'rotateZ', 'translateX', 'translateY',
        'translateZ'
    ]
    if scales:
        attrs = attrs + ['scaleX', 'scaleY', 'scaleZ']

    for sJnt, dJnt in match_given_hierarchys(sourceJoints, destJoints):
        if method == 'connect':
            for attr in attrs:
                try:
                    cmds.connectAttr('%s.%s' % (sJnt, attr),
                                     '%s.%s' % (dJnt, attr),
                                     f=True)
                except:
                    pass
        elif method == 'constrain':
            # need to see if the channels are open if not, change this binding code
            try:
                cmds.parentConstraint(sJnt, dJnt, mo=True)
            except:
                chns = r9Anim.getSettableChannels(dJnt)
                if all([
                        'translateX' in chns, 'translateY' in chns,
                        'translateZ' in chns
                ]):
                    cmds.pointConstraint(sJnt, dJnt, mo=True)
                elif all(
                    ['rotateX' in chns, 'rotateY' in chns, 'rotateZ' in chns]):
                    cmds.orientConstraint(sJnt, dJnt, mo=True)
                else:
                    log.info('Failed to Bind joints: %s >> %s' % (sJnt, dJnt))

            # if we have incoming scale connections then run the scaleConstraint
            if scales:  # and cmds.listConnections('%s.sx' % sJnt):
                try:
                    cmds.scaleConstraint(sJnt, dJnt, mo=True)
                    # turn off the compensation so that the rig can still be scaled correctly by the MasterNode
                    # cmds.setAttr('%s.segmentScaleCompensate' % dJnt, 0)
                except:
                    print 'failed : scales ', dJnt
Example #39
0
    def createModule(self):
        """
        Instantiate our module class to create with the user specified name, creating the network node, building
        the Skeleton Settings UI for the module, adding the joint mover for that module (importing the joint mover
        file), and adding the joint mover to the outliner.

        """

        mod = __import__("RigModules." + self.className, {}, {},
                         [self.className])
        reload(mod)

        # get the class name from that module file (returns RigModules.ART_Root.ART_Root for example)
        moduleClass = getattr(mod, mod.className)
        jmPath = mod.jointMover

        # find the instance of that module and call on the skeletonSettings_UI function
        userSpecName = str(self.previewName.text())

        # check to see if a module already has that name
        modules = utils.returnRigModules()
        validName = False
        for module in modules:
            name = cmds.getAttr(module + ".moduleName")
            if name == userSpecName:
                cmds.confirmDialog(
                    title="Name Exists",
                    message=
                    "A module with that name already exists. Please enter a unique name.",
                    icon="critical")
                return

        # call functions to create network node, skeleton settings UI
        moduleInst = moduleClass(self.rigUiInst, userSpecName)
        self.rigUiInst.moduleInstances.append(
            moduleInst
        )  # add this instance to the ui's list of module instances
        networkNode = moduleInst.buildNetwork()

        # figure out side
        specialCaseModules = ["ART_Leg_Standard", "ART_Arm_Standard"]
        if self.className in specialCaseModules:
            side = "Left"
            if self.rightRadioBtn.isChecked():
                side = "Right"
                cmds.setAttr(networkNode + ".side", lock=False)
                cmds.setAttr(networkNode + ".side",
                             "Right",
                             type="string",
                             lock=True)

            # build new jmPath name
            jmPath = jmPath.partition(".ma")[0] + "_" + side + ".ma"

        moduleInst.skeletonSettings_UI(userSpecName)
        moduleInst.jointMover_Build(jmPath)
        moduleInst.addJointMoverToOutliner()

        # update the created joints attribute on the network node with the new names
        prefix = str(self.prefix.text())
        suffix = str(self.suffix.text())

        if len(prefix) > 0:
            prefix = prefix + "_"
        if len(suffix) > 0:
            suffix = "_" + suffix

        createdBones = cmds.getAttr(networkNode + ".Created_Bones")
        createdBones = createdBones.split("::")

        attrString = ""
        for bone in createdBones:
            if len(bone) > 1:
                attrString += prefix + bone + suffix + "::"

        cmds.setAttr(networkNode + ".Created_Bones", lock=False)
        cmds.setAttr(networkNode + ".Created_Bones",
                     attrString,
                     type="string",
                     lock=True)

        # update the self.currentParent label and the parentModuleBone attr on the network node
        parent = (self.hierarchyTree.currentItem().text())
        moduleInst.currentParent.setText(parent)

        cmds.setAttr(networkNode + ".parentModuleBone", lock=False)
        cmds.setAttr(networkNode + ".parentModuleBone",
                     parent,
                     type="string",
                     lock=True)

        # parent the joint mover to the offset mover of the parent
        mover = ""

        if parent == "root":
            mover = "root_mover"

        else:
            # find the parent mover name to parent to
            networkNodes = utils.returnRigModules()
            mover = utils.findMoverNodeFromJointName(networkNodes, parent,
                                                     False, True)

        if mover is not None:
            cmds.parentConstraint(mover, userSpecName + "_mover_grp", mo=True)
            cmds.scaleConstraint(mover, userSpecName + "_mover_grp")

        # create the connection geo between the two
        globalMover = utils.findGlobalMoverFromName(userSpecName)
        cmds.select(globalMover)
        cmds.setToolTo("moveSuperContext")

        utils.fitViewAndShade()

        # delete the UI
        cmds.deleteUI(windowObject)

        # obey the current UI visibility toggles
        self.rigUiInst.setMoverVisibility()
        moduleInst.updateBoneCount()
        self.rigUiInst.populateNetworkList()

        # turn on aim mode
        moduleInst.aimMode(True)
Example #40
0
    def createGuide(self, *args):
        Base.StartClass.createGuide(self)
        # Custom GUIDE:
        cmds.addAttr(self.moduleGrp, longName="flip", attributeType='bool')
        cmds.setAttr(self.moduleGrp + ".flip", 0)

        cmds.addAttr(self.moduleGrp,
                     longName="indirectSkin",
                     attributeType='bool')
        cmds.setAttr(self.moduleGrp + ".indirectSkin", 0)
        cmds.addAttr(self.moduleGrp, longName='holder', attributeType='bool')
        cmds.setAttr(self.moduleGrp + ".holder", 0)
        cmds.addAttr(self.moduleGrp,
                     longName='sdkLocator',
                     attributeType='bool')
        cmds.setAttr(self.moduleGrp + ".sdkLocator", 0)

        cmds.setAttr(self.moduleGrp + ".moduleNamespace",
                     self.moduleGrp[:self.moduleGrp.rfind(":")],
                     type='string')

        self.cvJointLoc = self.ctrls.cvJointLoc(ctrlName=self.guideName +
                                                "_JointLoc1",
                                                r=0.3,
                                                d=1,
                                                guide=True)
        self.jGuide1 = cmds.joint(name=self.guideName + "_JGuide1",
                                  radius=0.001)
        cmds.setAttr(self.jGuide1 + ".template", 1)
        cmds.parent(self.jGuide1, self.moduleGrp, relative=True)

        self.cvEndJoint = self.ctrls.cvLocator(ctrlName=self.guideName +
                                               "_JointEnd",
                                               r=0.1,
                                               d=1,
                                               guide=True)
        cmds.parent(self.cvEndJoint, self.cvJointLoc)
        cmds.setAttr(self.cvEndJoint + ".tz", 1.3)
        self.jGuideEnd = cmds.joint(name=self.guideName + "_JGuideEnd",
                                    radius=0.001)
        cmds.setAttr(self.jGuideEnd + ".template", 1)
        cmds.transformLimits(self.cvEndJoint, tz=(0.01, 1), etz=(True, False))
        self.ctrls.setLockHide(
            [self.cvEndJoint],
            ['tx', 'ty', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])

        cmds.parent(self.cvJointLoc, self.moduleGrp)
        cmds.parent(self.jGuideEnd, self.jGuide1)
        cmds.parentConstraint(self.cvJointLoc,
                              self.jGuide1,
                              maintainOffset=False,
                              name=self.jGuide1 + "_PaC")
        cmds.parentConstraint(self.cvEndJoint,
                              self.jGuideEnd,
                              maintainOffset=False,
                              name=self.jGuideEnd + "_PaC")
        cmds.scaleConstraint(self.cvJointLoc,
                             self.jGuide1,
                             maintainOffset=False,
                             name=self.jGuide1 + "_ScC")
        cmds.scaleConstraint(self.cvEndJoint,
                             self.jGuideEnd,
                             maintainOffset=False,
                             name=self.jGuideEnd + "_ScC")
Example #41
0
def makeribbon():
    spans = 2
    pointlist = [(0, 0, 0), (.30, 0, 0)]
    knotlist = [0, 0, 0]
    clusterlist = []
    offsetgrpfklist = []
    circlefklist = []
    for each in range(1, spans):
        pointlist += (each - .30, 0, 0), (each, 0, 0), (each + .30, 0, 0)
        knotlist += [each, each, each]
    pointlist += (spans - .30, 0, 0), (spans, 0, 0)
    knotlist += [spans, spans, spans]
    curvename = cmds.curve(bezier=1, d=3, p=pointlist, k=knotlist)
    curvename2 = cmds.duplicate(curvename, rr=1, ic=1)
    cmds.move(0, 0, .5, curvename)
    cmds.move(0, 0, -.5, curvename2[0])
    cmds.loft(curvename, curvename2[0])
    newcluster = cmds.cluster(
        str(curvename) + '.cv[0]',
        str(curvename) + '.cv[1]',
        str(curvename2[0]) + '.cv[0]',
        str(curvename2[0]) + '.cv[1]')
    clusterlist.append(newcluster[1])
    for each in range(1, spans):
        newcluster = cmds.cluster(
            str(curvename) + '.cv[' + str(3 * each - 1) + ']',
            str(curvename) + '.cv[' + str(3 * each) + ']',
            str(curvename) + '.cv[' + str(3 * each + 1) + ']',
            str(curvename2[0]) + '.cv[' + str(3 * each - 1) + ']',
            str(curvename2[0]) + '.cv[' + str(3 * each) + ']',
            str(curvename2[0]) + '.cv[' + str(3 * each + 1) + ']')
        clusterlist.append(newcluster[1])
    newcluster = cmds.cluster(
        str(curvename) + '.cv[' + str(3 * spans - 1) + ']',
        str(curvename) + '.cv[' + str(3 * spans) + ']',
        str(curvename2[0]) + '.cv[' + str(3 * spans - 1) + ']',
        str(curvename2[0]) + '.cv[' + str(3 * spans) + ']')
    clusterlist.append(newcluster[1])
    cmds.move(0, 0, 0, clusterlist[0] + '.scalePivot',
              clusterlist[0] + '.rotatePivot')
    cmds.setAttr(clusterlist[0] + 'Shape.originX', 0)
    cmds.move(spans, 0, 0, clusterlist[-1] + '.scalePivot',
              clusterlist[-1] + '.rotatePivot')
    cmds.setAttr(clusterlist[-1] + 'Shape.originX', spans)
    for each in clusterlist:
        circle = cmds.circle(n='ctrl_' + each, nrx=1, nrz=0, r=.5)
        circlefk = cmds.circle(n='ctrl_FK_' + each, nrx=1, nrz=0, r=1)
        circlefklist.append(circlefk[0])
        offsetgrp = cmds.group(circle[0], n='ctrl_' + each + '_offset')
        offsetgrpfk = cmds.group(circlefk[0], n='ctrl_FK_' + each + '_offset')
        offsetgrpfklist.append(offsetgrpfk)
        clustcoord = cmds.getAttr(each + 'Shape.origin')
        cmds.move(clustcoord[0][0], clustcoord[0][1], clustcoord[0][2],
                  offsetgrp)
        cmds.move(clustcoord[0][0] - 0.5, clustcoord[0][1], clustcoord[0][2],
                  offsetgrpfk)
        prtcst = cmds.parentConstraint(circle[0], each, mo=1)
        prtcstfk = cmds.parentConstraint(circlefk[0], offsetgrp, mo=1)
        cmds.scaleConstraint(circle[0], each)
        cmds.disconnectAttr(circle[0] + '.scale',
                            prtcst[0] + '.target[0].targetScale')
        cmds.disconnectAttr(circlefk[0] + '.scale',
                            prtcstfk[0] + '.target[0].targetScale')
    for each in range(1, len(offsetgrpfklist)):
        parentcst_fk = cmds.parentConstraint(circlefklist[each - 1],
                                             offsetgrpfklist[each],
                                             mo=1)
        cmds.disconnectAttr(circlefklist[each - 1] + '.scale',
                            parentcst_fk[0] + '.target[0].targetScale')
Example #42
0
    def rigModule(self, *args):
        Base.StartClass.rigModule(self)
        # verify if the guide exists:
        if cmds.objExists(self.moduleGrp):
            try:
                hideJoints = cmds.checkBox('hideJointsCB', query=True, value=True)
            except:
                hideJoints = 1
            # declare lists to store names and attributes:
            self.suspensionBCtrlGrpList, self.fatherBList, self.ctrlHookGrpList = [], [], []
            # start as no having mirror:
            sideList = [""]
            # analisys the mirror module:
            self.mirrorAxis = cmds.getAttr(self.moduleGrp+".mirrorAxis")
            if self.mirrorAxis != 'off':
                # get rigs names:
                self.mirrorNames = cmds.getAttr(self.moduleGrp+".mirrorName")
                # get first and last letters to use as side initials (prefix):
                sideList = [ self.mirrorNames[0]+'_', self.mirrorNames[len(self.mirrorNames)-1]+'_' ]
                for s, side in enumerate(sideList):
                    duplicated = cmds.duplicate(self.moduleGrp, name=side+self.userGuideName+'_Guide_Base')[0]
                    allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
                    for item in allGuideList:
                        cmds.rename(item, side+self.userGuideName+"_"+item)
                    self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True)
                    cmds.parent(side+self.userGuideName+'_Guide_Base', self.mirrorGrp, absolute=True)
                    # re-rename grp:
                    cmds.rename(self.mirrorGrp, side+self.userGuideName+'_'+self.mirrorGrp)
                    # do a group mirror with negative scaling:
                    if s == 1:
                        if cmds.getAttr(self.moduleGrp+".flip") == 0:
                            for axis in self.mirrorAxis:
                                gotValue = cmds.getAttr(side+self.userGuideName+"_Guide_Base.translate"+axis)
                                flipedValue = gotValue*(-2)
                                cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.translate'+axis, flipedValue)
                        else:
                            for axis in self.mirrorAxis:
                                cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.scale'+axis, -1)
                # joint labelling:
                jointLabelAdd = 1
            else: # if not mirror:
                duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName+'_Guide_Base')[0]
                allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
                for item in allGuideList:
                    cmds.rename(item, self.userGuideName+"_"+item)
                self.mirrorGrp = cmds.group(self.userGuideName+'_Guide_Base', name="Guide_Base_Grp", relative=True)
                #for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp"
                # re-rename grp:
                cmds.rename(self.mirrorGrp, self.userGuideName+'_'+self.mirrorGrp)
                # joint labelling:
                jointLabelAdd = 0
            # store the number of this guide by module type
            dpAR_count = utils.findModuleLastNumber(CLASS_NAME, "dpAR_type") + 1
            # run for all sides
            for s, side in enumerate(sideList):
                # declare guide:
                self.base = side+self.userGuideName+'_Guide_Base'
                self.cvALoc = side+self.userGuideName+"_Guide_JointLocA"
                self.cvBLoc = side+self.userGuideName+"_Guide_JointLocB"
                self.locatorsGrp = cmds.group(name=side+self.userGuideName+"_Loc_Grp", empty=True)
                # calculate distance between guide and end:
                self.dist = self.ctrls.distanceBet(self.cvALoc, self.cvBLoc)[0] * 0.2
                self.jointList, self.mainCtrlList, self.ctrlZeroList, self.ctrlList, self.aimLocList, self.upLocList = [], [], [], [], [], []
                for p, letter in enumerate(["A", "B"]):
                    # create joints:
                    cmds.select(clear=True)
                    jnt = cmds.joint(name=side+self.userGuideName+"_"+letter+"_1_Jnt", scaleCompensate=False)
                    endJoint = cmds.joint(name=side+self.userGuideName+"_"+letter+"_JEnd", scaleCompensate=False)
                    cmds.addAttr(jnt, longName='dpAR_joint', attributeType='float', keyable=False)
                    cmds.setAttr(endJoint+".translateZ", self.dist)
                    # joint labelling:
                    utils.setJointLabel(jnt, s+jointLabelAdd, 18, self.userGuideName+"_"+letter)
                    self.jointList.append(jnt)
                    
                    # create a control:
                    mainCtrl = self.ctrls.cvControl("id_055_SuspensionMain", side+self.userGuideName+"_"+self.langDic[self.langName]["c058_main"]+"_"+letter+"_Ctrl", r=self.ctrlRadius, d=self.curveDegree)
                    ctrl = self.ctrls.cvControl("id_056_SuspensionAB", side+self.userGuideName+"_"+letter+"_Ctrl", r=self.ctrlRadius*0.5, d=self.curveDegree)
                    upLocCtrl = self.ctrls.cvControl("id_057_SuspensionUpLoc", side+self.userGuideName+"_"+letter+"_UpLoc_Ctrl", r=self.ctrlRadius*0.1, d=self.curveDegree)
                    self.ctrls.setLockHide([ctrl], ['tx', 'ty', 'tz', 'v'])
                    self.ctrls.setLockHide([upLocCtrl], ['rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'])
                    # position and orientation of joint and control:
                    cmds.parent(ctrl, upLocCtrl, mainCtrl)
                    cmds.parentConstraint(ctrl, jnt, maintainOffset=False, name=jnt+"_ParentConstraint")
                    cmds.scaleConstraint(ctrl, jnt, maintainOffset=False, name=jnt+"_ScaleConstraint")
                    self.ctrlList.append(ctrl)
                    # zeroOut controls:
                    zeroOutCtrlGrp = utils.zeroOut([mainCtrl, ctrl, upLocCtrl])
                    self.mainCtrlList.append(zeroOutCtrlGrp[0])
                    self.ctrlZeroList.append(zeroOutCtrlGrp[1])
                    cmds.setAttr(zeroOutCtrlGrp[2]+".translateX", self.dist)
                    # origined from data:
                    if p == 0:
                        utils.originedFrom(objName=mainCtrl, attrString=self.base+";"+self.cvALoc)
                        utils.originedFrom(objName=ctrl, attrString=self.base+";"+self.cvALoc)
                        cmds.delete(cmds.parentConstraint(self.cvALoc, zeroOutCtrlGrp[0], maintainOffset=False))
                    else:
                        utils.originedFrom(objName=mainCtrl, attrString=self.cvBLoc)
                        utils.originedFrom(objName=ctrl, attrString=self.cvBLoc)
                        cmds.delete(cmds.parentConstraint(self.cvBLoc, zeroOutCtrlGrp[0], maintainOffset=False))
                        # integrating data:
                        self.suspensionBCtrlGrpList.append(zeroOutCtrlGrp[0])
                    # hide visibility attribute:
                    cmds.setAttr(mainCtrl+'.visibility', keyable=False)
                    # fixing flip mirror:
                    if s == 1:
                        if cmds.getAttr(self.moduleGrp+".flip") == 1:
                            cmds.setAttr(zeroOutCtrlGrp[0]+".scaleX", -1)
                            cmds.setAttr(zeroOutCtrlGrp[0]+".scaleY", -1)
                            cmds.setAttr(zeroOutCtrlGrp[0]+".scaleZ", -1)
                    cmds.addAttr(ctrl, longName='scaleCompensate', attributeType="bool", keyable=False)
                    cmds.setAttr(ctrl+".scaleCompensate", 1, channelBox=True)
                    cmds.connectAttr(ctrl+".scaleCompensate", jnt+".segmentScaleCompensate", force=True)
                    
                    # working with aim setup:
                    cmds.addAttr(ctrl, longName="active", attributeType="bool", defaultValue=1, keyable=True)
                    aimLoc = cmds.spaceLocator(name=side+self.userGuideName+"_"+letter+"_Aim_Loc")[0]
                    upLoc = cmds.spaceLocator(name=side+self.userGuideName+"_"+letter+"_Up_Loc")[0]
                    locGrp = cmds.group(aimLoc, upLoc, name=side+self.userGuideName+"_"+letter+"_Loc_Grp")
                    cmds.parent(locGrp, self.locatorsGrp, relative=True)
                    cmds.delete(cmds.parentConstraint(ctrl, locGrp, maintainOffset=False))
                    cmds.parentConstraint(upLocCtrl, upLoc, maintainOffset=False, name=upLoc+"_ParentConstraint")
                    cmds.parentConstraint(mainCtrl, locGrp, maintainOffset=True, name=locGrp+"_ParentConstraint")
                    cmds.setAttr(locGrp+".visibility", 0)
                    self.aimLocList.append(aimLoc)
                    self.upLocList.append(upLoc)

                # aim constraints:
                # B to A:
                aAimConst = cmds.aimConstraint(self.aimLocList[1], self.ctrlZeroList[0], aimVector=(0, 0, 1), upVector=(1, 0, 0), worldUpType="object", worldUpObject=self.upLocList[0], maintainOffset=True, name=self.ctrlZeroList[0]+"_AimConstraint")[0]
                cmds.connectAttr(self.ctrlList[0]+".active", aAimConst+"."+self.aimLocList[1]+"W0", force=True)
                # A to B:
                bAimConst = cmds.aimConstraint(self.aimLocList[0], self.ctrlZeroList[1], aimVector=(0, 0, 1), upVector=(1, 0, 0), worldUpType="object", worldUpObject=self.upLocList[1], maintainOffset=True, name=self.ctrlZeroList[0]+"_AimConstraint")[0]
                cmds.connectAttr(self.ctrlList[1]+".active", bAimConst+"."+self.aimLocList[0]+"W0", force=True)
                
                # integrating data:
                self.loadedFatherB = cmds.getAttr(self.moduleGrp+".fatherB")
                if self.loadedFatherB:
                    self.fatherBList.append(self.loadedFatherB)
                else:
                    self.fatherBList.append(None)
                
                # create a masterModuleGrp to be checked if this rig exists:
                self.toCtrlHookGrp     = cmds.group(self.mainCtrlList, name=side+self.userGuideName+"_Control_Grp")
                self.toScalableHookGrp = cmds.group(self.jointList, name=side+self.userGuideName+"_Joint_Grp")
                self.toStaticHookGrp   = cmds.group(self.toCtrlHookGrp, self.toScalableHookGrp, self.locatorsGrp, name=side+self.userGuideName+"_Grp")
                # add hook attributes to be read when rigging integrated modules:
                utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
                utils.addHook(objName=self.toScalableHookGrp, hookType='scalableHook')
                utils.addHook(objName=self.toStaticHookGrp, hookType='staticHook')
                cmds.addAttr(self.toStaticHookGrp, longName="dpAR_name", dataType="string")
                cmds.addAttr(self.toStaticHookGrp, longName="dpAR_type", dataType="string")
                cmds.setAttr(self.toStaticHookGrp+".dpAR_name", self.userGuideName, type="string")
                cmds.setAttr(self.toStaticHookGrp+".dpAR_type", CLASS_NAME, type="string")
                # add module type counter value
                cmds.addAttr(self.toStaticHookGrp, longName='dpAR_count', attributeType='long', keyable=False)
                cmds.setAttr(self.toStaticHookGrp+'.dpAR_count', dpAR_count)
                self.ctrlHookGrpList.append(self.toCtrlHookGrp)
                if hideJoints:
                    cmds.setAttr(self.toScalableHookGrp+".visibility", 0)
                # delete duplicated group for side (mirror):
                cmds.delete(side+self.userGuideName+'_'+self.mirrorGrp)
            # finalize this rig:
            self.integratingInfo()
            cmds.select(clear=True)
        # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
        self.deleteModule()
Example #43
0
    def rigModule(self, *args):
        Base.StartClass.rigModule(self)
        # verify if the guide exists:
        if cmds.objExists(self.moduleGrp):
            try:
                hideJoints = cmds.checkBox('hideJointsCB',
                                           query=True,
                                           value=True)
            except:
                hideJoints = 1
            # create lists to be integrated:
            # start as no having mirror:
            sideList = [""]
            # analisys the mirror module:
            self.mirrorAxis = cmds.getAttr(self.moduleGrp + ".mirrorAxis")
            if self.mirrorAxis != 'off':
                # get rigs names:
                self.mirrorNames = cmds.getAttr(self.moduleGrp + ".mirrorName")
                # get first and last letters to use as side initials (prefix):
                sideList = [
                    self.mirrorNames[0] + '_',
                    self.mirrorNames[len(self.mirrorNames) - 1] + '_'
                ]
                for s, side in enumerate(sideList):
                    duplicated = cmds.duplicate(
                        self.moduleGrp,
                        name=side + self.userGuideName + '_Guide_Base')[0]
                    allGuideList = cmds.listRelatives(duplicated,
                                                      allDescendents=True)
                    for item in allGuideList:
                        cmds.rename(item,
                                    side + self.userGuideName + "_" + item)
                    self.mirrorGrp = cmds.group(name="Guide_Base_Grp",
                                                empty=True)
                    cmds.parent(side + self.userGuideName + '_Guide_Base',
                                self.mirrorGrp,
                                absolute=True)
                    # re-rename grp:
                    cmds.rename(
                        self.mirrorGrp,
                        side + self.userGuideName + '_' + self.mirrorGrp)
                    # do a group mirror with negative scaling:
                    if s == 1:
                        for axis in self.mirrorAxis:
                            cmds.setAttr(
                                side + self.userGuideName + '_' +
                                self.mirrorGrp + '.scale' + axis, -1)
                # joint labelling:
                jointLabelAdd = 1
            else:  # if not mirror:
                duplicated = cmds.duplicate(self.moduleGrp,
                                            name=self.userGuideName +
                                            '_Guide_Base')[0]
                allGuideList = cmds.listRelatives(duplicated,
                                                  allDescendents=True)
                for item in allGuideList:
                    cmds.rename(item, self.userGuideName + "_" + item)
                self.mirrorGrp = cmds.group(self.userGuideName + '_Guide_Base',
                                            name="Guide_Base_Grp",
                                            relative=True)
                # re-rename grp:
                cmds.rename(self.mirrorGrp,
                            self.userGuideName + '_' + self.mirrorGrp)
                # joint labelling:
                jointLabelAdd = 0
            # store the number of this guide by module type
            dpAR_count = utils.findModuleLastNumber(CLASS_NAME,
                                                    "dpAR_type") + 1
            # run for all sides
            for s, side in enumerate(sideList):
                # redeclaring variables:
                self.base = side + self.userGuideName + "_Guide_Base"
                self.cvFootLoc = side + self.userGuideName + "_Guide_Foot"
                self.cvRFALoc = side + self.userGuideName + "_Guide_RfA"
                self.cvRFBLoc = side + self.userGuideName + "_Guide_RfB"
                self.cvRFCLoc = side + self.userGuideName + "_Guide_RfC"
                self.cvRFDLoc = side + self.userGuideName + "_Guide_RfD"
                self.cvRFELoc = side + self.userGuideName + "_Guide_RfE"
                self.cvEndJoint = side + self.userGuideName + "_Guide_JointEnd"

                # declaring attributes reading from dictionary:
                ankleRFAttr = self.langDic[self.langName]['c009_leg_extrem']
                middleRFAttr = self.langDic[
                    self.langName]['c017_RevFoot_middle']
                outsideRFAttr = self.langDic[self.langName]['c010_RevFoot_A']
                insideRFAttr = self.langDic[self.langName]['c011_RevFoot_B']
                heelRFAttr = self.langDic[self.langName]['c012_RevFoot_C']
                toeRFAttr = self.langDic[self.langName]['c013_RevFoot_D']
                ballRFAttr = self.langDic[self.langName]['c014_RevFoot_E']
                footRFAttr = self.langDic[self.langName]['c015_RevFoot_F']
                sideRFAttr = self.langDic[self.langName]['c016_RevFoot_G']
                rfRoll = self.langDic[
                    self.langName]['c018_RevFoot_roll'].capitalize()
                rfSpin = self.langDic[
                    self.langName]['c019_RevFoot_spin'].capitalize()
                rfTurn = self.langDic[
                    self.langName]['c020_RevFoot_turn'].capitalize()
                rfAngle = self.langDic[
                    self.langName]['c102_angle'].capitalize()
                rfPlant = self.langDic[
                    self.langName]['c103_plant'].capitalize()
                showCtrlsAttr = self.langDic[
                    self.langName]['c021_showControls']

                # creating joints:
                cmds.select(clear=True)
                self.footJnt = cmds.joint(name=side + self.userGuideName +
                                          "_" + ankleRFAttr.capitalize() +
                                          "_Jnt")
                utils.setJointLabel(
                    self.footJnt, s + jointLabelAdd, 18,
                    self.userGuideName + "_" + ankleRFAttr.capitalize())
                self.middleFootJxt = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    middleRFAttr.capitalize() + "_Jxt")
                self.endJnt = cmds.joint(name=side + self.userGuideName +
                                         "_JEnd")
                cmds.select(clear=True)
                self.middleFootJnt = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    middleRFAttr.capitalize() + "_Jnt")
                utils.setJointLabel(
                    self.middleFootJnt, s + jointLabelAdd, 18,
                    self.userGuideName + "_" + middleRFAttr.capitalize())
                self.endBJnt = cmds.joint(name=side + self.userGuideName +
                                          "B_JEnd")
                cmds.parent(self.middleFootJnt, self.middleFootJxt)
                cmds.addAttr(self.footJnt,
                             longName='dpAR_joint',
                             attributeType='float',
                             keyable=False)
                cmds.addAttr(self.middleFootJnt,
                             longName='dpAR_joint',
                             attributeType='float',
                             keyable=False)
                cmds.select(clear=True)
                '''
                Deactivate the segment scale compensate on the bone to prevent scaling problem in maya 2016
                It will prevent a double scale problem that will come from the upper parent in the rig
                '''
                if (int(cmds.about(version=True)[:4]) >= 2016):
                    cmds.setAttr(self.footJnt + ".segmentScaleCompensate", 0)
                    cmds.setAttr(
                        self.middleFootJxt + ".segmentScaleCompensate", 0)
                    cmds.setAttr(
                        self.middleFootJnt + ".segmentScaleCompensate", 0)

                # reverse foot controls:
                self.RFACtrl = self.ctrls.cvControl(
                    "id_018_FootReverse",
                    side + self.userGuideName + "_" +
                    outsideRFAttr.capitalize() + "_Ctrl",
                    r=(self.ctrlRadius * 0.1),
                    d=self.curveDegree)
                self.RFBCtrl = self.ctrls.cvControl(
                    "id_018_FootReverse",
                    side + self.userGuideName + "_" +
                    insideRFAttr.capitalize() + "_Ctrl",
                    r=(self.ctrlRadius * 0.1),
                    d=self.curveDegree)
                self.RFCCtrl = self.ctrls.cvControl(
                    "id_018_FootReverse",
                    side + self.userGuideName + "_" + heelRFAttr.capitalize() +
                    "_Ctrl",
                    r=(self.ctrlRadius * 0.1),
                    d=self.curveDegree,
                    dir="+Y",
                    rot=(0, 90, 0))
                self.RFDCtrl = self.ctrls.cvControl(
                    "id_018_FootReverse",
                    side + self.userGuideName + "_" + toeRFAttr.capitalize() +
                    "_Ctrl",
                    r=(self.ctrlRadius * 0.1),
                    d=self.curveDegree,
                    dir="+Y",
                    rot=(0, 90, 0))
                self.RFECtrl = self.ctrls.cvControl(
                    "id_019_FootReverseE",
                    side + self.userGuideName + "_" + ballRFAttr.capitalize() +
                    "_Ctrl",
                    r=(self.ctrlRadius * 0.1),
                    d=self.curveDegree,
                    rot=(0, 90, 0))

                # reverse foot groups:
                self.RFAGrp = cmds.group(self.RFACtrl,
                                         name=self.RFACtrl + "_Grp")
                self.RFBGrp = cmds.group(self.RFBCtrl,
                                         name=self.RFBCtrl + "_Grp")
                self.RFCGrp = cmds.group(self.RFCCtrl,
                                         name=self.RFCCtrl + "_Grp")
                self.RFDGrp = cmds.group(self.RFDCtrl,
                                         name=self.RFDCtrl + "_Grp")
                self.RFEGrp = cmds.group(self.RFECtrl,
                                         name=self.RFECtrl + "_Grp")
                rfGrpList = [
                    self.RFAGrp, self.RFBGrp, self.RFCGrp, self.RFDGrp,
                    self.RFEGrp
                ]
                self.ballRFList.append(self.RFEGrp)

                # putting groups in the correct place:
                tempToDelA = cmds.parentConstraint(self.cvFootLoc,
                                                   self.footJnt,
                                                   maintainOffset=False)
                tempToDelB = cmds.parentConstraint(self.cvRFELoc,
                                                   self.middleFootJxt,
                                                   maintainOffset=False)
                tempToDelC = cmds.parentConstraint(self.cvEndJoint,
                                                   self.endJnt,
                                                   maintainOffset=False)
                tempToDelD = cmds.parentConstraint(self.cvEndJoint,
                                                   self.endBJnt,
                                                   maintainOffset=False)
                tempToDelE = cmds.parentConstraint(self.cvRFALoc,
                                                   self.RFAGrp,
                                                   maintainOffset=False)
                tempToDelF = cmds.parentConstraint(self.cvRFBLoc,
                                                   self.RFBGrp,
                                                   maintainOffset=False)
                tempToDelG = cmds.parentConstraint(self.cvRFCLoc,
                                                   self.RFCGrp,
                                                   maintainOffset=False)
                tempToDelH = cmds.parentConstraint(self.cvRFDLoc,
                                                   self.RFDGrp,
                                                   maintainOffset=False)
                tempToDelI = cmds.parentConstraint(self.cvRFELoc,
                                                   self.RFEGrp,
                                                   maintainOffset=False)
                cmds.delete(tempToDelA, tempToDelB, tempToDelC, tempToDelD,
                            tempToDelE, tempToDelF, tempToDelG, tempToDelH,
                            tempToDelI)

                # mounting hierarchy:
                cmds.parent(self.RFBGrp, self.RFACtrl)
                cmds.parent(self.RFCGrp, self.RFBCtrl)
                cmds.parent(self.RFDGrp, self.RFCCtrl)
                cmds.parent(self.RFEGrp, self.RFDCtrl)

                # reverse foot zero out groups:
                self.RFEZero = utils.zeroOut([self.RFEGrp])[0]
                self.RFEZeroExtra = utils.zeroOut([self.RFEZero])[0]
                self.RFDZero = utils.zeroOut([self.RFDGrp])[0]
                self.RFCZero = utils.zeroOut([self.RFCGrp])[0]
                self.RFBZero = utils.zeroOut([self.RFBGrp])[0]
                self.RFAZero = utils.zeroOut([self.RFAGrp])[0]
                self.RFAZeroExtra = utils.zeroOut([self.RFAZero])[0]
                rfJointZeroList = [
                    self.RFAZero, self.RFBZero, self.RFCZero, self.RFDZero,
                    self.RFEZero
                ]

                # fixing side rool rotation order:
                cmds.setAttr(self.RFBZero + ".rotateOrder", 5)

                # creating ikHandles:
                ikHandleAnkleList = cmds.ikHandle(
                    name=side + self.userGuideName + "_" +
                    ankleRFAttr.capitalize() + "_IkHandle",
                    startJoint=self.footJnt,
                    endEffector=self.middleFootJxt,
                    solver='ikSCsolver')
                ikHandleMiddleList = cmds.ikHandle(
                    name=side + self.userGuideName + "_" +
                    middleRFAttr.capitalize() + "_IkHandle",
                    startJoint=self.middleFootJxt,
                    endEffector=self.endJnt,
                    solver='ikSCsolver')
                cmds.rename(ikHandleAnkleList[1],
                            ikHandleAnkleList[0] + "_Effector")
                cmds.rename(ikHandleMiddleList[1],
                            ikHandleMiddleList[0] + "_Effector")
                cmds.setAttr(ikHandleAnkleList[0] + '.visibility', 0)
                cmds.setAttr(ikHandleMiddleList[0] + '.visibility', 0)

                # creating Fk controls:
                self.footCtrl = self.ctrls.cvControl(
                    "id_020_FootFk",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c009_leg_extrem'] + "_Ctrl",
                    r=(self.ctrlRadius * 0.5),
                    d=self.curveDegree,
                    dir="+Z")
                self.footCtrlList.append(self.footCtrl)
                cmds.setAttr(self.footCtrl + ".rotateOrder", 1)

                self.revFootCtrlShapeList.append(
                    cmds.listRelatives(self.footCtrl,
                                       children=True,
                                       type='nurbsCurve')[0])

                self.middleFootCtrl = self.ctrls.cvControl(
                    "id_021_FootMiddle",
                    side + self.userGuideName + "_" + self.langDic[
                        self.langName]['c017_RevFoot_middle'].capitalize() +
                    "_Ctrl",
                    r=(self.ctrlRadius * 0.5),
                    d=self.curveDegree)
                cmds.setAttr(self.middleFootCtrl + '.overrideEnabled', 1)
                cmds.setAttr(self.middleFootCtrl + ".rotateOrder", 4)
                tempToDelA = cmds.parentConstraint(self.cvFootLoc,
                                                   self.footCtrl,
                                                   maintainOffset=False)
                tempToDelB = cmds.parentConstraint(self.cvRFELoc,
                                                   self.middleFootCtrl,
                                                   maintainOffset=False)
                cmds.delete(tempToDelA, tempToDelB)
                if s == 1:
                    cmds.setAttr(self.middleFootCtrl + ".scaleX", -1)
                    cmds.setAttr(self.middleFootCtrl + ".scaleY", -1)
                    cmds.setAttr(self.middleFootCtrl + ".scaleZ", -1)
                self.footCtrlZeroList = utils.zeroOut(
                    [self.footCtrl, self.middleFootCtrl])
                self.middleFootCtrlList.append(self.middleFootCtrl)

                # mount hierarchy:
                cmds.parent(self.footCtrlZeroList[1],
                            self.RFDCtrl,
                            absolute=True)
                cmds.parent(ikHandleMiddleList[0],
                            self.middleFootCtrl,
                            absolute=True)
                self.toLimbIkHandleGrp = cmds.group(
                    empty=True,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c009_leg_extrem'] + "_Grp")
                self.toLimbIkHandleGrpList.append(self.toLimbIkHandleGrp)
                cmds.parent(ikHandleAnkleList[0],
                            self.toLimbIkHandleGrp,
                            self.RFECtrl,
                            absolute=True)
                cmds.makeIdentity(self.toLimbIkHandleGrp,
                                  apply=True,
                                  translate=True,
                                  rotate=True,
                                  scale=True)
                parentConst = cmds.parentConstraint(self.RFECtrl,
                                                    self.footJnt,
                                                    maintainOffset=True,
                                                    name=self.footJnt +
                                                    "_ParentConstraint")[0]
                self.parentConstList.append(parentConst)
                self.footJntList.append(self.footJnt)
                cmds.parent(self.RFAZeroExtra, self.footCtrl, absolute=True)

                scaleConst = cmds.scaleConstraint(self.footCtrl,
                                                  self.footJnt,
                                                  maintainOffset=True,
                                                  name=self.footJnt +
                                                  "_ScaleConstraint")
                self.scaleConstList.append(scaleConst)
                cmds.parentConstraint(self.middleFootCtrl,
                                      self.middleFootJnt,
                                      maintainOffset=True,
                                      name=self.middleFootJnt +
                                      "_ParentConstraint")
                cmds.scaleConstraint(self.middleFootCtrl,
                                     self.middleFootJnt,
                                     maintainOffset=True,
                                     name=self.middleFootJnt +
                                     "_ScaleConstraint")

                # add attributes to footCtrl and connect them to reverseFoot groups rotation:
                rfAttrList = [
                    outsideRFAttr, insideRFAttr, heelRFAttr, toeRFAttr,
                    ballRFAttr
                ]
                rfTypeAttrList = [rfRoll, rfSpin]
                for j, rfAttr in enumerate(rfAttrList):
                    for t, rfType in enumerate(rfTypeAttrList):
                        if t == 1 and j == (len(rfAttrList) -
                                            1):  # create turn attr to ball
                            cmds.addAttr(self.footCtrl,
                                         longName=rfAttr + rfTurn,
                                         attributeType='float',
                                         keyable=True)
                            cmds.connectAttr(self.footCtrl + "." + rfAttr +
                                             rfTurn,
                                             rfGrpList[j] + ".rotateZ",
                                             force=True)
                            self.reverseFootAttrList.append(rfAttr + rfTurn)
                        cmds.addAttr(self.footCtrl,
                                     longName=rfAttr + rfType,
                                     attributeType='float',
                                     keyable=True)
                        self.reverseFootAttrList.append(rfAttr + rfType)
                        if t == 0:
                            if j > 1:
                                cmds.connectAttr(self.footCtrl + "." + rfAttr +
                                                 rfType,
                                                 rfGrpList[j] + ".rotateX",
                                                 force=True)
                            else:
                                cmds.connectAttr(self.footCtrl + "." + rfAttr +
                                                 rfType,
                                                 rfGrpList[j] + ".rotateZ",
                                                 force=True)
                        else:
                            cmds.connectAttr(self.footCtrl + "." + rfAttr +
                                             rfType,
                                             rfGrpList[j] + ".rotateY",
                                             force=True)

                # creating the originedFrom attributes (in order to permit integrated parents in the future):
                utils.originedFrom(objName=self.footCtrl,
                                   attrString=self.base + ";" +
                                   self.cvFootLoc + ";" + self.cvRFALoc + ";" +
                                   self.cvRFBLoc + ";" + self.cvRFCLoc + ";" +
                                   self.cvRFDLoc)
                utils.originedFrom(objName=self.middleFootCtrl,
                                   attrString=self.cvRFELoc + ";" +
                                   self.cvEndJoint)

                # creating pre-defined attributes for footRoll and sideRoll attributes, also rollAngle:
                cmds.addAttr(self.footCtrl,
                             longName=footRFAttr + rfRoll,
                             attributeType='float',
                             keyable=True)
                cmds.addAttr(self.footCtrl,
                             longName=footRFAttr + rfRoll + rfAngle,
                             attributeType='float',
                             defaultValue=30,
                             keyable=True)
                cmds.addAttr(self.footCtrl,
                             longName=footRFAttr + rfRoll + rfPlant,
                             attributeType='float',
                             defaultValue=0,
                             keyable=True)
                cmds.addAttr(self.footCtrl,
                             longName=sideRFAttr + rfRoll,
                             attributeType='float',
                             keyable=True)

                # create clampNodes in order to limit the side rotations:
                sideClamp = cmds.createNode("clamp",
                                            name=side + self.userGuideName +
                                            "_Side_Clp")
                # outside values in R
                cmds.setAttr(sideClamp + ".minR", -360)
                # inside values in G
                cmds.setAttr(sideClamp + ".maxG", 360)
                # inverting sideRoll values:
                sideMD = cmds.createNode("multiplyDivide",
                                         name=side + self.userGuideName +
                                         "_Side_MD")
                cmds.setAttr(sideMD + ".input2X", -1)
                # connections:
                cmds.connectAttr(self.footCtrl + "." + sideRFAttr + rfRoll,
                                 sideMD + ".input1X",
                                 force=True)
                cmds.connectAttr(sideMD + ".outputX",
                                 sideClamp + ".inputR",
                                 force=True)
                cmds.connectAttr(sideMD + ".outputX",
                                 sideClamp + ".inputG",
                                 force=True)
                cmds.connectAttr(sideClamp + ".outputR",
                                 self.RFAZero + ".rotateZ",
                                 force=True)
                cmds.connectAttr(sideClamp + ".outputG",
                                 self.RFBZero + ".rotateZ",
                                 force=True)

                # for footRoll:
                footHeelClp = cmds.createNode("clamp",
                                              name=side + self.userGuideName +
                                              "_Roll_Heel_Clp")
                # heel values in R
                cmds.setAttr(footHeelClp + ".minR", -360)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll,
                                 footHeelClp + ".inputR",
                                 force=True)
                cmds.connectAttr(footHeelClp + ".outputR",
                                 self.RFCZero + ".rotateX",
                                 force=True)

                # footRoll with angle limit:
                footPMA = cmds.createNode("plusMinusAverage",
                                          name=side + self.userGuideName +
                                          "_Roll_PMA")
                footSR = cmds.createNode("setRange",
                                         name=side + self.userGuideName +
                                         "_Roll_SR")
                cmds.setAttr(footSR + ".oldMaxY", 180)
                cmds.setAttr(footPMA + ".input1D[0]", 180)
                cmds.setAttr(footPMA + ".operation", 2)  #substract
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll,
                                 footSR + ".valueX",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll,
                                 footSR + ".valueY",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfAngle,
                                 footSR + ".maxX",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfAngle,
                                 footSR + ".oldMinY",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfAngle,
                                 footSR + ".oldMaxX",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfAngle,
                                 footPMA + ".input1D[1]",
                                 force=True)
                cmds.connectAttr(footPMA + ".output1D",
                                 footSR + ".maxY",
                                 force=True)

                # plant angle for foot roll:
                footPlantClp = cmds.createNode("clamp",
                                               name=side + self.userGuideName +
                                               "_Roll_Plant_Clp")
                footPlantCnd = cmds.createNode("condition",
                                               name=side + self.userGuideName +
                                               "_Roll_Plant_Cnd")
                cmds.setAttr(footPlantCnd + ".operation", 4)  #less than
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll,
                                 footPlantClp + ".inputR",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfPlant,
                                 footPlantClp + ".maxR",
                                 force=True)
                cmds.connectAttr(footPlantClp + ".outputR",
                                 footPlantCnd + ".firstTerm",
                                 force=True)
                cmds.connectAttr(footPlantClp + ".outputR",
                                 footPlantCnd + ".colorIfTrueR",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfPlant,
                                 footPlantCnd + ".secondTerm",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfPlant,
                                 footPlantCnd + ".colorIfFalseR",
                                 force=True)

                # back to zero footRoll when greather then angle plus plant values:
                anglePlantPMA = cmds.createNode(
                    "plusMinusAverage",
                    name=side + self.userGuideName + "_AnglePlant_PMA")
                anglePlantMD = cmds.createNode("multiplyDivide",
                                               name=side + self.userGuideName +
                                               "_AnglePlant_MD")
                anglePlantRmV = cmds.createNode(
                    "remapValue",
                    name=side + self.userGuideName + "_AnglePlant_RmV")
                anglePlantCnd = cmds.createNode(
                    "condition",
                    name=side + self.userGuideName + "_AnglePlant_Cnd")
                cmds.setAttr(anglePlantMD + ".input2X", -1)
                cmds.setAttr(anglePlantRmV + ".inputMax", 90)
                cmds.setAttr(anglePlantRmV + ".value[0].value_Interp",
                             3)  #spline
                cmds.setAttr(anglePlantRmV + ".value[1].value_Interp",
                             3)  #spline
                cmds.setAttr(anglePlantCnd + ".operation", 2)  #greather than
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfAngle,
                                 anglePlantPMA + ".input1D[0]",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll +
                                 rfPlant,
                                 anglePlantPMA + ".input1D[1]",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll,
                                 anglePlantCnd + ".firstTerm",
                                 force=True)
                cmds.connectAttr(anglePlantPMA + ".output1D",
                                 anglePlantCnd + ".secondTerm",
                                 force=True)
                cmds.connectAttr(anglePlantPMA + ".output1D",
                                 anglePlantMD + ".input1X",
                                 force=True)
                cmds.connectAttr(anglePlantPMA + ".output1D",
                                 anglePlantRmV + ".inputMin",
                                 force=True)
                cmds.connectAttr(anglePlantMD + ".outputX",
                                 anglePlantRmV + ".outputMax",
                                 force=True)
                cmds.connectAttr(self.footCtrl + "." + footRFAttr + rfRoll,
                                 anglePlantRmV + ".inputValue",
                                 force=True)
                cmds.connectAttr(anglePlantRmV + ".outColorR",
                                 anglePlantCnd + ".colorIfTrueR",
                                 force=True)
                cmds.connectAttr(anglePlantCnd + ".outColorR",
                                 self.RFEZeroExtra + ".rotateX",
                                 force=True)

                # connect to groups in order to rotate them:
                cmds.connectAttr(footSR + ".outValueY",
                                 self.RFDZero + ".rotateX",
                                 force=True)
                cmds.connectAttr(footSR + ".outValueX",
                                 self.RFEZero + ".rotateX",
                                 force=True)
                if s == 0:  #left
                    cmds.connectAttr(footPlantCnd + ".outColorR",
                                     self.footCtrlZeroList[1] + ".rotateX",
                                     force=True)
                else:  #fix right side mirror
                    footPlantInvMD = cmds.createNode(
                        "multiplyDivide",
                        name=side + self.userGuideName + "_Plant_Inv_MD")
                    cmds.setAttr(footPlantInvMD + ".input2X", -1)
                    cmds.connectAttr(footPlantCnd + ".outColorR",
                                     footPlantInvMD + ".input1X",
                                     force=True)
                    cmds.connectAttr(footPlantInvMD + ".outputX",
                                     self.footCtrlZeroList[1] + ".rotateX",
                                     force=True)

                # organizing keyable attributes:
                self.ctrls.setLockHide([self.middleFootCtrl, self.footCtrl],
                                       ['v'],
                                       l=False)

                # show or hide reverseFoot controls:
                cmds.addAttr(self.footCtrl,
                             longName=showCtrlsAttr,
                             attributeType='long',
                             min=0,
                             max=1,
                             defaultValue=1)
                cmds.setAttr(self.footCtrl + "." + showCtrlsAttr,
                             keyable=False,
                             channelBox=True)
                showHideCtrlList = [
                    self.RFACtrl, self.RFBCtrl, self.RFCCtrl, self.RFDCtrl
                ]
                for rfCtrl in showHideCtrlList:
                    rfCtrlShape = cmds.listRelatives(rfCtrl,
                                                     children=True,
                                                     type='nurbsCurve')[0]
                    cmds.connectAttr(self.footCtrl + "." + showCtrlsAttr,
                                     rfCtrlShape + ".visibility",
                                     force=True)

                # create a masterModuleGrp to be checked if this rig exists:
                self.toCtrlHookGrp = cmds.group(
                    self.footCtrlZeroList[0],
                    name=side + self.userGuideName + "_Control_Grp")
                self.revFootCtrlGrpFinalList.append(self.toCtrlHookGrp)

                self.toScalableHookGrp = cmds.createNode(
                    "transform", name=side + self.userGuideName + "_Joint_Grp")
                mWorldFoot = cmds.getAttr(self.footJnt + ".worldMatrix")
                cmds.xform(self.toScalableHookGrp,
                           matrix=mWorldFoot,
                           worldSpace=True)
                cmds.parent(self.footJnt,
                            self.toScalableHookGrp,
                            absolute=True)
                #Remove the Joint orient to make sure the bone is at the same orientation than it's parent
                cmds.setAttr(self.footJnt + ".jointOrientX", 0)
                cmds.setAttr(self.footJnt + ".jointOrientY", 0)
                cmds.setAttr(self.footJnt + ".jointOrientZ", 0)
                self.aScalableGrp.append(self.toScalableHookGrp)

                self.toStaticHookGrp = cmds.group(self.toCtrlHookGrp,
                                                  self.toScalableHookGrp,
                                                  name=side +
                                                  self.userGuideName + "_Grp")
                cmds.addAttr(self.toStaticHookGrp,
                             longName="dpAR_name",
                             dataType="string")
                cmds.addAttr(self.toStaticHookGrp,
                             longName="dpAR_type",
                             dataType="string")
                cmds.setAttr(self.toStaticHookGrp + ".dpAR_name",
                             self.userGuideName,
                             type="string")
                cmds.setAttr(self.toStaticHookGrp + ".dpAR_type",
                             CLASS_NAME,
                             type="string")
                # add module type counter value
                cmds.addAttr(self.toStaticHookGrp,
                             longName='dpAR_count',
                             attributeType='long',
                             keyable=False)
                cmds.setAttr(self.toStaticHookGrp + '.dpAR_count', dpAR_count)
                # create a locator in order to avoid delete static group
                loc = cmds.spaceLocator(name=side + self.userGuideName +
                                        "_DO_NOT_DELETE")[0]
                cmds.parent(loc, self.toStaticHookGrp, absolute=True)
                cmds.setAttr(loc + ".visibility", 0)
                self.ctrls.setLockHide([loc], [
                    'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'
                ])
                # add hook attributes to be read when rigging integrated modules:
                utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
                utils.addHook(objName=self.toScalableHookGrp,
                              hookType='scalableHook')
                utils.addHook(objName=self.toStaticHookGrp,
                              hookType='staticHook')
                if hideJoints:
                    cmds.setAttr(self.toScalableHookGrp + ".visibility", 0)

                # delete duplicated group for side (mirror):
                cmds.delete(side + self.userGuideName + '_' + self.mirrorGrp)
            # finalize this rig:
            self.integratingInfo()
            cmds.select(clear=True)
        # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
        self.deleteModule()
Example #44
0
 def rigModule(self, *args):
     Base.StartClass.rigModule(self)
     # verify if the guide exists:
     if cmds.objExists(self.moduleGrp):
         try:
             hideJoints = cmds.checkBox('hideJointsCB',
                                        query=True,
                                        value=True)
         except:
             hideJoints = 1
         # start as no having mirror:
         sideList = [""]
         # analisys the mirror module:
         self.mirrorAxis = cmds.getAttr(self.moduleGrp + ".mirrorAxis")
         if self.mirrorAxis != 'off':
             # get rigs names:
             self.mirrorNames = cmds.getAttr(self.moduleGrp + ".mirrorName")
             # get first and last letters to use as side initials (prefix):
             sideList = [
                 self.mirrorNames[0] + '_',
                 self.mirrorNames[len(self.mirrorNames) - 1] + '_'
             ]
             for s, side in enumerate(sideList):
                 duplicated = cmds.duplicate(
                     self.moduleGrp,
                     name=side + self.userGuideName + '_Guide_Base')[0]
                 allGuideList = cmds.listRelatives(duplicated,
                                                   allDescendents=True)
                 for item in allGuideList:
                     cmds.rename(item,
                                 side + self.userGuideName + "_" + item)
                 self.mirrorGrp = cmds.group(name="Guide_Base_Grp",
                                             empty=True)
                 cmds.parent(side + self.userGuideName + '_Guide_Base',
                             self.mirrorGrp,
                             absolute=True)
                 # re-rename grp:
                 cmds.rename(
                     self.mirrorGrp,
                     side + self.userGuideName + '_' + self.mirrorGrp)
                 # do a group mirror with negative scaling:
                 if s == 1:
                     if cmds.getAttr(self.moduleGrp + ".flip") == 0:
                         for axis in self.mirrorAxis:
                             gotValue = cmds.getAttr(
                                 side + self.userGuideName +
                                 "_Guide_Base.translate" + axis)
                             flipedValue = gotValue * (-2)
                             cmds.setAttr(
                                 side + self.userGuideName + '_' +
                                 self.mirrorGrp + '.translate' + axis,
                                 flipedValue)
                     else:
                         for axis in self.mirrorAxis:
                             cmds.setAttr(
                                 side + self.userGuideName + '_' +
                                 self.mirrorGrp + '.scale' + axis, -1)
             # joint labelling:
             jointLabelAdd = 1
         else:  # if not mirror:
             duplicated = cmds.duplicate(self.moduleGrp,
                                         name=self.userGuideName +
                                         '_Guide_Base')[0]
             allGuideList = cmds.listRelatives(duplicated,
                                               allDescendents=True)
             for item in allGuideList:
                 cmds.rename(item, self.userGuideName + "_" + item)
             self.mirrorGrp = cmds.group(self.userGuideName + '_Guide_Base',
                                         name="Guide_Base_Grp",
                                         relative=True)
             #for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp"
             # re-rename grp:
             cmds.rename(self.mirrorGrp,
                         self.userGuideName + '_' + self.mirrorGrp)
             # joint labelling:
             jointLabelAdd = 0
         # store the number of this guide by module type
         dpAR_count = utils.findModuleLastNumber(CLASS_NAME,
                                                 "dpAR_type") + 1
         # run for all sides
         for s, side in enumerate(sideList):
             self.base = side + self.userGuideName + '_Guide_Base'
             cmds.select(clear=True)
             # declare guide:
             self.guide = side + self.userGuideName + "_Guide_JointLoc1"
             self.cvEndJoint = side + self.userGuideName + "_Guide_JointEnd"
             self.radiusGuide = side + self.userGuideName + "_Guide_Base_RadiusCtrl"
             # create a joint:
             self.jnt = cmds.joint(name=side + self.userGuideName + "_Jnt",
                                   scaleCompensate=False)
             cmds.addAttr(self.jnt,
                          longName='dpAR_joint',
                          attributeType='float',
                          keyable=False)
             utils.setJointLabel(self.jnt, s + jointLabelAdd, 18,
                                 self.userGuideName)
             # create a control:
             if not self.getHasIndirectSkin():
                 if self.curveDegree == 0:
                     self.curveDegree = 1
             # work with curve shape and rotation cases:
             indirectSkinRot = (0, 0, 0)
             if self.langDic[
                     self.langName]['c058_main'] in self.userGuideName:
                 ctrlTypeID = "id_054_SingleMain"
                 if len(sideList) > 1:
                     if self.langDic[self.langName][
                             'c041_eyebrow'] in self.userGuideName:
                         indirectSkinRot = (0, 0, -90)
                     else:
                         indirectSkinRot = (0, 0, 90)
             else:
                 ctrlTypeID = "id_029_SingleIndSkin"
                 if self.langDic[
                         self.langName]['c045_lower'] in self.userGuideName:
                     indirectSkinRot = (0, 0, 180)
                 elif self.langDic[self.langName][
                         'c043_corner'] in self.userGuideName:
                     if "00" in self.userGuideName:
                         indirectSkinRot = (0, 0, 90)
                     else:
                         indirectSkinRot = (0, 0, -90)
             self.singleCtrl = self.ctrls.cvControl(
                 ctrlTypeID,
                 side + self.userGuideName + "_Ctrl",
                 r=self.ctrlRadius,
                 d=self.curveDegree,
                 rot=indirectSkinRot)
             utils.originedFrom(objName=self.singleCtrl,
                                attrString=self.base + ";" + self.guide +
                                ";" + self.cvEndJoint + ";" +
                                self.radiusGuide)
             # position and orientation of joint and control:
             cmds.delete(
                 cmds.parentConstraint(self.guide,
                                       self.jnt,
                                       maintainOffset=False))
             cmds.delete(
                 cmds.parentConstraint(self.guide,
                                       self.singleCtrl,
                                       maintainOffset=False))
             # zeroOut controls:
             zeroOutCtrlGrp = utils.zeroOut([self.singleCtrl],
                                            offset=True)[0]
             # hide visibility attribute:
             cmds.setAttr(self.singleCtrl + '.visibility', keyable=False)
             # fixing flip mirror:
             if s == 1:
                 if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                     cmds.setAttr(zeroOutCtrlGrp + ".scaleX", -1)
                     cmds.setAttr(zeroOutCtrlGrp + ".scaleY", -1)
                     cmds.setAttr(zeroOutCtrlGrp + ".scaleZ", -1)
             if not self.getHasIndirectSkin():
                 cmds.addAttr(self.singleCtrl,
                              longName='scaleCompensate',
                              attributeType="bool",
                              keyable=False)
                 cmds.setAttr(self.singleCtrl + ".scaleCompensate",
                              1,
                              channelBox=True)
                 cmds.connectAttr(self.singleCtrl + ".scaleCompensate",
                                  self.jnt + ".segmentScaleCompensate",
                                  force=True)
             if self.getHasIndirectSkin():
                 # create fatherJoints in order to zeroOut the skinning joint:
                 cmds.select(clear=True)
                 jxtName = self.jnt.replace("_Jnt", "_Jxt")
                 jxt = cmds.duplicate(self.jnt, name=jxtName)[0]
                 utils.clearDpArAttr([jxt])
                 cmds.makeIdentity(self.jnt, apply=True, jointOrient=False)
                 cmds.parent(self.jnt, jxt)
                 attrList = [
                     'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'
                 ]
                 for attr in attrList:
                     cmds.connectAttr(self.singleCtrl + '.' + attr,
                                      self.jnt + '.' + attr)
                 if self.getHasHolder():
                     cmds.delete(self.singleCtrl + "0Shape", shape=True)
                     self.singleCtrl = cmds.rename(
                         self.singleCtrl, self.singleCtrl + "_" +
                         self.langDic[self.langName]['c046_holder'] +
                         "_Grp")
                     self.ctrls.setLockHide([self.singleCtrl], [
                         'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy',
                         'sz'
                     ])
                     self.jnt = cmds.rename(
                         self.jnt,
                         self.jnt.replace(
                             "_Jnt", "_" +
                             self.langDic[self.langName]['c046_holder'] +
                             "_Jis"))
                     self.ctrls.setLockHide([self.jnt], [
                         'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy',
                         'sz'
                     ], True, True)
                 else:
                     if self.getHasSDKLocator():
                         if not self.langDic[self.langName][
                                 'c058_main'] in self.userGuideName:
                             # this one will be used to receive inputs from sdk locator:
                             sdkJisName = self.jnt.replace(
                                 "_Jnt", "_SDK_Jis")
                             sdkJis = cmds.duplicate(self.jnt,
                                                     name=sdkJisName)[0]
                             # sdk locator:
                             sdkLoc = cmds.spaceLocator(
                                 name=sdkJis.replace("_Jis", "_Loc"))[0]
                             sdkLocGrp = cmds.group(sdkLoc,
                                                    name=sdkLoc + "_Grp")
                             cmds.delete(
                                 cmds.parentConstraint(
                                     self.singleCtrl,
                                     sdkLocGrp,
                                     maintainOffset=False))
                             cmds.parent(sdkLocGrp,
                                         self.singleCtrl,
                                         relative=True)
                             sdkLocMD = cmds.createNode("multiplyDivide",
                                                        name=sdkLoc + "_MD")
                             cmds.addAttr(sdkLoc,
                                          longName="intensityX",
                                          attributeType="float",
                                          defaultValue=-1,
                                          keyable=False)
                             cmds.addAttr(sdkLoc,
                                          longName="intensityY",
                                          attributeType="float",
                                          defaultValue=-1,
                                          keyable=False)
                             cmds.addAttr(sdkLoc,
                                          longName="intensityZ",
                                          attributeType="float",
                                          defaultValue=-1,
                                          keyable=False)
                             cmds.connectAttr(sdkLoc + ".translateX",
                                              sdkLocMD + ".input1X",
                                              force=True)
                             cmds.connectAttr(sdkLoc + ".translateY",
                                              sdkLocMD + ".input1Y",
                                              force=True)
                             cmds.connectAttr(sdkLoc + ".translateZ",
                                              sdkLocMD + ".input1Z",
                                              force=True)
                             cmds.connectAttr(sdkLoc + ".intensityX",
                                              sdkLocMD + ".input2X",
                                              force=True)
                             cmds.connectAttr(sdkLoc + ".intensityY",
                                              sdkLocMD + ".input2Y",
                                              force=True)
                             cmds.connectAttr(sdkLoc + ".intensityZ",
                                              sdkLocMD + ".input2Z",
                                              force=True)
                             cmds.connectAttr(sdkLocMD + ".outputX",
                                              sdkLocGrp + ".translateX",
                                              force=True)
                             cmds.connectAttr(sdkLocMD + ".outputY",
                                              sdkLocGrp + ".translateY",
                                              force=True)
                             cmds.connectAttr(sdkLocMD + ".outputZ",
                                              sdkLocGrp + ".translateZ",
                                              force=True)
                             cmds.addAttr(self.singleCtrl,
                                          longName="displayLocator",
                                          attributeType="bool",
                                          keyable=False)
                             cmds.setAttr(self.singleCtrl +
                                          ".displayLocator",
                                          0,
                                          channelBox=True)
                             cmds.connectAttr(self.singleCtrl +
                                              ".displayLocator",
                                              sdkLoc + ".visibility",
                                              force=True)
                             cmds.setAttr(sdkLoc + ".visibility", lock=True)
                             for attr in attrList:
                                 cmds.connectAttr(sdkLoc + '.' + attr,
                                                  sdkJis + '.' + attr)
                             cmds.setAttr(sdkLocGrp + ".rotateX", 0)
                             cmds.setAttr(sdkLocGrp + ".rotateY", 0)
                             cmds.setAttr(sdkLocGrp + ".rotateZ", 0)
                     # rename indirectSkinning joint from Jnt to Jis:
                     self.jnt = cmds.rename(
                         self.jnt, self.jnt.replace("_Jnt", "_Jis"))
                 # fix mirror issue:
                 if s == 1:
                     if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                         cmds.setAttr(jxt + ".scaleX", -1)
                         cmds.setAttr(jxt + ".scaleY", -1)
                         cmds.setAttr(jxt + ".scaleZ", -1)
             else:  # like a fkLine
                 # create parentConstraint from ctrl to jnt:
                 cmds.parentConstraint(self.singleCtrl,
                                       self.jnt,
                                       maintainOffset=False,
                                       name=self.jnt + "_PaC")
                 # create scaleConstraint from ctrl to jnt:
                 cmds.scaleConstraint(self.singleCtrl,
                                      self.jnt,
                                      maintainOffset=True,
                                      name=self.jnt + "_ScC")
             # create end joint:
             cmds.select(self.jnt)
             self.endJoint = cmds.joint(name=side + self.userGuideName +
                                        "_JEnd",
                                        radius=0.5)
             cmds.delete(
                 cmds.parentConstraint(self.cvEndJoint,
                                       self.endJoint,
                                       maintainOffset=False))
             self.mainJisList.append(self.jnt)
             # create a masterModuleGrp to be checked if this rig exists:
             self.toCtrlHookGrp = cmds.group(
                 side + self.userGuideName + "_Ctrl_Zero_0_Grp",
                 name=side + self.userGuideName + "_Control_Grp")
             if self.getHasIndirectSkin():
                 locScale = cmds.spaceLocator(
                     name=side + self.userGuideName +
                     "_Scalable_DO_NOT_DELETE_PLEASE_Loc")[0]
                 cmds.setAttr(locScale + ".visibility", 0)
                 self.toScalableHookGrp = cmds.group(
                     locScale,
                     name=side + self.userGuideName + "_IndirectSkin_Grp")
                 jxtGrp = cmds.group(side + self.userGuideName + "_Jxt",
                                     name=side + self.userGuideName +
                                     "_Joint_Grp")
                 self.toStaticHookGrp = cmds.group(
                     jxtGrp,
                     self.toScalableHookGrp,
                     self.toCtrlHookGrp,
                     name=side + self.userGuideName + "_Grp")
             else:
                 self.toScalableHookGrp = cmds.group(
                     side + self.userGuideName + "_Jnt",
                     name=side + self.userGuideName + "_Joint_Grp")
                 self.toStaticHookGrp = cmds.group(
                     self.toCtrlHookGrp,
                     self.toScalableHookGrp,
                     name=side + self.userGuideName + "_Grp")
             # create a locator in order to avoid delete static or scalable group
             loc = cmds.spaceLocator(name=side + self.userGuideName +
                                     "_DO_NOT_DELETE_PLEASE_Loc")[0]
             cmds.parent(loc, self.toStaticHookGrp, absolute=True)
             cmds.setAttr(loc + ".visibility", 0)
             self.ctrls.setLockHide([loc], [
                 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'
             ])
             # add hook attributes to be read when rigging integrated modules:
             utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
             utils.addHook(objName=self.toScalableHookGrp,
                           hookType='scalableHook')
             utils.addHook(objName=self.toStaticHookGrp,
                           hookType='staticHook')
             cmds.addAttr(self.toStaticHookGrp,
                          longName="dpAR_name",
                          dataType="string")
             cmds.addAttr(self.toStaticHookGrp,
                          longName="dpAR_type",
                          dataType="string")
             cmds.setAttr(self.toStaticHookGrp + ".dpAR_name",
                          self.userGuideName,
                          type="string")
             cmds.setAttr(self.toStaticHookGrp + ".dpAR_type",
                          CLASS_NAME,
                          type="string")
             self.aStaticGrpList.append(self.toStaticHookGrp)
             self.aCtrlGrpList.append(self.toCtrlHookGrp)
             # add module type counter value
             cmds.addAttr(self.toStaticHookGrp,
                          longName='dpAR_count',
                          attributeType='long',
                          keyable=False)
             cmds.setAttr(self.toStaticHookGrp + '.dpAR_count', dpAR_count)
             if hideJoints:
                 cmds.setAttr(self.toScalableHookGrp + ".visibility", 0)
             # delete duplicated group for side (mirror):
             cmds.delete(side + self.userGuideName + '_' + self.mirrorGrp)
         # check mirror indirectSkin bug in Maya2018:
         if (int(cmds.about(version=True)[:4]) == 2018):
             if self.mirrorAxis != 'off':
                 if self.getHasIndirectSkin():
                     meshList = cmds.ls(selection=False, type="mesh")
                     if meshList:
                         self.detectedBug = True
         # finalize this rig:
         self.integratingInfo()
         cmds.select(clear=True)
     # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
     self.deleteModule()
Example #45
0
    def rigModule(self, *args):
        Base.StartClass.rigModule(self)
        # verify if the guide exists:
        if cmds.objExists(self.moduleGrp):
            try:
                hideJoints = cmds.checkBox('hideJointsCB', query=True, value=True)
            except:
                hideJoints = 1
            # declare lists to store names and attributes:
            self.worldRefList, self.headCtrlList = [], []
            self.aCtrls, self.aLCtrls, self.aRCtrls = [], [], []
            # start as no having mirror:
            sideList = [""]
            # analisys the mirror module:
            self.mirrorAxis = cmds.getAttr(self.moduleGrp+".mirrorAxis")
            if self.mirrorAxis != 'off':
                # get rigs names:
                self.mirrorNames = cmds.getAttr(self.moduleGrp+".mirrorName")
                # get first and last letters to use as side initials (prefix):
                sideList = [ self.mirrorNames[0]+'_', self.mirrorNames[len(self.mirrorNames)-1]+'_' ]
                for s, side in enumerate(sideList):
                    duplicated = cmds.duplicate(self.moduleGrp, name=side+self.userGuideName+'_Guide_Base')[0]
                    allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
                    for item in allGuideList:
                        cmds.rename(item, side+self.userGuideName+"_"+item)
                    self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True)
                    cmds.parent(side+self.userGuideName+'_Guide_Base', self.mirrorGrp, absolute=True)
                    # re-rename grp:
                    cmds.rename(self.mirrorGrp, side+self.userGuideName+'_'+self.mirrorGrp)
                    # do a group mirror with negative scaling:
                    if s == 1:
                        for axis in self.mirrorAxis:
                            cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.scale'+axis, -1)
            else: # if not mirror:
                duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName+'_Guide_Base')[0]
                allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
                for item in allGuideList:
                    cmds.rename(item, self.userGuideName+"_"+item)
                self.mirrorGrp = cmds.group(self.userGuideName+'_Guide_Base', name="Guide_Base_Grp", relative=True)
                # re-rename grp:
                cmds.rename(self.mirrorGrp, self.userGuideName+'_'+self.mirrorGrp)
            # store the number of this guide by module type
            dpAR_count = utils.findModuleLastNumber(CLASS_NAME, "dpAR_type") + 1
            # run for all sides
            for s, side in enumerate(sideList):
                # redeclaring variables:
                self.base       = side+self.userGuideName+"_Guide_Base"
                self.cvNeckLoc  = side+self.userGuideName+"_Guide_neck"
                self.cvHeadLoc  = side+self.userGuideName+"_Guide_head"
                self.cvJawLoc   = side+self.userGuideName+"_Guide_jaw"
                self.cvChinLoc  = side+self.userGuideName+"_Guide_chin"
                self.cvLLipLoc  = side+self.userGuideName+"_Guide_lLip"
                self.cvRLipLoc  = side+self.userGuideName+"_Guide_rLip"
                self.cvEndJoint = side+self.userGuideName+"_Guide_JointEnd"
                
                # creating joints:
                self.neckJnt = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['c_neck']+"_Jnt")
                self.headJxt = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['c_head']+"_Jxt")
                cmds.select(clear=True)
                self.headJnt = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['c_head']+"_Jnt", scaleCompensate=False)
                self.jawJnt  = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['c_jaw']+"_Jnt", scaleCompensate=False)
                self.chinJnt = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['c_chin']+"_Jnt", scaleCompensate=False)
                self.endJnt  = cmds.joint(name=side+self.userGuideName+"_JEnd", scaleCompensate=False)
                cmds.select(clear=True)
                self.lLipJnt = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['p002_left']+"_"+self.langDic[self.langName]['c_lip']+"_Jnt", scaleCompensate=False)
                cmds.select(clear=True)
                self.rLipJnt = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['p003_right']+"_"+self.langDic[self.langName]['c_lip']+"_Jnt", scaleCompensate=False)
                dpARJointList = [self.neckJnt, self.headJnt, self.jawJnt, self.chinJnt, self.lLipJnt, self.rLipJnt]
                for dpARJoint in dpARJointList:
                    cmds.addAttr(dpARJoint, longName='dpAR_joint', attributeType='float', keyable=False)
                # creating controls:
                self.neckCtrl = ctrls.cvNeck(ctrlName=side+self.userGuideName+"_"+self.langDic[self.langName]['c_neck']+"_Ctrl", r=self.ctrlRadius/2.0)
                self.headCtrl = ctrls.cvHead(ctrlName=side+self.userGuideName+"_"+self.langDic[self.langName]['c_head']+"_Ctrl", r=self.ctrlRadius/2.0)
                self.jawCtrl  = ctrls.cvJaw( ctrlName=side+self.userGuideName+"_"+self.langDic[self.langName]['c_jaw']+"_Ctrl",  r=self.ctrlRadius/2.0)
                self.chinCtrl = ctrls.cvChin(ctrlName=side+self.userGuideName+"_"+self.langDic[self.langName]['c_chin']+"_Ctrl", r=self.ctrlRadius/2.0)
                self.lLipCtrl = cmds.circle(name=self.langDic[self.langName]['p002_left']+"_"+side+self.userGuideName+"_"+self.langDic[self.langName]['c_lip']+"_Ctrl", ch=False, o=True, nr=(0, 0, 1), d=3, s=8, radius=(self.ctrlRadius * 0.25))[0]
                self.rLipCtrl = cmds.circle(name=self.langDic[self.langName]['p003_right']+"_"+side+self.userGuideName+"_"+self.langDic[self.langName]['c_lip']+"_Ctrl", ch=False, o=True, nr=(0, 0, 1), d=3, s=8, radius=(self.ctrlRadius * 0.25))[0]
                self.headCtrlList.append(self.headCtrl)
                self.aCtrls.append([self.neckCtrl, self.headCtrl, self.jawCtrl, self.chinCtrl])
                self.aLCtrls.append([self.lLipCtrl])
                self.aRCtrls.append([self.rLipCtrl])
                
                #Setup Axis Order
                if self.rigType == Base.RigType.quadruped:
                    cmds.setAttr(self.neckCtrl + ".rotateOrder", 1)
                    cmds.setAttr(self.headCtrl + ".rotateOrder", 1)
                    cmds.setAttr(self.jawCtrl + ".rotateOrder", 1)
                else:
                    cmds.setAttr(self.neckCtrl + ".rotateOrder", 3)
                    cmds.setAttr(self.headCtrl + ".rotateOrder", 3)
                    cmds.setAttr(self.jawCtrl + ".rotateOrder", 3)

                # creating the originedFrom attributes (in order to permit integrated parents in the future):
                utils.originedFrom(objName=self.neckCtrl, attrString=self.base+";"+self.cvNeckLoc)
                utils.originedFrom(objName=self.headCtrl, attrString=self.cvHeadLoc)
                utils.originedFrom(objName=self.jawCtrl, attrString=self.cvJawLoc)
                utils.originedFrom(objName=self.chinCtrl, attrString=self.cvChinLoc+";"+self.cvEndJoint)
                
                # edit the mirror shape to a good direction of controls:
                ctrlList = [ self.neckCtrl, self.headCtrl, self.jawCtrl, self.chinCtrl ]
                if s == 1:
                    for ctrl in ctrlList:
                        if self.mirrorAxis == 'X':
                            cmds.setAttr(ctrl+'.rotateY', 180)
                        elif self.mirrorAxis == 'Y':
                            cmds.setAttr(ctrl+'.rotateY', 180)
                        elif self.mirrorAxis == 'Z':
                            cmds.setAttr(ctrl+'.rotateX', 180)
                            cmds.setAttr(ctrl+'.rotateZ', 180)
                        elif self.mirrorAxis == 'XYZ':
                            cmds.setAttr(ctrl+'.rotateX', 180)
                            cmds.setAttr(ctrl+'.rotateZ', 180)
                    cmds.makeIdentity(ctrlList, apply=True, translate=False, rotate=True, scale=False)

                # temporary parentConstraints:
                tempDelNeck = cmds.parentConstraint(self.cvNeckLoc, self.neckCtrl, maintainOffset=False)
                tempDelHead = cmds.parentConstraint(self.cvHeadLoc, self.headCtrl, maintainOffset=False)
                tempDelJaw  = cmds.parentConstraint(self.cvJawLoc, self.jawCtrl, maintainOffset=False)
                tempDelChin = cmds.parentConstraint(self.cvChinLoc, self.chinCtrl, maintainOffset=False)
                tempDelLLip = cmds.parentConstraint(self.cvLLipLoc, self.lLipCtrl, maintainOffset=False)
                tempDelRLip = cmds.parentConstraint(self.cvRLipLoc, self.rLipCtrl, maintainOffset=False)
                cmds.delete(tempDelNeck, tempDelHead, tempDelJaw, tempDelChin, tempDelLLip, tempDelRLip)
                
                # zeroOut controls:
                self.zeroLipCtrlList = utils.zeroOut([self.lLipCtrl, self.rLipCtrl])
                self.lLipGrp = cmds.group(self.lLipCtrl, name=self.lLipCtrl+"_Grp")
                self.rLipGrp = cmds.group(self.rLipCtrl, name=self.rLipCtrl+"_Grp")
                self.zeroCtrlList = utils.zeroOut([self.neckCtrl, self.headCtrl, self.jawCtrl, self.chinCtrl, self.zeroLipCtrlList[0], self.zeroLipCtrlList[1]])

                # make joints be ride by controls:
                cmds.makeIdentity(self.neckJnt, self.headJxt, self.headJnt, self.jawJnt, self.chinJnt, self.endJnt, rotate=True, apply=True)
                cmds.parentConstraint(self.neckCtrl, self.neckJnt, maintainOffset=False, name=self.neckJnt+"_ParentConstraint")
                cmds.scaleConstraint(self.neckCtrl, self.neckJnt, maintainOffset=False, name=self.neckJnt+"_ScaleConstraint")
                cmds.delete(cmds.parentConstraint(self.headCtrl, self.headJxt, maintainOffset=False))
                cmds.parentConstraint(self.headCtrl, self.headJnt, maintainOffset=False, name=self.headJnt+"_ParentConstraint")
                cmds.parentConstraint(self.jawCtrl, self.jawJnt, maintainOffset=False, name=self.jawJnt+"_ParentConstraint")
                cmds.parentConstraint(self.chinCtrl, self.chinJnt, maintainOffset=False, name=self.chinJnt+"_ParentConstraint")
                cmds.parentConstraint(self.lLipCtrl, self.lLipJnt, maintainOffset=False, name=self.lLipJnt+"_ParentConstraint")
                cmds.parentConstraint(self.rLipCtrl, self.rLipJnt, maintainOffset=False, name=self.rLipJnt+"_ParentConstraint")
                cmds.scaleConstraint(self.headCtrl, self.headJnt, maintainOffset=False, name=self.headJnt+"_ScaleConstraint")
                cmds.scaleConstraint(self.jawCtrl, self.jawJnt, maintainOffset=False, name=self.jawJnt+"_ScaleConstraint")
                cmds.scaleConstraint(self.chinCtrl, self.chinJnt, maintainOffset=False, name=self.chinJnt+"_ScaleConstraint")
                cmds.scaleConstraint(self.lLipCtrl, self.lLipJnt, maintainOffset=False, name=self.lLipJnt+"_ScaleConstraint")
                cmds.scaleConstraint(self.rLipCtrl, self.rLipJnt, maintainOffset=False, name=self.rLipJnt+"_ScaleConstraint")
                cmds.delete(cmds.parentConstraint(self.cvEndJoint, self.endJnt, maintainOffset=False))
                cmds.setAttr(self.jawJnt+".segmentScaleCompensate", 0)
                cmds.setAttr(self.chinJnt+".segmentScaleCompensate", 0)

                # create interations between neck and head:
                self.grpNeck = cmds.group(self.zeroCtrlList[0], name=self.neckCtrl+"_Grp")
                self.grpHeadA = cmds.group(empty=True, name=self.headCtrl+"_A_Grp")
                self.grpHead = cmds.group(self.grpHeadA, name=self.headCtrl+"_Grp")
                # arrange pivots:
                self.neckPivot = cmds.xform(self.neckCtrl, query=True, worldSpace=True, translation=True)
                self.headPivot = cmds.xform(self.headCtrl, query=True, worldSpace=True, translation=True)
                cmds.xform(self.grpNeck, pivots=(self.neckPivot[0], self.neckPivot[1], self.neckPivot[2]))
                cmds.xform(self.grpHead, self.grpHeadA, pivots=(self.headPivot[0], self.headPivot[1], self.headPivot[2]))
                
                self.worldRef = cmds.group(empty=True, name=side+self.userGuideName+"_WorldRef")
                self.worldRefList.append(self.worldRef)
                cmds.delete(cmds.parentConstraint(self.neckCtrl, self.worldRef, maintainOffset=False))
                cmds.parentConstraint(self.neckCtrl, self.grpHeadA, maintainOffset=True, skipRotate=["x", "y", "z"], name=self.grpHeadA+"_ParentConstraint")
                orientConst = cmds.orientConstraint(self.neckCtrl, self.worldRef, self.grpHeadA, maintainOffset=False, name=self.grpHeadA+"_OrientConstraint")[0]
                cmds.scaleConstraint(self.neckCtrl, self.grpHeadA, maintainOffset=True, name=self.grpHeadA+"_ScaleConstraint")
                cmds.parent(self.zeroCtrlList[1], self.grpHeadA, absolute=True)

                # connect reverseNode:
                cmds.addAttr(self.headCtrl, longName=self.langDic[self.langName]['c_Follow'], attributeType='float', minValue=0, maxValue=1, keyable=True)
                cmds.connectAttr(self.headCtrl+'.'+self.langDic[self.langName]['c_Follow'], orientConst+"."+self.neckCtrl+"W0", force=True)
                self.headRevNode = cmds.createNode('reverse', name=side+self.userGuideName+"_Rev")
                cmds.connectAttr(self.headCtrl+'.'+self.langDic[self.langName]['c_Follow'], self.headRevNode+".inputX", force=True)
                cmds.connectAttr(self.headRevNode+'.outputX', orientConst+"."+self.worldRef+"W1", force=True)
                
                # mount controls hierarchy:
                cmds.parent(self.zeroCtrlList[3], self.jawCtrl, absolute=True)
                
                # jaw follow head or root ctrl (using worldRef)
                jawParentConst = cmds.parentConstraint(self.headCtrl, self.worldRef, self.zeroCtrlList[2], maintainOffset=True, name=self.zeroCtrlList[2]+"_ParentConstraint")[0]
                cmds.setAttr(jawParentConst+".interpType", 2) #Shortest, no flip cause problem with scrubing
                cmds.addAttr(self.jawCtrl, longName=self.langDic[self.langName]['c_Follow'], attributeType="float", minValue=0, maxValue=1, defaultValue=1, keyable=True)
                cmds.connectAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_Follow'], jawParentConst+"."+self.headCtrl+"W0", force=True)
                jawFollowRev = cmds.createNode("reverse", name=self.jawCtrl+"_Rev")
                cmds.connectAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_Follow'], jawFollowRev+".inputX", force=True)
                cmds.connectAttr(jawFollowRev+".outputX", jawParentConst+"."+self.worldRef+"W1", force=True)
                cmds.scaleConstraint(self.headCtrl, self.zeroCtrlList[2], maintainOffset=True, name=self.zeroCtrlList[2]+"_ScaleConstraint")[0]

                # setup jaw auto translation
                self.jawSdkGrp = cmds.group(self.jawCtrl, name=self.jawCtrl+"_SDK_Grp")
                cmds.addAttr(self.jawCtrl, longName=self.langDic[self.langName]['c_moveIntensity']+"Y", attributeType='float', keyable=True)
                cmds.addAttr(self.jawCtrl, longName=self.langDic[self.langName]['c_moveIntensity']+"Z", attributeType='float', keyable=True)
                cmds.addAttr(self.jawCtrl, longName=self.langDic[self.langName]['c_moveStartRotation'], attributeType='float', keyable=True)
                cmds.setAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveIntensity']+"Y", keyable=False, channelBox=True)
                cmds.setAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveIntensity']+"Z", keyable=False, channelBox=True)
                cmds.setAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveStartRotation'], keyable=False, channelBox=True)
                cmds.setAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveIntensity']+"Y", 1)
                cmds.setAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveIntensity']+"Z", 2)
                cmds.setAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveStartRotation'], 10)
                self.jawIntensityFixUnitMD = cmds.createNode('multiplyDivide', name="JawMoveIntensityFixUnit_MD")
                self.jawIntensityMD = cmds.createNode('multiplyDivide', name="JawMoveIntensity_MD")
                self.jawIntensityZMD = cmds.createNode('multiplyDivide', name="JawMoveIntensityZ_MD")
                self.jawStartIntensityMD = cmds.createNode('multiplyDivide', name="JawMoveIntensityStart_MD")
                self.jawIntensityPMA = cmds.createNode('plusMinusAverage', name="JawMoveIntensity_PMA")
                self.jawIntensityCnd = cmds.createNode('condition', name="JawMoveIntensity_Cnd")
                cmds.connectAttr(self.jawCtrl+".rotateX", self.jawIntensityMD+".input1Y", force=True)
                cmds.connectAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveIntensity']+"Y", self.jawIntensityFixUnitMD+".input1Y", force=True)
                cmds.connectAttr(self.jawIntensityFixUnitMD+".outputY", self.jawIntensityMD+".input2Y", force=True)
                cmds.setAttr(self.jawIntensityFixUnitMD+".input2Y", -0.01)
                cmds.connectAttr(self.jawIntensityFixUnitMD+".outputY", self.jawStartIntensityMD+".input1X", force=True)
                cmds.connectAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveStartRotation'], self.jawStartIntensityMD+".input2X", force=True)
                cmds.setAttr(self.jawIntensityPMA+".operation", 2)
                cmds.connectAttr(self.jawIntensityMD+".outputY", self.jawIntensityPMA+".input1D[0]", force=True)
                cmds.connectAttr(self.jawStartIntensityMD+".outputX", self.jawIntensityPMA+".input1D[1]", force=True)
                cmds.connectAttr(self.jawIntensityPMA+".output1D", self.jawIntensityCnd+".colorIfTrueG", force=True)
                cmds.connectAttr(self.jawCtrl+".rotateX", self.jawIntensityCnd+".firstTerm", force=True)
                cmds.connectAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveStartRotation'], self.jawIntensityCnd+".secondTerm", force=True)
                cmds.setAttr(self.jawIntensityCnd+".operation", 2)
                cmds.setAttr(self.jawIntensityCnd+".colorIfFalseG", 0)
                cmds.connectAttr(self.jawIntensityCnd+".outColorG", self.jawSdkGrp+".translateY", force=True)
                cmds.connectAttr(self.jawIntensityCnd+".outColorG", self.jawIntensityZMD+".input1Z", force=True)
                cmds.connectAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveIntensity']+"Z", self.jawIntensityFixUnitMD+".input1Z", force=True)
                cmds.setAttr(self.jawIntensityFixUnitMD+".input2Z", -0.1)
                cmds.connectAttr(self.jawIntensityFixUnitMD+".outputZ", self.jawIntensityZMD+".input2Z", force=True)
                cmds.connectAttr(self.jawIntensityZMD+".outputZ", self.jawSdkGrp+".translateZ", force=True)

                # create lip setup:
                # left side lip:
                lLipParentConst = cmds.parentConstraint(self.jawCtrl, self.headCtrl, self.lLipGrp, maintainOffset=True, name=self.lLipGrp+"_ParentConstraint")[0]
                cmds.setAttr(lLipParentConst+".interpType", 2)
                cmds.addAttr(self.lLipCtrl, longName=self.langDic[self.langName]['c_Follow'], attributeType='float', minValue=0, maxValue=1, defaultValue=0.5, keyable=True)
                cmds.connectAttr(self.lLipCtrl+'.'+self.langDic[self.langName]['c_Follow'], lLipParentConst+"."+self.jawCtrl+"W0", force=True)
                self.lLipRevNode = cmds.createNode('reverse', name=side+self.userGuideName+"_"+self.langDic[self.langName]['p002_left']+"_"+self.langDic[self.langName]['c_lip']+"_Rev")
                cmds.connectAttr(self.lLipCtrl+'.'+self.langDic[self.langName]['c_Follow'], self.lLipRevNode+".inputX", force=True)
                cmds.connectAttr(self.lLipRevNode+'.outputX', lLipParentConst+"."+self.headCtrl+"W1", force=True)
                cmds.scaleConstraint(self.headCtrl, self.lLipGrp, maintainOffset=True, name=self.lLipGrp+"_ScaleConstraint")[0]
                # right side lip:
                rLipParentConst = cmds.parentConstraint(self.jawCtrl, self.headCtrl, self.rLipGrp, maintainOffset=True, name=self.rLipGrp+"_ParentConstraint")[0]
                cmds.setAttr(rLipParentConst+".interpType", 2)
                cmds.addAttr(self.rLipCtrl, longName=self.langDic[self.langName]['c_Follow'], attributeType='float', minValue=0, maxValue=1, defaultValue=0.5, keyable=True)
                cmds.connectAttr(self.rLipCtrl+'.'+self.langDic[self.langName]['c_Follow'], rLipParentConst+"."+self.jawCtrl+"W0", force=True)
                self.rLipRevNode = cmds.createNode('reverse', name=side+self.userGuideName+"_"+self.langDic[self.langName]['p003_right']+"_"+self.langDic[self.langName]['c_lip']+"_Rev")
                cmds.connectAttr(self.rLipCtrl+'.'+self.langDic[self.langName]['c_Follow'], self.rLipRevNode+".inputX", force=True)
                cmds.connectAttr(self.rLipRevNode+'.outputX', rLipParentConst+"."+self.headCtrl+"W1", force=True)
                cmds.scaleConstraint(self.headCtrl, self.rLipGrp, maintainOffset=True, name=self.rLipGrp+"_ScaleConstraint")[0]
                
                # create a locator in order to avoid delete static group
                loc = cmds.spaceLocator(name=side+self.userGuideName+"_DO_NOT_DELETE")[0]
                cmds.parent(loc, self.worldRef, absolute=True)
                cmds.setAttr(loc+".visibility", 0)
                ctrls.setLockHide([loc], ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'])
                
                # hiding visibility attributes:
                ctrls.setLockHide([self.headCtrl, self.neckCtrl, self.jawCtrl, self.chinCtrl], ['v'], l=False)
                
                # create a masterModuleGrp to be checked if this rig exists:
                self.toCtrlHookGrp     = cmds.group(self.grpNeck, self.grpHead, self.zeroCtrlList[2], self.zeroCtrlList[4], self.zeroCtrlList[5], name=side+self.userGuideName+"_Control_Grp")
                self.toScalableHookGrp = cmds.group(self.neckJnt, self.headJnt, self.lLipJnt, self.rLipJnt, name=side+self.userGuideName+"_Joint_Grp")
                self.toStaticHookGrp   = cmds.group(self.toCtrlHookGrp, self.toScalableHookGrp, self.grpHead, self.worldRef, name=side+self.userGuideName+"_Grp")
                cmds.addAttr(self.toStaticHookGrp, longName="dpAR_name", dataType="string")
                cmds.addAttr(self.toStaticHookGrp, longName="dpAR_type", dataType="string")
                cmds.setAttr(self.toStaticHookGrp+".dpAR_name", self.userGuideName, type="string")
                cmds.setAttr(self.toStaticHookGrp+".dpAR_type", CLASS_NAME, type="string")
                # add module type counter value
                cmds.addAttr(self.toStaticHookGrp, longName='dpAR_count', attributeType='long', keyable=False)
                cmds.setAttr(self.toStaticHookGrp+'.dpAR_count', dpAR_count)
                # add hook attributes to be read when rigging integrated modules:
                utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
                utils.addHook(objName=self.grpHead, hookType='rootHook')
                utils.addHook(objName=self.toScalableHookGrp, hookType='scalableHook')
                utils.addHook(objName=self.toStaticHookGrp, hookType='staticHook')

                #Ensure head Jxt matrix
                mHead = cmds.getAttr(self.headCtrl + ".worldMatrix")
                cmds.xform(self.headJxt, m=mHead, ws=True)

                if hideJoints:
                    cmds.setAttr(self.toScalableHookGrp+".visibility", 0)
                
                # delete duplicated group for side (mirror):
                cmds.delete(side+self.userGuideName+'_'+self.mirrorGrp)
            # finalize this rig:
            self.integratingInfo()
            cmds.select(clear=True)
        # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
        self.deleteModule()
def VK_system(num_ctr=1, num_jt=20, fk=True):
    """
	final assembly of the entire system
	"""
    fk_hide_attr = lambda node, b: [
        cmds.setAttr('%s.%s' % (node, a), l=b, k=not b)
        for a in 'tx,ty,tz,sx,sy,sz,v'.split(',')
    ]
    ik_hide_attr = lambda node, b: [
        cmds.setAttr('%s.%s' % (node, a), l=b, k=not b)
        for a in 'tx,ty,tz,ry,rz,sx,sy,sz,v'.split(',')
    ]
    ctrl_hide_attr = lambda node, b: [
        cmds.setAttr('%s.%s' % (node, a), l=b, k=not b)
        for a in 'rx,ry,rz,sx,sy,sz,v'.split(',')
    ]

    orig_cu = setup.get_curve()[0]
    cu = cmds.duplicate(orig_cu, n='vks_curve#')[0]
    jts = setup.chain(cu, num_jt, 'vks_orig_joint')
    d_jts = setup.chain(cu, num_jt, 'vks_skin_joint')
    cmds.toggle(d_jts, localAxis=True)
    parameter_attr(jts)
    #loft,skin
    surf = create_loft(jts, 'vks_lofted_mesh')
    surf_s = cmds.listRelatives(surf, c=1)[0]
    #hierarchical groups
    vks_grp = cmds.group(surf, name='VariableKinematicsSystem#')
    mov_grp = cmds.group(em=True, parent=vks_grp, name='vks_move_grp#')
    rig_grp = cmds.group(em=True, parent=vks_grp, name='vks_rig_grp#')
    flc_grp = cmds.group(em=True, parent=rig_grp, name='vks_follice_grp#')
    setup.lock_attr(flc_grp, 1)
    setup.off_vis(rig_grp)

    #create vks controls
    vks_ctr = []
    vks_ctr_grp = []
    for i in range(num_ctr):
        #create follice
        vPos = setup.linstep(0., num_ctr - 1, i)
        flc = setup.create_follicle(surf_s, 0.5, vPos, 'vks_follice')
        flc_tr = cmds.listRelatives(flc, p=1)[0]
        cmds.parent(flc_tr, flc_grp)
        #create control
        vkss = create_control(flc, 'vks_parametric')
        vks_ctr_grp.append(vkss[0])
        vks_ctr.append(vkss[-1])
    #ikspline
    ikhnd = cmds.ikHandle(sj=jts[0],
                          ee=jts[-1],
                          c=cu,
                          ccv=False,
                          sol='ikSplineSolver')
    #create joint orig group
    org_grp = cmds.group(jts[0], parent=rig_grp, n='vks_orig_grp#')
    rot = cmds.xform(jts[0], q=True, ws=True, ro=True)
    cmds.xform(org_grp, ws=True, ro=(rot[0], rot[1], rot[2]), piv=(0, 0, 0))
    cmds.parent(cu, ikhnd[0], rig_grp)

    #building explicit control
    m_ctr = setup.ctrl_cube('vks_explicit#', sz=2)
    cmds.parent(m_ctr, vks_grp)
    tr = cmds.xform(jts[0], q=True, ws=True, t=True)
    cmds.xform(m_ctr, ws=True, t=tr)
    cmds.makeIdentity(m_ctr, apply=1, t=1, r=1, s=1, n=0)
    cmds.parent(vks_ctr_grp, m_ctr)

    cmds.parentConstraint(m_ctr, org_grp, mo=1)
    cmds.parentConstraint(m_ctr, mov_grp, mo=1)
    cmds.scaleConstraint(m_ctr, mov_grp)

    if fk:  #FK module
        for c in vks_ctr:
            fk_hide_attr(c, 1)
            for j in jts:
                jgroup = cmds.group(j, n='%s_%s' % (j, c))
                piv = cmds.xform(j, q=True, ws=True, piv=True)
                cmds.xform(jgroup, ws=True, piv=(piv[0], piv[1], piv[2]))
                connection(c, j, jgroup)

        for n, j in enumerate(jts):
            cmds.parentConstraint(j, d_jts[n])
        #fk length
        cmds.addAttr(m_ctr, ln='length', at='double', k=1, min=0, max=10, dv=1)
        v_tx = cmds.getAttr('%s.tx' % jts[1])
        pma = cmds.createNode('plusMinusAverage',
                              n='vfk_lengthConversion_%s' % m_ctr)
        cmds.setAttr("%s.input1D[0]" % pma, -1)
        cmds.setAttr("%s.input1D[1]" % pma, v_tx)
        cmds.connectAttr('%s.length' % m_ctr, '%s.input1D[2]' % pma)
        for j in jts[1:-1]:
            cmds.connectAttr('%s.output1D' % pma, '%s.tx' % j)

        cmds.scaleConstraint(m_ctr, org_grp)
        cmds.parent(d_jts[0], mov_grp)
        cmds.delete(ikhnd)
    if not fk:  #IK module
        jj = [j for j in jts]
        for c in vks_ctr:
            ik_hide_attr(c, 1)
            for n, j in enumerate(jts):
                jgroup = cmds.group(em=True, n='%s_%s' % (j, c), parent=jj[n])
                jj[n] = jgroup
                connection(c, j, jgroup)
        for n in range(num_jt):
            cmds.parentConstraint(jj[n], d_jts[n])
        #ik stretch
        cu_sc = ik_stretch(ikhnd[0])
        cmds.addAttr(m_ctr,
                     ln="stretch",
                     at='double',
                     k=1,
                     min=0,
                     max=10,
                     dv=10)
        ucn = setup.onetenthNode(m_ctr, 'stretch')
        cmds.connectAttr('%s.output' % ucn, '%s.ik_stretch' % ikhnd[0])

        cls_grp = cmds.group(em=True, name='vks_cluster_grp#')
        setup.off_vis(cls_grp)
        ik_cls = cluster_on_curve(cu)
        for ik_cl in ik_cls:
            l_ctrl, l_null = setup.local_cluster_control2(ik_cl)
            ctrl_hide_attr(l_ctrl, 1)
            cmds.parent(l_ctrl, m_ctr)
            cmds.parent(ik_cl, l_null, cls_grp)
        cmds.parent(d_jts[0], cls_grp, cu_sc, mov_grp)

    cmds.select(cl=True)
Example #47
0
def broken_fk():
    '''Creates a broken fk system along a single chain of joints'''

    #Variables
    master_control_grp = ''
    last_ctrl = ''
    first_pass = '******'
    replace = "Jnt"

    #Get selection with hierarchy
    cmds.select(hi=True)
    sels = cmds.ls(sl=True)

    #Loop through selection
    for sel in sels:
        #Set up control names
        if replace in sel:
            ctrl_name = sel.replace(replace, "FK_Ctrl")
            grp_name = sel.replace(replace, "FK_Grp")
        else:
            ctrl_name = '%s_FK_Ctrl' % sel
            grp_name = '%s_FK_Grp' % sel

        #Create control and control group
        ctrl = cmds.circle(c=(0, 0, 0),
                           nr=(1, 0, 0),
                           sw=360,
                           r=1,
                           d=3,
                           ut=0,
                           tol=0,
                           s=8,
                           ch=0,
                           n=ctrl_name)
        grp = cmds.group(ctrl, n=grp_name)

        #Match control group to joint transform
        pos = cmds.xform(sel, q=True, rotatePivot=True, ws=True)
        rot = cmds.xform(sel, q=True, ro=True, ws=True)
        cmds.move(pos[0], pos[1], pos[2], grp, ws=True, a=True, rpr=True)
        cmds.rotate(rot[0], rot[1], rot[2], grp, a=True, ws=True)

        #Constrain joint to control
        cmds.parentConstraint(ctrl, sel)
        cmds.scaleConstraint(ctrl, sel)

        #Add Follow Transform and Follow Rotate
        cmds.addAttr(ctrl[0],
                     ln='FollowTransform',
                     at='double',
                     min=0,
                     max=1,
                     dv=True,
                     keyable=True)
        cmds.addAttr(ctrl[0],
                     ln='FollowRotate',
                     at='double',
                     min=0,
                     max=1,
                     dv=True,
                     keyable=True)

        #If its the first control
        if first_pass == 'true':
            first_pass = '******'

            #Create master control, move, rotate, and freeze transformations
            master_ctrl = cmds.spaceLocator(n='%s_Master_Ctrl' % sel)
            cmds.move(pos[0],
                      pos[1],
                      pos[2],
                      master_ctrl,
                      ws=True,
                      a=True,
                      rpr=True)
            cmds.rotate(rot[0], rot[1], rot[2], master_ctrl, a=True, ws=True)
            cmds.makeIdentity(master_ctrl, apply=True)

            #Create master ctrl group and constain it to master ctrl
            master_ctrl_grp = cmds.group(empty=True, n='%s_Master_Grp' % sel)
            cmds.scaleConstraint(master_ctrl, master_ctrl_grp)
            cmds.parent(grp, master_ctrl_grp)

            #Constrain first control to master control
            transform_constraint = cmds.parentConstraint(
                master_ctrl,
                grp,
                mo=True,
                skipTranslate=('x', 'y', 'z'),
                n='%s_parentTransformConstaint' % grp)
            rotate_constraint = cmds.parentConstraint(
                master_ctrl,
                grp,
                mo=True,
                skipRotate=('x', 'y', 'z'),
                n='%s_parentRotateConstaint' % grp)

            #Create main control croup
            main_ctrl_grp = cmds.group(master_ctrl, n='%s_Ctrl_Grp' % sel)
            cmds.parent(master_ctrl_grp, main_ctrl_grp)

            #Connect Follow Transform and Follow Rotate
            cmds.connectAttr('%s.FollowTransform' % ctrl[0],
                             transform_constraint[0] +
                             '.%sW0' % master_ctrl[0],
                             f=True)
            cmds.connectAttr('%s.FollowRotate' % ctrl[0],
                             rotate_constraint[0] + '.%sW0' % master_ctrl[0],
                             f=True)

            #Create 'Controls' group if it doesn't exist
            if cmds.objExists('Controls'):
                cmds.parent(main_ctrl_grp, 'Controls')
            else:
                controls_grp = cmds.group(main_ctrl_grp, n='Controls')
                if cmds.listRelatives(controls_grp, p=True):
                    cmds.parent(controls_grp, world=True)

            #Create 'Skeleton' group if it doesn't exist
            if cmds.objExists('Skeleton'):
                if cmds.listRelatives(sel, p=True):
                    cmds.parent(sel, world=True)
                cmds.parent(sel, 'Skeleton')
            else:
                skeleton_grp = cmds.group(sel, n='Skeleton')
                if cmds.listRelatives(skeleton_grp, p=True):
                    cmds.parent(skeleton_grp, world=True)

        #If it's not the first control
        else:
            #Move to master control group
            cmds.parent(grp, master_ctrl_grp)

            #Contrain to previous control
            transform_constraint = cmds.parentConstraint(
                last_ctrl,
                grp,
                mo=True,
                skipRotate=('x', 'y', 'z'),
                n='%s_parentTransformConstaint' % grp)
            rotate_constraint = cmds.parentConstraint(
                last_ctrl,
                grp,
                mo=True,
                skipTranslate=('x', 'y', 'z'),
                n='%s_parentRotateConstaint' % grp)

            #Connect Follow Transform and Follow Rotate
            cmds.connectAttr('%s.FollowTransform' % ctrl[0],
                             transform_constraint[0] + '.%sW0' % last_ctrl[0],
                             f=True)
            cmds.connectAttr('%s.FollowRotate' % ctrl[0],
                             rotate_constraint[0] + '.%sW0' % last_ctrl[0],
                             f=True)

        #Save last ctrl
        last_ctrl = ctrl

        #Freeze Transformations and delete history
        cmds.makeIdentity(ctrl, apply=True)
        #cmds.delete(ctrl, ch=True)

        #Lock and/or hide scale and visibility
        cmds.setAttr('%s.v' % ctrl[0],
                     lock=True,
                     keyable=False,
                     channelBox=False)
        cmds.setAttr('%s.sx' % ctrl[0], lock=True, keyable=False)
        cmds.setAttr('%s.sy' % ctrl[0], lock=True, keyable=False)
        cmds.setAttr('%s.sz' % ctrl[0], lock=True, keyable=False)

    #Clear selection
    cmds.select(clear=True)
Example #48
0
def ribbonize(surf_tr,
              equal=1,
              num_of_ctrls=5,
              num_of_jnts=29,
              prefix="",
              constrain=1,
              add_fk=0,
              wire=0):

    attrs = [
        ".tx", ".ty", ".tz", ".rx", ".ry", ".rz", ".sx", ".sy", ".sz", ".v"
    ]

    if prefix == "":
        mc.warning("care to name it?")
        return

    else:
        prefix = prefix + "_"

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

    surf_tr = mc.rename(surf_tr, prefix + "ribbon_surface")
    surf = mc.listRelatives(surf_tr, shapes=True)[0]

    # freeze transformations and delete the surface history
    mc.makeIdentity(surf_tr, t=True, r=True, s=True, apply=True)
    mc.delete(surf_tr, ch=True)

    # duplicate surface curves to determine the direction
    u_curve = mc.duplicateCurve(surf_tr + ".v[.5]", local=True, ch=0)
    v_curve = mc.duplicateCurve(surf_tr + ".u[.5]", local=True, ch=0)

    # delete the history just in case
    mc.delete(surf_tr, ch=True)

    u_length = mc.arclen(u_curve)
    v_length = mc.arclen(v_curve)

    if u_length < v_length:
        mc.reverseSurface(surf_tr, d=3, ch=False, rpo=True)
        mc.reverseSurface(surf_tr, d=0, ch=False, rpo=True)

    parameter = ".parameterU"
    other_param = ".parameterV"

    # correct u_curve after reversing to calculate the length
    u_curve_corr = mc.duplicateCurve(surf_tr + ".v[.5]", local=True, ch=0)[0]

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

    # selected surface is periodic or open? (cylinder or a plane)
    if mc.getAttr(surf + ".formU") == 2 or mc.getAttr(surf + ".formV") == 2:
        curve_type = "periodic"
        divider_for_ctrls = num_of_ctrls
    elif mc.getAttr(surf + ".formU") == 0 or mc.getAttr(surf + ".formV") == 0:
        curve_type = "open"
        divider_for_ctrls = num_of_ctrls - 1

    #############################################################################
    param_ctrls = param_from_length(u_curve_corr, num_of_ctrls, curve_type,
                                    "uv")
    param_joints = param_from_length(u_curve_corr, num_of_jnts, curve_type,
                                     "uv")

    length = mc.arclen(u_curve_corr)
    mc.delete(u_curve, v_curve, u_curve_corr)

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

    # create groups, main control and main control offset
    final_group = mc.group(n=prefix + "ribbon_grp", em=True)
    ctrl_joints_grp = mc.group(n=prefix + "ctrl_joints_grp", em=True)
    ctrl_grp = mc.group(n=prefix + "ctrls_grp", em=True)
    follicles_grp = mc.group(n=prefix + "follicles_grp", em=True)
    rig_grp = mc.group(n=prefix + "rig_grp", em=True)
    main_ctrl = mc.circle(n=prefix + "ctrl_main",
                          nr=(0, 1, 0),
                          r=length / 5,
                          ch=0)[0]
    main_ctrl_offset = mc.group(n=prefix + "ctrl_main_offset", em=True)

    mc.parent(main_ctrl, main_ctrl_offset)
    mc.parent(ctrl_grp, main_ctrl)
    mc.parent(main_ctrl_offset, rig_grp, final_group)
    mc.parent(surf_tr, ctrl_joints_grp, follicles_grp, rig_grp)

    # move main_ctrl_offset to the center of the surfaces bbox (in case its pivot is somewhere else)
    mid_point = get_bbox_center(surf_tr)
    for attr, mid_pnt_el in izip(attrs[:3], mid_point):
        mc.setAttr(main_ctrl_offset + attr, mid_pnt_el)

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

    fols = []
    fols_tr = []
    bind_jnts = []
    bnd_joints_rad = (length / 60) / (float(num_of_jnts) / 40)

    for x in range(num_of_jnts):

        fol = mc.createNode("follicle")
        mc.setAttr(fol + ".visibility", 0)
        temp_fol = mc.listRelatives(fol, p=True)[0]
        fols_tr.append(
            mc.rename(temp_fol, "{}follicle_{:02d}".format(prefix, x + 1)))
        fols.append(mc.listRelatives(fols_tr[-1], s=True)[0])

        # connect follicle shapes to their transforms
        mc.connectAttr(fols[-1] + ".outTranslate",
                       fols_tr[-1] + ".translate",
                       f=True)
        mc.connectAttr(fols[-1] + ".outRotate",
                       fols_tr[-1] + ".rotate",
                       f=True)

        # attach follicle shapes to the surface
        mc.connectAttr(surf + ".worldMatrix[0]",
                       fols[-1] + ".inputWorldMatrix")
        mc.connectAttr(surf + ".local", fols[-1] + ".inputSurface")

        mc.setAttr(fols[-1] + parameter, param_joints[x])
        mc.setAttr(fols[-1] + other_param, 0.5)

        mc.parent(fols_tr[-1], follicles_grp)

        # create final bind joints on the surface
        bind_jnts.append(
            mc.createNode("joint", n="{}bnd_jnt_{:02d}".format(prefix, x + 1)))

        mc.parent(bind_jnts[-1], fols_tr[-1], r=True)
        mc.setAttr(bind_jnts[-1] + ".radius", bnd_joints_rad)

    set_color(bind_jnts, "mid_blue")

    #create temp follicles for control offset groups to align
    temp_fols = []
    temp_fols_tr = []

    for x in range(num_of_ctrls):

        temp_fols.append(mc.createNode("follicle"))
        temp_fols_tr.append(mc.listRelatives(temp_fols[-1], p=True)[0])

        mc.connectAttr(temp_fols[-1] + ".outTranslate",
                       temp_fols_tr[-1] + ".translate",
                       f=True)
        mc.connectAttr(temp_fols[-1] + ".outRotate",
                       temp_fols_tr[-1] + ".rotate",
                       f=True)

        mc.connectAttr(surf + ".worldMatrix[0]",
                       temp_fols[-1] + ".inputWorldMatrix")
        mc.connectAttr(surf + ".local", temp_fols[-1] + ".inputSurface")

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

    if equal == 1:
        for x, temp_fol in enumerate(temp_fols):
            mc.setAttr(temp_fol + parameter, param_ctrls[x])
            mc.setAttr(temp_fol + other_param, 0.5)
    if equal == 0:
        v = 0
        for temp_fol in temp_fols:
            mc.setAttr(temp_fol + parameter, v)
            mc.setAttr(temp_fol + other_param, 0.5)
            v = v + (1.0 / divider_for_ctrls)

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

    #create controls and control joints
    controls = ctrl_maker(prefix,
                          ctrl_type="cube",
                          count=num_of_ctrls,
                          deg=3,
                          sp=8)

    ctrl_ofs_grps = []
    ctrl_joints = []
    ctrl_jnt_ofs_grps = []
    ctrl_joints_rad = bnd_joints_rad * 2
    ik_ctrl_scale = (length / 35) / (float(num_of_ctrls) / 5)

    for x, ctrl in enumerate(controls):

        ctrl_ofs_grp = mc.group(ctrl, n="{}_offset".format(ctrl))
        mc.delete(mc.parentConstraint(temp_fols_tr[x], ctrl_ofs_grp))
        ctrl_ofs_grps.append(ctrl_ofs_grp)

        #scale ik controls
        ctrl_shapes = mc.listRelatives(ctrl, s=True)
        for ctrl_shape in ctrl_shapes:
            ctrl_cvs_count = mc.getAttr(ctrl_shape + ".controlPoints",
                                        size=True)
            mc.scale(ik_ctrl_scale,
                     ik_ctrl_scale,
                     ik_ctrl_scale,
                     "{}.cv[0:{}]".format(ctrl_shape, ctrl_cvs_count - 1),
                     r=True,
                     ocp=True)

        #create the control joints
        ctrl_joints.append(
            mc.createNode("joint", n="{}ctrl_jnt_{:02d}".format(prefix,
                                                                x + 1)))
        #set the radius of controls joints to 2 times that of the surface joints
        mc.setAttr(ctrl_joints[x] + ".radius", ctrl_joints_rad)
        #create offset groups for ctrl joints
        ctrl_jnt_ofs_grp = mc.group(ctrl_joints[-1],
                                    n="{}_offset".format(ctrl_joints[-1]))
        mc.delete(mc.parentConstraint(temp_fols_tr[x], ctrl_jnt_ofs_grp))
        ctrl_jnt_ofs_grps.append(ctrl_jnt_ofs_grp)

    ###
    set_color(controls, "green")
    set_color(ctrl_joints, "red")

    mc.parent(ctrl_ofs_grps, ctrl_grp)
    mc.parent(ctrl_jnt_ofs_grps, ctrl_joints_grp)

    lock_hide(ctrl_ofs_grps, attrs[:9])
    lock_hide(ctrl_jnt_ofs_grps, attrs[:9])

    mc.delete(temp_fols_tr)

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

    #determine if constraint or connection method is chosen
    if constrain == 0:
        for (c, j) in izip(controls, ctrl_joints):
            for attr in attrs[:7]:  #skip scale attributes
                mc.connectAttr(c + attr, j + attr)

        mc.parentConstraint(main_ctrl, ctrl_joints_grp, mo=True)
        mc.scaleConstraint(main_ctrl, ctrl_joints_grp)

        #scale the follicles with the main control
        for flt in fols_tr:
            mc.connectAttr(main_ctrl + ".sx", flt + ".sx")
            mc.connectAttr(main_ctrl + ".sx", flt + ".sy")
            mc.connectAttr(main_ctrl + ".sx", flt + ".sz")

    elif constrain == 1:
        for (c, j) in izip(controls, ctrl_joints):
            mc.parentConstraint(c, j)
            mc.scaleConstraint(c, j)

        #scale the follicles with the main control
        for flt in fols_tr:
            mc.scaleConstraint(main_ctrl, flt)

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

    if wire == True and num_of_ctrls > 1:

        temp_crv = mc.duplicateCurve(surf_tr + ".v[.5]",
                                     n=prefix + "wire_crv",
                                     local=False,
                                     ch=0)[0]

        if num_of_ctrls == 2:
            degree = 1
        else:
            degree = 3

        wire_crv = mc.curve(p=param_from_length(
            temp_crv, num_of_ctrls + (num_of_ctrls - 1), "open", "world"),
                            d=degree)

        mc.delete(temp_crv)

        wire_crv = mc.rename(
            wire_crv, prefix + "wire_crv"
        )  # if name at the creation time, the shape doesn't get renamed
        mc.delete(wire_crv, ch=True)
        wire = mc.wire(surf_tr,
                       gw=False,
                       en=1.0,
                       ce=0.0,
                       li=0.0,
                       dds=(0, 50),
                       w=wire_crv,
                       n=prefix + "wire")[0]
        mc.connectAttr(main_ctrl + ".sx", wire + ".scale[0]")

        cps = param_from_length(wire_crv,
                                num_of_ctrls,
                                "open",
                                "uv",
                                normalized=False)

        for cp in cps:
            mc.select("{}.u[{}]".format(wire_crv, cp), r=True)
            mc.dropoffLocator(1.0, 1.0, wire)

        mc.select(cl=True)

        for x, ctrl in enumerate(controls):
            mc.connectAttr(ctrl + ".rx",
                           "{}.wireLocatorTwist[{}]".format(wire, x))

        wire_grp = mc.group(wire_crv,
                            wire_crv + "BaseWire",
                            n=prefix + "wire_crv_grp")
        mc.parent(wire_grp, rig_grp)
        lock_hide([wire_grp], attrs[:9])

        wire_skin_cluster = mc.skinCluster(ctrl_joints,
                                           wire_crv,
                                           dr=2,
                                           mi=2,
                                           bm=0)[0]

    else:
        #bind the surface to the joints
        nurbs_skin_cluster = mc.skinCluster(ctrl_joints,
                                            surf_tr,
                                            dr=2,
                                            mi=num_of_ctrls - 1,
                                            ns=num_of_ctrls * 5,
                                            bm=0,
                                            n=prefix + "skinCluster")[0]
        mc.skinPercent(nurbs_skin_cluster, surf_tr, pruneWeights=0.2)

    if wire == True and num_of_ctrls == 1:
        mc.warning("wire skipped. at least 2 controls needed")

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

    mc.setAttr(surf_tr + ".v", 0)
    mc.setAttr(rig_grp + ".v", 0)

    mc.connectAttr(main_ctrl + ".sx", main_ctrl + ".sy")
    mc.connectAttr(main_ctrl + ".sx", main_ctrl + ".sz")
    mc.aliasAttr("Scale", main_ctrl + ".sx")

    set_color(main_ctrl, "yellow")

    mc.connectAttr(main_ctrl_offset + ".sx", main_ctrl_offset + ".sy")
    mc.connectAttr(main_ctrl_offset + ".sx", main_ctrl_offset + ".sz")
    mc.aliasAttr("Scale", main_ctrl_offset + ".sx")

    #lock and hide attributes
    lock_hide([
        final_group, follicles_grp, ctrl_joints_grp, surf_tr, ctrl_grp, rig_grp
    ], attrs[:9])
    lock_hide([ctrl_grp, main_ctrl, main_ctrl_offset], attrs[7:])
    lock_hide(controls, attrs[7:])

    #clear selection
    mc.select(
        cl=True
    )  #if selection isn't cleared a control joint gets added to the bind joints set

    #create a set with bind joints
    bind_jnts_set = mc.sets(n=prefix + "bind_jnts_set")
    mc.sets(bind_jnts, add=bind_jnts_set)

    mc.select(cl=True)

    ik_ctrls_set = mc.sets(n=prefix + "ik_ctrls_set")
    mc.sets(controls, add=ik_ctrls_set)

    mc.select(cl=True)

    controls_set = mc.sets(n=prefix + "controls_set")
    mc.sets(main_ctrl, ik_ctrls_set, add=controls_set)

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

    if add_fk == 1 and mc.getAttr(surf + ".formU") != 2 and mc.getAttr(
            surf + ".formV") != 2:

        fk_ctrls, fk_ctrl_off_grps = make_fk_ctrls(prefix, num_of_ctrls)
        mc.parent(fk_ctrl_off_grps[0], ctrl_grp)

        #scale fk controls
        fk_ctrl_scale = ik_ctrl_scale * 2

        for fk_ctrl in fk_ctrls:
            fk_ctrl_shapes = mc.listRelatives(fk_ctrl, s=True)
            for fk_ctrl_shape in fk_ctrl_shapes:
                fk_ctrl_cvs_count = mc.getAttr(fk_ctrl_shape +
                                               ".controlPoints",
                                               size=True)
                mc.scale(fk_ctrl_scale,
                         fk_ctrl_scale,
                         fk_ctrl_scale,
                         "{}.cv[0:{}]".format(fk_ctrl_shape,
                                              fk_ctrl_cvs_count - 1),
                         r=True,
                         ocp=True)

        #add fk controls to a set
        mc.select(cl=True)
        fk_ctrls_set = mc.sets(n=prefix + "fk_ctrls_set")
        mc.sets(fk_ctrls, add=fk_ctrls_set)

        ########
        ik_ctrl_constr_grps = [
            mc.group(ctrl, n=ctrl + "_constr_grp") for ctrl in controls
        ]
        [
            mc.xform(ik_ctrl_constr_grp, piv=(0, 0, 0), os=True)
            for ik_ctrl_constr_grp in ik_ctrl_constr_grps
        ]

        for ik, fk in izip(controls[:-1], fk_ctrl_off_grps):
            mc.delete(mc.parentConstraint(ik, fk))

        for fk, ik in izip(fk_ctrls, ik_ctrl_constr_grps[:-1]):
            mc.parentConstraint(fk, ik)

        #constrain last ik ctrl
        mc.parentConstraint(fk_ctrls[-1], ik_ctrl_constr_grps[-1], mo=True)
        lock_hide(ik_ctrl_constr_grps, attrs[:9])

        ########
        set_color(fk_ctrls, "blue")
        lock_hide(fk_ctrl_off_grps, attrs[:9])

        mc.sets(fk_ctrls_set, add=controls_set)

        mc.select(cl=True)

    elif add_fk == 1 and (mc.getAttr(surf + ".formU") == 2
                          or mc.getAttr(surf + ".formV") == 2):

        mc.warning("surface is periodic. fk controls skipped")

    ################ADD MESSAGE ATTRS################

    mc.addAttr(main_ctrl, ln="joints", at="message")
    mc.addAttr(main_ctrl, ln="follicles", at="message")
    mc.addAttr(main_ctrl, ln="surface", at="message")

    if mc.attributeQuery("i_am_the_surface", node=surf, exists=True) == False:
        mc.addAttr(surf, ln="i_am_the_surface", at="message")

    mc.connectAttr(main_ctrl + ".surface", surf + ".i_am_the_surface")

    for j, f in izip(bind_jnts, fols):
        mc.addAttr(j, ln="i_am_a_joint", at="message")
        mc.addAttr(f, ln="i_am_a_follicle", at="message")
        mc.connectAttr(main_ctrl + ".joints", j + ".i_am_a_joint")
        mc.connectAttr(main_ctrl + ".follicles", f + ".i_am_a_follicle")
Example #49
0
def mkTwistSplineControllers(pfx, numCVs, spread, closed=False):
    """ Make and position all the controller objects

	Arguments:
		pfx (str): The user name of the spline. Will be formatted into the given naming convention
		numCVs (int): The number of CVs to create for a spline
		spread (float): The distance between each controller (including tangents)
		closed (bool): Whether the spline forms a closed loop

	Returns:
		[str, ...]: All the CV's
		[str, ...]: All the CV Buffers
		[str, ...]: All the Out-Tangents
		[str, ...]: All the In-Tangents
		[str, ...]: All the Auto-Out-Tangents
		[str, ...]: All the Auto-In-Tangents
		[str, ...]: All the Twisters
		[str, ...]: All the Twister Buffers
		str: The base controller
	"""

    # Make bases for the controllers
    cvCtrl, outTanCtrl, inTanCtrl, twistCtrl, masterCtrl = _mkMasterControllers(
    )

    master = cmds.duplicate(masterCtrl, name=MASTER_FMT.format(pfx))[0]
    cmds.addAttr(master,
                 longName="Offset",
                 attributeType='double',
                 defaultValue=0.0)
    cmds.setAttr(master + '.Offset', edit=True, keyable=True)
    cmds.addAttr(master,
                 longName="Stretch",
                 attributeType='double',
                 defaultValue=1.0,
                 minValue=0.0001)
    cmds.setAttr(master + '.Stretch', edit=True, keyable=True)

    # make the requested number of CV's
    # don't hide the .rx attribute
    cvs, tws, cvBfrs, twBfrs = [], [], [], []
    controlsGrp = cmds.createNode("transform", name=CTRL_ORG_FMT.format(pfx))
    cmds.parentConstraint(master, controlsGrp, mo=True)
    cmds.scaleConstraint(master, controlsGrp, mo=True)

    for i in range(numCVs):
        cvBfr = cmds.createNode("transform",
                                name=BFR_CV_FMT.format(pfx, i + 1),
                                parent=controlsGrp)
        cv = cmds.duplicate(cvCtrl, name=CTRL_CV_FMT.format(pfx, i + 1))[0]
        twBfr = cmds.createNode("transform",
                                name=BFR_TWIST_FMT.format(pfx, i + 1),
                                parent=controlsGrp)
        tw = cmds.duplicate(twistCtrl, name=CTRL_TWIST_FMT.format(pfx,
                                                                  i + 1))[0]

        cmds.addAttr(cv,
                     longName="Pin",
                     attributeType='double',
                     defaultValue=0.0,
                     minValue=0.0,
                     maxValue=1.0)
        cmds.setAttr(cv + '.Pin', edit=True, keyable=True)
        cmds.addAttr(cv,
                     longName="PinParam",
                     attributeType='double',
                     defaultValue=0.0,
                     minValue=0.0)
        cmds.setAttr(cv + '.PinParam', edit=True, keyable=True)

        for h in [
                '.tx', '.ty', '.tz', '.ry', '.rz', '.sx', '.sy', '.sz', '.v'
        ]:
            cmds.setAttr(tw + h, lock=True, keyable=False, channelBox=False)
        cmds.addAttr(tw,
                     longName="UseTwist",
                     attributeType='double',
                     defaultValue=0.0,
                     minValue=0.0,
                     maxValue=1.0)
        cmds.setAttr(tw + '.UseTwist', edit=True, keyable=True)
        cv, = cmds.parent(cv, cvBfr)
        twBfr, = cmds.parent(twBfr, cv)
        tw, = cmds.parent(tw, twBfr)
        cmds.xform(cvBfr, translation=(spread * 3 * i, 0, 0))
        cvs.append(cv)
        tws.append(tw)
        cvBfrs.append(cvBfr)
        twBfrs.append(twBfr)

    # make the tangents and auto-tangents
    oTans, iTans, aoTans, aiTans = [], [], [], []

    segments = numCVs if closed else numCVs - 1
    for i in range(segments):
        # make oTan, and iTan
        otNum = i
        itNum = (i + 1) % numCVs

        oTan = cmds.duplicate(outTanCtrl,
                              name=CTRL_OUTTAN_FMT.format(pfx, otNum + 1))[0]
        iTan = cmds.duplicate(inTanCtrl,
                              name=CTRL_INTAN_FMT.format(pfx, itNum + 1))[0]
        for ndTan in [oTan, iTan]:
            cmds.addAttr(ndTan,
                         longName="Auto",
                         attributeType='double',
                         defaultValue=1.0,
                         minValue=0.0,
                         maxValue=1.0)
            cmds.setAttr(ndTan + '.Auto', edit=True, keyable=True)
            cmds.addAttr(ndTan,
                         longName="Smooth",
                         attributeType='double',
                         defaultValue=1.0,
                         minValue=0.0,
                         maxValue=1.0)
            cmds.setAttr(ndTan + '.Smooth', edit=True, keyable=True)
            cmds.addAttr(ndTan,
                         longName="Weight",
                         attributeType='double',
                         defaultValue=1.0,
                         minValue=0.0001,
                         maxValue=5.0)
            cmds.setAttr(ndTan + '.Weight', edit=True, keyable=True)

        cmds.xform(oTan, translation=(spread * (3 * otNum + 1), 0, 0))
        cmds.xform(iTan, translation=(spread * (3 * itNum - 1), 0, 0))

        aoTan = cmds.createNode("transform",
                                name=BFR_AOUTTAN_FMT.format(pfx, otNum + 1),
                                parent=cvs[otNum])
        aiTan = cmds.createNode("transform",
                                name=BFR_AINTAN_FMT.format(pfx, itNum + 1),
                                parent=cvs[itNum])

        cmds.xform(aoTan, translation=(spread * (3 * otNum + 1), 0, 0))
        cmds.xform(aiTan, translation=(spread * (3 * itNum - 1), 0, 0))
        oTan = cmds.parent(oTan, cvs[otNum])[0]
        iTan = cmds.parent(iTan, cvs[itNum])[0]

        oTans.append(oTan)
        iTans.append(iTan)
        aoTans.append(aoTan)
        aiTans.append(aiTan)

        for nd in [aiTan, aoTan]:
            cmds.setAttr(nd + ".overrideEnabled", 1)
            cmds.setAttr(nd + ".overrideDisplayType", 2)
            cmds.setAttr(nd + ".visibility", 0)

        makeLinkLine(aoTan, cvs[otNum], selectNode=oTan)
        makeLinkLine(aiTan, cvs[itNum], selectNode=iTan)

    cmds.delete((cvCtrl, outTanCtrl, inTanCtrl, twistCtrl, masterCtrl))
    return cvs, cvBfrs, oTans, iTans, aoTans, aiTans, tws, twBfrs, master
Example #50
0
 def rigModule(self, *args):
     Base.StartClass.rigModule(self)
     # verify if the guide exists:
     if cmds.objExists(self.moduleGrp):
         try:
             hideJoints = cmds.checkBox('hideJointsCB',
                                        query=True,
                                        value=True)
         except:
             hideJoints = 1
         # start as no having mirror:
         sideList = [""]
         # analisys the mirror module:
         self.mirrorAxis = cmds.getAttr(self.moduleGrp + ".mirrorAxis")
         if self.mirrorAxis != 'off':
             # get rigs names:
             self.mirrorNames = cmds.getAttr(self.moduleGrp + ".mirrorName")
             # get first and last letters to use as side initials (prefix):
             sideList = [
                 self.mirrorNames[0] + '_',
                 self.mirrorNames[len(self.mirrorNames) - 1] + '_'
             ]
             for s, side in enumerate(sideList):
                 duplicated = cmds.duplicate(
                     self.moduleGrp,
                     name=side + self.userGuideName + '_Guide_Base')[0]
                 allGuideList = cmds.listRelatives(duplicated,
                                                   allDescendents=True)
                 for item in allGuideList:
                     cmds.rename(item,
                                 side + self.userGuideName + "_" + item)
                 self.mirrorGrp = cmds.group(name="Guide_Base_Grp",
                                             empty=True)
                 cmds.parent(side + self.userGuideName + '_Guide_Base',
                             self.mirrorGrp,
                             absolute=True)
                 # re-rename grp:
                 cmds.rename(
                     self.mirrorGrp,
                     side + self.userGuideName + '_' + self.mirrorGrp)
                 # do a group mirror with negative scaling:
                 if s == 1:
                     if cmds.getAttr(self.moduleGrp + ".flip") == 0:
                         for axis in self.mirrorAxis:
                             gotValue = cmds.getAttr(
                                 side + self.userGuideName +
                                 "_Guide_Base.translate" + axis)
                             flipedValue = gotValue * (-2)
                             cmds.setAttr(
                                 side + self.userGuideName + '_' +
                                 self.mirrorGrp + '.translate' + axis,
                                 flipedValue)
                     else:
                         for axis in self.mirrorAxis:
                             cmds.setAttr(
                                 side + self.userGuideName + '_' +
                                 self.mirrorGrp + '.scale' + axis, -1)
         else:  # if not mirror:
             duplicated = cmds.duplicate(self.moduleGrp,
                                         name=self.userGuideName +
                                         '_Guide_Base')[0]
             allGuideList = cmds.listRelatives(duplicated,
                                               allDescendents=True)
             for item in allGuideList:
                 cmds.rename(item, self.userGuideName + "_" + item)
             self.mirrorGrp = cmds.group(self.userGuideName + '_Guide_Base',
                                         name="Guide_Base_Grp",
                                         relative=True)
             #for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp"
             # re-rename grp:
             cmds.rename(self.mirrorGrp,
                         self.userGuideName + '_' + self.mirrorGrp)
         # store the number of this guide by module type
         dpAR_count = utils.findModuleLastNumber(CLASS_NAME,
                                                 "dpAR_type") + 1
         # run for all sides
         for s, side in enumerate(sideList):
             self.base = side + self.userGuideName + '_Guide_Base'
             cmds.select(clear=True)
             # declare guide:
             self.guide = side + self.userGuideName + "_Guide_JointLoc1"
             # create a joint:
             self.jnt = cmds.joint(name=side + self.userGuideName + "_Jnt",
                                   scaleCompensate=False)
             cmds.addAttr(self.jnt,
                          longName='dpAR_joint',
                          attributeType='float',
                          keyable=False)
             # create a control:
             if self.getHasIndirectSkin():
                 self.ctrl = cmds.circle(name=side + self.userGuideName +
                                         "_Ctrl",
                                         degree=3,
                                         normal=(0, 0, 1),
                                         r=self.ctrlRadius,
                                         s=8,
                                         ch=False)[0]
             else:
                 self.ctrl = cmds.circle(name=side + self.userGuideName +
                                         "_Ctrl",
                                         degree=1,
                                         normal=(0, 0, 1),
                                         r=self.ctrlRadius,
                                         s=8,
                                         ch=False)[0]
             # edit circle shape to Upper or Lower controls:
             if "Upper" in self.userGuideName:
                 cmds.setAttr(self.ctrl + "Shape.controlPoints[4].yValue",
                              0)
                 cmds.setAttr(self.ctrl + "Shape.controlPoints[5].yValue",
                              0)
                 cmds.setAttr(self.ctrl + "Shape.controlPoints[6].yValue",
                              0)
                 if not self.getHasIndirectSkin():
                     cmds.setAttr(
                         self.ctrl + "Shape.controlPoints[3].yValue", 0)
             elif "Lower" in self.userGuideName:
                 cmds.setAttr(self.ctrl + "Shape.controlPoints[0].yValue",
                              0)
                 cmds.setAttr(self.ctrl + "Shape.controlPoints[1].yValue",
                              0)
                 cmds.setAttr(self.ctrl + "Shape.controlPoints[2].yValue",
                              0)
                 if not self.getHasIndirectSkin():
                     cmds.setAttr(
                         self.ctrl + "Shape.controlPoints[7].yValue", 0)
                     cmds.setAttr(
                         self.ctrl + "Shape.controlPoints[8].yValue", 0)
             utils.originedFrom(objName=self.ctrl,
                                attrString=self.base + ";" + self.guide)
             # position and orientation of joint and control:
             cmds.delete(
                 cmds.parentConstraint(self.guide,
                                       self.jnt,
                                       maintainOffset=False))
             cmds.delete(
                 cmds.parentConstraint(self.guide,
                                       self.ctrl,
                                       maintainOffset=False))
             # zeroOut controls:
             zeroOutCtrlGrp = utils.zeroOut([self.ctrl])[0]
             # hide visibility attribute:
             cmds.setAttr(self.ctrl + '.visibility', keyable=False)
             # fixing flip mirror:
             if s == 1:
                 if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                     cmds.setAttr(zeroOutCtrlGrp + ".scaleX", -1)
                     cmds.setAttr(zeroOutCtrlGrp + ".scaleY", -1)
                     cmds.setAttr(zeroOutCtrlGrp + ".scaleZ", -1)
             cmds.addAttr(self.ctrl,
                          longName='scaleCompensate',
                          attributeType="bool",
                          keyable=True)
             cmds.setAttr(self.ctrl + ".scaleCompensate", 1)
             cmds.connectAttr(self.ctrl + ".scaleCompensate",
                              self.jnt + ".segmentScaleCompensate",
                              force=True)
             if self.getHasIndirectSkin():
                 # create a fatherJoint in order to zeroOut the skinning joint:
                 cmds.select(clear=True)
                 jxtName = self.jnt.replace("_Jnt", "_Jxt")
                 self.jxt = cmds.duplicate(self.jnt, name=jxtName)[0]
                 cmds.deleteAttr(self.jxt, attribute="dpAR_joint")
                 cmds.parent(self.jnt, self.jxt)
                 cmds.makeIdentity(self.jnt, apply=True, jointOrient=False)
                 attrList = [
                     'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'
                 ]
                 for attr in attrList:
                     cmds.connectAttr(self.ctrl + '.' + attr,
                                      self.jnt + '.' + attr)
                 if s == 1:
                     if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                         cmds.setAttr(self.jxt + ".scaleX", -1)
                         cmds.setAttr(self.jxt + ".scaleY", -1)
                         cmds.setAttr(self.jxt + ".scaleZ", -1)
                 if self.getHasHolder():
                     cmds.delete(self.ctrl + "Shape", shape=True)
                     self.ctrl = cmds.rename(
                         self.ctrl, self.ctrl + "_" +
                         self.langDic[self.langName]['c_holder'] + "_Grp")
                     ctrls.setLockHide([self.ctrl], [
                         'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy',
                         'sz', 'scaleCompensate'
                     ])
                     self.jnt = cmds.rename(
                         self.jnt,
                         self.jnt.replace(
                             "_Jnt",
                             "_" + self.langDic[self.langName]['c_holder'] +
                             "_Jis"))
                     ctrls.setLockHide([self.jnt], [
                         'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy',
                         'sz'
                     ], True, True)
                 else:
                     self.jnt = cmds.rename(
                         self.jnt, self.jnt.replace("_Jnt", "_Jis"))
             else:  # like a fkLine
                 # create parentConstraint from ctrl to jnt:
                 cmds.parentConstraint(self.ctrl,
                                       self.jnt,
                                       maintainOffset=False,
                                       name=self.jnt + "_ParentConstraint")
                 # create scaleConstraint from ctrl to jnt:
                 cmds.scaleConstraint(self.ctrl,
                                      self.jnt,
                                      maintainOffset=True,
                                      name=self.jnt + "_ScaleConstraint")
             # create end joint:
             cmds.select(self.jnt)
             self.cvEndJoint = side + self.userGuideName + "_Guide_JointEnd"
             self.endJoint = cmds.joint(name=side + self.userGuideName +
                                        "_JEnd")
             cmds.delete(
                 cmds.parentConstraint(self.cvEndJoint,
                                       self.endJoint,
                                       maintainOffset=False))
             self.mainJisList.append(self.jnt)
             # create a masterModuleGrp to be checked if this rig exists:
             self.toCtrlHookGrp = cmds.group(
                 side + self.userGuideName + "_Ctrl_Zero",
                 name=side + self.userGuideName + "_Control_Grp")
             if self.getHasIndirectSkin():
                 locScale = cmds.spaceLocator(name=side +
                                              self.userGuideName +
                                              "_Scalable_DO_NOT_DELETE")[0]
                 cmds.setAttr(locScale + ".visibility", 0)
                 self.toScalableHookGrp = cmds.group(
                     locScale,
                     name=side + self.userGuideName + "_IndirectSkin_Grp")
                 jxtGrp = cmds.group(side + self.userGuideName + "_Jxt",
                                     name=side + self.userGuideName +
                                     "_Joint_Grp")
                 self.toStaticHookGrp = cmds.group(
                     jxtGrp,
                     self.toScalableHookGrp,
                     self.toCtrlHookGrp,
                     name=side + self.userGuideName + "_Grp")
             else:
                 self.toScalableHookGrp = cmds.group(
                     side + self.userGuideName + "_Jnt",
                     name=side + self.userGuideName + "_Joint_Grp")
                 self.toStaticHookGrp = cmds.group(
                     self.toCtrlHookGrp,
                     self.toScalableHookGrp,
                     name=side + self.userGuideName + "_Grp")
             # create a locator in order to avoid delete static or scalable group
             loc = cmds.spaceLocator(name=side + self.userGuideName +
                                     "_DO_NOT_DELETE")[0]
             cmds.parent(loc, self.toStaticHookGrp, absolute=True)
             cmds.setAttr(loc + ".visibility", 0)
             ctrls.setLockHide([loc], [
                 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'
             ])
             # add hook attributes to be read when rigging integrated modules:
             utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
             utils.addHook(objName=self.toScalableHookGrp,
                           hookType='scalableHook')
             utils.addHook(objName=self.toStaticHookGrp,
                           hookType='staticHook')
             cmds.addAttr(self.toStaticHookGrp,
                          longName="dpAR_name",
                          dataType="string")
             cmds.addAttr(self.toStaticHookGrp,
                          longName="dpAR_type",
                          dataType="string")
             cmds.setAttr(self.toStaticHookGrp + ".dpAR_name",
                          self.userGuideName,
                          type="string")
             cmds.setAttr(self.toStaticHookGrp + ".dpAR_type",
                          CLASS_NAME,
                          type="string")
             self.aStaticGrpList.append(self.toStaticHookGrp)
             self.aCtrlGrpList.append(self.toCtrlHookGrp)
             # add module type counter value
             cmds.addAttr(self.toStaticHookGrp,
                          longName='dpAR_count',
                          attributeType='long',
                          keyable=False)
             cmds.setAttr(self.toStaticHookGrp + '.dpAR_count', dpAR_count)
             if hideJoints:
                 cmds.setAttr(self.toScalableHookGrp + ".visibility", 0)
             # delete duplicated group for side (mirror):
             cmds.delete(side + self.userGuideName + '_' + self.mirrorGrp)
         # check mirror indirectSkin bug in Maya2018:
         if (int(cmds.about(version=True)[:4]) == 2018):
             if self.mirrorAxis != 'off':
                 if self.getHasIndirectSkin():
                     meshList = cmds.ls(selection=False, type="mesh")
                     if meshList:
                         self.detectedBug = True
         # finalize this rig:
         self.integratingInfo()
         cmds.select(clear=True)
     # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
     self.deleteModule()
Example #51
0
    controlador = input("digite o nome do controlador:")
    for i in sel:
        pos = [
            cmds.getAttr(i + ".center.boundingBoxCenterX"),
            cmds.getAttr(i + ".center.boundingBoxCenterY"),
            cmds.getAttr(i + ".center.boundingBoxCenterZ")
        ]
        cmds.select(clear=True)
        jnt = cmds.joint(name=controlador + "_%d_jnt" % number)
        cmds.xform(jnt, t=pos)
        ctrlGrp = cmds.group(em=True, name=controlador + "_%d_grp" % number)
        ctrls = cmds.circle(name=controlador + "_%d_ctrl" % number,
                            c=[0, 0, 0],
                            sw=360,
                            d=3,
                            r=5,
                            nr=[0, 0, 1],
                            ch=False)
        cmds.parent(ctrls, ctrlGrp)
        cmds.xform(ctrlGrp, t=pos)
        cmds.parentConstraint(ctrls, jnt)
        cmds.scaleConstraint(ctrls, jnt)
        number = number + 1
        joints.append(jnt)
        controls.append(ctrlGrp)

    jointGrp = cmds.group(em=True, name=controlador + "_joints_grp")
    cmds.parent(joints, jointGrp)
except Exception as error:
    print(error)
def ParScaCon():
	cmds.parentConstraint(mo = True, weight = 1)
	cmds.scaleConstraint(mo = True, weight = 1)
Example #53
0
def simple_fk():
    '''Creates a FK system along a single chain of joints'''
    #Variables
    last_ctrl = ''
    replace = "Jnt"

    #Get selection with hierarchy
    cmds.select(hi=True)
    sels = cmds.ls(sl=True)

    #Loop through selection
    for sel in sels:
        #Set up control names
        if replace in sel:
            ctrl_name = sel.replace(replace, "FK_Ctrl")
            grp_name = sel.replace(replace, "FK_Grp")
        else:
            ctrl_name = '%s_FK_Ctrl' % sel
            grp_name = '%s_FK_Grp' % sel

        #Create control and control group
        ctrl = cmds.circle(c=(0, 0, 0),
                           nr=(1, 0, 0),
                           sw=360,
                           r=1,
                           d=3,
                           ut=0,
                           tol=0,
                           s=8,
                           ch=1,
                           n=ctrl_name)
        grp = cmds.group(ctrl, n=grp_name)

        #Match control group to joint transform
        pos = cmds.xform(sel, q=True, rotatePivot=True, ws=True)
        rot = cmds.xform(sel, q=True, ro=True, ws=True)
        cmds.move(pos[0], pos[1], pos[2], grp, ws=True, a=True, rpr=True)
        cmds.rotate(rot[0], rot[1], rot[2], grp, a=True, ws=True)

        #Constrain joint to control
        cmds.parentConstraint(ctrl, sel)
        cmds.scaleConstraint(ctrl, sel)

        #If it's not the first control parent to last control
        if last_ctrl != '':
            cmds.parent(grp, last_ctrl, a=True)

        #If it's  the first control
        else:
            #Create 'Controls' group if it doesn't exist
            if cmds.objExists('Controls'):
                cmds.parent(grp, 'Controls')
            else:
                controls_grp = cmds.group(grp, n='Controls')
                if cmds.listRelatives(controls_grp, p=True):
                    cmds.parent(controls_grp, world=True)

            #Create 'Skeleton' group if it doesn't exist
            if cmds.objExists('Skeleton'):
                if cmds.listRelatives(sel, p=True):
                    cmds.parent(sel, world=True)
                cmds.parent(sel, 'Skeleton')
            else:
                skeleton_grp = cmds.group(sel, n='Skeleton')
                if cmds.listRelatives(skeleton_grp, p=True):
                    cmds.parent(skeleton_grp, world=True)

        #Save last ctrl
        last_ctrl = ctrl

        #Freeze Transformations and delete history
        cmds.makeIdentity(ctrl, apply=True)
        cmds.delete(ctrl, ch=True)

        #Lock and hide  visibility
        cmds.setAttr('%s.v' % ctrl[0],
                     lock=True,
                     keyable=False,
                     channelBox=False)

    #Clear selection
    cmds.select(clear=True)
Example #54
0
def dupeRig(dupeRig, pNameSearchField, pNameReplaceField):

	#The order in which these are assigned matters more than the first arguement
	searchForField = cmds.textField(nameSearchField, query=True, text=True)
	replaceWithField = cmds.textField(nameReplaceField, query=True, text=True)

	print('dupeRig(), the searchForField is: ' + searchForField)
	print('dupeRig(), the replaceWithField is: ' + replaceWithField)

	objectType = cmds.objectType(globalRigToDupe)

	if (objectType != 'joint'):
		print('You must load a joint to duplicate')
	elif (objectType == 'joint'):

		originalRootName = globalRigToDupe[0]  #Storing the original name of root
		print('dupeRig(), the originalRootName is : ' + str(originalRootName))
		newObject = cmds.duplicate(globalRigToDupe[0], n='temp', rc=True) #the objects have to be renamed because there is nothing you can do with them until they have a different name from their originals
		cmds.parent(newObject[0], world = True)
		print('dupeRig(), the newObject is : ' + str(newObject))
		reps = {searchForField: replaceWithField, 'SknNoWeight':'TARGET', '1': ''}
		nameForRootObject = renameObject(originalRootName, reps) #replacing the prefix
		print('dupeRig(), the newObject[0] is : ' + str(newObject[0]))
		duplicatedJoint = cmds.rename(newObject[0], nameForRootObject) #Changing the name back to something that makes sense
		print('dupeRig(), the duplicatedJoint is : ' + str(duplicatedJoint))
		global globalTargetRig
		globalTargetRig = duplicatedJoint
		newSelection = cmds.listRelatives(duplicatedJoint, allDescendents=True)#creating a new list from the childern of the duplicated object, note we had to use the new name for the root object
		print('dupeRig(), the newSelection is: ' + str(newSelection))

		#renaming the childen
		i=0
		originalNameList = cmds.listRelatives(globalRigToDupe[0], allDescendents = True)
		print('dupeRig(), the originalNameList is: ' + str(originalNameList))
		reps = {searchForField: replaceWithField, 'SknNoWeight': 'TARGET', 'SknGeo' : 'TARGET', 'Hair':'TARGET_Hair'}
		for eachObject in newSelection:
			objectName = originalNameList[i]
			# bind the returned text of the method
			# to a variable and print it
			newNameA = renameObject(objectName, reps)
			#print newNameAs
			print('dupeRig(), the object to rename is: ' + str(eachObject))
			newName = cmds.rename(eachObject, newNameA)
			i= i+1

	#parent constraining original rig to duplicated rig	
	parentConstrainedRigList = cmds.listRelatives(globalRigToDupe[0], allDescendents = True, type = 'joint')
	print('dupRig(), globalTargetRig is: ' + str(globalTargetRig)) #at this point globalTargetRig is the root of the target rig
	targetRigList = cmds.listRelatives(globalTargetRig, allDescendents = True, type = 'joint')
	parentConstrainedRigList.insert(0, globalRigToDupe[0])
	targetRigList.insert(0, globalTargetRig)
	print('dupeRig(), the parentConstrainedRigList[0] is: ' + str(parentConstrainedRigList[0]))
	print('dupeRig(), the targetRigList[0] is: ' + str(targetRigList[0]))
	#if cmds.attributeQuery(parentConstrainedRigList[0], node = 'RigFollow'):
	if (cmds.objExists(parentConstrainedRigList[0] + '.RigFollow')):
		print('dupeRig(), attribute RigFollow found')
		#cmds.select(parentConstrainedRigList[0])
		cmds.deleteAttr(parentConstrainedRigList[0], attribute = 'RigFollow')
	cmds.addAttr(parentConstrainedRigList[0], attributeType = 'float', longName = 'RigFollow', hasMinValue = True, minValue = 0, maxValue = 1, defaultValue = 1, keyable = True)

	i=0
	for eachJoint in parentConstrainedRigList:
		print('dupeRig(), the parentConstrainedRigList[i] is: ' + str(parentConstrainedRigList[i]))
		print('dupeRig(), the targetRigList[i] is: ' + str(targetRigList[i]))
		newParentConstraint = cmds.parentConstraint(targetRigList[i], parentConstrainedRigList[i])
		newScaleConstraint = cmds.scaleConstraint(targetRigList[i], parentConstrainedRigList[i])
		reps = {'|':''}
		targetRigString = renameObject(targetRigList[i], reps)
		#The following lines connect each parent and scale constraint to an attribute on the root joint that will dictate if the constraints have any effect
		cmds.connectAttr(str(parentConstrainedRigList[0])  + '.RigFollow', newParentConstraint[0].encode('utf8') + '.' + targetRigString + 'W0', force = True)
		cmds.connectAttr(str(parentConstrainedRigList[0])  + '.RigFollow', newScaleConstraint[0].encode('utf8') + '.' + targetRigString + 'W0', force = True)		
		i=i+1
	
		
	#This is all cleanup for the rig skeleton.  It's just deleting all of the unused artifacts from the skin joint skeleton
	keepShapes = cmds.checkBox(keepShapesCheckBox, editable = True, query = True, value = True)
	
	if keepShapes == False:
		print('dupeRig(), keep shapes is false')
		shapeSelection = cmds.listRelatives(globalTargetRig, allDescendents = True, type = 'shape' ) #creating a list to select any unwanted shapes in the hierarchy
		#The reason why this is done as a loop is because if it throws an error you will know which shape to deal with
		for eachObject in shapeSelection:
			shapeTransform = cmds.listRelatives(eachObject, type = 'transform', parent = True ); #selecting the transforms of the shape nodes
			cmds.delete(shapeTransform)
		typeToPrune = 'transform'
		deleteFilteredObjects(globalTargetRig, typeToPrune)
	
	typeToPrune = 'ikEffector'
	deleteFilteredObjects(globalTargetRig, typeToPrune)
Example #55
0
def Rig(nameSpace):
    
    #- get guides -
    guides = ['%s:link_start_gui'%nameSpace, '%s:link_end_gui'%nameSpace, '%s:link_up_gui'%nameSpace]
    
    #- make curve -
    pathCurve = buildeCurve(guides[0], guides[1])
    
    #- make up curve -
    upvectorCurve = buidleUpCurve(*guides)
    
    #- make Joints and locators-
    Joints = []
    locators = []
    multiNodes = []
    counts = mc.getAttr('%s.jointCount'%guides[0])
    for i in range(counts):
        #- 1 create 
        Joints.append(mc.createNode('joint'))
        locators.append(mc.spaceLocator(p=(0,0,0))[0])
        
        #- 2 
        parameter = (((float(i + 1) - 0) / (counts + 1 - 0)) * (1 - 0)) + 0
        
        #- 3 attact to curve
        multiNodes.append(attachToCurve(Joints[-1], pathCurve, parameter))
        attachToCurve(locators[-1], upvectorCurve, parameter)
    
        #- 4 connect object up
        addUpObject(Joints[-1], locators[-1])
    
    
    #- add rig Joins -
    rigJoints = []
    for i in range(4):
        rigJoints.append(mc.createNode('joint'))
        #- move
        position = mc.pointOnCurve(pathCurve, pr= 1.0 / 3 * i)
        mc.move(position[0], position[1], position[2], rigJoints[-1], a=True)
        #- orient
        mc.delete(mc.orientConstraint(Joints[0], rigJoints[-1]))
    
    #- bind Curve
    mc.skinCluster(rigJoints, pathCurve)    
    mc.skinCluster(rigJoints, upvectorCurve)

    #- rig rigJoints -
    controlLst = []
    for jnt in rigJoints:
        
        #- make control
        controls = [mc.createNode('transform')  for i in range(4)]
        for i in range(len(controls) - 1):
            mc.parent(controls[i], controls[i+1])
        controlLst.append(controls)
        
        #- match positions, parent Joint
        mc.delete(mc.parentConstraint(jnt, controls[-1]))
        mc.parent(jnt, controls[0])
        
        #-add Shape
        circle = mc.circle(nr=(1,0,0), ch=0)
        mc.parent(mc.listRelatives(circle, s=True, path=True), controls[0], r=True, s=True)
        mc.delete(circle)
  
        
    #- Constraint control
    appLocators = []
    for controls in controlLst:
        appLocators.append(mc.spaceLocator(p=(0,0,0))[0])
        mc.delete(mc.parentConstraint(controls[0], appLocators[-1]))
        mc.parentConstraint(appLocators[-1], controls[-2])
        mc.scaleConstraint(appLocators[-1], controls[-2])

    #- add def
    mc.addAttr(appLocators[-1], sn='IKFKSwitch', min=0, max=1, dv=0, k=True)
    mc.addAttr(appLocators[-1], sn='fkRotate', dv=0, k=True)
    mc.addAttr(appLocators[-1], sn='ikRotate', dv=0, k=True)
    
    blendNode = mc.createNode('blendTwoAttr')
    mc.connectAttr('%s.IKFKSwitch'%appLocators[-1], '%s.ab'%blendNode)
    mc.connectAttr('%s.fkRotate'%appLocators[-1], '%s.input[0]'%blendNode)
    mc.connectAttr('%s.ikRotate'%appLocators[-1], '%s.input[1]'%blendNode)
    
    for md in multiNodes:
        mc.connectAttr('%s.output'%blendNode, '%s.input1'%md)
    
    #-- comp hery --
    curveGrp   = mc.group(pathCurve, upvectorCurve)
    jointGrp   = mc.group(Joints) 
    locatorGrp = mc.group(locators)    
    controlGrp = mc.group([L[-1] for L in controlLst])
    RootGrp    = mc.group(curveGrp, jointGrp, locatorGrp, controlGrp)
    
    #-- clean scene --
    mc.hide(curveGrp, locatorGrp, rigJoints)
    
    #-* rename *-
    
    #- groups -
    curveGrp   = mc.rename(curveGrp,   '%s_cusg_0'%nameSpace)
    jointGrp   = mc.rename(jointGrp,   '%s_jntg_0'%nameSpace)
    locatorGrp = mc.rename(locatorGrp, '%s_locg_0'%nameSpace)
    controlGrp = mc.rename(controlGrp, '%s_ctlg_0'%nameSpace)
    RootGrp    = mc.rename(RootGrp,    '%s_setg_0'%nameSpace)
    
    #- joints -
    for i,jnt in enumerate(Joints):
        Joints[i] = mc.rename(jnt, '%s_bnd%s_0'%(nameSpace, string.uppercase[i]))
    
    #- locators -
    for i,loc in enumerate(locators):
        locators[i] = mc.rename(loc, '%s_loc%s_0'%(nameSpace, string.uppercase[i]))    
    
    #- aooLocators -
    for i, loc in enumerate(appLocators):
        appLocators[i] = mc.rename(loc, '%s_apploc%s_0'%(nameSpace, string.uppercase[i]))    
    
    #- rig Joints -
    for i,jnt in enumerate(rigJoints):
        rigJoints[i] = mc.rename(jnt, '%s_ctj%s_0'%(nameSpace, string.uppercase[i]))   

    #- control -
    ctlType = ('ctl', 'ctu', 'cth', 'ctg') 
    for i, ctls in enumerate(controlLst):
        for d, ctl in enumerate(ctls):
            controlLst[i][d] = mc.rename(ctl, '%s%s_%s_0'%(nameSpace, string.uppercase[i], ctlType[d]))   
    
    #- curve -
    pathCurve = mc.rename(pathCurve, '%s_TWbaseCus_0'%nameSpace)    
    upvectorCurve = mc.rename(upvectorCurve , '%s_TWupperCus_0'%nameSpace)    
Example #56
0
    def rigModule(self, *args):
        Base.StartClass.rigModule(self)
        # verify if the guide exists:
        if cmds.objExists(self.moduleGrp):
            try:
                hideJoints = cmds.checkBox('hideJointsCB',
                                           query=True,
                                           value=True)
            except:
                hideJoints = 1
            # declare lists to store names and attributes:
            self.mainCtrlList, self.wheelCtrlList, self.steeringGrpList, self.ctrlHookGrpList = [], [], [], []
            # start as no having mirror:
            sideList = [""]
            # analisys the mirror module:
            self.mirrorAxis = cmds.getAttr(self.moduleGrp + ".mirrorAxis")
            if self.mirrorAxis != 'off':
                # get rigs names:
                self.mirrorNames = cmds.getAttr(self.moduleGrp + ".mirrorName")
                # get first and last letters to use as side initials (prefix):
                sideList = [
                    self.mirrorNames[0] + '_',
                    self.mirrorNames[len(self.mirrorNames) - 1] + '_'
                ]
                for s, side in enumerate(sideList):
                    duplicated = cmds.duplicate(
                        self.moduleGrp,
                        name=side + self.userGuideName + '_Guide_Base')[0]
                    allGuideList = cmds.listRelatives(duplicated,
                                                      allDescendents=True)
                    for item in allGuideList:
                        cmds.rename(item,
                                    side + self.userGuideName + "_" + item)
                    self.mirrorGrp = cmds.group(name="Guide_Base_Grp",
                                                empty=True)
                    cmds.parent(side + self.userGuideName + '_Guide_Base',
                                self.mirrorGrp,
                                absolute=True)
                    # re-rename grp:
                    cmds.rename(
                        self.mirrorGrp,
                        side + self.userGuideName + '_' + self.mirrorGrp)
                    # do a group mirror with negative scaling:
                    if s == 1:
                        if cmds.getAttr(self.moduleGrp + ".flip") == 0:
                            for axis in self.mirrorAxis:
                                gotValue = cmds.getAttr(
                                    side + self.userGuideName +
                                    "_Guide_Base.translate" + axis)
                                flipedValue = gotValue * (-2)
                                cmds.setAttr(
                                    side + self.userGuideName + '_' +
                                    self.mirrorGrp + '.translate' + axis,
                                    flipedValue)
                        else:
                            for axis in self.mirrorAxis:
                                cmds.setAttr(
                                    side + self.userGuideName + '_' +
                                    self.mirrorGrp + '.scale' + axis, -1)
                # joint labelling:
                jointLabelAdd = 1
            else:  # if not mirror:
                duplicated = cmds.duplicate(self.moduleGrp,
                                            name=self.userGuideName +
                                            '_Guide_Base')[0]
                allGuideList = cmds.listRelatives(duplicated,
                                                  allDescendents=True)
                for item in allGuideList:
                    cmds.rename(item, self.userGuideName + "_" + item)
                self.mirrorGrp = cmds.group(self.userGuideName + '_Guide_Base',
                                            name="Guide_Base_Grp",
                                            relative=True)
                #for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp"
                # re-rename grp:
                cmds.rename(self.mirrorGrp,
                            self.userGuideName + '_' + self.mirrorGrp)
                # joint labelling:
                jointLabelAdd = 0
            # store the number of this guide by module type
            dpAR_count = utils.findModuleLastNumber(CLASS_NAME,
                                                    "dpAR_type") + 1
            # run for all sides
            for s, side in enumerate(sideList):
                # declare guides:
                self.base = side + self.userGuideName + '_Guide_Base'
                self.cvCenterLoc = side + self.userGuideName + "_Guide_CenterLoc"
                self.cvFrontLoc = side + self.userGuideName + "_Guide_FrontLoc"
                self.cvInsideLoc = side + self.userGuideName + "_Guide_InsideLoc"
                self.cvOutsideLoc = side + self.userGuideName + "_Guide_OutsideLoc"

                # create a joint:
                cmds.select(clear=True)
                # center joint:
                self.centerJoint = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Jnt",
                    scaleCompensate=False)
                cmds.addAttr(self.centerJoint,
                             longName='dpAR_joint',
                             attributeType='float',
                             keyable=False)
                # joint labelling:
                utils.setJointLabel(
                    self.centerJoint, s + jointLabelAdd, 18,
                    self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'])
                # create end joint:
                self.endJoint = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_JEnd")
                # main joint:
                cmds.select(clear=True)
                self.mainJoint = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c058_main'] + "_Jnt",
                    scaleCompensate=False)
                cmds.addAttr(self.mainJoint,
                             longName='dpAR_joint',
                             attributeType='float',
                             keyable=False)
                # joint labelling:
                utils.setJointLabel(
                    self.mainJoint, s + jointLabelAdd, 18, self.userGuideName +
                    "_" + self.langDic[self.langName]['c058_main'])
                # create end joint:
                self.mainEndJoint = cmds.joint(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c058_main'] + "_JEnd")

                # create controls:
                self.wheelCtrl = self.ctrls.cvControl(
                    "id_060_WheelCenter",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Ctrl",
                    r=self.ctrlRadius,
                    d=self.curveDegree)
                self.mainCtrl = self.ctrls.cvControl(
                    "id_061_WheelMain",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c058_main'] + "_Ctrl",
                    r=self.ctrlRadius * 0.4,
                    d=self.curveDegree)
                self.insideCtrl = self.ctrls.cvControl(
                    "id_062_WheelPivot",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c011_RevFoot_B'].capitalize()
                    + "_Ctrl",
                    r=self.ctrlRadius * 0.2,
                    d=self.curveDegree,
                    rot=(0, 90, 0))
                self.outsideCtrl = self.ctrls.cvControl(
                    "id_062_WheelPivot",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c010_RevFoot_A'].capitalize()
                    + "_Ctrl",
                    r=self.ctrlRadius * 0.2,
                    d=self.curveDegree,
                    rot=(0, 90, 0))
                self.mainCtrlList.append(self.mainCtrl)
                self.wheelCtrlList.append(self.wheelCtrl)

                # origined from attributes:
                utils.originedFrom(objName=self.mainCtrl,
                                   attrString=self.base + ";" +
                                   self.cvCenterLoc + ";" + self.cvFrontLoc +
                                   ";" + self.cvInsideLoc + ";" +
                                   self.cvOutsideLoc)
                #utils.originedFrom(objName=self.wheelCtrl, attrString=self.cvCenterLoc)

                # prepare group to receive steering wheel connection:
                self.toSteeringGrp = cmds.group(
                    self.insideCtrl,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c070_steering'].capitalize() +
                    "_Grp")
                cmds.addAttr(
                    self.toSteeringGrp,
                    longName=self.langDic[self.langName]['c070_steering'],
                    attributeType='bool',
                    keyable=True)
                cmds.addAttr(
                    self.toSteeringGrp,
                    longName=self.langDic[self.langName]['c070_steering'] +
                    self.langDic[self.langName]['m151_invert'],
                    attributeType='bool',
                    keyable=True)
                cmds.setAttr(
                    self.toSteeringGrp + "." +
                    self.langDic[self.langName]['c070_steering'], 1)
                self.steeringGrpList.append(self.toSteeringGrp)

                # position and orientation of joint and control:
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.centerJoint,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvFrontLoc,
                                          self.endJoint,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.wheelCtrl,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.mainCtrl,
                                          maintainOffset=False))
                cmds.parentConstraint(self.mainCtrl,
                                      self.mainJoint,
                                      maintainOffset=False)
                cmds.delete(
                    cmds.parentConstraint(self.cvFrontLoc,
                                          self.mainEndJoint,
                                          maintainOffset=False))
                if s == 1 and cmds.getAttr(self.moduleGrp + ".flip") == 1:
                    cmds.move(self.ctrlRadius,
                              self.mainCtrl,
                              moveY=True,
                              relative=True,
                              objectSpace=True,
                              worldSpaceDistance=True)
                else:
                    cmds.move(-self.ctrlRadius,
                              self.mainCtrl,
                              moveY=True,
                              relative=True,
                              objectSpace=True,
                              worldSpaceDistance=True)
                cmds.delete(
                    cmds.parentConstraint(self.cvInsideLoc,
                                          self.toSteeringGrp,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvOutsideLoc,
                                          self.outsideCtrl,
                                          maintainOffset=False))

                # zeroOut controls:
                zeroGrpList = utils.zeroOut([
                    self.mainCtrl, self.wheelCtrl, self.toSteeringGrp,
                    self.outsideCtrl
                ])
                wheelAutoGrp = utils.zeroOut([self.wheelCtrl])
                wheelAutoGrp = cmds.rename(
                    wheelAutoGrp, side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Auto_Grp")

                # fixing flip mirror:
                if s == 1:
                    if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                        for zeroOutGrp in zeroGrpList:
                            cmds.setAttr(zeroOutGrp + ".scaleX", -1)
                            cmds.setAttr(zeroOutGrp + ".scaleY", -1)
                            cmds.setAttr(zeroOutGrp + ".scaleZ", -1)

                cmds.addAttr(self.wheelCtrl,
                             longName='scaleCompensate',
                             attributeType="bool",
                             keyable=False)
                cmds.setAttr(self.wheelCtrl + ".scaleCompensate",
                             1,
                             channelBox=True)
                cmds.connectAttr(self.wheelCtrl + ".scaleCompensate",
                                 self.centerJoint + ".segmentScaleCompensate",
                                 force=True)
                cmds.addAttr(self.mainCtrl,
                             longName='scaleCompensate',
                             attributeType="bool",
                             keyable=False)
                cmds.setAttr(self.mainCtrl + ".scaleCompensate",
                             1,
                             channelBox=True)
                cmds.connectAttr(self.mainCtrl + ".scaleCompensate",
                                 self.mainJoint + ".segmentScaleCompensate",
                                 force=True)
                # hide visibility attributes:
                self.ctrls.setLockHide(
                    [self.mainCtrl, self.insideCtrl, self.outsideCtrl], ['v'])
                self.ctrls.setLockHide(
                    [self.wheelCtrl],
                    ['tx', 'ty', 'tz', 'rx', 'ry', 'sx', 'sy', 'sz', 'v'])

                # grouping:
                cmds.parentConstraint(self.wheelCtrl,
                                      self.centerJoint,
                                      maintainOffset=False,
                                      name=self.centerJoint +
                                      "_ParentConstraint")
                cmds.scaleConstraint(self.wheelCtrl,
                                     self.centerJoint,
                                     maintainOffset=True,
                                     name=self.centerJoint +
                                     "_ScaleConstraint")
                cmds.parent(zeroGrpList[1], self.mainCtrl, absolute=True)
                cmds.parent(zeroGrpList[0], self.outsideCtrl, absolute=True)
                cmds.parent(zeroGrpList[3], self.insideCtrl, absolute=True)

                # add attributes:
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c047_autoRotate'],
                    attributeType="bool",
                    defaultValue=1,
                    keyable=True)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c068_startFrame'],
                    attributeType="long",
                    defaultValue=1,
                    keyable=False)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c067_radius'],
                    attributeType="float",
                    min=0.01,
                    defaultValue=self.ctrlRadius,
                    keyable=True)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c069_radiusScale'],
                    attributeType="float",
                    defaultValue=1,
                    keyable=False)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c021_showControls'],
                    attributeType="long",
                    min=0,
                    max=1,
                    defaultValue=0,
                    keyable=True)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c070_steering'],
                    attributeType="bool",
                    defaultValue=0,
                    keyable=True)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['i037_to'] +
                    self.langDic[self.langName]['c070_steering'].capitalize(),
                    attributeType="float",
                    defaultValue=0,
                    keyable=False)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c070_steering'] +
                    self.langDic[self.langName]['c053_invert'].capitalize(),
                    attributeType="long",
                    min=0,
                    max=1,
                    defaultValue=1,
                    keyable=False)
                cmds.addAttr(
                    self.wheelCtrl,
                    longName=self.langDic[self.langName]['c093_tryKeepUndo'],
                    attributeType="long",
                    min=0,
                    max=1,
                    defaultValue=1,
                    keyable=False)

                # get stored values by user:
                startFrameValue = cmds.getAttr(self.moduleGrp + ".startFrame")
                steeringValue = cmds.getAttr(self.moduleGrp + ".steering")
                showControlsValue = cmds.getAttr(self.moduleGrp +
                                                 ".showControls")
                cmds.setAttr(self.wheelCtrl + "." +
                             self.langDic[self.langName]['c068_startFrame'],
                             startFrameValue,
                             channelBox=True)
                cmds.setAttr(self.wheelCtrl + "." +
                             self.langDic[self.langName]['c070_steering'],
                             steeringValue,
                             channelBox=True)
                cmds.setAttr(self.wheelCtrl + "." +
                             self.langDic[self.langName]['c021_showControls'],
                             showControlsValue,
                             channelBox=True)
                cmds.setAttr(
                    self.wheelCtrl + "." +
                    self.langDic[self.langName]['c070_steering'] +
                    self.langDic[self.langName]['c053_invert'].capitalize(),
                    1,
                    channelBox=True)
                cmds.setAttr(self.wheelCtrl + "." +
                             self.langDic[self.langName]['c093_tryKeepUndo'],
                             1,
                             channelBox=True)
                if s == 1:
                    if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                        cmds.setAttr(
                            self.wheelCtrl + "." +
                            self.langDic[self.langName]['c070_steering'] +
                            self.langDic[
                                self.langName]['c053_invert'].capitalize(), 0)

                # automatic rotation wheel setup:
                receptSteeringMD = cmds.createNode(
                    'multiplyDivide',
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c070_steering'] + "_MD")
                inverseSteeringMD = cmds.createNode(
                    'multiplyDivide',
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c070_steering'] + "_Inv_MD")
                steeringInvCnd = cmds.createNode(
                    'condition',
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c070_steering'] + "_Inv_Cnd")
                cmds.setAttr(steeringInvCnd + ".colorIfTrueR", 1)
                cmds.setAttr(steeringInvCnd + ".colorIfFalseR", -1)
                cmds.connectAttr(
                    self.wheelCtrl + "." +
                    self.langDic[self.langName]['i037_to'] +
                    self.langDic[self.langName]['c070_steering'].capitalize(),
                    receptSteeringMD + ".input1X",
                    force=True)
                cmds.connectAttr(self.wheelCtrl + "." +
                                 self.langDic[self.langName]['c070_steering'],
                                 receptSteeringMD + ".input2X",
                                 force=True)
                cmds.connectAttr(receptSteeringMD + ".outputX",
                                 inverseSteeringMD + ".input1X",
                                 force=True)
                cmds.connectAttr(steeringInvCnd + ".outColorR",
                                 inverseSteeringMD + ".input2X",
                                 force=True)
                cmds.connectAttr(
                    self.wheelCtrl + "." +
                    self.langDic[self.langName]['c070_steering'] +
                    self.langDic[self.langName]['c053_invert'].capitalize(),
                    steeringInvCnd + ".firstTerm",
                    force=True)
                cmds.connectAttr(inverseSteeringMD + ".outputX",
                                 self.toSteeringGrp + ".rotateY",
                                 force=True)
                # create locators (frontLoc to get direction and oldLoc to store wheel old position):
                self.frontLoc = cmds.spaceLocator(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] +
                    "_Front_Loc")[0]
                self.oldLoc = cmds.spaceLocator(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Old_Loc")[0]
                cmds.delete(
                    cmds.parentConstraint(self.cvFrontLoc,
                                          self.frontLoc,
                                          maintainOffset=False))
                cmds.parent(self.frontLoc, self.mainCtrl)
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.oldLoc,
                                          maintainOffset=False))
                cmds.setAttr(self.frontLoc + ".visibility", 0, lock=True)
                cmds.setAttr(self.oldLoc + ".visibility", 0, lock=True)
                # this wheel auto group locator could be replaced by a decomposeMatrix to get the translation in world space of the Wheel_Auto_Ctrl_Grp instead:
                self.wheelAutoGrpLoc = cmds.spaceLocator(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m156_wheel'] + "_Auto_Loc")[0]
                cmds.pointConstraint(wheelAutoGrp,
                                     self.wheelAutoGrpLoc,
                                     maintainOffset=False,
                                     name=self.wheelAutoGrpLoc +
                                     "_PointConstraint")
                cmds.setAttr(self.wheelAutoGrpLoc + ".visibility",
                             0,
                             lock=True)
                expString = "if ("+self.wheelCtrl+"."+self.langDic[self.langName]['c047_autoRotate']+" == 1) {"+\
                        "\nif ("+self.wheelCtrl+"."+self.langDic[self.langName]['c093_tryKeepUndo']+" == 1) { undoInfo -stateWithoutFlush 0; };"+\
                        "\nfloat $radius = "+self.wheelCtrl+"."+self.langDic[self.langName]['c067_radius']+" * "+self.wheelCtrl+"."+self.langDic[self.langName]['c069_radiusScale']+\
                        ";\nvector $moveVectorOld = `xform -q -ws -t \""+self.oldLoc+\
                        "\"`;\nvector $moveVector = << "+self.wheelAutoGrpLoc+".translateX, "+self.wheelAutoGrpLoc+".translateY, "+self.wheelAutoGrpLoc+".translateZ >>;"+\
                        "\nvector $dirVector = `xform -q -ws -t \""+self.frontLoc+\
                        "\"`;\nvector $wheelVector = ($dirVector - $moveVector);"+\
                        "\nvector $motionVector = ($moveVector - $moveVectorOld);"+\
                        "\nfloat $distance = mag($motionVector);"+\
                        "\n$dot = dotProduct($motionVector, $wheelVector, 1);\n"+\
                        wheelAutoGrp+".rotateZ = "+wheelAutoGrp+".rotateZ - 360 / (6.283*$radius) * ($dot*$distance);"+\
                        "\nxform -t ($moveVector.x) ($moveVector.y) ($moveVector.z) "+self.oldLoc+\
                        ";\nif (frame == "+self.wheelCtrl+"."+self.langDic[self.langName]['c068_startFrame']+") { "+wheelAutoGrp+".rotateZ = 0; };"+\
                        "\nif ("+self.wheelCtrl+"."+self.langDic[self.langName]['c093_tryKeepUndo']+" == 1) { undoInfo -stateWithoutFlush 1; };};"
                # expression:
                cmds.expression(name=side + self.userGuideName + "_" +
                                self.langDic[self.langName]['m156_wheel'] +
                                "_Exp",
                                object=self.frontLoc,
                                string=expString)
                self.ctrls.setLockHide([self.frontLoc, self.wheelAutoGrpLoc], [
                    'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'
                ])

                # deformers:
                self.loadedGeo = cmds.getAttr(self.moduleGrp + ".geo")

                # geometry holder:
                self.geoHolder = cmds.polyCube(
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c046_holder'] + "_Geo",
                    constructionHistory=False)[0]
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          self.geoHolder,
                                          maintainOffset=False))
                cmds.setAttr(self.geoHolder + ".visibility", 0, lock=True)

                # skinning:
                cmds.skinCluster(self.centerJoint,
                                 self.geoHolder,
                                 toSelectedBones=True,
                                 dropoffRate=4.0,
                                 maximumInfluences=3,
                                 skinMethod=0,
                                 normalizeWeights=1,
                                 removeUnusedInfluence=False,
                                 name=side + self.userGuideName + "_" +
                                 self.langDic[self.langName]['c046_holder'] +
                                 "_SC")
                if self.loadedGeo:
                    if cmds.objExists(self.loadedGeo):
                        baseName = utils.extractSuffix(self.loadedGeo)
                        skinClusterName = baseName + "_SC"
                        if "|" in skinClusterName:
                            skinClusterName = skinClusterName[skinClusterName.
                                                              rfind("|") + 1:]
                        try:
                            cmds.skinCluster(self.centerJoint,
                                             self.loadedGeo,
                                             toSelectedBones=True,
                                             dropoffRate=4.0,
                                             maximumInfluences=3,
                                             skinMethod=0,
                                             normalizeWeights=1,
                                             removeUnusedInfluence=False,
                                             name=skinClusterName)
                        except:
                            childList = cmds.listRelatives(self.loadedGeo,
                                                           children=True,
                                                           allDescendents=True)
                            if childList:
                                for item in childList:
                                    itemType = cmds.objectType(item)
                                    if itemType == "mesh" or itemType == "nurbsSurface":
                                        try:
                                            skinClusterName = utils.extractSuffix(
                                                item) + "_SC"
                                            cmds.skinCluster(
                                                self.centerJoint,
                                                item,
                                                toSelectedBones=True,
                                                dropoffRate=4.0,
                                                maximumInfluences=3,
                                                skinMethod=0,
                                                normalizeWeights=1,
                                                removeUnusedInfluence=False,
                                                name=skinClusterName)
                                        except:
                                            pass

                # lattice:
                latticeList = cmds.lattice(self.geoHolder,
                                           divisions=(6, 6, 6),
                                           outsideLattice=2,
                                           outsideFalloffDistance=1,
                                           position=(0, 0, 0),
                                           scale=(self.ctrlRadius * 2,
                                                  self.ctrlRadius * 2,
                                                  self.ctrlRadius * 2),
                                           name=side + self.userGuideName +
                                           "_FFD")  #[deformer, lattice, base]
                cmds.scale(self.ctrlRadius * 2, self.ctrlRadius * 2,
                           self.ctrlRadius * 2, latticeList[2])
                # clusters:
                upperClusterList = cmds.cluster(
                    latticeList[1] + ".pt[0:5][4:5][0:5]",
                    relative=True,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c044_upper'] +
                    "_Cls")  #[deform, handle]
                middleClusterList = cmds.cluster(
                    latticeList[1] + ".pt[0:5][2:3][0:5]",
                    relative=True,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m033_middle'] +
                    "_Cls")  #[deform, handle]
                lowerClusterList = cmds.cluster(
                    latticeList[1] + ".pt[0:5][0:1][0:5]",
                    relative=True,
                    name=side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c045_lower'] +
                    "_Cls")  #[deform, handle]
                clusterGrpList = utils.zeroOut([
                    upperClusterList[1], middleClusterList[1],
                    lowerClusterList[1]
                ])
                clustersGrp = cmds.group(clusterGrpList,
                                         name=side + self.userGuideName +
                                         "_Clusters_Grp")

                # deform controls:
                upperDefCtrl = self.ctrls.cvControl(
                    "id_063_WheelDeform",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c044_upper'] + "_Ctrl",
                    r=self.ctrlRadius * 0.5,
                    d=self.curveDegree)
                middleDefCtrl = self.ctrls.cvControl(
                    "id_064_WheelMiddle",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['m033_middle'] + "_Ctrl",
                    r=self.ctrlRadius * 0.5,
                    d=self.curveDegree)
                lowerDefCtrl = self.ctrls.cvControl(
                    "id_063_WheelDeform",
                    side + self.userGuideName + "_" +
                    self.langDic[self.langName]['c045_lower'] + "_Ctrl",
                    r=self.ctrlRadius * 0.5,
                    d=self.curveDegree,
                    rot=(0, 0, 180))
                defCtrlGrpList = utils.zeroOut(
                    [upperDefCtrl, middleDefCtrl, lowerDefCtrl])
                defCtrlGrp = cmds.group(defCtrlGrpList,
                                        name=side + self.userGuideName +
                                        "_Ctrl_Grp")

                # positions:
                cmds.delete(
                    cmds.parentConstraint(upperClusterList[1],
                                          defCtrlGrpList[0],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(middleClusterList[1],
                                          defCtrlGrpList[1],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(lowerClusterList[1],
                                          defCtrlGrpList[2],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          latticeList[1],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          latticeList[2],
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          clustersGrp,
                                          maintainOffset=False))
                cmds.delete(
                    cmds.parentConstraint(self.cvCenterLoc,
                                          defCtrlGrp,
                                          maintainOffset=False))
                outsideDist = cmds.getAttr(self.cvOutsideLoc + ".tz")
                if s == 1:
                    if cmds.getAttr(self.moduleGrp + ".flip") == 1:
                        outsideDist = -outsideDist
                cmds.move(outsideDist,
                          defCtrlGrp,
                          moveZ=True,
                          relative=True,
                          objectSpace=True,
                          worldSpaceDistance=True)
                self.ctrls.directConnect(upperDefCtrl, upperClusterList[1])
                self.ctrls.directConnect(middleDefCtrl, middleClusterList[1])
                self.ctrls.directConnect(lowerDefCtrl, lowerClusterList[1])
                # grouping deformers:
                if self.loadedGeo:
                    if cmds.objExists(self.loadedGeo):
                        cmds.lattice(latticeList[0],
                                     edit=True,
                                     geometry=self.loadedGeo)
                defGrp = cmds.group(latticeList[1],
                                    latticeList[2],
                                    clustersGrp,
                                    name=side + self.userGuideName +
                                    "_Deform_Grp")
                cmds.parentConstraint(self.mainCtrl,
                                      defGrp,
                                      maintainOffset=True,
                                      name=defGrp + "_ParentConstraint")
                cmds.scaleConstraint(self.mainCtrl,
                                     defGrp,
                                     maintainOffset=True,
                                     name=defGrp + "_ScaleConstraint")
                cmds.parent(defCtrlGrp, self.mainCtrl)
                cmds.connectAttr(
                    self.wheelCtrl + "." +
                    self.langDic[self.langName]['c021_showControls'],
                    defCtrlGrp + ".visibility",
                    force=True)

                # create a masterModuleGrp to be checked if this rig exists:
                self.toCtrlHookGrp = cmds.group(
                    zeroGrpList[2],
                    name=side + self.userGuideName + "_Control_Grp")
                self.toScalableHookGrp = cmds.group(
                    self.centerJoint,
                    self.mainJoint,
                    defGrp,
                    name=side + self.userGuideName + "_Joint_Grp")
                self.toStaticHookGrp = cmds.group(self.toCtrlHookGrp,
                                                  self.toScalableHookGrp,
                                                  self.oldLoc,
                                                  self.wheelAutoGrpLoc,
                                                  self.geoHolder,
                                                  name=side +
                                                  self.userGuideName + "_Grp")
                # add hook attributes to be read when rigging integrated modules:
                utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
                utils.addHook(objName=self.toScalableHookGrp,
                              hookType='scalableHook')
                utils.addHook(objName=self.toStaticHookGrp,
                              hookType='staticHook')
                cmds.addAttr(self.toStaticHookGrp,
                             longName="dpAR_name",
                             dataType="string")
                cmds.addAttr(self.toStaticHookGrp,
                             longName="dpAR_type",
                             dataType="string")
                cmds.setAttr(self.toStaticHookGrp + ".dpAR_name",
                             self.userGuideName,
                             type="string")
                cmds.setAttr(self.toStaticHookGrp + ".dpAR_type",
                             CLASS_NAME,
                             type="string")
                # add module type counter value
                cmds.addAttr(self.toStaticHookGrp,
                             longName='dpAR_count',
                             attributeType='long',
                             keyable=False)
                cmds.setAttr(self.toStaticHookGrp + '.dpAR_count', dpAR_count)
                self.ctrlHookGrpList.append(self.toCtrlHookGrp)
                if hideJoints:
                    cmds.setAttr(self.toScalableHookGrp + ".visibility", 0)
                # delete duplicated group for side (mirror):
                cmds.delete(side + self.userGuideName + '_' + self.mirrorGrp)
            # finalize this rig:
            self.integratingInfo()
            cmds.select(clear=True)
        # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
        self.deleteModule()
Example #57
0
def ribbonJoints(sj,
                 ej,
                 bendyName,
                 module,
                 extraName='',
                 moduleType=None,
                 par=None,
                 endCtrl=False,
                 basePar=None):
    """ Create a ribbon setup.
    [Args]:
    sj (string) -
    ej (string) -
    bendyName (string) - The name of the ribbon setup
    module (class) - The class of the body part module
    extraName (string) - The extra name of the ribbon setup
    moduleType (string) - The type of module
    par (string) - The name of the mechanics parent
    endCtrl (bool) - Toggles creating an end control
    basePar (string) - The name of the joints parent
    [Returns]:
    bendyEndCtrl (class) - The end control class or False
    """
    if not basePar:
        basePar = sj
    moduleName = utils.setupBodyPartName(module.extraName, module.side)
    bendyName = '{}{}'.format(moduleType, bendyName)
    col = utils.getColors(module.side)

    distance = cmds.getAttr('{}.tx'.format(ej))
    nPlane = cmds.nurbsPlane(p=(distance / 2, 0, 0),
                             lr=0.1,
                             w=distance,
                             axis=[0, 1, 0],
                             u=3,
                             d=3)
    nPlane = cmds.rename(
        nPlane[0], '{}{}Bendy{}'.format(moduleName, bendyName,
                                        suffix['nurbsSurface']))
    if par:
        cmds.parent(nPlane, par)
    utils.matchTransforms(nPlane, sj)
    ## ctrl
    if not cmds.objExists('{}{}Ctrls{}'.format(moduleName, moduleType,
                                               suffix['group'])):
        ctrlGrp = cmds.group(
            n='{}{}Ctrls{}'.format(moduleName, moduleType, suffix['group']))
        cmds.parent(ctrlGrp, module.rig.ctrlsGrp.name)
    bendyCtrl = ctrlFn.ctrl(name='{}{}Bendy'.format(extraName, bendyName),
                            side=module.side,
                            offsetGrpNum=2,
                            skipNum=True,
                            rig=module.rig,
                            scaleOffset=module.rig.scaleOffset,
                            parent='{}{}Ctrls{}'.format(
                                moduleName, moduleType, suffix['group']))
    bendyCtrl.modifyShape(color=col['col3'],
                          shape='starFour',
                          scale=(0.3, 0.3, 0.3))
    cmds.pointConstraint(sj, ej, bendyCtrl.offsetGrps[0].name)
    cmds.orientConstraint(sj, bendyCtrl.offsetGrps[0].name, sk='x')
    orientConstr = cmds.orientConstraint(basePar,
                                         ej,
                                         bendyCtrl.offsetGrps[1].name,
                                         sk=['y', 'z'],
                                         mo=1)
    cmds.setAttr('{}.interpType'.format(orientConstr[0]), 2)
    ## clusters
    cmds.select('{}.cv[0:1][0:3]'.format(nPlane))
    baseClu = utils.newNode('cluster',
                            name='{}{}BendyBase'.format(extraName, bendyName),
                            side=module.side,
                            parent=par)
    cmds.select('{}.cv[2:3][0:3]'.format(nPlane))
    midClu = utils.newNode('cluster',
                           name='{}{}BendyMid'.format(extraName, bendyName),
                           side=module.side,
                           parent=par)
    bendyCtrl.constrain(midClu.name)
    bendyCtrl.constrain(midClu.name, typ='scale')
    endCluGrpTrans = utils.newNode('group',
                                   name='{}{}BendyEndCluTrans'.format(
                                       extraName, bendyName),
                                   side=module.side,
                                   parent=par)
    utils.matchTransforms(endCluGrpTrans.name, ej)
    endCluGrpOrientYZ = utils.newNode('group',
                                      name='{}{}BendyEndCluOrient'.format(
                                          extraName, bendyName),
                                      side=module.side,
                                      parent=endCluGrpTrans.name)
    utils.matchTransforms(endCluGrpOrientYZ.name, endCluGrpTrans.name)
    endCluGrpOrientX = utils.newNode('group',
                                     name='{}{}BendyEndCluOrientX'.format(
                                         extraName, bendyName),
                                     side=module.side,
                                     parent=endCluGrpOrientYZ.name)
    utils.matchTransforms(endCluGrpOrientX.name, endCluGrpOrientYZ.name)
    cmds.select('{}.cv[4:5][0:3]'.format(nPlane))
    endClu = utils.newNode('cluster',
                           name='{}{}BendyEnd'.format(extraName, bendyName),
                           side=module.side,
                           parent=endCluGrpOrientX.name)
    cmds.parentConstraint(basePar, baseClu.name, mo=1)
    cmds.scaleConstraint(basePar, baseClu.name, mo=1)
    if not endCtrl:
        cmds.pointConstraint(ej, endCluGrpTrans.name, mo=1)
        cmds.orientConstraint(ej, endCluGrpOrientX.name, mo=1, sk=['y', 'z'])
        cmds.orientConstraint(sj, endCluGrpOrientYZ.name, mo=1, sk='x')
        bendyEndCtrl = False
    else:
        bendyEndCtrl = ctrlFn.ctrl(
            name='{}{}BendyEnd'.format(extraName, bendyName),
            side=module.side,
            skipNum=True,
            rig=module.rig,
            scaleOffset=module.rig.scaleOffset,
            parent='{}{}Ctrls{}'.format(moduleName, moduleType,
                                        suffix['group']))
        bendyEndCtrl.modifyShape(color=col['col3'],
                                 shape='starFour',
                                 scale=(0.3, 0.3, 0.3))
        cmds.parentConstraint(ej, bendyEndCtrl.offsetGrps[0].name)
        bendyEndCtrl.constrain(endCluGrpTrans.name)
        bendyEndCtrl.constrain(endCluGrpTrans.name, typ='scale')
    ## rivets
    rivJntPar = sj
    for i in [0.1, 0.3, 0.5, 0.7, 0.9]:
        rivJnt = createRivet('{}Bendy'.format(bendyName),
                             extraName,
                             module,
                             nPlane,
                             pv=0.5,
                             pu=i,
                             parent=par,
                             rivJntPar=rivJntPar)
        rivJntPar = rivJnt
    return bendyEndCtrl
Example #58
0
    def rigModule(self, *args):
        Base.StartClass.rigModule(self)
        # verify if the guide exists:
        if cmds.objExists(self.moduleGrp):
            try:
                hideJoints = cmds.checkBox('hideJointsCB', query=True, value=True)
            except:
                hideJoints = 1
            # declaring lists to send information for integration:
            self.scalableGrpList, self.ikCtrlZeroList = [], []
            # start as no having mirror:
            sideList = [""]
            # analisys the mirror module:
            self.mirrorAxis = cmds.getAttr(self.moduleGrp + ".mirrorAxis")
            if self.mirrorAxis != 'off':
                # get rigs names:
                self.mirrorNames = cmds.getAttr(self.moduleGrp + ".mirrorName")
                # get first and last letters to use as side initials (prefix):
                sideList = [self.mirrorNames[0] + '_', self.mirrorNames[len(self.mirrorNames) - 1] + '_']
                for s, side in enumerate(sideList):
                    duplicated = cmds.duplicate(self.moduleGrp, name=side + self.userGuideName + '_Guide_Base')[0]
                    allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
                    for item in allGuideList:
                        cmds.rename(item, side + self.userGuideName + "_" + item)
                    self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True)
                    cmds.parent(side + self.userGuideName + '_Guide_Base', self.mirrorGrp, absolute=True)
                    # re-rename grp:
                    cmds.rename(self.mirrorGrp, side + self.userGuideName + '_' + self.mirrorGrp)
                    # do a group mirror with negative scaling:
                    if s == 1:
                        for axis in self.mirrorAxis:
                            cmds.setAttr(side + self.userGuideName + '_' + self.mirrorGrp + '.scale' + axis, -1)
            else:  # if not mirror:
                duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName + '_Guide_Base')[0]
                allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
                for item in allGuideList:
                    cmds.rename(item, self.userGuideName + "_" + item)
                self.mirrorGrp = cmds.group(self.userGuideName + '_Guide_Base', name="Guide_Base_Grp", relative=True)
                # re-rename grp:
                cmds.rename(self.mirrorGrp, self.userGuideName + '_' + self.mirrorGrp)
            # store the number of this guide by module type
            dpAR_count = utils.findModuleLastNumber(CLASS_NAME, "dpAR_type") + 1
            # run for all sides
            for s, side in enumerate(sideList):
                self.skinJointList = []
                self.base = side + self.userGuideName + '_Guide_Base'
                # get the number of joints to be created:
                self.nJoints = cmds.getAttr(self.base + ".nJoints")
                for n in range(0, self.nJoints + 1):
                    cmds.select(clear=True)
                    # declare guide:
                    self.guide = side + self.userGuideName + "_Guide_JointLoc" + str(n)
                    # create a joint:
                    self.jnt = cmds.joint(name=side + self.userGuideName + "_" + str(n) + "_Jnt", scaleCompensate=False)
                    self.skinJointList.append(self.jnt)
                    cmds.addAttr(self.jnt, longName='dpAR_joint', attributeType='float', keyable=False)
                    # create a control:
                    if n == 1:
                        self.ctrl = ctrls.cvFinger(ctrlName=side + self.userGuideName + "_" + str(n) + "_Ctrl", r=self.ctrlRadius)
                        cmds.setAttr(self.ctrl + ".rotateOrder", 1)
                        utils.originedFrom(objName=self.ctrl, attrString=self.base + ";" + self.guide)
                        # edit the mirror shape to a good direction of controls:
                        if s == 1:
                            if self.mirrorAxis == 'X':
                                cmds.setAttr(self.ctrl + '.rotateZ', 180)
                            elif self.mirrorAxis == 'Y':
                                cmds.setAttr(self.ctrl + '.rotateY', 180)
                            elif self.mirrorAxis == 'Z':
                                cmds.setAttr(self.ctrl + '.rotateZ', 180)
                            elif self.mirrorAxis == 'XY':
                                cmds.setAttr(self.ctrl + '.rotateX', 180)
                            elif self.mirrorAxis == 'XYZ':
                                cmds.setAttr(self.ctrl + '.rotateZ', 180)
                            cmds.makeIdentity(self.ctrl, apply=True, translate=False, rotate=True, scale=False)
                    else:
                        self.ctrl = cmds.circle(name=side + self.userGuideName + "_" + str(n) + "_Ctrl", degree=1, normal=(0, 0, 1), r=self.ctrlRadius, s=6, ch=False)[0]
                        cmds.setAttr(self.ctrl + ".rotateOrder", 1)
                        utils.originedFrom(objName=self.ctrl, attrString=self.guide)
                        if n == 0:
                            if self.nJoints == 2:
                                # problably we are creating the first control to a thumb
                                cmds.scale(2, 2, 2, self.ctrl, relative=True)
                                cmds.makeIdentity(self.ctrl, apply=True)
                            else:
                                # problably we are creating other base controls
                                cmds.scale(2, 0.5, 1, self.ctrl, relative=True)
                                cmds.makeIdentity(self.ctrl, apply=True)

                    # scaleCompensate attribute:
                    #Not needed in Maya 2016 since we need to deactivate scale compensate on all finger bone
                    if (int(cmds.about(version=True)[:4]) < 2016):
                        if n > 0 or self.nJoints == 2:
                            cmds.addAttr(self.ctrl, longName="scaleCompensate", attributeType='bool', keyable=True)
                            scaleCompensateCond = cmds.createNode("condition", name=side + self.userGuideName + "_" + str(n) + "_ScaleCompensate_Cnd")
                            cmds.setAttr(scaleCompensateCond + ".secondTerm", 1)
                            cmds.connectAttr(self.ctrl + ".scaleCompensate", scaleCompensateCond + ".colorIfTrueR", force=True)
                            cmds.connectAttr(scaleCompensateCond + ".outColorR", self.jnt + ".segmentScaleCompensate", force=True)

                    # hide visibility attribute:
                    cmds.setAttr(self.ctrl + '.visibility', keyable=False)
                    # put another group over the control in order to use this to connect values from mainFingerCtrl:
                    self.sdkGrp = cmds.group(self.ctrl, name=side + self.userGuideName + "_" + str(n) + "_SDKGrp")
                    if n == 1:
                        # change pivot of this group to control pivot:
                        pivotPos = cmds.xform(self.ctrl, query=True, worldSpace=True, rotatePivot=True)
                        cmds.setAttr(self.sdkGrp + '.rotatePivotX', pivotPos[0])
                        cmds.setAttr(self.sdkGrp + '.rotatePivotY', pivotPos[1])
                        cmds.setAttr(self.sdkGrp + '.rotatePivotZ', pivotPos[2])
                    # position and orientation of joint and control:
                    tempDel = cmds.parentConstraint(self.guide, self.jnt, maintainOffset=False)
                    cmds.delete(tempDel)
                    tempDel = cmds.parentConstraint(self.guide, self.sdkGrp, maintainOffset=False)
                    cmds.delete(tempDel)
                    # zeroOut controls:
                    utils.zeroOut([self.sdkGrp])
                # create end joint:
                self.cvEndJoint = side + self.userGuideName + "_Guide_JointEnd"
                self.endJoint = cmds.joint(name=side + self.userGuideName + "_JEnd", scaleCompensate=False)
                tempDel = cmds.parentConstraint(self.cvEndJoint, self.endJoint, maintainOffset=False)
                cmds.delete(tempDel)
                cmds.parent(self.endJoint, side + self.userGuideName + "_" + str(self.nJoints) + "_Jnt", absolute=True)
                # grouping:
                for n in range(0, self.nJoints + 1):
                    self.jnt = side + self.userGuideName + "_" + str(n) + "_Jnt"
                    self.ctrl = side + self.userGuideName + "_" + str(n) + "_Ctrl"
                    self.zeroCtrl = side + self.userGuideName + "_" + str(n) + "_SDKGrp_Zero"
                    if n > 0:
                        if n == 1:
                            if not cmds.objExists(self.ctrl + '.ikFkBlend'):
                                cmds.addAttr(self.ctrl, longName="ikFkBlend", attributeType='float', keyable=True, minValue=0.0, maxValue=1.0, defaultValue=1.0)
                                self.ikFkRevNode = cmds.createNode("reverse", name=side + self.userGuideName + "_ikFk_Rev")
                                cmds.connectAttr(self.ctrl + ".ikFkBlend", self.ikFkRevNode + ".inputX", force=True)
                            if not cmds.objExists(self.ctrl + '.' + self.langDic[self.langName]['c_showControls']):
                                cmds.addAttr(self.ctrl, longName=self.langDic[self.langName]['c_showControls'], attributeType='float', keyable=True, minValue=0.0, maxValue=1.0, defaultValue=1.0)
                                self.ctrlShape0 = cmds.listRelatives(side + self.userGuideName + "_0_Ctrl", children=True, type='nurbsCurve')[0]
                                cmds.connectAttr(self.ctrl + "." + self.langDic[self.langName]['c_showControls'], self.ctrlShape0 + ".visibility", force=True)
                                cmds.setAttr(self.ctrl + '.' + self.langDic[self.langName]['c_showControls'], keyable=False, channelBox=True)
                            for j in range(1, self.nJoints + 1):
                                cmds.addAttr(self.ctrl, longName=self.langDic[self.langName]['c_falange'] + str(j), attributeType='float', keyable=True)
                        # parent joints as a simple chain (line)
                        self.fatherJnt = side + self.userGuideName + "_" + str(n - 1) + "_Jnt"
                        cmds.parent(self.jnt, self.fatherJnt, absolute=True)
                        # parent zeroCtrl Group to the before ctrl:
                        self.fatherCtrl = side + self.userGuideName + "_" + str(n - 1) + "_Ctrl"
                        cmds.parent(self.zeroCtrl, self.fatherCtrl, absolute=True)
                    # freeze joints rotation
                    cmds.makeIdentity(self.jnt, apply=True)
                    # create parent and scale constraints from ctrl to jnt:
                    cmds.delete(cmds.parentConstraint(self.ctrl, self.jnt, maintainOffset=False, name=self.jnt + "_ParentConstraint"))
                # make first falange be leads from base finger control:
                cmds.parentConstraint(side + self.userGuideName + "_0_Ctrl", side + self.userGuideName + "_1_SDKGrp_Zero", maintainOffset=True, name=side + self.userGuideName + "_1_SDKGrp_Zero" + "_ParentConstraint")
                cmds.scaleConstraint(side + self.userGuideName + "_0_Ctrl", side + self.userGuideName + "_1_SDKGrp_Zero", maintainOffset=True, name=side + self.userGuideName + "_1_SDKGrp_Zero" + "_ScaleConstraint")
                if self.nJoints != 2:
                    cmds.parentConstraint(side + self.userGuideName + "_0_Ctrl", side + self.userGuideName + "_0_Jnt", maintainOffset=True, name=side + self.userGuideName + "_ParentConstraint")
                    cmds.scaleConstraint(side + self.userGuideName + "_0_Ctrl", side + self.userGuideName + "_0_Jnt", maintainOffset=True, name=side + self.userGuideName + "_ScaleConstraint")
                # connecting the attributes from control 1 to falanges rotate:
                for n in range(1, self.nJoints + 1):
                    self.ctrl = side + self.userGuideName + "_1_Ctrl"
                    self.sdkGrp = side + self.userGuideName + "_" + str(n) + "_SDKGrp"
                    cmds.connectAttr(self.ctrl + "." + self.langDic[self.langName]['c_falange'] + str(n), self.sdkGrp + ".rotateY", force=True)
                    if n > 1:
                        self.ctrlShape = cmds.listRelatives(side + self.userGuideName + "_" + str(n) + "_Ctrl", children=True, type='nurbsCurve')[0]
                        cmds.connectAttr(self.ctrl + "." + self.langDic[self.langName]['c_showControls'], self.ctrlShape + ".visibility", force=True)

                # ik and Fk setup
                if self.nJoints == 2:
                    dupIk = cmds.duplicate(self.skinJointList[0])[0]
                    dupFk = cmds.duplicate(self.skinJointList[0])[0]
                else:
                    dupIk = cmds.duplicate(self.skinJointList[1])[0]
                    dupFk = cmds.duplicate(self.skinJointList[1])[0]
                
                # hide ik and fk joints in order to be rigger friendly whe skinning
                cmds.setAttr(dupIk+".visibility", 0)
                cmds.setAttr(dupFk+".visibility", 0)
                
                # ik setup
                childrenIkList = cmds.listRelatives(dupIk, children=True, allDescendents=True, fullPath=True)
                if childrenIkList:
                    for child in childrenIkList:
                        if not cmds.objectType(child) == "joint":
                            cmds.delete(child)
                jointIkList = cmds.listRelatives(dupIk, children=True, allDescendents=True, fullPath=True)
                for jointNode in jointIkList:
                    if "_Jnt" in jointNode[jointNode.rfind("|"):]:
                        cmds.rename(jointNode, jointNode[jointNode.rfind("|") + 1:].replace("_Jnt", "_Ik_Jxt"))
                    elif "_JEnd" in jointNode[jointNode.rfind("|"):]:
                        cmds.rename(jointNode, jointNode[jointNode.rfind("|") + 1:].replace("_JEnd", "_Ik_JEnd"))
                ikBaseJoint = cmds.rename(dupIk, dupIk.replace("_Jnt1", "_Ik_Jxt"))
                ikJointList = cmds.listRelatives(ikBaseJoint, children=True, allDescendents=True)
                ikJointList.append(ikBaseJoint)

                # Fk setup
                childrenFkList = cmds.listRelatives(dupFk, children=True, allDescendents=True, fullPath=True)
                if childrenFkList:
                    for child in childrenFkList:
                        if not cmds.objectType(child) == "joint":
                            cmds.delete(child)
                jointFkList = cmds.listRelatives(dupFk, children=True, allDescendents=True, fullPath=True)
                for jointNode in jointFkList:
                    if "_Jnt" in jointNode[jointNode.rfind("|"):]:
                        cmds.rename(jointNode, jointNode[jointNode.rfind("|") + 1:].replace("_Jnt", "_Fk_Jxt"))
                    elif "_JEnd" in jointNode[jointNode.rfind("|"):]:
                        cmds.rename(jointNode, jointNode[jointNode.rfind("|") + 1:].replace("_JEnd", "_Fk_JEnd"))
                fkBaseJoint = cmds.rename(dupFk, dupFk.replace("_Jnt2", "_Fk_Jxt"))
                fkJointList = cmds.listRelatives(fkBaseJoint, children=True, allDescendents=True)
                fkJointList.append(fkBaseJoint)
                # ik fk blend connnections
                for i, ikJoint in enumerate(ikJointList):
                    if not "_JEnd" in ikJoint:
                        if cmds.objExists(ikJoint + ".dpAR_joint"):
                            cmds.deleteAttr(ikJoint + ".dpAR_joint")
                        fkJoint = ikJoint.replace("_Ik_Jxt", "_Fk_Jxt")
                        skinJoint = ikJoint.replace("_Ik_Jxt", "_Jnt")
                        self.ctrl = side + self.userGuideName + "_1_Ctrl"
                        scaleCompensateCond = ikJoint.replace("_Ik_Jxt", "_ScaleCompensate_Cnd")
                        ikFkParentConst = cmds.parentConstraint(ikJoint, fkJoint, skinJoint, maintainOffset=True, name=skinJoint + "_ParentConstraint")[0]
                        ikFkScaleConst = cmds.scaleConstraint(ikJoint, fkJoint, skinJoint, maintainOffset=True, name=skinJoint + "_ScaleConstraint")[0]
                        cmds.connectAttr(self.ctrl + ".ikFkBlend", ikFkParentConst + "." + fkJoint + "W1", force=True)
                        cmds.connectAttr(self.ikFkRevNode + ".outputX", ikFkParentConst + "." + ikJoint + "W0", force=True)
                        cmds.connectAttr(self.ctrl + ".ikFkBlend", ikFkScaleConst + "." + fkJoint + "W1", force=True)
                        cmds.connectAttr(self.ikFkRevNode + ".outputX", ikFkScaleConst + "." + ikJoint + "W0", force=True)
                        cmds.setAttr(ikJoint + ".segmentScaleCompensate", 1)
                        #Condition for scale compensate will not exist in maya 2016 since we need to have the compensate
                        #off for almost every joint
                        if (int(cmds.about(version=True)[:4]) < 2016):
                            cmds.connectAttr(self.ctrl + ".ikFkBlend", scaleCompensateCond + ".firstTerm", force=True)
                # fk control drives fk joints
                for i, fkJoint in enumerate(fkJointList):
                    if not "_JEnd" in fkJoint:
                        if cmds.objExists(fkJoint + ".dpAR_joint"):
                            cmds.deleteAttr(fkJoint + ".dpAR_joint")
                        fkCtrl = fkJoint.replace("_Fk_Jxt", "_Ctrl")
                        scaleCompensateCond = fkCtrl.replace("_Ctrl", "_ScaleCompensate_Cnd")
                        cmds.parentConstraint(fkCtrl, fkJoint, maintainOffset=True, name=fkJoint + "_ParentConstraint")
                        cmds.scaleConstraint(fkCtrl, fkJoint, maintainOffset=True, name=fkJoint + "_ScaleConstraint")
                        #Not needed in Maya 2016 since we need to deactivate scale compensate on all finger bone
                        if (int(cmds.about(version=True)[:4]) < 2016):
                            cmds.connectAttr(fkCtrl + ".scaleCompensate", fkJoint + ".segmentScaleCompensate", force=True)
                        else:
                            cmds.setAttr(fkJoint + ".segmentScaleCompensate", 0)
                        cmds.setAttr(fkCtrl + ".rotateOrder", 1)

                #Force Scale compensate to prevent scale problem in Maya 2016
                for nJnt in self.skinJointList:
                    if (int(cmds.about(version=True)[:4]) >= 2016):
                        cmds.setAttr(nJnt + ".segmentScaleCompensate", 0)

                # ik handle
                if self.nJoints >= 2:
                    if self.nJoints == 2:
                        ikHandleList = cmds.ikHandle(startJoint=side + self.userGuideName + "_0_Ik_Jxt", endEffector=side + self.userGuideName + "_" + str(self.nJoints) + "_Ik_Jxt", solver="ikRPsolver", name=side + self.userGuideName + "_IkHandle")
                    else:
                        ikHandleList = cmds.ikHandle(startJoint=side + self.userGuideName + "_1_Ik_Jxt", endEffector=side + self.userGuideName + "_" + str(self.nJoints) + "_Ik_Jxt", solver="ikRPsolver", name=side + self.userGuideName + "_IkHandle")
                    cmds.rename(ikHandleList[1], side + self.userGuideName + "_Effector")
                    endIkHandleList = cmds.ikHandle(startJoint=side + self.userGuideName + "_" + str(self.nJoints) + "_Ik_Jxt", endEffector=side + self.userGuideName + "_Ik_JEnd", solver="ikSCsolver", name=side + self.userGuideName + "_EndIkHandle")
                    cmds.rename(endIkHandleList[1], side + self.userGuideName + "_EndEffector")
                    self.ikCtrl = ctrls.cvBox(ctrlName=side + self.userGuideName + "_Ik_Ctrl", r=self.ctrlRadius*0.3)
                    cmds.addAttr(self.ikCtrl, longName='twist', attributeType='float', keyable=True)
                    cmds.connectAttr(self.ikCtrl + ".twist", ikHandleList[0] + ".twist", force=True)
                    cmds.delete(cmds.parentConstraint(side + self.userGuideName + "_Ik_JEnd", self.ikCtrl))
                    cmds.setAttr(self.ikCtrl + ".rotateOrder", 1)
                    self.ikCtrlZero = utils.zeroOut([self.ikCtrl])[0]
                    self.ikCtrlZeroList.append(self.ikCtrlZero)
                    cmds.connectAttr(self.ikFkRevNode + ".outputX", self.ikCtrlZero + ".visibility", force=True)
                    for q in range(2, self.nJoints):
                        cmds.connectAttr(side + self.userGuideName + "_1_Ctrl.ikFkBlend", side + self.userGuideName + "_" + str(q) + "_Ctrl.visibility", force=True)
                    cmds.parentConstraint(self.ikCtrl, ikHandleList[0], name=side + self.userGuideName + "_IkHandle_ParentConstraint", maintainOffset=True)
                    cmds.parentConstraint(self.ikCtrl, endIkHandleList[0], name=side + self.userGuideName + "_EndIkHandle_ParentConstraint", maintainOffset=True)
                    ikHandleGrp = cmds.group(ikHandleList[0], endIkHandleList[0], name=side + self.userGuideName + "_IkHandle_Grp")
                    cmds.setAttr(ikHandleGrp+".visibility", 0)
                    ctrls.setLockHide([self.ikCtrl], ['sx', 'sy', 'sz', 'v'])

                    if self.nJoints == 2:
                        cmds.parentConstraint(side + self.userGuideName + "_0_Ctrl", side + self.userGuideName + "_0_Ik_Jxt", maintainOffset=True, name=side + self.userGuideName + "_0_Ik_Jxt_ParentConstraint")
                        cmds.scaleConstraint(side + self.userGuideName + "_0_Ctrl", side + self.userGuideName + "_0_Ik_Jxt", maintainOffset=True, name=side + self.userGuideName + "_0_Ik_Jxt_ScaleConstraint")

                    # stretch
                    cmds.addAttr(self.ikCtrl, longName='stretchable', attributeType='float', minValue=0, maxValue=1, defaultValue=0, keyable=True)
                    stretchNormMD = cmds.createNode("multiplyDivide", name=side + self.userGuideName + "_StretchNormalize_MD")
                    cmds.setAttr(stretchNormMD + ".operation", 2)
                    distBetweenList = ctrls.distanceBet(side + self.userGuideName + "_0_Ctrl", self.ikCtrl, name=side + self.userGuideName + "_DistBet", keep=True)
                    cmds.connectAttr(self.ikFkRevNode + ".outputX", distBetweenList[5] + "." + self.ikCtrl + "W0", force=True)
                    cmds.connectAttr(self.ctrl + ".ikFkBlend", distBetweenList[5] + "." + distBetweenList[4] + "W1", force=True)
                    cmds.connectAttr(distBetweenList[1] + ".distance", stretchNormMD + ".input1X", force=True)
                    cmds.setAttr(stretchNormMD + ".input2X", distBetweenList[0])
                    stretchScaleMD = cmds.createNode("multiplyDivide", name=side + self.userGuideName + "_StretchScale_MD")
                    cmds.connectAttr(stretchNormMD + ".outputX", stretchScaleMD + ".input1X", force=True)
                    cmds.connectAttr(self.ikCtrl + ".stretchable", stretchScaleMD + ".input2X", force=True)
                    stretchCond = cmds.createNode("condition", name=side + self.userGuideName + "_Stretch_Cnd")
                    cmds.connectAttr(stretchScaleMD + ".outputX", stretchCond + ".firstTerm", force=True)
                    cmds.setAttr(stretchCond + ".secondTerm", 1)
                    cmds.setAttr(stretchCond + ".operation", 2)
                    cmds.connectAttr(stretchScaleMD + ".outputX", stretchCond + ".colorIfTrueR", force=True)
                    for i, ikJoint in enumerate(ikJointList):
                        if not "_JEnd" in ikJoint:
                            if self.nJoints == 2 and i == 0:
                                pass
                            else:
                                cmds.connectAttr(stretchCond + ".outColorR", ikJoint + ".scaleZ", force=True)

                    # create a masterModuleGrp to be checked if this rig exists:
                    self.toCtrlHookGrp = cmds.group(self.ikCtrlZero, side + self.userGuideName + "_0_SDKGrp_Zero", side + self.userGuideName + "_1_SDKGrp_Zero", name=side + self.userGuideName + "_Control_Grp")
                    if self.nJoints == 2:
                        self.toScalableHookGrp = cmds.group(side + self.userGuideName + "_0_Jnt", ikBaseJoint, fkBaseJoint, ikHandleGrp, distBetweenList[2], distBetweenList[3], distBetweenList[4], name=side + self.userGuideName + "_Joint_Grp")
                    else:
                        self.toScalableHookGrp = cmds.group(side + self.userGuideName + "_0_Jnt", ikHandleGrp, distBetweenList[2], distBetweenList[3], distBetweenList[4], name=side + self.userGuideName + "_Joint_Grp")
                else:
                    self.toCtrlHookGrp = cmds.group(side + self.userGuideName + "_0_SDKGrp_Zero", side + self.userGuideName + "_1_SDKGrp_Zero", name=side + self.userGuideName + "_Control_Grp")
                    self.toScalableHookGrp = cmds.group(side + self.userGuideName + "_0_Jnt", name=side + self.userGuideName + "_Joint_Grp")
                self.scalableGrpList.append(self.toScalableHookGrp)
                self.toStaticHookGrp = cmds.group(self.toCtrlHookGrp, self.toScalableHookGrp, name=side + self.userGuideName + "_Grp")
                # add hook attributes to be read when rigging integrated modules:
                utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
                utils.addHook(objName=self.toScalableHookGrp, hookType='scalableHook')
                utils.addHook(objName=self.toStaticHookGrp, hookType='staticHook')
                cmds.addAttr(self.toStaticHookGrp, longName="dpAR_name", dataType="string")
                cmds.addAttr(self.toStaticHookGrp, longName="dpAR_type", dataType="string")
                cmds.setAttr(self.toStaticHookGrp + ".dpAR_name", self.userGuideName, type="string")
                cmds.setAttr(self.toStaticHookGrp + ".dpAR_type", CLASS_NAME, type="string")
                # add module type counter value
                cmds.addAttr(self.toStaticHookGrp, longName='dpAR_count', attributeType='long', keyable=False)
                cmds.setAttr(self.toStaticHookGrp + '.dpAR_count', dpAR_count)
                # create a locator in order to avoid delete static group
                loc = cmds.spaceLocator(name=side + self.userGuideName + "_DO_NOT_DELETE")[0]
                cmds.parent(loc, self.toStaticHookGrp, absolute=True)
                cmds.setAttr(loc + ".visibility", 0)
                ctrls.setLockHide([loc], ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'])
                if hideJoints:
                    cmds.setAttr(self.toScalableHookGrp + ".visibility", 0)
                # delete duplicated group for side (mirror):
                cmds.delete(side + self.userGuideName + '_' + self.mirrorGrp)
            # finalize this rig:
            self.integratingInfo()
            cmds.select(clear=True)
        # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
        self.deleteModule()
 def StretchyIkSetup(self, armSels):
     
     if hasattr(armSels, '__getitem__'):
 
         #declare variables for the various joints
         self.firstJointPos=cmds.xform(armSels[0], q=1, ws=1, t=1)
         self.secondJointPos=cmds.xform(armSels[1], q=1, ws=1, t=1)
         self.lastJointPos=cmds.xform(armSels[2], q=1, ws=1, t=1)
         self.lastJointRot=cmds.xform(armSels[2], q=1, ws=1, ro=1)
         self.secondJointPosLocal=cmds.xform(armSels[1], q=1, t=1)
         self.lastJointPosLocal=cmds.xform(armSels[2], q=1, t=1)
             
         #Create an IK handle on first and last Joints.
         self.tempIKName= str(armSels[0]) + "IK_Hndl"
         self.ikName=cmds.ikHandle(ee=armSels[2], sj=armSels[0], n=self.tempIKName)
         
         #Create locators for the first and last joint. 
         self.jnt1Loc=cmds.spaceLocator(p=(0, 0, 0))
         cmds.move(self.firstJointPos[0], self.firstJointPos[1], self.firstJointPos[2])
         self.jnt2Loc=cmds.spaceLocator(p=(0, 0, 0))
         cmds.move(self.lastJointPos[0], self.lastJointPos[1], self.lastJointPos[2])
         self.jnt1LocShape=cmds.listRelatives(self.jnt1Loc, s=1)
         self.jnt2LocShape=cmds.listRelatives(self.jnt2Loc, s=1)
         
         #create a control for the IK handle, give it a stretchy attribute.
         self.ikCtrlTempName = str(armSels[0]) + "_IK_Ctrl"
         self.ikJointControl = cmds.circle(c=(0, 0, 0), n=self.ikCtrlTempName)
         cmds.addAttr(ln="Stretchy", at="float", keyable=True)
         self.ourControlGrp = cmds.group(n=(str(armSels[0]) + "_IK_Ctrl_Grp"), em=True)
         cmds.move(self.lastJointPos[0], self.lastJointPos[1], self.lastJointPos[2], self.ourControlGrp, ws=1)  
         cmds.rotate(self.lastJointRot[0], self.lastJointRot[1], self.lastJointRot[2], self.ourControlGrp, ws=1)  
         cmds.parent(self.ikCtrlTempName , self.ourControlGrp)
         cmds.move(0,0,0, self.ikJointControl, ls=True)
         cmds.rotate(0,0,0, self.ikJointControl)
         
         #create a "Distance between" Node for... well. getting the distance between the two nodes. 
         self.distanceTest=str(cmds.shadingNode('distanceBetween', asUtility=1))
         
         #create all of these nodes for all the different things we need to set up for the system.
         self.arm01DistanceNode=str(cmds.shadingNode('multiplyDivide', asUtility=1))
         cmds.setAttr((self.arm01DistanceNode + ".input1X"), self.secondJointPosLocal[0])
         self.arm02DistanceNode=str(cmds.shadingNode('multiplyDivide', asUtility=1))
         cmds.setAttr((self.arm02DistanceNode + ".input1X"), self.lastJointPosLocal[0])
         self.chainLengthPMA=str(cmds.shadingNode('plusMinusAverage', asUtility=1))
         self.distanceScalar=str(cmds.shadingNode('multiplyDivide', asUtility=1))
         cmds.setAttr((self.distanceScalar + ".operation"), 2)
         self.stretchCondition=str(cmds.shadingNode('condition', asUtility=1))
         cmds.setAttr((self.stretchCondition + ".operation"), 2)
         self.colorBlendNode=str(cmds.shadingNode('blendColors', asUtility=1))
         cmds.setAttr((self.colorBlendNode + ".color2R"), 1)
         self.arm01ScaleMD=str(cmds.shadingNode('multiplyDivide', asUtility=1))
         self.arm02ScaleMD=str(cmds.shadingNode('multiplyDivide', asUtility=1))
         
         
         #connect them attributes
         self.LinkConstraints(self.jnt1LocShape[0], "worldPosition[0]", self.distanceTest, "point1")
         self.LinkConstraints(self.jnt2LocShape[0], "worldPosition[0]", self.distanceTest, "point2")
         self.LinkConstraints(self.arm01DistanceNode, "outputX", self.chainLengthPMA, "input1D[0]")
         self.LinkConstraints(self.arm02DistanceNode, "outputX", self.chainLengthPMA, "input1D[1]")
         self.LinkConstraints(self.chainLengthPMA, "output1D", self.distanceScalar, "input2X")
         self.LinkConstraints(self.distanceTest, "distance", self.distanceScalar, "input1X")
         self.LinkConstraints(self.distanceTest, "distance", self.stretchCondition, "firstTerm")
         self.LinkConstraints(self.chainLengthPMA, "output1D", self.stretchCondition, "secondTerm")
         self.LinkConstraints(self.distanceScalar, "outputX", self.stretchCondition, "colorIfTrueR")
         self.LinkConstraints(self.stretchCondition, "outColorR", self.colorBlendNode, "color1R")
         self.LinkConstraints(self.arm01DistanceNode, "outputX", self.arm01ScaleMD, "input1X")
         self.LinkConstraints(self.arm02DistanceNode, "outputX", self.arm02ScaleMD, "input1X")
         self.LinkConstraints(self.colorBlendNode, "outputR", self.arm01ScaleMD, "input2X")
         self.LinkConstraints(self.colorBlendNode, "outputR", self.arm02ScaleMD, "input2X")
         self.LinkConstraints(self.arm01ScaleMD, "outputX", armSels[1], "translateX")
         self.LinkConstraints(self.arm02ScaleMD, "outputX", armSels[2], "translateX")
         self.LinkConstraints((str(armSels[0]) + "_IK_Ctrl"), "Stretchy", self.colorBlendNode, "blender")
         cmds.parentConstraint(self.ikCtrlTempName, self.tempIKName,  mo=True )
         cmds.parentConstraint(self.ikCtrlTempName, self.jnt2Loc,  mo=True )
         cmds.scaleConstraint(self.ikCtrlTempName, self.tempIKName,  mo=True )
         cmds.scaleConstraint(self.ikCtrlTempName, self.jnt2Loc,  mo=True )
 
     else:
         print("Generic Error Message")
         return        
Example #60
0
#在原骨骼和精简的骨骼之间做父子约束和缩放约束
import maya.cmds as cmds
basejnt = cmds.ls(sl=True)
jntAll = cmds.listRelatives(basejnt, allDescendents=True, type="joint")
grp = cmds.group(em=True, name="CW_Constraints_GRP")
cmds.parent(grp, "Deformers_GRP")
for i in jntAll:
    j = i[3:]
    parentCon = cmds.parentConstraint(j, i)
    cmds.parent(parentCon, grp)
    scaleCon = cmds.scaleConstraint(j, i)
    cmds.parent(scaleCon, grp)