def build(self):
     
     root  = 'root%s' % self.count
     backa = 'backA%s' % self.count
     backb = 'backB%s' % self.count
     chest = 'chest%s' % self.count
     neck  = 'neck%s' % self.count
     
     if not cmds.objExists(root): return
     
     # root
     cmds.parent(backa,w=True)
     cmds.setAttr('%s.jointOrientY' % root,0)
     cmds.parent(backa,root)
     
     # midsection
     cmds.joint(backa,e=True,oj='xyz',sao='zup',zso=True)
     cmds.joint(backb,e=True,oj='xyz',sao='zup',zso=True)
     
     # chest
     cmds.parent(neck,w=True)
     cmds.makeIdentity(chest,a=True,t=False,r=True,s=False,n=False,jo=True)    
     rx,ry,rz = cmds.xform(chest,q=True,ws=True,ro=True)
     cmds.setAttr('%s.jointOrientZ' % chest,ry)
     cmds.parent(neck,chest)
     
     grp = cmds.group(n='fit',em=True)
     cmds.parent(root,grp)
示例#2
0
文件: head.py 项目: skarone/PipeL
	def __init__(self, objs = [], vertices = []):
		self.objs = objs
		self.vertices = vertices
		#lattice  -divisions 2 3 2 -objectCentered true  -ol 1;
		#mc.select( self.objs, self.vertices )
		#CREATION
		grp = mn.Node( mc.group( n = "head_toon_GRP", em = True ) )
		deGrp = mn.Node( mc.group( n = "head_toon_deformer_GRP", em = True ) )
		deGrp.parent = grp
		deGrp.a.v.v = False
		deGrp.a.v.locked = True
		latNods = mc.lattice( self.objs, self.vertices, divisions = [ 2,3,2], objectCentered = True, ol = 1, n = 'head_toon_LAT' )
		latBase = mn.Node( latNods[2] )
		latBase.parent = deGrp
		lat = mn.Node( latNods[1] )
		lat.parent = deGrp
		#mc.select( lat + ".pt[0:1][2][0]", lat + ".pt[0:1][2][1]" )
		topClus = mn.Node( mc.cluster(  lat.shape.name + ".pt[0:1][2][0]", lat.shape.name + ".pt[0:1][2][1]", n = 'top_face_toon_CLU' )[1] )
		topClus.a.v.v = False
		topClus.a.v.locked = True
		#mc.select( lat + ".pt[0:1][1][0]", lat + ".pt[0:1][1][1]" )
		midClus = mn.Node( mc.cluster(  lat.shape.name + ".pt[0:1][1][0]", lat.shape.name + ".pt[0:1][1][1]", n = 'mid_face_toon_CLU' )[1] )
		#mc.select( lat + ".pt[0:1][0][0]", lat + ".pt[0:1][0][1]" )
		lowClus = mn.Node( mc.cluster(  lat.shape.name + ".pt[0:1][0][0]", lat.shape.name + ".pt[0:1][0][1]", n = 'low_face_toon_CLU' )[1] )
		ctl = crv.Curve( "head_toon_CTL" )
		ctl = ctl.create( "sphere" )
		ctl.a.t.v = topClus.worldPosition
		mc.makeIdentity( ctl.name, apply = True, t = 1, r = 1, s = 1, n = 2 )
		topClus.parent = ctl
		midClus.parent = deGrp
		lowClus.parent = deGrp
		ctl.parent = grp
		#CONSTRAINS
		midClus.a.r >> topClus.a.r
		mc.pointConstraint( topClus.name, lowClus.name, midClus.name, mo = True )
		#SCALE FOR MID CLUSTER
		dist = mn.createNode( 'distanceBetween', n = 'head_toon_DIS' )
		ctl.a.worldMatrix >> dist.a.inMatrix1
		ctl.a.rp >> dist.a.point1
		lowClus.a.worldMatrix >> dist.a.inMatrix2
		lowClus.a.rp >> dist.a.point2
		mul = mn.createNode( 'multiplyDivide', n = 'head_toon_scale_MUL' )
		mul.a.input1.v = [dist.a.distance.v]*3
		mul.a.operation.v = 2
		dist.a.distance >> mul.a.input2X
		dist.a.distance >> mul.a.input2Y
		dist.a.distance >> mul.a.input2Z
		mul.a.output >> midClus.a.s
		#AIM CONSTRAINT
		upLocGrp = mn.Node( mc.group( n = "head_upVector_GRP", em = True ) )
		upLocGrp.a.t.v = midClus.worldPosition
		mc.makeIdentity( upLocGrp.name, apply = True, t = 1, r = 1, s = 1, n = 2 )
		upLocGrp.parent = deGrp
		mc.orientConstraint( ctl.name, lowClus.name, upLocGrp.name, mo = True )
		upLoc = mn.Node( mc.spaceLocator( n = 'head_upVector_LOC' )[0] )
		upLoc.a.t.v = midClus.worldPosition
		upLoc.a.tz.v = upLoc.a.tz.v + 5
		mc.aimConstraint( topClus.name, midClus.name, mo = True, weight = 1, aimVector = [1, 0, 0], upVector = [0, 1, 0], worldUpType = "object", worldUpObject = upLoc.name )
		upLoc.parent = upLocGrp
		mc.pointConstraint( topClus.name, lowClus.name, upLoc.name, mo = True )
示例#3
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()
示例#4
0
 def createMasterCtrl(self, ctrl, offsetCtrl, curveShape, size, offsetScale):
     cmds.file(PATH + curveShape + ".ma", i=True, rdn =True)
     cmds.rename('control', ctrl)
 
     cmds.file(PATH + "circle.ma", i=True, rdn =True)
     cmds.rename('control', offsetCtrl)
     
     cmds.xform(offsetCtrl, scale=[offsetScale, offsetScale, offsetScale ])
     cmds.makeIdentity(offsetCtrl, apply=True, s=True)
     
     cmds.parent(offsetCtrl, ctrl)
 
     cmds.addAttr(ctrl, at='bool', ln="offsetCtrl", dv=1)
     cmds.setAttr(ctrl + ".offsetCtrl", k=False, cb=True)        
     offsetCtrlShapes = cmds.listRelatives(offsetCtrl, shapes=True)
     for offsetCtrlShape in offsetCtrlShapes:
         cmds.connectAttr(ctrl+".offsetCtrl", offsetCtrlShape+".visibility")
     
     cluster, clusterHandle = cmds.cluster(ctrl, name=ctrl+"_cluster")
     cmds.setAttr(clusterHandle + '.visibility', 0)
     cmds.setAttr(cluster + '.relative', 1)
     cmds.parent(clusterHandle, ctrl)
     
     cmds.addAttr(ctrl, at='double', ln="iconSize", minValue=0.1, dv=size, k=True)
     cmds.setAttr(ctrl + ".iconSize", k=False, cb=True)        
     cmds.connectAttr(ctrl+".iconSize", clusterHandle+".scaleX")
     cmds.connectAttr(ctrl+".iconSize", clusterHandle+".scaleY")
     cmds.connectAttr(ctrl+".iconSize", clusterHandle+".scaleZ")
 
     cmds.setAttr(ctrl+".offsetCtrl", 0)
示例#5
0
 def orientJoints(s):
     """
     Face joints in the correct direction.
     """
     sel = cmds.ls(sl=True)
     err = cmds.undoInfo(openChunk=True)
     try:
         markers = s.markers
         joints = markers.keys()
         with ReSeat(joints):
             for j in joints:
                 m = markers[j]
                 if cmds.objExists(m.marker) and cmds.objExists(j):
                     with Isolate(j):
                         m.setJoint()
                         try:
                             cmds.makeIdentity(
                                 j,
                                 apply=True,
                                 r=True) # Freeze Rotations
                         except RuntimeError:
                             pass
                 else: # User deleted marker / joint. Stop tracking.
                     m.removeMarker()
                     del markers[j]
             cmds.select(sel, r=True)
     except Exception as err:
         raise
     finally:
         cmds.undoInfo(closeChunk=True)
         if err: cmds.undo()
示例#6
0
    def doIt(self, argList):
        # get objects from argument list (size >= 2)
        try:
            obj = misc.getArgObj(self.syntax(), argList)
            if (len(obj) < 2):
                cmds.error("Select at least 2 objects!")
                return
            if (cmds.objectType(obj[0]) != 'transform' or cmds.objectType(obj[1]) != 'transform'):
                cmds.error("Object is not of type transform!")
                return
        except:
            cmds.warning("No objects selected or only one object given!")
            return

        argData = om.MArgParser(self.syntax(), argList)

        # read all arguments and set default values
        keepCD = argData.flagArgumentBool('keepConvexDecomposition', 0) if (argData.isFlagSet('keepConvexDecomposition')) else True
        nvol = argData.flagArgumentDouble('normVolume', 0) if (
            argData.isFlagSet('normVolume')) else 100.0
        norm = argData.flagArgumentBool('norm', 0) if (
            argData.isFlagSet('norm')) else True
        s_file = os.path.abspath(argData.flagArgumentString('saveFile', 0)) if (argData.isFlagSet('saveFile')) else ""
        save = False
        if s_file != "":
            o_file = open(s_file, 'w')
            o_file.write("i0, i1, name0, name1, its_volume, dice\n")
            save = True

        # get all flags for vhacd over static parsing method
        vhacd_par = vhacd.vhacd.readArgs(argData)
        if (vhacd_par is None):
            cmds.error("V-HACD: one or more arguments are invalid!")
            return

        #norm the volume
        if norm:
            for o in obj:
                v = cmds.getVolume(o)
                scale_factor = (nvol/ v) ** (1./3)
                # cmds.xform(o, scale=[scale_factor, scale_factor, scale_factor])
                cmds.scale(scale_factor, scale_factor, scale_factor, o, relative=True)
                cmds.makeIdentity(o, apply=True)

        intersection_matrix = np.matrix(str(cmds.intersection(obj, kcd=keepCD, matlabOutput=True, **vhacd_par)))
        dice_matrix = np.matrix(intersection_matrix)

        for i in range(0, intersection_matrix.shape[0]):
            for j in range(i, intersection_matrix.shape[1]):
                its_volume = intersection_matrix[i, j]
                dice_matrix[i, j] = (its_volume*2)/(intersection_matrix[i, i]+intersection_matrix[j, j])
                if save:
                    o_file.write(",".join((str(i), str(j), obj[i], obj[j], str(its_volume), str(dice_matrix[i, j]))))
                    o_file.write("\n")
                    o_file.flush()

        if save:
            o_file.close()

        self.setResult(str(dice_matrix))
示例#7
0
def create_base_rig(cog, rig_region_name):
    # create curve and scale it to the correct size
    base_curve, base_curve_group = jt_ctl_curve.create(None, 'star_30')
    cmds.select(base_curve)
    cmds.setAttr(base_curve + '.scale', 5,5,5)
    cmds.makeIdentity(apply=True, t=0, r=1, s=1, n=0)

    # unparent the curve from the default group it is given so its a child of the world
    base_curve = cmds.rename('base')
    cmds.parent(w=True)
    cmds.select(base_curve_group, r=True)
    cmds.delete()

    # add a string attribute to keep track of all the nodes that are used for easy de-rigging
    # NOTE: text is stored in the attr as a string formatted like a python dict with the key being
    # the name of the body region and the value being a list of the nodes involved this makes 
    # de-rigging nice and easy as you just need to find the entry in the dict and delete all the nodes

    cmds.select(base_curve)
    cmds.addAttr(ln='rig_nodes', dt='string')
    cmds.setAttr(base_curve + '.rig_nodes', '{}', type='string')

    # add base_curve to base curve attr list
    add_node_to_rig_nodes(base_curve, 'base', base_curve)

    # update ui base_curve_field
    cmds.textField('jt_autorig_base_name_select_text', e=True, tx=base_curve)
示例#8
0
def orientJoint (objects = [], aim = [1,0,0], up = [0,0,1]):

    crossVector = getCrossVector(objects[0], objects[1], objects[-1])
    
    for i in range(len(objects)-1):
        jointParents = cmds.listRelatives(objects[i], p=True)
        
        if jointParents:
            jointParent = jointParents[0]
            
        children = cmds.listRelatives(objects[i], c=True, type='transform')
        tempGrp = cmds.group(objects[i])
        
        cmds.parent(children, tempGrp)
        cmds.parent(objects[i], world=True)
        
        cmds.delete(cmds.aimConstraint(objects[i+1], objects[i], aimVector=aim, upVector=up, worldUpType='vector', worldUpVector = crossVector))

        cmds.parent(children, objects[i])
        
        if jointParents:
            cmds.parent(objects[i], jointParent)
            
        cmds.delete(tempGrp)
    
    cmds.makeIdentity(objects[0], apply=True, r=True) 
	def __init__( self, fkik_snap_set ):
		cmds.select( cl = True )
		self.get_globals()

		for obj in cmds.sets( fkik_snap_set, q = True ):
			controller = DAG_Node( obj )

			obj_snap_attr = '{0}.{1}'.format( controller.name(), self.snap_parent_str )

			if cmds.objExists( obj_snap_attr ):
				obj_snap = cmds.listConnections( obj_snap_attr )

				if obj_snap:
					obj_snap = obj_snap[0]
					snap_grp = DAG_Node( cmds.group( n = '{0}_Snap_Grp'.format( obj.split( '|' )[-1] ), em = True ) )

					snap_grp.set_parent( controller.parent() )

					obj_tra = cmds.xform( controller.name(), ws = True, rp = True, q = True )
					cmds.xform( snap_grp.name(), ws = True, t = obj_tra )

					obj_rot = cmds.xform( controller.name(), ws = True, ro = True, q = True )
					cmds.xform( snap_grp.name(), ws = True, ro = obj_rot )

					cmds.makeIdentity( snap_grp.name(), a = True, t = True, r = True, s = True )

					cmds.parentConstraint( obj_snap, snap_grp.name(), mo = True )

					snap_grp_attr = Maya_Util().add_attr( snap_grp.name(), self.snap_parent_str, 'message' )
					cmds.connectAttr( snap_grp_attr, obj_snap_attr, force = True )

		cmds.select( cl = True )
示例#10
0
def myPrimer(myjtText,mycvText):
	#myjtText=cmds.textField('jtText',q=1,text=1)	
	#mycvText=cmds.textField('cvText',q=1,text=1)	
	#mypadInt=cmds.intField('padInt',q=1,v=1)
	mypadInt=3
	cmds.pointConstraint(myjtText,mycvText,n='tmpCt')
	cmds.delete('tmpCt')
	print myjtText
	print mycvText
	cmds.parent(mycvText,myjtText)
	i=0
	while(i<mypadInt):
		if(i==0):
			newname=[mycvText[0] + '_wa']
			topNode=newname

		else:
			newname=[mycvText[0] + '_pad']

		cmds.group(mycvText,n=newname[0])
		i=i+1
		print topNode
		
	cmds.select(topNode)
	cmds.parent(w=1)
	cmds.makeIdentity(mycvText,apply=1,t=1,r=1,s=1,n=0)
def create_pointer(m):
    if (BAXER_POINTER == True):
        # import Baxter Pointer model and use it
        try:
            cmds.loadPlugin("objExport")
        except:
            pass
        name = os.path.dirname(os.path.realpath(__file__)) + "/models/baxter_gripper.obj"
        mel.eval('file -import -type "OBJ"  -ignoreVersion -ra true -mergeNamespacesOnClash false -rpr "gripper" -options "mo=1"  -pr "%s";' \
             % name)
        try:
            mel.eval('rename "gripper_Mesh" "pointer' + str(m) + '";')
        except:
            pass
    else:
        # Create a pointer mesh that represents the robot claw
        cmds.polyCone(name="pointer" + str(m), sx=3, r=0.5, h=2)
        cmds.select("pointer" + str(m))
        cmds.rotate("180deg", 0, 0, r=True)
        cmds.move(0, -1, 0, "pointer" + str(m) + ".scalePivot", "pointer" + str(m) + ".rotatePivot")
        cmds.move(0, 1, 0, absolute=True)
        cmds.makeIdentity(apply=True, t=1, r=1, s=1)
    bbx = cmds.xform("table", q=True, bb=True, ws=True)
    cur_size = abs(bbx[3] - bbx[0])
    cmds.scale(cur_size/TABLE_SIZE, cur_size/TABLE_SIZE, cur_size/TABLE_SIZE, "pointer" + str(m), centerPivot = True)
    mel.eval('select -r pointer' + str(m) + '; sets -e -forceElement pointer_matSG;')
    mel.eval("makeCollideNCloth")
示例#12
0
文件: utils.py 项目: Bumpybox/Tapp
def Square(name='square_cnt',group=False,size=1.0):
    ''' Creates a square shape.
        If group is True, will group control and
        return a list [group,control].
    '''
    
    #creating the curve
    curve=cmds.curve(d=1, p=[(0,1,1),(0,1,-1),(0,-1,-1),
                             (0,-1,1),(0,1,1)])
    
    #setup curve
    cmds.makeIdentity(curve,apply=True, t=1, r=1, s=1, n=0)
    
    #naming control
    node=cmds.rename(curve,name)
    
    #sizing
    cmds.scale(size,size,size,node)
    cmds.FreezeTransformations(node)
    
    #grouping control
    if group==True:
        grp=cmds.group(node,n=name+'_grp')
        
        return [grp,node]
    
    #return
    return node
示例#13
0
def createIKCtrlsOnJnts(ikCrv, parentCtrl, size=1):
    ikCVNum = ll.getCurveCVCount(ikCrv)
    prev=parentCtrl
    for i in range(1, ikCVNum):
        clus = mc.cluster('%s.cv[%d]'%(ikCrv, i), n=parentCtrl.replace('masterctrl','ikClus%d')%i)
        cvPos = mc.xform('%s.cv[%d]'%(ikCrv, i), q=1, ws=1, t=1)
        mc.select(parentCtrl)
        meval('wireShape("plus")')
        ikCtrl = mc.rename(masterCtrl.replace('masterctrl','ikCtrl%d'%i))
        mc.xform(ikCtrl, t=cvPos, ws=1)
        mc.scale(size, size, size, ikCtrl, ocp=1)
        mc.makeIdentity(ikCtrl, a=1, s=1)
        mc.parent(ikCtrl, parentCtrl)
        lsZeroOut(ikCtrl)
        ctrlPR = lsZeroOut(ikCtrl, 'PR')
        mc.addAttr(ikCtrl, ln='SPACE', at='bool', k=1)
        mc.setAttr(ikCtrl+'.SPACE', l=1)
        mc.addAttr(ikCtrl, ln='parent', at='float', dv=0, min=0, max=1, k=1)
        mc.addAttr(ikCtrl, ln='master', at='float', dv=1, min=0, max=1, k=1)
        mc.addAttr(ikCtrl, ln='world', at='float', dv=0, min=0, max=1, k=1)
        mc.parentConstraint(ikCtrl, clus)
        cons = mc.parentConstraint(prev, parentCtrl, ctrlPR, mo=1)[0]
        wal = mc.parentConstraint(cons, q=1, wal=1)
        if len(wal) > 1:
            mc.connectAttr(ikCtrl+'.parent', '%s.%s'%(cons, wal[0]), f=1)
            mc.connectAttr(ikCtrl+'.master', '%s.%s'%(cons, wal[1]), f=1)
        prev=ikCtrl
示例#14
0
文件: utils.py 项目: Bumpybox/Tapp
def Circle(name='circle_cnt',group=False,size=1.0):
    ''' Creates a circle shape.
        If group is True, will group control and
        return a list [group,control].
    '''
    
    #creating the curve
    curve=cmds.circle(radius=1,constructionHistory=False)
    
    #transform to standard
    cmds.rotate(0,90,0,curve)
    
    cmds.makeIdentity(curve,apply=True, t=1, r=1, s=1, n=0)
    
    #naming control
    node=cmds.rename(curve,name)
    
    #sizing
    cmds.scale(size,size,size,node)
    cmds.FreezeTransformations(node)
    
    #grouping control
    if group==True:
        grp=cmds.group(node,n=name+'_grp')
        
        return [grp,node]
    
    #return
    return node
示例#15
0
文件: utils.py 项目: Bumpybox/Tapp
def implicitSphere(name,group=False,size=1.0):
    ''' Creates a square shape.
        If group is True, will group control and
        return a list [group,control].
    '''
    
    #creating the curve
    curve=cmds.createNode('implicitSphere')
    curve=cmds.listRelatives(curve,parent=True)[0]
    
    #setup curve
    cmds.makeIdentity(curve,apply=True, t=1, r=1, s=1, n=0)
    
    #naming control
    node=cmds.rename(curve,name)
    
    #sizing
    cmds.scale(size,size,size,node)
    cmds.FreezeTransformations(node)
    
    #grouping control
    if group==True:
        grp=cmds.group(node,n=name+'_grp')
        
        return [grp,node]
    
    #return
    return node
示例#16
0
def mirrorOrient(joint, rollAxis):
    """
    Reorient joint to replicate mirrored behaviour
    @param joint: Joint to mirror orientation for
    @type joint: str
    @param rollAxis: Axis to maintain orientation for
    @type rollAxis: str
    """
    # Check Joint
    if not cmds.objExists(joint):
        raise Exception('Joint "' + joint + '" does not exist!')

    # Check Roll Axis
    if not ['x', 'y', 'z'].count(rollAxis):
        raise Exception('Invalid roll axis "' + rollAxis + '"!')

    # UnParent Children
    childList = cmds.listRelatives(joint, c=True)
    if childList: cmds.parent(childList, w=True)

    # ReOrient Joint
    rt = [0, 0, 0]
    axisDict = {'x': 0, 'y': 1, 'z': 2}
    rt[axisDict[rollAxis]] = 180
    cmds.setAttr(joint + '.r', *rt)
    cmds.makeIdentity(joint, apply=True, t=True, r=True, s=True)

    # Reparent children
    if childList: cmds.parent(childList, joint)
示例#17
0
def template_joints(joints=None, reorient_children=True, reset_orientation=True):
    if joints is None:
        joints = cmds.ls(sl=True, type='joint')
    if not joints:
        raise RuntimeError('No joint selected to orient.')

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

    red, green, blue = create_shaders()

    orient_group = cmds.createNode('transform', name=ORIENT_GROUP)
    manips = []
    for joint in joints:
        if reset_orientation:
            cmds.makeIdentity(joint, apply=True)
            cmds.joint(joint, edit=True, orientJoint='xyz', secondaryAxisOrient='yup', children=False, zeroScaleOrient=True)
        if not cmds.listRelatives(joint, children=True):
            zero_orient([joint])
            continue
        group, manip = create_orient_manipulator(joint, blue)
        manips.append(manip)
        cmds.parent(group, orient_group)
        cmds.parentConstraint(joint, group)
        cmds.setAttr(joint + '.template', 1)
    cmds.select(manips)
示例#18
0
	def CreateFingerSquareRig(self,Finger):

		if self.NameConv.RMGetFromName(Finger[0],"Side")=="LF":
			sideVariation = 1
		else:
			sideVariation = -1

		BoxResetPoint , BoxControl = RMRigShapeControls.RMCreateBoxCtrl(Finger[len(Finger)-1], ParentBaseSize = True, Xratio = .5 ,Yratio = .5 ,Zratio = .5)
		self.RMaddFinguerControls(BoxControl)
		
		cmds.makeIdentity(BoxControl, apply = True , r = False, t = True, s = True, n = 0)
		cmds.parentConstraint(Finger[len(Finger)-1],BoxResetPoint)

		RMRigTools.RMLockAndHideAttributes(BoxControl,"0000000000")

		RMRigTools.RMConnectWithLimits (BoxControl + ".MidUD",    Finger[0] + ".rotateY", [[-10,100],[0,0],[10,-100]])
		RMRigTools.RMConnectWithLimits (BoxControl + ".MidLR",    Finger[0] + ".rotateZ", [[-10,sideVariation * 120],[0,0],[10,sideVariation * -127]])
		RMRigTools.RMConnectWithLimits (BoxControl + ".MidTwist", Finger[0] + ".rotateX" ,[[-10,sideVariation * 90],[0,0],[10,sideVariation * -90]])
		index = 1
		for eachjoint in range(0,len(Finger)-1):
			RMRigTools.RMConnectWithLimits (BoxControl + ".UD" + str(index),    Finger[eachjoint] + ".rotateY", [[-10,100],[0,0],[10,-100]])
			RMRigTools.RMConnectWithLimits (BoxControl + ".LR" + str(index),    Finger[eachjoint] + ".rotateZ", [[-10,sideVariation * 120],[0,0],[10,sideVariation * -127]])
			RMRigTools.RMConnectWithLimits (BoxControl + ".Twist" + str(index), Finger[eachjoint] + ".rotateX" ,[[-10, sideVariation * 90],[0,0],[10, sideVariation * -90]])
			index += 1
		self.fingerControlsReset.append(BoxResetPoint)
		self.fingerContols.append(BoxControl)
示例#19
0
def freezeCenterPivot():
    """
    freeze transfoms, delete history and center pivot
    """
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
    cmds.delete(ch=True)
    cmds.xform(cp=True)
    def duplicate_button( self, *args  ):
        self.original_selected_objects = cmds.ls( selection=True )

        if( len(self.original_selected_objects) == 0 ):
            print "Nothing selected"
            return 0

        elif( len(self.original_selected_objects) == 1 ):
            self.relatives = cmds.listRelatives( children=True )

            if( len(self.relatives) == 1 ):
                print "Skip combine"
                cmds.duplicate( self.original_selected_objects, name=self.original_selected_objects[0] + "_Copy" )
                cmds.delete( constructionHistory=True )
                the_parent = cmds.listRelatives( parent=True )
                if( the_parent != None ):
                    cmds.parent( self.original_selected_objects[0] + "_Copy", world=True )

            else:
                self.combine()

        else:
            self.combine()

        self.newOriginCopy = cmds.ls( selection=True )[0]
        self.bbox = cmds.exactWorldBoundingBox( self.newOriginCopy )
        cmds.move((self.bbox[0] + self.bbox[3])/2, self.bbox[1], (self.bbox[2] + self.bbox[5])/2, self.newOriginCopy + ".scalePivot", self.newOriginCopy + ".rotatePivot", absolute=True)
        cmds.move( 0, 0, 0, self.newOriginCopy, rpr=True )
        cmds.makeIdentity( apply=True, t=1, r=1, s=1 )
        cmds.delete( constructionHistory=True )
示例#21
0
def Lab_colourspace_cube(colourspace, density=20):
    """
    Creates a *CIE L\\*a\\*b\\** colourspace cube with geometric density.

    Parameters
    ----------
    colourspace : RGB_Colourspace
        *RGB* Colourspace description.
    density : int, optional
        Cube divisions count.

    Returns
    -------
    unicode
        *CIE L\\*a\\*b\\** Colourspace cube.
    """

    cube = RGB_identity_cube(colourspace.name, density)
    it_mesh_vertex = OpenMaya.MItMeshVertex(dag_path(cube))
    while not it_mesh_vertex.isDone():
        position = it_mesh_vertex.position(OpenMaya.MSpace.kObject)
        it_mesh_vertex.setPosition(
            mpoint(tuple(np.ravel(RGB_to_Lab((position[0],
                                              position[1],
                                              position[2],),
                                             colourspace)))))
        it_mesh_vertex.next()
    set_attributes({'{0}.rotateX'.format(cube): 180,
                    '{0}.rotateZ'.format(cube): 90})
    cmds.makeIdentity(cube, apply=True, t=True, r=True, s=True)
    return cube
示例#22
0
def freezeToJoint(proxyGeo):
	'''
	Freeze the transforms of a proxy geometry to the target joint defined by the string value of its "jointProxy" attribute.
	@param proxyGeo: Proxy geometry to freeze transforms based on an associated joint.
	@type proxyMesh: str
	'''
	# Checks
	if not isProxyBound(proxyGeo):
		raise Exception('Object "'+proxyGeo+'" is not a valid proxy bounds object!')
	
	# Get Target Joint
	joint = mc.getAttr(proxyGeo+'.jointProxy')
	# Get Proxy Parent
	proxyGrp = mc.listRelatives(proxyGeo,p=True,pa=True)[0]
	
	# Match Joint Pivot
	piv = mc.xform(joint,q=True,ws=True,rp=True)
	mc.xform(proxyGrp,ws=True,piv=piv)
	mc.xform(proxyGeo,ws=True,piv=piv)
	
	# Freeze Transforms
	grpParent = mc.listRelatives(proxyGrp,p=True,pa=True)
	mc.parent(proxyGrp,joint)
	mc.makeIdentity(proxyGrp,apply=True,t=True,r=True,s=True)
	if grpParent: mc.parent(proxyGrp,grpParent[0])
	else: mc.parent(proxyGrp,w=True)
		
	# Return Result
	return joint
示例#23
0
	def ori_ctrl_joint_get_ori(self,joint,clean_parent):

		new_clean_parent = cmds.duplicate(joint, parentOnly=True)[0]

		if not clean_parent in cmds.listRelatives(new_clean_parent, parent=True):
			cmds.parent(new_clean_parent, clean_parent, absolute=True)

		cmds.makeIdentity(
							new_clean_parent,
							apply=True,
							rotate=True, 
							scale=False, 
							translate=False
						)

		ori_ctrl = self.get_ori_ctrl(joint)
		cmds.setAttr(new_clean_parent+".rotateX", cmds.getAttr(ori_ctrl+".rotateX"))

		cmds.makeIdentity(
							new_clean_parent,
							apply=True,
							rotate=True, 
							scale=False, 
							translate=False
						)

		orient_x = cmds.getAttr(new_clean_parent+".jointOrientX")
		orient_y = cmds.getAttr(new_clean_parent+".jointOrientY")
		orient_z = cmds.getAttr(new_clean_parent+".jointOrientZ")

		ori_values = (orient_x, orient_y, orient_z)

		return (ori_values, new_clean_parent)
示例#24
0
def cleanup(transform):
  # Select the transform
  cmds.select(transform, replace=True)
  # Scale 1/10x
  cmds.scale(centerPivot=True, scaleXYZ=1/10)
  # Freeze transformations
  cmds.makeIdentity(apply=True, translate=True, rotate=True, scale=True, normal=1)
示例#25
0
def circleH(name, position, size=1):
    j=cmds.circle(c=[0,0,0], nr=[0,1,0], sw=360, r=size, d=3, ut=0, tol=0.01, s=8, ch=1, n=name)
    i=cmds.pointConstraint(position, j)
    # deletes constraint nad freezes transforms
    cmds.delete(i)
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=1)
    return j
示例#26
0
def setAndFreeze(nodeName="", tx=None, ty=None, tz=None, rx=None, ry=None, rz=None, sx=None, sy=None, sz=None, freeze=True):
    """This function set attribute values and do a freezeTransfomation.
    """
    if nodeName != "":
        attrNameList  = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz']
        attrValueList = [tx, ty, tz, rx, ry, rz, sx, sy, sz]
        # setting attribute values:
        for v, attrValue in enumerate(attrValueList):
            if attrValue:
                try:
                    cmds.setAttr(nodeName+'.'+attrNameList[v], attrValue)
                except:
                    pass
        # looking the need of freeze:
        if freeze:
            freezeT = False
            freezeR = False
            freezeS = False
            if tx != None or ty != None or tz != None:
                freezeT = True
            if rx != None or ry != None or rz != None:
                freezeR = True
            if sx != None or sy != None or sz != None:
                freezeS = True
            try:
                cmds.makeIdentity(nodeName, apply=freeze, translate=freezeT, rotate=freezeR, scale=freezeS)
            except:
                pass
示例#27
0
def primeControl(driver, driven):	
	'''
	# Priming a control
	
	Return driver, grp, driven
	'''
	
	# Group needs to be created
	# Name group after control icon that is going to be created.
	grpNamePieces = driven.split("_")
	if( len(grpNamePieces) > 1 ): 
	    grpNamePieces = grpNamePieces[0:-1]
	grpNamePieces.append("grp")
	grpName = "_".join(grpNamePieces)
	grp = cmds.group( name=grpName, em=True, world=True )
	pc = cmds.pointConstraint( driver, grp )
	oc = cmds.orientConstraint( driver, grp )
	cmds.delete(pc, oc)
	# Option to snap control to position.
	pc = cmds.pointConstraint( driver, driven )
	
	cmds.delete( pc )
	cmds.parent( driven, grp )
	cmds.makeIdentity( apply=True, t=1, r=1, s=1, n=0 )
	
	# Position option to constrain driver to driven
	# Options: Point, Orient, Parent, and None

	return [driver, grp, driven]
示例#28
0
def makeFlake(branches,radius):
    '''
    Creates a single snowflake
    
    branches : number of side branches
    radius   : radius of the snowflake
    
    A cube is created and transformed to taper with a diamond cross-section. 
    It is passed to flakeIterate to generate 1/6 of the snowflake. This branch 
    is duplicated and rotated around the centre to create the full snowflake. 
    The parts are combined, the flake is scaled and transformations are frozen. 
    The snowflake name is returned.
    '''
    name=cmds.polyCube()[0]
    cmds.rotate(45,0,0,name,r=1)
    cmds.move(0.5,0,0,name+'.vtx[0:7]',r=1)
    cmds.scale(0.7,0.2,0.1,p=[0,0,0],r=1)
    cmds.scale(1,0.7,0.7,name+'.f[4]',r=1,p=[0,0,0])
    cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0)
    partList=flakeIterate(name,7,random.uniform(30,70),0.7)
    branches=[combineParts(partList,'branch')]
    for i in range(1,6):
        branches[len(branches):]=[cmds.duplicate('branch')[0]]
        cmds.rotate(0,i*60,0,branches[-1],r=1)
    flake = combineParts(branches,'snowflake')
    scale = radius/6
    cmds.scale(scale,scale,scale,flake)
    cmds.makeIdentity(flake,apply=True, s=1, n=0)
    return flake
示例#29
0
def quickOrient( aimVec=[0,1,0] , upVec=[-1,0,0] ) :
	
	sels = mc.ls( sl=True )
	targ = sels[0]
	src = sels[1]
	
	chldrn = mc.listRelatives( src , s=False , c=True , p=False )

	if chldrn :
		for chld in chldrn :
			mc.parent( chld , w=True )
	
	mc.select( src , r=True )
	tmpUp = mc.duplicate( src , rr=True )[0]
	tmpUpChldrn = mc.listRelatives( tmpUp , f=True )
	
	if tmpUpChldrn :
		mc.delete( tmpUpChldrn )
	
	aim = aimVec
	wu = upVec
	u = upVec
	wuo = tmpUp
	wut = 'objectrotation'
	
	aimCon = mc.aimConstraint( targ , src , aim=aim , wu=wu , wuo=wuo , wut=wut , u=u )
	mc.delete( aimCon )
	mc.delete( tmpUp )
	mc.makeIdentity( src , a=True , r=True , t=True , s=True , jo=False )
	
	if chldrn :
		for chld in chldrn :
			mc.parent( chld , src )
	
	mc.select( src , r=True )
	def	__init__	(self,	pos):
		self.cone	=	cmds.polyCone	(axis	=	(0,-1,0),
										subdivisionsX	=	16,	constructionHistory	=	False)
		cmds.xform	(self.cone,	worldSpace	=	True,	absolute	=	True,	translation	=	(0,1,0))
		cmds.xform	(self.cone,	pivots	=(0,-1,0))
		cmds.makeIdentity	(apply	=	True,	translate	=	True)
		cmds.xform	(self.cone,	worldSpace	=	True,	absolute	=	True,	translation	=	pos)
def createShape(prefix='', scale=1.0):
    List = []
    List.append(
        cmds.curve(
            n=prefix,
            p=[(11.65040520317079, 0.0, -1.0753491255960874),
               (11.260327870011457, 0.0, -1.0753491255960874),
               (10.919827839642535, 0.0, -0.8669835460599025),
               (10.731345094628578, 0.0, -0.5561779839591772),
               (8.827645335077547, 0.0, -0.7404428130644156),
               (1.7165524628499949, 0.0, -0.7404428130644156),
               (0.7006951136854465, 0.0, -0.7404428130644156),
               (0.7006951136854465, 0.0, -1.7563012592434397),
               (0.7006951136854465, 3.552713678800501e-15, -8.867401810671094),
               (0.7006951136854465, 3.552713678800501e-15, -9.883260256850125),
               (1.1144722701987622, 3.552713678800501e-15,
                -10.134188373311648),
               (1.391870513759761, 3.552713678800501e-15, -10.587497938965694),
               (1.391870513759761, 3.552713678800501e-15, -11.106800167630926),
               (1.391870513759761, 3.552713678800501e-15, -11.897477970132908),
               (0.7509301031230269, 3.552713678800501e-15,
                -12.538418380769645),
               (-0.03974769937895495, 3.552713678800501e-15,
                -12.538418380769645),
               (-0.8304255018809439, 3.552713678800501e-15,
                -12.538418380769645),
               (-1.471365912517678, 3.552713678800501e-15,
                -11.897477970132908),
               (-1.471365912517678, 3.552713678800501e-15,
                -11.106800167630926),
               (-1.471365912517678, 3.552713678800501e-15,
                -10.587547305110977),
               (-1.1939775421857295, 3.552713678800501e-15,
                -10.134237739456932),
               (-0.78023987858864, 3.552713678800501e-15, -9.883260256850125),
               (-0.78023987858864, 3.552713678800501e-15, -8.867401810671094),
               (-0.78023987858864, 0.0, -1.7563012592434397),
               (-0.78023987858864, 0.0, -0.7404428130644156),
               (-1.7960928396952713, 0.0, -0.7404428130644156),
               (-8.907154995122445, 0.0, -0.7404428130644156),
               (-11.001958686483563, 0.0, -0.4807034302220181),
               (-11.164895964918708, 0.0, -0.7493320062227404),
               (-11.459189405705198, 0.0, -0.9294219265576693),
               (-11.796332402209199, 0.0, -0.9294219265576693),
               (-12.309648927343797, 0.0, -0.9294219265576693),
               (-12.72575432876686, 0.0, -0.5133165251346163),
               (-12.72575432876686, 0.0, -1.7763568394002505e-14),
               (-12.72575432876686, 0.0, 0.5133165251345808),
               (-12.309648927343797, 0.0, 0.9294219265576551),
               (-11.796332402209199, 0.0, 0.9294219265576551),
               (-11.459221454737152, 0.0, 0.9294219265576551),
               (-11.164928013950659, 0.0, 0.7493320062227262),
               (-11.00199073551551, 0.0, 0.4807354792539478),
               (-8.907198876195322, 0.0, 0.7404921792096708),
               (-1.7960983247676712, 0.0, 0.7404921792096708),
               (-0.78023987858864, 0.0, 0.7404921792096708),
               (-0.78023987858864, 0.0, 1.7563451403163022),
               (-0.78023987858864, -3.552713678800501e-15, 8.86740729574348),
               (-0.78023987858864, -3.552713678800501e-15, 9.883260256850118),
               (-1.194026908331006, -3.552713678800501e-15,
                10.134188373311627),
               (-1.471415278662958, -3.552713678800501e-15,
                10.587497938965694),
               (-1.471415278662958, -3.552713678800501e-15,
                11.106800167630926),
               (-1.471415278662958, -3.552713678800501e-15, 11.8974779701329),
               (-0.830474868026224, -3.552713678800501e-15,
                12.538418380769645),
               (-0.03979706552423856, -3.552713678800501e-15,
                12.538418380769645),
               (0.7508807369777433, -3.552713678800501e-15,
                12.538418380769645),
               (1.3918211476144808, -3.552713678800501e-15, 11.8974779701329),
               (1.3918211476144808, -3.552713678800501e-15,
                11.106800167630926),
               (1.3918211476144808, -3.552713678800501e-15,
                10.587547305110963),
               (1.114422904053475, -3.552713678800501e-15, 10.134237739456903),
               (0.7006951136854465, -3.552713678800501e-15, 9.883260256850118),
               (0.7006951136854465, -3.552713678800501e-15, 8.86740729574348),
               (0.7006951136854465, 0.0, 1.7563451403163022),
               (0.7006951136854465, 0.0, 0.7404921792096708),
               (1.7165524628499949, 0.0, 0.7404921792096708),
               (8.827645335077547, 0.0, 0.7404921792096708),
               (10.731345094628578, 0.0, 0.556215064963471),
               (10.919864920646871, 0.0, 0.866983546059874),
               (11.260364951015786, 0.0, 1.075349125596059),
               (11.65040520317079, 0.0, 1.075349125596059),
               (12.244316817137067, 0.0, 1.075349125596059),
               (12.72575432876686, 0.0, 0.5939116139662737),
               (12.72575432876686, 0.0, -1.7763568394002505e-14),
               (12.72575432876686, 0.0, -0.593911613966295),
               (12.244316817137067, 0.0, -1.0753491255960874),
               (11.65040520317079, 0.0, -1.0753491255960874)],
            per=False,
            d=3,
            k=[
                0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6,
                7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12,
                13, 13, 13, 14, 14, 14, 15, 15, 15, 16, 16, 16, 17, 17, 17, 18,
                18, 18, 19, 19, 19, 20, 20, 20, 21, 21, 21, 22, 22, 22, 23, 23,
                23, 24, 24, 24
            ]))
    for x in range(len(List) - 1):
        cmds.makeIdentity(List[x + 1], apply=True, t=1, r=1, s=1, n=0)
        shapeNode = cmds.ListRelatives(List[x + 1], shapes=True)
        cmds.parent(shapeNode, List[0], add=True, s=True)
        cmds.delete(List[x + 1])

    #print List[0]
    sel = List[0]

    cmds.setAttr(sel + '.s', scale, scale, scale)

    cmds.makeIdentity(sel, apply=1, t=1, r=1, s=1, n=0)

    return sel
示例#32
0
def Option_doItChestLine():

	if cmds.objExists("Chest_M_all_G"):

		chestJoint = cmds.listRelatives("Chest_M_all_G",c=1,type="joint")[0]
		j = cmds.listRelatives(chestJoint,ad=1,type="joint")

		p1 = cmds.xform(chestJoint,q=1,ws=1,t=1)
		p2 = cmds.xform(j[1],q=1,ws=1,t=1)
		p3 = cmds.xform(j[0],q=1,ws=1,t=1)

		cmds.delete("Chest_M_all_G")

		j1 = cmds.joint(n="Left_bosomA_joint1",p=p1)
		j2 = cmds.joint(n="Left_bosomA_joint2",p=p2)
		cmds.joint(j1,e=1,zso=1,oj="xyz",sao="yup")
		j3 = cmds.joint(n="Left_bosomA_joint3",p=p3)
		cmds.joint(j2,e=1,zso=1,oj="xyz",sao="yup")
		j4 = cmds.joint(n="Left_bosomA_joint4",p=p3)
		cmds.joint(j3,e=1,zso=1,oj="xyz",sao="yup")
		cmds.select(cl=1)
		cmds.setAttr(j3+".drawStyle",2)

		cmds.setAttr(j4+".ry",-90)
		cmds.makeIdentity(j4,apply=1,r=1,n=0,pn=1)

		n = [(x-y)/3.0 for x,y in zip(p2,p3)]
		p4 = [x-y for x,y in zip(p2,n)]
		p5 = [x-y for x,y in zip(p4,n)]

		j1_B = cmds.joint(n="Left_bosomB_joint1",p=p1)
		j2_B = cmds.joint(n="Left_bosomB_joint2",p=p4)
		cmds.joint(j1_B,e=1,zso=1,oj="xyz",sao="yup")

		cmds.select(cl=1)

		j1_C = cmds.joint(n="Left_bosomC_joint1",p=p1)
		j2_C = cmds.joint(n="Left_bosomC_joint2",p=p5)
		cmds.joint(j1_C,e=1,zso=1,oj="xyz",sao="yup")

		cmds.select(cl=1)

		[cmds.mirrorJoint(x,mirrorYZ=1,mirrorBehavior=1,searchReplace=("Left","Right")) for x in [j1,j1_B,j1_C] ]

		ikH1 = cmds.ikHandle(sj=j2,ee=j3,n="Left_bosomA_ikHandle1")[0]
		ikH2 = cmds.ikHandle(sj=j1_B,ee=j2_B,n="Left_bosomB_ikHandle1")[0]
		ikH3 = cmds.ikHandle(sj=j1_C,ee=j2_C,n="Left_bosomC_ikHandle1")[0]

		ctrl = option_createCircle("Left_bosomA")
		cmds.delete(cmds.parentConstraint(j4,ctrl[1]))

		[ cmds.parentConstraint(j2,x,mo=1) for x in [ikH2,ikH3] ]
		[ cmds.parentConstraint(ctrl[0],x,mo=1) for x in [ikH1,j4]]

		up = cmds.group(n="Left_bosom_Aim_up",em=1)
		up_g = cmds.group(n="Left_bosom_Aim_up_g",em=1)
		cmds.parent(up,up_g)
		cmds.delete( cmds.parentConstraint(j1,up_g,weight=1))
		cmds.setAttr(up+".ty",0.05)
		cmds.parent(up,w=1)
		cmds.delete(up_g)

		j1_r = j1.replace("Left","Right")
		j2_r = j2.replace("Left","Right")
		j3_r = j3.replace("Left","Right")
		j4_r = j4.replace("Left","Right")
		cmds.setAttr(j3_r+".drawStyle",2)

		j1_B_r = j1_B.replace("Left","Right")
		j2_B_r = j2_B.replace("Left","Right")
		j1_C_r = j1_C.replace("Left","Right")
		j2_C_r = j2_C.replace("Left","Right")

		ikH1_r = cmds.ikHandle(sj=j2_r,ee=j3_r,n="Right_bosomA_ikHandle1")[0]
		ikH2_r = cmds.ikHandle(sj=j1_B_r,ee=j2_B_r,n="Right_bosomB_ikHandle1")[0]
		ikH3_r = cmds.ikHandle(sj=j1_C_r,ee=j2_C_r,n="Right_bosomC_ikHandle1")[0]

		ctrl_r = option_createCircle("Right_bosomA")
		cmds.delete(cmds.parentConstraint(j4_r,ctrl_r[1]))

		[ cmds.parentConstraint(j2_r,x,mo=1) for x in [ikH2_r,ikH3_r] ]
		[ cmds.parentConstraint(ctrl_r[0],x,mo=1) for x in [ikH1_r,j4_r]]

		up_r = cmds.group(n="Right_bosom_Aim_up",em=1)
		up_g_r = cmds.group(n="Right_bosom_Aim_up_g")
		cmds.select(cl=1)
		cmds.delete( cmds.parentConstraint(j1_r,up_g_r,weight=1))
		cmds.setAttr(up_r+".ty",-0.05)
		cmds.parent(up_r,w=1)
		cmds.delete(up_g_r)

		if cmds.objExists("Shoulder_L_optionAim"):
			cmds.aimConstraint("Shoulder_L_optionAim",j1,mo=1,weight=1,aimVector=(1,0,0) ,upVector=(0,1,0),worldUpType="object",worldUpObject=up)
		if cmds.objExists("Shoulder_R_optionAim"):
			cmds.aimConstraint("Shoulder_R_optionAim",j1_r,mo=1,weight=1,aimVector=(1,0,0) ,upVector=(0,1,0),worldUpType="object",worldUpObject=up_r)


		if not cmds.objExists("Left_bosom_G"):
			cmds.group(n="Left_bosom_G",em=1)

		cmds.parent([j1,j1_B,j1_C,ctrl[1],ikH1,ikH2,ikH3,up],"Left_bosom_G")

		if not cmds.objExists("Right_bosom_G"):
			cmds.group(n="Right_bosom_G",em=1)

		cmds.parent([j1_r,j1_B_r,j1_C_r,ctrl_r[1],ikH1_r,ikH2_r,ikH3_r,up_r],"Right_bosom_G")
		cmds.select(cl=1)

		[cmds.setAttr(x+".v",0) for x in [ikH1_r,ikH2_r,ikH3_r,up_r,ikH1,ikH2,ikH3,up] ]

		if cmds.objExists("optionYiIK_G"):
			cmds.parent(("Left_bosom_G","Right_bosom_G"),"optionYiIK_G")

		[cmds.setAttr(x+".radi",getNum.num) for x in [j1,j2,j3,j4,j1_B,j2_B,j1_C,j2_C] ]

		[cmds.parentConstraint("Chest_M",x,mo=1,weight=1) for x in ["Left_bosom_G","Right_bosom_G"] if cmds.objExists(x) and cmds.objExists("Chest_M")]
示例#33
0
def freezeOnlyScale():
    cmds.makeIdentity(apply=True, t=False, r=False, s=True, n=False)
示例#34
0
def freezeAll():
    cmds.makeIdentity(apply=True, t=True, r=True, s=True, n=False)
示例#35
0
def freezeOnlyRotation():
    cmds.makeIdentity(apply=True, t=False, r=True, s=False, n=False)
示例#36
0
def freezeOnlyTranslation():
    cmds.makeIdentity(apply=True, t=True, r=False, s=False, n=False)
示例#37
0
def createShape(prefix=''):
    """
    Create a vertical slider control with proper name
    :param prefix: str, prefixName of the control
    :return: list(str), [sliderPath, mainCtrlBox]
    """
    # create slider
    ctrl = cmds.circle(radius=0.15, nr=(0, 1, 0), n=prefix + '_Ctrl')[0]

    cmds.transformLimits(ctrl, tx=(-1, 1), ty=(0, 0), tz=(-1, 1), etx=(1, 1), ety=(1, 1), etz=(1, 1))

    ctrlBox = cmds.curve(d=1, p=[(-1, 0, 1),
                                 (1, 0, 1),
                                 (1, 0, -1),
                                 (-1, 0, -1),
                                 (-1, 0, 1)], k=[0, 1, 2, 3, 4], n=prefix + '_Path')
    parentCrvShape = cmds.listRelatives(ctrlBox, s=1)
    cmds.setAttr(parentCrvShape[0] + '.template', 1)
    cmds.parent(ctrl, ctrlBox)

    cmds.select(cl=1)

    # create text
    textCrv = cmds.textCurves(n=prefix + '_text', font='Times-Roman', t=name.removeSuffix(prefix))[0]

    cmds.setAttr(textCrv + '.overrideEnabled', 1)
    cmds.setAttr(textCrv + '.overrideDisplayType', 2)

    cmds.setAttr(textCrv + '.s', 0.5, 0.5, 0.5)

    cmds.setAttr(textCrv + '.rx', 90)
    cmds.makeIdentity(textCrv, apply=1, t=0, r=1, s=1)

    textHeight = cmds.getAttr(textCrv + '.boundingBoxMaxZ')
    textWidth = cmds.getAttr(textCrv + '.boundingBoxMaxX')

    cmds.setAttr(textCrv + '.tx', (0 - (textWidth/2)))
    cmds.setAttr(textCrv + '.tz', 1.5)

    betterWidth = 1.15
    if textWidth/2 >= 1.15:
        betterWidth = textWidth/2

    # create Main CtrlBox
    mainCtrlBox = cmds.curve(d=1, p=[((0 - (betterWidth + 0.2)), 0, (1.85 + textHeight)),
                                     ((betterWidth + 0.2), 0, (1.85 + textHeight)),
                                     ((betterWidth + 0.2), 0, -1.35),
                                     ((0 - (betterWidth + 0.2)), 0, -1.35),
                                     ((0 - (betterWidth + 0.2)), 0, (1.85 + textHeight))],
                             k=[0, 1, 2, 3, 4], n=prefix + '_ctrlBox')

    parentCrvShape1 = cmds.listRelatives(mainCtrlBox, s=1)
    cmds.setAttr(parentCrvShape1[0] + '.template', 1)

    # clean hierarchy
    cmds.parent(ctrlBox, mainCtrlBox)
    cmds.parent(textCrv, mainCtrlBox)

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

    cmds.select(cl=1)

    return [ctrlBox, mainCtrlBox]
示例#38
0
def create():
    # select all geometry that you would like to bank
    selected = mc.ls(sl=True)

    # warning for selecting nothing
    if len(selected) < 1:
        mc.warning(
            "You have nothing selected, must select at least one object")
        return

    # this lets you perform the operation on more than one object! yay for loops!
    for selection in selected:

        # Gets all the verts from selected object and adds the to a list called "verts"
        xOrig = mc.xform(selection + '.vtx[*]', q=True, ws=True, t=True)
        verts = zip(xOrig[0::3], xOrig[1::3], xOrig[2::3])

        # variable lists for x, y, z coordinates of verts
        vx = []
        vy = []
        vz = []

        # gets all the y values from the verts and adds them to the list "vy"
        for vert in verts:
            vy.append(vert[1])

        # gets the lowest vert of the object, gets the highest, gets the length of the object, and makes the threshold. The treshold is the height of the sole of the footing
        minVY = min(vy)
        maxVY = max(vy)
        length = maxVY - minVY
        threshold = ((length / 35) + minVY)

        # if the vert is inside the threshold, add its x to vx, and it z to vz.
        for vert in verts:
            if vert[1] <= threshold:
                vx.append(vert[0])
                vz.append(vert[2])

        # variables for the vert at the right of the foot, the left, the front, and the back
        minVX = min(vx)
        maxVX = max(vx)
        minVZ = min(vz)
        maxVZ = max(vz)

        # naming variables to make code more readable
        bankingName = selection + "_banking_grp"
        control_name = selection + "_cntrl"
        geometry_grp_name = selection + "_geo_grp"

        # there is that fat curve. Add attributes to it called "bankSideways", and "bankForwards". move the curve to the base of the selected object
        quad_arrow = createQuadArrow()
        mc.rename(quad_arrow, control_name)
        mc.addAttr(ln="bankSideways",
                   at="double",
                   dv=0,
                   w=True,
                   r=True,
                   k=True)
        mc.addAttr(ln="bankForwards",
                   at="double",
                   dv=0,
                   w=True,
                   r=True,
                   k=True)
        mc.setAttr(control_name + ".tx", ((maxVX + minVX) / 2))
        mc.setAttr(control_name + ".ty", minVY)
        mc.setAttr(control_name + ".tz", ((maxVZ + minVZ) / 2))

        # creating banking grp null
        mc.createNode('transform', n=bankingName)

        # create bank left null and place at the left of the footing
        mc.createNode('transform', n="bankLeft")
        mc.move(maxVX, minVY, ((maxVZ + minVZ) / 2), "|bankLeft")

        # create bank right null and place at the right of the footing
        mc.createNode('transform', n="bankRight")
        mc.move(minVX, minVY, ((maxVZ + minVZ) / 2), "|bankRight")

        # create bank bankward null and place at the back of the footing
        mc.createNode('transform', n="bankBackward")
        mc.move(((maxVX + minVX) / 2), minVY, minVZ, "|bankBackward")

        # create bank forward null and place at the front of the footing
        mc.createNode('transform', n="bankForward")
        mc.move(((maxVX + minVX) / 2), minVY, maxVZ, "|bankForward")

        # create a condition node that makes cntrl.bankSideways rotate bank left only if it is greater than 0
        mc.createNode('condition', n=selection + "_bankLeft_condition")
        mc.setAttr(selection + "_bankLeft_condition.operation", 3)
        mc.setAttr(selection + "_bankLeft_condition.colorIfFalseR", 0)
        mc.connectAttr(control_name + ".bankSideways",
                       selection + "_bankLeft_condition.colorIfTrueR")
        mc.connectAttr(control_name + ".bankSideways",
                       selection + "_bankLeft_condition.secondTerm")
        mc.connectAttr(selection + "_bankLeft_condition.outColorR",
                       "|bankLeft.rz")

        # create a condition node that makes cntrl.bankForwards rotate bank backward only if it is greater than 0
        mc.createNode('condition', n=selection + "_bankBackward_condition")
        mc.setAttr(selection + "_bankBackward_condition.operation", 3)
        mc.setAttr(selection + "_bankBackward_condition.colorIfFalseR", 0)
        mc.connectAttr(control_name + ".bankForwards",
                       selection + "_bankBackward_condition.colorIfTrueR")
        mc.connectAttr(control_name + ".bankForwards",
                       selection + "_bankBackward_condition.secondTerm")
        mc.connectAttr(selection + "_bankBackward_condition.outColorR",
                       "|bankBackward.rx")

        # create a condition node that makes cntrl.bankSideways rotate bank right only if it is less than 0
        mc.createNode('condition', n=selection + "_bankRight_condition")
        mc.setAttr(selection + "_bankRight_condition.operation", 4)
        mc.setAttr(selection + "_bankRight_condition.colorIfFalseR", 0)
        mc.connectAttr(control_name + ".bankSideways",
                       selection + "_bankRight_condition.colorIfTrueR")
        mc.connectAttr(control_name + ".bankSideways",
                       selection + "_bankRight_condition.secondTerm")
        mc.connectAttr(selection + "_bankRight_condition.outColorR",
                       "|bankRight.rz")

        # create a condition node that makes cntrl.bankForwards rotate bank forward only if it is less than 0
        mc.createNode('condition', n=selection + "_bankForward_condition")
        mc.setAttr(selection + "_bankForward_condition.operation", 4)
        mc.setAttr(selection + "_bankForward_condition.colorIfFalseR", 0)
        mc.connectAttr(control_name + ".bankForwards",
                       selection + "_bankForward_condition.colorIfTrueR")
        mc.connectAttr(control_name + ".bankForwards",
                       selection + "_bankForward_condition.secondTerm")
        mc.connectAttr(selection + "_bankForward_condition.outColorR",
                       "|bankForward.rx")

        # parent the cntrl under bankLeft, freezetransforms, delete history.
        # parent bankleft under bankright, bankright under bankbackward, bankbackwards under bankforwards, bankforwards under bank_grp.
        # at last, group the geometry
        mc.parent(control_name, "|bankLeft")
        mc.makeIdentity("|bankLeft|" + control_name, apply=True)
        mc.delete("|bankLeft|" + control_name, ch=1)
        mc.parent("|bankLeft", "|bankRight")
        mc.parent("|bankRight", "|bankBackward")
        mc.parent("|bankBackward", "|bankForward")
        mc.parent("|bankForward", bankingName)
        mc.group(selection, n=geometry_grp_name)

        # make the cntrl drive geo_grp by using a parent constraint
        mc.parentConstraint(bankingName +
                            "|bankForward|bankBackward|bankRight|bankLeft|" +
                            control_name,
                            geometry_grp_name,
                            mo=True)
        mc.select(control_name)
示例#39
0
	def setupControl(self,*args):
		#Load variables
		name = cmds.textFieldGrp(self.nameField,q=True,text=True)
		control = cmds.textFieldButtonGrp(self.controlField,q=True,text=True)
		rivet = cmds.textFieldButtonGrp(self.rivetField,q=True,text=True)
		constObj = cmds.textFieldButtonGrp(self.jointField,q=True,text=True)


		#Load selection
		verts = cmds.ls(sl=True,fl=True)

		#Create Cluster
		clusterName,clusterHandle = cmds.cluster(rel=True,n=name+'_clstr')

		#Delete Rivet's aim constraint because it causes flipping if the rivets lofted nurbs plane flips.
		#Add parent constraint to object.(constObj)
		"""
		try:
			temp = cmds.listConnections(rivet)
			cmds.delete(temp[1])
		except:
			# No constraint to delete on rivet
			pass
		"""
		#Rivet WS location
		rivetLocation = cmds.xform(rivet,q=True,ws=True,t=True)

		#Snap Cluster pivots to rivetLocation
		self.move(clusterHandle, rivetLocation,t=False,sp=True,rp=True)

		#Snap Controls pivots to rivetLocation
		self.move(control, rivetLocation,t=False,sp=True,rp=True)

		#Group Cluster
		clusterGrp = cmds.group(clusterHandle)
		clusterGrp = cmds.rename(clusterGrp, name + 'Cluster_' + clusterHandle)

		#Create over ride group
		or_grp = cmds.group(em=True,name=name+"OR1") 
		or2_grp = cmds.group(em=True,name=name+"OR2") 

		#Parent override group to rivet
		cmds.parent(or_grp,or2_grp)  
		cmds.parent(or2_grp,rivet)   

		#Freeze transforms on override group
		cmds.makeIdentity(or_grp,apply=True,t=True,r=True,s=True,n=True)

		#Zero Control
		zeroNode = cmds.group(em=True,n=name + "nullGrp")

		pos = cmds.xform( control, q=1, ws=True, t=1)
		cmds.xform( zeroNode, ws=True, t=[pos[0], pos[1], pos[2]]) 

		rot = cmds.xform( control, q=1, ws=True, ro=1)
		cmds.xform( zeroNode, ws=True, ro=[rot[0], rot[1], rot[2]]) 

		scale = cmds.xform( control, q=1, r=1, s=1)
		cmds.xform( zeroNode, ws=True, s=[scale[0], scale[1], scale[2]])		

		#Snap zeroNode pivot to control
		controlLocation = cmds.xform(control,q=True,ws=True,rp=True)
		self.move(zeroNode, controlLocation, t=False, sp=True, rp=True)

		#parent control to OverRide group
		cmds.parent(control, zeroNode, a=True)		
		cmds.parent(zeroNode,or_grp)

		#Connect control t,r,s to cluster, then hide the cluster and rivet group 
		cmds.connectAttr(control + ".translate", clusterHandle + ".translate")
		cmds.connectAttr(control + ".rotate", clusterHandle + ".rotate")
		cmds.connectAttr(control + ".scale", clusterHandle + ".scale")		

		#Create utility node and negate double transform
		#by reversing the transformation of or_grp <---- Cause of double transforms
		mdNode = cmds.createNode("multiplyDivide")
		nodeName = name + "_MD"
		cmds.rename(mdNode,nodeName)
		mdNode = nodeName

		#Unparent control
		cmds.parent(zeroNode,w=True)

		#Set up the MD node
		cmds.setAttr( "%s.input2X"%mdNode, -1)
		cmds.setAttr( "%s.input2Y"%mdNode, -1)
		cmds.setAttr( "%s.input2Z"%mdNode, -1)

		#Connect the nodes
		# control ---> mdNode
		cmds.connectAttr("%s.translateX"%control,"%s.input1X"%mdNode,f=True)
		cmds.connectAttr("%s.translateY"%control,"%s.input1Y"%mdNode,f=True)
		cmds.connectAttr("%s.translateZ"%control,"%s.input1Z"%mdNode,f=True)

		#mdNode ---> or_grp
		cmds.connectAttr("%s.outputX"%mdNode,"%s.translateX"%or_grp,f=True)
		cmds.connectAttr("%s.outputY"%mdNode,"%s.translateY"%or_grp,f=True)
		cmds.connectAttr("%s.outputZ"%mdNode,"%s.translateZ"%or_grp,f=True)

		#Reparent control
		cmds.parent(zeroNode,or_grp)

		#Get mesh name 
		# ex. "meshName.vtx[35]"
		mesh = verts[0].split('.')[0]

		#Get meshDeformer
		meshDeformer = None
		try:
			meshDeformer = mel.eval('findRelatedSkinCluster("%s");'%mesh)
		except:
			pass
		"""
		history = cmds.listHistory(mesh)  
		for each in history:
			#print " History: " + each
			if("skinCluster" in str(each)):
				#Possible match for meshDeformer
				if("Group" not in str(each)):
					meshDeformer = each
			if("cMuscleSystem" in str(each)):
				if("Group" not in str(each)):
					meshDeformer = each
		"""
		#Reorder deformer nodes
		if meshDeformer:
			#Move cluster + meshDeformer to top of deformer stack
			cmds.reorderDeformers(clusterHandle,meshDeformer,mesh)

			#Move meshDeformer to top of deformer stack
			cmds.reorderDeformers(meshDeformer,clusterHandle,mesh)

		#Create final group
		topGrp = cmds.group(em=True,name=name+"_followCnt_grp")
		cmds.parent(clusterGrp,rivet,topGrp)

		#Orient constrain rivet to constrain object
		if constObj:
			cmds.orientConstraint(constObj,rivet,mo=True)

		#Hide cluster grp
		cmds.setAttr(clusterGrp + ".visibility",0) 

		#Hide the rivet
		rivetShape = cmds.listRelatives(rivet,shapes=True)
		cmds.setAttr(rivetShape[0] + ".visibility",0)
		
		# Add cluster atttribute to control
		cmds.addAttr(control,ln='cluster',min=0.0,max=1.0,dv=1.0)
		cmds.setAttr('%s.cluster'%control,l=False,k=True)
		
		# Connect it to the deformer
		cmds.connectAttr('%s.cluster'%control,'%s.envelope'%clusterName,f=True)

		#Clear selection
		cmds.select(clear=True)
示例#40
0
import maya.cmds as mc

objGrps = mc.group(empty=True)
ctlGrps = mc.group(empty=True)
for obj in mc.ls(sl=True):
    objGrp = mc.group(n=obj.rpartition('_')[0] + '_GRP', empty=True)
    mc.parent(objGrp, obj)
    mc.makeIdentity(objGrp, t=True, s=True, r=True)
    mc.parent(objGrp, world=True)
    mc.parent(obj, objGrp)
    mc.parent(objGrp, objGrps)
    position = mc.xform(obj, query=True, worldSpace=True, translation=True)
    ctl = mc.sphere(n=obj.replace('_JNT', '_CTL'), radius=.1)[0]
    mc.xform(ctl, worldSpace=True, translation=position)
    mc.makeIdentity(ctl, apply=True, t=1, r=1, s=1)
    ctlGrp = mc.group(ctl, n=ctl.replace('_CTL', 'ctl_GRP'))
    mc.parent(ctlGrp, obj)
    mc.makeIdentity(ctlGrp, )
    mc.parent(ctlGrp, world=True)
    mc.parent(ctlGrp, ctlGrps)
    mc.connectAttr(ctl + '.translate', obj + '.translate')
示例#41
0
	def createCrvCtrls (self, eyePrefix, parentCtrl, ctrlJnts):
		'''Creates controller curve for each controller joint.
		
		Called by 'buildRig' function.
		Call functions: None '''
		
		# Organize rig hierarchy
		hierarchySecondGrp = cmds.group (n = (eyePrefix + "_Eyelids_CTRL_GRP"), em = 1)
		
		hierarchyMainGrp = "Eyelids_CTRL_GRP"
		
		if parentCtrl != None :
			ctrlChildren = cmds.listRelatives (parentCtrl, children = 1)
			if hierarchyMainGrp in ctrlChildren :
				cmds.parent (hierarchySecondGrp, (parentCtrl + "|" + hierarchyMainGrp))
			else :
				cmds.group (n = hierarchyMainGrp, em = 1, p = parentCtrl)
				cmds.parent (hierarchySecondGrp, (parentCtrl + "|" + hierarchyMainGrp))
		else :
			if cmds.objExists ("|" + hierarchyMainGrp) :
				cmds.parent (hierarchySecondGrp, ("|" + hierarchyMainGrp))
			else :
				cmds.group (n = hierarchyMainGrp, em = 1)
				cmds.parent (hierarchySecondGrp, ("|" + hierarchyMainGrp))
		
		# Creates the controller object
		cmds.select (cl = 1)
		TEMP_CTRL1 = cmds.circle (r = 0.15) [0]
		TEMP_CTRL2 = cmds.duplicate () [0]
		cmds.setAttr (TEMP_CTRL2 + ".rotateY", 90)
		TEMP_CTRL3 = cmds.duplicate () [0]
		cmds.setAttr (TEMP_CTRL3 + ".rotateX", 90)
		cmds.parent (TEMP_CTRL2, TEMP_CTRL3, TEMP_CTRL1)
		cmds.makeIdentity (apply = 1, t = 1, r = 1, s = 1, n = 0, pn = 1)
		cmds.pickWalk (d = "down")
		cmds.select (TEMP_CTRL1, tgl = 1)
		cmds.parent (r = 1, s = 1)
		cmds.delete (TEMP_CTRL2, TEMP_CTRL3)
		cmds.select (cl = 1)
		
		# Place the controllers and constrain the joints
		self.ctrlList = []
		ctrlOffsetGrpList = []
		
		for jnt in ctrlJnts:
			ctrlName = jnt [:-9]
			ctrlName = "CTRL_" + ctrlName
			ctrl = cmds.duplicate (TEMP_CTRL1, n = ctrlName) [0]
			self.ctrlList.append (ctrl)
			pointC_TEMP = cmds.pointConstraint (jnt, ctrl)
			cmds.delete (pointC_TEMP)
			origName = "ORIG_" + ctrlName
			origGrp = cmds.group (n = origName, em = 1)
			parentC_TEMP = cmds.parentConstraint (ctrl, origGrp)
			cmds.delete (parentC_TEMP)
			if ctrl.find ("_Secondary") != -1 : # If controller is 'secondary'
				offsetGrpName = origName.replace ("ORIG_", "OFFSET_")
				offsetGrp = cmds.duplicate (origGrp, n = offsetGrpName)
				cmds.parent (ctrl, offsetGrp)
				cmds.parent (offsetGrp, origGrp)
				ctrlOffsetGrpList.extend (offsetGrp)
			else:
				cmds.parent (ctrl, origGrp)
			cmds.parent (origGrp, hierarchySecondGrp)
			cmds.parentConstraint (ctrl, jnt)
		
		cmds.delete (TEMP_CTRL1)
		cmds.select (cl = 1)
		
		# Constraints between main controllers and secondary ones
			# self.ctrlList = same order as 'ctrlJnts' list
			# [ctrl_CornerA, ctrl_upLidSecA, ctrl_upLidMain, ctrl_upLidSecB, ctrl_CornerB, ctrl_lowLidSecB, ctrl_lowLidMain, ctrl_lowLidSecA]
			# Index: 0				1				2				3				4				5				6			7
			# ctrlOffsetGrpList = [OFFSET_Up_secondaryA, OFFSET_Up_secondaryB, OFFSET_Low_secondaryB, OFFSET_Low_secondaryA]
			# Index: 						0					1						2						3
		cmds.parentConstraint (self.ctrlList[0], ctrlOffsetGrpList[0], mo = 1)
		cmds.parentConstraint (self.ctrlList[2], ctrlOffsetGrpList[0], mo = 1)
		cmds.parentConstraint (self.ctrlList[2], ctrlOffsetGrpList[1], mo = 1)
		cmds.parentConstraint (self.ctrlList[4], ctrlOffsetGrpList[1], mo = 1)
		cmds.parentConstraint (self.ctrlList[4], ctrlOffsetGrpList[2], mo = 1)
		cmds.parentConstraint (self.ctrlList[6], ctrlOffsetGrpList[2], mo = 1)
		cmds.parentConstraint (self.ctrlList[6], ctrlOffsetGrpList[3], mo = 1)
		cmds.parentConstraint (self.ctrlList[0], ctrlOffsetGrpList[3], mo = 1)
		
		# Secondary controllers visibility (drove by main controllers)
		cmds.select (cl = 1)
		cmds.select (self.ctrlList[2], self.ctrlList[6])
		cmds.addAttr (ln = "SecondaryControls", at = "bool", k = 0)
		cmds.setAttr ((self.ctrlList[2] + ".SecondaryControls"), 1, channelBox = 1)
		cmds.setAttr ((self.ctrlList[6] + ".SecondaryControls"), 1, channelBox = 1)
		# Upper lid
		cmds.connectAttr ((self.ctrlList[2] + ".SecondaryControls"), (self.ctrlList[1] + ".visibility"), f = 1)
		cmds.connectAttr ((self.ctrlList[2] + ".SecondaryControls"), (self.ctrlList[3] + ".visibility"), f = 1)
		# Lower lid
		cmds.connectAttr ((self.ctrlList[6] + ".SecondaryControls"), (self.ctrlList[5] + ".visibility"), f = 1)
		cmds.connectAttr ((self.ctrlList[6] + ".SecondaryControls"), (self.ctrlList[7] + ".visibility"), f = 1)
		
		# Lock and hide unused channels
		for ctrl in self.ctrlList :
			cmds.setAttr ((ctrl + ".sx"), lock = 1, keyable = 0, channelBox = 0)
			cmds.setAttr ((ctrl + ".sy"), lock = 1, keyable = 0, channelBox = 0)
			cmds.setAttr ((ctrl + ".sz"), lock = 1, keyable = 0, channelBox = 0)
			cmds.setAttr ((ctrl + ".v"), lock = 1, keyable = 0, channelBox = 0)
示例#42
0
import maya.cmds as cmd
''' costruzione del palazzo '''
building = cmd.polyCube(sx=1, sy=1, sz=1, w=10, h=25, d=10, n='testBuilding')
''' costruzione del blocco di strada intorno al palazzo '''
buildingBlock = cmd.polyPlane(sx=1, sy=1, w=15, h=15, n='testBuildingBlock')

for o in [building, buildingBlock]:
    bbox = cmd.exactWorldBoundingBox(o)  # Preleva il bounding box dell'oggetto
    height = abs(bbox[1]) + abs(bbox[4])
    cmd.xform(o, piv=[0, bbox[1], 0],
              ws=True)  # Sposta il pivot dell'oggetto alla sua base
    cmd.move(0, bbox[4], 0,
             o)  # sposta l'oggetto verso l'alto affinché il pivot sia a zero
    cmd.makeIdentity(o, apply=True, t=True, r=True,
                     s=True)  # effettua il freeze transform
    cmd.delete(o, constructionHistory=True
               )  # cancella la construction history dell'oggetto

cmd.select(clear=True)  # pulisce la selezione in viewport
示例#43
0
def duplycateSymmetry(object):
    meshNode = cmds.listRelatives(object,
                                  s=True,
                                  pa=True,
                                  type='mesh',
                                  fullPath=True)
    if meshNode is not None:
        #エラー吐くことがあるのでノンデフォーマヒストリを削除
        cmds.bakePartialHistory(object, ppt=True)
    #ネームスペースから分割
    nemeSplit = object.split('|')
    newName = nemeSplit[-1]
    #左右リネーム関数呼び出し
    newName = renameLR(newName)
    #複製して反転
    duplicated = pm.duplicate(object, name=newName)
    try:
        parentNode = duplicated[0].firstParent(
        )  #Pymelの機能で親の階層を取得しておく。listRelativesと同じような。
        parentNode = str(parentNode)  #cmdsで使えるように文字列に変換
        #左右リネーム関数呼び出し
        newParent = renameLR(parentNode)
    except:
        parentNode = None
        newParent = None
    duplicated = str(duplicated[0])  #cmdsで使えるように文字列に変換
    #子供のオブジェクト取得関数呼び出し
    children = pm.listRelatives(duplicated, ad=True, type='transform', f=True)
    #子供のオブジェクトがある場合は重複を避けるため削除
    if len(children) != 0:
        cmds.delete(children)
    #アトリビュートのロック解除
    #全部のロック解除しないと親が変わったときのロカール値が変わらず、ズレることがある。
    attr = ['.translate', '.rotate', '.scale']
    axis = ['X', 'Y', 'Z']
    for varA in range(0, 3):
        for varB in range(0, 3):
            cmds.setAttr(duplicated + attr[varA] + axis[varB], lock=False)
    #ワールドスケール用ダミーロケータ作成
    dummy = common.TemporaryReparent().main(mode='create')
    cmds.parent(duplicated, dummy)
    #X方向に-1スケーリングしてからスケールフリーズ
    cmds.scale(-1, 1, 1, dummy, relative=True, pivot=(0, 0, 0))
    #杏仁生成を防ぐためにダミーロケータのスケールをフリーズ、負の値が親に入ってると杏仁が生成されるような。
    if cmds.nodeType(duplicated) == 'joint':
        #ジョイントを正しい回転、位置に修正するため、スケールフリーズ前のグローバル値を取得しておく
        pos = cmds.xform(duplicated, q=True, t=True, ws=True)
        rot = cmds.xform(duplicated, q=True, ro=True, ws=True)
        cmds.makeIdentity(dummy,
                          apply=True,
                          translate=False,
                          rotate=False,
                          scale=True,
                          preserveNormals=True)
    #元の親名と違い、かつ新しい親名のオブジェクトが存在する場合は付け替え
    if parentNode is None:
        cmds.parent(duplicated, w=True)
    else:
        if parentNode != newParent and cmds.ls(newParent):
            cmds.parent(duplicated, newParent)
        else:
            cmds.parent(duplicated, parentNode)
    #ダミーペアレントを削除
    common.TemporaryReparent().main(dummyParent=dummy, mode='delete')
    cmds.makeIdentity(duplicated,
                      apply=True,
                      translate=False,
                      rotate=False,
                      scale=True,
                      preserveNormals=True)
    if cmds.nodeType(duplicated) == 'joint':
        cmds.xform(duplicated, t=pos, ro=rot, ws=True)
    return duplicated
示例#44
0
		# Create controller
		try:
			self.createController(cnt)
		except Exception,e:
			print 'Error: ',e
			raise Exception('Failed to create controller: %s'%cnt)

		# Load part 2 GUI fields with created objects
		cmds.textFieldButtonGrp(self.controlField,e=True,text=cnt)
		cmds.textFieldButtonGrp(self.rivetField,e=True,text=rivet)

		# Snap controller to rivet and zero/orient to world
		temp = cmds.pointConstraint(rivet,cnt,mo=False)
		cmds.delete(temp)
		cmds.makeIdentity(cnt,apply=True,t=True,r=True,s=True,n=True)

		# Hide rivet shape visibility
		cmds.setAttr('%sShape.visibility'%rivet,0)

	def setupControl(self,*args):
		#Load variables
		name = cmds.textFieldGrp(self.nameField,q=True,text=True)
		control = cmds.textFieldButtonGrp(self.controlField,q=True,text=True)
		rivet = cmds.textFieldButtonGrp(self.rivetField,q=True,text=True)
		constObj = cmds.textFieldButtonGrp(self.jointField,q=True,text=True)


		#Load selection
		verts = cmds.ls(sl=True,fl=True)
示例#45
0
    def freezeRot(self):
        sel = cmds.ls(sl=1)

        if sel:
            cmds.makeIdentity(sel[:], apply=1, t=0, r=1, s=0)
示例#46
0
    def attachToMeshFol(cls, srcObj, trgMeshShp, oriOpt, revGrpOpt, mPosOffOpt,
                        mOriOffOpt):
        # Mesh uv is must exists.
        # Follicle ignore target mesh's transform value. So, Duplicate target mesh and freeze transform temporarily to get accurate u and v parameter.
        cmds.select(cls.trgObj, r=True)
        tak_cleanUpModel.cleanChBox()

        tmpMesh = cmds.duplicate(trgMeshShp)
        try:
            cmds.parent(tmpMesh, world=True)
        except:
            pass
        cmds.makeIdentity(tmpMesh, apply=True)
        tmpMeshShp = cmds.listRelatives(tmpMesh, s=True)[0]

        tmpSrcObj = cmds.duplicate(srcObj)[0]
        if not cmds.listRelatives(tmpSrcObj, p=True) is None:
            cmds.parent(tmpSrcObj, world=True)

        clPtOnMeshNode = cmds.createNode('closestPointOnMesh',
                                         n=srcObj + '_clPtOnMesh')
        cmds.connectAttr('%s.outMesh' % (tmpMeshShp),
                         '%s.inMesh' % (clPtOnMeshNode),
                         force=True)
        cmds.connectAttr('%s.translate' % (tmpSrcObj),
                         '%s.inPosition' % (clPtOnMeshNode),
                         force=True)

        parmUVal = cmds.getAttr('%s.parameterU' % (clPtOnMeshNode))
        parmVVal = cmds.getAttr('%s.parameterV' % (clPtOnMeshNode))
        cmds.delete(clPtOnMeshNode, tmpMesh, tmpSrcObj)

        # Create follicle and connect nodes.
        fol = cmds.createNode('follicle')
        folPrnt = cmds.listRelatives(fol, parent=True)[0]
        folPrnt = cmds.rename(folPrnt, srcObj + '_fol')
        fol = cmds.listRelatives(folPrnt, s=True)[0]

        cmds.connectAttr('{0}.worldMesh'.format(trgMeshShp),
                         '{0}.inputMesh'.format(fol))
        cmds.connectAttr('{0}.worldMatrix'.format(trgMeshShp),
                         '{0}.inputWorldMatrix'.format(fol))
        cmds.connectAttr('{0}.outTranslate'.format(fol),
                         '{0}.translate'.format(folPrnt))
        cmds.setAttr('{0}.parameterU'.format(fol), parmUVal)
        cmds.setAttr('{0}.parameterV'.format(fol), parmVVal)
        cmds.setAttr('%s.visibility' % (fol), False)

        anchorGrp = cmds.createNode('transform', n=srcObj + '_anchor')

        cmds.connectAttr('{0}.translate'.format(folPrnt),
                         '{0}.translate'.format(anchorGrp))

        if oriOpt:
            cmds.connectAttr('{0}.outRotate'.format(fol),
                             '{0}.rotate'.format(folPrnt))
            cmds.connectAttr('{0}.rotate'.format(folPrnt),
                             '{0}.rotate'.format(anchorGrp))

        # Get srcObj parent before parent to anchorGrp.
        srcPrnt = cmds.listRelatives(srcObj, p=True)

        # Parent srcObj to anchorGrp.
        cmds.parent(srcObj, anchorGrp)

        # If srcPrnt exists, reparent anchorGrp to srcObj's old parent.
        if srcPrnt:
            cmds.parent(anchorGrp, srcPrnt[0])

        if not mPosOffOpt:
            cls.setZeroAttr(srcObj, 'pos')

        if not mOriOffOpt:
            cls.setZeroAttr(srcObj, 'ori')
            if cmds.objectType(srcObj) == "joint":
                cls.setZeroJntOri(srcObj)

        if revGrpOpt:
            cls.reverseGrp(srcObj)

        return folPrnt
示例#47
0
    def createFKControls(self, joints):
        """ You can define empty lists to store any items that may be created as you run through your for loops """
        """ Any variables defined inside a for loop are throw away because they get overwritten when the loop runs again"""
        """ A list outside of the for loop used to store the fk control names.  [] indicates an empty list. """
        fkControls = []
        """ Create another list to store the control groups """
        fkADJGroups = []
        """ Iterate through the joints and create a control for each """
        for joint in joints:
            """ Define a name for our control by using the replace command """
            fk_joint = ("FK_" + joint)
            fkJnt = ("FK" + joint)
            controlName = ("CTL_" + fkJnt)
            FKCTL = cmds.circle(name=controlName)
            cmds.setAttr(FKCTL[0] + ".overrideEnabled", 1)
            cmds.setAttr(FKCTL[0] + ".overrideColor", 13)
            """ Here is where we append the new fk control to the fkControl list """
            fkControls.append(FKCTL)
            print joint
            """ PointConstrain the control to the joint.  We do this so the control is moved to the position of the joint """

            tempConstraint = cmds.pointConstraint(fk_joint, FKCTL)
            cmds.rotate(0, 90, 0)
            """ We no longer need the pointConstraint so we delete it """
            cmds.delete(tempConstraint)
            cmds.makeIdentity(FKCTL[0], apply=True)
            cmds.delete(constructionHistory=True)
            """ Now we group the control so we can zero out the controls attributes """
            """ This keeps the control at it's current position while creating clean channels for animation """
            """ Lets make a name for this group """
            ADJGrpName = ('ADJ_' + 'CTL_' + fkJnt)
            ADJGroup = cmds.group(em=True, name=ADJGrpName)

            tempConstraint = cmds.parentConstraint(fk_joint, ADJGroup)
            cmds.delete(tempConstraint)
            """ Parent the control to the control group """
            cmds.parent(FKCTL[0], ADJGroup)
            """ Append the control group to the fkADJGroup list """
            fkADJGroups.append(ADJGroup)
            """ orientConstrain the joint to the control """
            cmds.orientConstraint(FKCTL[0],
                                  fk_joint,
                                  maintainOffset=True,
                                  weight=1)
            cmds.makeIdentity(FKCTL[0], apply=True)
            cmds.delete(constructionHistory=True)
            lockAttr = [
                '.translateX', '.translateY', '.translateZ', '.scaleX',
                '.scaleY', '.scaleZ', '.visibility'
            ]
            for items in lockAttr:
                lock = cmds.setAttr(FKCTL[0] + items,
                                    lock=True,
                                    keyable=False,
                                    channelBox=False)
        """ Now you can do a new for loop for the parenting and orientation """
        """ joints lives outside the for loop so you can still use it here """
        """ Now we need to set up a hierarchy that will give us the functionality of an fk arm """
        """ We can do this by parenting each control group to the joint that is one up in the chain.
        Or we can create a hierarchy of control objects.  See the image in the post for details """

        for index in range(len(fkControls)):
            if index != 0:
                cmds.parent(fkADJGroups[index], fkControls[index - 1][0])
        for index in range(len(fkControls)):
            print fkControls[index][0]
            cmds.setAttr(fkControls[index][0] + ".rotateOrder", 2)

        print fkADJGroups
        for index in range(len(fkADJGroups)):
            print fkADJGroups[index]
            cmds.setAttr(fkADJGroups[index] + ".rotateOrder", 2)

        print fkADJGroups[index]
        groupFK = cmds.group(fkADJGroups[0], name='CTL_FKArm_GRP')
        cmds.setAttr(groupFK + ".rotateOrder", 2)
示例#48
0
 def freezeScale(self):
     sel = cmds.ls(sl=1)
     if sel:
         cmds.makeIdentity(sel[:], apply=1, t=0, r=0, s=1)
import maya.cmds as cmds

sels = cmds.ls(sl=True)

for i in sels:

    cmds.makeIdentity(i, a=True, t=True, r=True, s=True, n=False)
示例#50
0
    def freezeTransform(self):
        sel = cmds.ls(sl=1)

        if sel:
            cmds.makeIdentity(sel[:], apply=1, t=1, r=1, s=1)
示例#51
0
    def sqCreateStickyLipsCtrlAttr(self, *args):
        if not cmds.objExists(self.optionCtrl):
            cmds.circle(name=self.optionCtrl, constructionHistory=False)
        cmds.addAttr(self.optionCtrl,
                     longName='stickyLips',
                     attributeType='bool')
        cmds.setAttr(self.optionCtrl + '.stickyLips', edit=True, keyable=True)

        for i in range(0, self.maxIter):
            cmds.addAttr(self.optionCtrl,
                         longName="stickyLipsWireLocator" + str(i),
                         attributeType='float',
                         keyable=False)

        for i in range(0, self.maxIter):
            for wireNode in self.wireNodeList:
                cmds.connectAttr(
                    self.optionCtrl + ".stickyLipsWireLocator" + str(i),
                    wireNode + ".wireLocatorEnvelope[" + str(i) + "]")

        slTextCurve = cmds.textCurves(ch=False,
                                      font="Arial|w400|h-08",
                                      text="StickyLips",
                                      name="StickyLips_Label_Txt")[0]
        if "Shape" in slTextCurve:
            slTextCurve = cmds.rename(slTextCurve,
                                      slTextCurve[:slTextCurve.find("Shape")])
        t = 0
        slCharTransformList = cmds.listRelatives(slTextCurve,
                                                 children=True,
                                                 type="transform")
        for charTransform in slCharTransformList:
            txValue = cmds.getAttr(charTransform + ".tx")
            sLTextShapeList = cmds.listRelatives(charTransform,
                                                 allDescendents=True,
                                                 type="nurbsCurve")
            for i, textShape in enumerate(sLTextShapeList):
                textShape = cmds.rename(textShape,
                                        "StickyLips_Txt_" + str(t) + "Shape")
                cmds.parent(textShape, slTextCurve, shape=True, relative=True)
                cmds.move(txValue, 0, 0, textShape + ".cv[:]", relative=True)
                t = t + 1
            cmds.delete(charTransform)
        cmds.setAttr(slTextCurve + ".translateX", -0.1)
        cmds.setAttr(slTextCurve + ".translateY", 0.25)
        cmds.setAttr(slTextCurve + ".scaleX", 0.1)
        cmds.setAttr(slTextCurve + ".scaleY", 0.1)
        cmds.setAttr(slTextCurve + ".scaleZ", 0.1)
        cmds.setAttr(slTextCurve + ".template", 1)
        cmds.makeIdentity(slTextCurve, apply=True)

        sideNameList = ["L", "R"]
        for side in sideNameList:
            bg = cmds.circle(name=side + "_StickyLips_Bg",
                             normal=(0, 0, 1),
                             radius=1,
                             degree=1,
                             sections=4,
                             constructionHistory=False)[0]
            cmds.setAttr(bg + ".rotateZ", 45)
            cmds.setAttr(bg + ".translateX", 0.5)
            cmds.makeIdentity(bg, apply=True)
            cmds.setAttr(bg + ".scaleX", 0.85)
            cmds.setAttr(bg + ".scaleY", 0.15)
            cmds.makeIdentity(bg, apply=True)
            cmds.setAttr(bg + ".template", 1)

            self.sliderCtrl = cmds.circle(name=side + "_StickyLips_Ctrl",
                                          normal=(0, 0, 1),
                                          radius=0.1,
                                          degree=3,
                                          constructionHistory=False)[0]
            attrToHideList = [
                'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'
            ]
            for attr in attrToHideList:
                cmds.setAttr(self.sliderCtrl + "." + attr,
                             edit=True,
                             lock=True,
                             keyable=False)
            cmds.transformLimits(self.sliderCtrl,
                                 translationX=(0, 1),
                                 enableTranslationX=(1, 1))

        distPos = 1.0 / self.maxIter
        for i in range(0, self.maxIter):
            lPosA = (i * distPos)
            lPosB = (lPosA + distPos)
            rPosB = 1 - (i * distPos)
            rPosA = (rPosB - distPos)
            if i > 0:
                lPosA = lPosA - (distPos * 0.33)
                rPosA = rPosA - (distPos * 0.33)
            cmds.setDrivenKeyframe(self.optionCtrl,
                                   attribute="stickyLipsWireLocator" + str(i),
                                   currentDriver=sideNameList[0] +
                                   "_StickyLips_Ctrl.translateX",
                                   driverValue=lPosA,
                                   value=0,
                                   inTangentType="linear",
                                   outTangentType="linear")
            cmds.setDrivenKeyframe(self.optionCtrl,
                                   attribute="stickyLipsWireLocator" + str(i),
                                   currentDriver=sideNameList[0] +
                                   "_StickyLips_Ctrl.translateX",
                                   driverValue=lPosB,
                                   value=1,
                                   inTangentType="linear",
                                   outTangentType="linear")
            cmds.setDrivenKeyframe(self.optionCtrl,
                                   attribute="stickyLipsWireLocator" + str(i),
                                   currentDriver=sideNameList[1] +
                                   "_StickyLips_Ctrl.translateX",
                                   driverValue=rPosA,
                                   value=0,
                                   inTangentType="linear",
                                   outTangentType="linear")
            cmds.setDrivenKeyframe(self.optionCtrl,
                                   attribute="stickyLipsWireLocator" + str(i),
                                   currentDriver=sideNameList[1] +
                                   "_StickyLips_Ctrl.translateX",
                                   driverValue=rPosB,
                                   value=1,
                                   inTangentType="linear",
                                   outTangentType="linear")

        lSliderGrp = cmds.group(sideNameList[0] + "_StickyLips_Ctrl",
                                sideNameList[0] + "_StickyLips_Bg",
                                name=sideNameList[0] + "_StickyLips_Ctrl_Grp")
        rSliderGrp = cmds.group(sideNameList[1] + "_StickyLips_Ctrl",
                                sideNameList[1] + "_StickyLips_Bg",
                                name=sideNameList[1] + "_StickyLips_Ctrl_Grp")
        cmds.setAttr(rSliderGrp + ".rotateZ", 180)
        cmds.setAttr(rSliderGrp + ".translateY", -0.25)
        sliderGrp = cmds.group(lSliderGrp,
                               rSliderGrp,
                               slTextCurve,
                               name="StickyLips_Ctrl_Grp")
def LumberyardCreateProxies(*args):
    ##This function creates the proxy objects and parents them to joints
  
    #create display layers for proxy's visibility to easily be toggled
    LumberyardCreateProxyLayer()
    
    #variable for the display layer
    layerPhys = g_nameOfDisplayLayer
    
    #make a list of all of the selected objects
    selectedObjects = cmds.ls(selection = True)
    
    #if nothing is selected throw a warning
    if (len(selectedObjects) == 0): 
        cmds.warning('No joints selected.  Select Joints and press the Add Joints button.')
        
    else:
        for selectedObject in selectedObjects:
        
            if cmds.objectType(selectedObject, isType = 'joint' ) == True:
                
                shapeOfProxy = proxyCreationSettings.shape
                
                #get the joint node's position in world space
                jointStartPosition = cmds.xform(selectedObject, query = True, worldSpace = True, translation = True)
                proxyPosition = jointStartPosition
                proxyWidth = float(proxyCreationSettings.width)
                proxyLength = proxyWidth

                if (g_centerString in proxyCreationSettings.objectOrient) == False:
                
                    proxyPosition = CreateProxyPositionFromChildren(selectedObject)
                    
                    #find out the length of the average child joints
                    distanceBetweenPoints = math.sqrt(math.pow((jointStartPosition[0] - proxyPosition[0]), 2) + math.pow((jointStartPosition[1] - proxyPosition[1]) ,2) + math.pow((jointStartPosition[2] - proxyPosition[2]), 2))
                    proxyLength = distanceBetweenPoints * 2

                #create the proxy shape
                if (shapeOfProxy == g_shapeTypes[g_boxIndex]):
                    proxyShape = cmds.polyCube(height = proxyLength, width = proxyWidth, depth = proxyWidth, createUVs = 1,constructionHistory = True)  
                else:
                    proxyRadius = proxyWidth/2
                    if (shapeOfProxy == g_shapeTypes[g_capsuleIndex]):
                        if (proxyLength > proxyWidth):
                            proxyShape = cmds.polyCylinder(radius = proxyRadius, height = proxyLength - (proxyRadius *2), roundCap = True, subdivisionsCaps = 3)
                        else:
                            proxyShape = cmds.polySphere(radius = proxyRadius * 2, subdivisionsAxis = 16, subdivisionsHeight = 16)
                    else: 
                        proxyShape = cmds.polySphere(radius = proxyRadius * 2, subdivisionsAxis = 16, subdivisionsHeight = 16)
            
                #add object to the phys display layer 
                cmds.editDisplayLayerMembers( layerPhys, proxyShape[0])
                
                #add an attribute to easily find our created proxy
                cmds.addAttr(proxyShape, longName = 'lumberyardPhysProxy', defaultValue = 1)
            
                #add material to proxy
                if (proxyCreationSettings.proxyMaterialName != 'no material'):
                
                    LumberyardAddMaterialToProxy(proxyShape)
            
                #add orientation to proxy
                LumberyardOrientProxy(proxyShape[0])
                 
                #move proxy into place
                cmds.move(proxyPosition[0], proxyPosition[1], proxyPosition[2], proxyShape, worldSpace = True)
                
                #orient the proxy so its aiming toward the parent joint. can we do this with vector math instead?
                aimConsProxy = cmds.aimConstraint(selectedObject, proxyShape)
                cmds.delete(aimConsProxy)
                orientConsProxy = cmds.orientConstraint(selectedObject, proxyShape, skip = 'none')
                cmds.delete(orientConsProxy)
            
                #if the orient pulldown defines this as a center, center its orient on the joint.
                if (g_centerString in proxyCreationSettings.objectOrient): 
                    cmds.move(jointStartPosition[0], jointStartPosition[1],jointStartPosition[2], proxyShape[0], worldSpace = True)
                else:
                    cmds.move(jointStartPosition[0], jointStartPosition[1], jointStartPosition[2], proxyShape[0] + ".scalePivot", proxyShape[0] + ".rotatePivot", worldSpace = True)
                    
                #parent it to the joint
                cmds.parent(proxyShape[0], selectedObject)
                
                #freeze the proxy.  this will zero out its translate values relative to its parent joint
                cmds.makeIdentity(proxyShape[0], apply = True, scale = 1, rotate = 1, translate = 1, normal = 0)
                
                #delete construction history
                cmds.delete(proxyShape[0],constructionHistory=True)
                
                #rename the proxy with the proper name
                cmds.rename(proxyShape[0], selectedObject + g_physPostfix)
            else:
                cmds.warning(selectedObject + " is not a joint.  No proxy created.")
示例#53
0
    cmds.parent(charName + 'SplineIK_01', charName + '_ikHandle_01')
    cmds.parent(charName + '_SplineIK_Crv_01', charName + '_ikHandle_01')
    cmds.parent(charName + '_neck_Jnt_00', charName + '_Joints_01')
    cmds.parent(charName + '_root_Jnt_01', charName + '_Joints_01')
    cmds.parent(charName + '_spline_Jnt_00', charName + '_Joints_01')
    cmds.parent(charName + '_Spline_Ctrl_01_grp', charName + '_Controls_01')
    cmds.parent(charName + '_Hip_Ctrl_01', charName + '_Controls_01')


def CreateCtr(nameCtr, ObjToParent, (posX, posY, posZ),
              (scaleX, scaleY, scaleZ), (rotateX, rotateY, rotateZ)):
    cmds.CreateNURBSCircle()
    cmds.rename('nurbsCircle1', nameCtr)
    cmds.move(posX, posY, posZ)
    cmds.scale(scaleX, scaleY, scaleZ)
    cmds.makeIdentity(apply=True)
    cmds.group(nameCtr, n=nameCtr + '_grp')
    cmds.rotate(rotateX, rotateY, rotateZ)
    cmds.parentConstraint(nameCtr, ObjToParent, mo=True)


'''def ImportOBJ():
    def importImage( fileName, fileType):
       cmds.file( fileName, i=True );
       return 1
    cmds.fileBrowserDialog( m=0, fc=ImportOBJ(), ft='OBJ', an='Import_Image', om='Import' )
'''


def Bind():
    charName = cmds.textFieldGrp(NameInput, q=True, text=True)
示例#54
0
def ar_orientChain(aimValue, objValue, sel=None):
    """
    @ select top joint and unparent it,
    @ then rotate or orient it for object up axis,
    @ then parent it again and execute script.
    Args:
        aimValue (list): aim value example [1,0,0].
        objValue (list): obj value example [1,0,0].
        sel (list): top joint of chain.

    Returns:
            bool.
    """
    if not sel:
        sel = cmds.ls(sl=True)
    if not sel:
        ar_qui.ar_displayMessage('warning',
                                 'Please select at least on object...')
        return False
    for x in range(len(sel)):
        cmds.select(cl=True)
        allJoints = cmds.ls(sel[x], dag=True)
        if len(allJoints) > 1:
            cmds.parent(allJoints[1:], w=True)
            for i in range(len(allJoints)):
                if i != len(allJoints) - 1:
                    cmds.select(cl=True)
                    # create locator and snap on selection one.
                    loc = cmds.spaceLocator(
                        n='TempLocatorForObjectUpOrientation')
                    cmds.delete(cmds.parentConstraint(allJoints[i], loc[0]))
                    if objValue == [1, 0, 0]:
                        cmds.move(3, 0, 0, loc[0], r=True, os=True, wd=True)
                    if objValue == [0, 1, 0]:
                        cmds.move(0, 3, 0, loc[0], r=True, os=True, wd=True)
                    if objValue == [0, 0, 1]:
                        cmds.move(0, 0, 3, loc[0], r=True, os=True, wd=True)
                    cmds.delete(
                        cmds.aimConstraint(allJoints[i + 1],
                                           allJoints[i],
                                           o=[0, 0, 0],
                                           w=True,
                                           aim=aimValue,
                                           u=objValue,
                                           wut="object",
                                           wuo=loc[0]))
                    cmds.delete(loc[0])
                    cmds.makeIdentity(allJoints[i],
                                      a=True,
                                      t=1,
                                      r=1,
                                      s=1,
                                      n=0,
                                      pn=1)
                    # parent joint.
                    cmds.parent(allJoints[i + 1], allJoints[i])
                    cmds.setAttr(allJoints[i + 1] + '.jointOrientX', 0)
                    cmds.setAttr(allJoints[i + 1] + '.jointOrientY', 0)
                    cmds.setAttr(allJoints[i + 1] + '.jointOrientZ', 0)
                    cmds.xform(allJoints[i + 1], ro=[0, 0, 0])
                else:
                    cmds.setAttr(allJoints[i] + '.jointOrientX', 0)
                    cmds.setAttr(allJoints[i] + '.jointOrientY', 0)
                    cmds.setAttr(allJoints[i] + '.jointOrientZ', 0)
                    cmds.xform(allJoints[i], ro=[0, 0, 0])
        else:
            ar_qui.ar_displayMessage('error', '%s has no children...' % sel[x])
            return False
    return True
示例#55
0
def rigLeg(joint1, joint2, joint3, moveX, moveZ):

    RenameChars = '_' + joint1[4] + '_' + joint1[6]

    # armazena a seleção atual numa variavel
    selection = cmds.ls(selection=True)

    # duplica a selção para duplicar os joints e nao fuder os joint existentes e guarda essa seleçao numa outra variável
    cmds.duplicate(selection)
    SKINJoint1 = selection
    # parenteia essa seleção no mundo, para desparentear dos joints atuais
    #cmds.parent(world = True)

    # renomeia essa seleçao e guarda numa variável, e logo depois seleciona o próximo joint na hierarquia
    cmds.rename(joint1)  # Cintura (inicial)
    RIGJoint1 = cmds.ls(selection=True)
    mel.eval("pickWalk -d down;")  #pega o prox joint na hierarquia

    cmds.rename(joint2)  # Joelho (meio)
    RIGJointMeio2 = cmds.ls(selection=True)
    mel.eval("pickWalk -d down;")

    cmds.rename(joint3)  # Pé (final)
    RIGJointFinal3 = cmds.ls(selection=True)
    mel.eval("pickWalk -d down;")

    #, peBool
    #if peBool == True:

    cmds.rename('peito_pe' + RenameChars)
    RIGJointPeitoPe = cmds.ls(selection=True)
    mel.eval("pickWalk -d down;")

    cmds.rename('ponta_pe' + RenameChars)
    RIGJointPontaPe = cmds.ls(selection=True)

    #Criar Controles
    FinalControl = cmds.circle(
        n=joint2 +
        "_Control")  # essa n (name) representa uma String no python Maya
    BaseControl = cmds.circle(n=joint1 + "_Control")

    #Criar Nulos
    FinalControlNull = cmds.group(empty=True, n=joint2 + "_POS_freeze")
    BaseControlNull = cmds.group(empty=True, n=joint1 + "_POS_freeze")

    #Parentear controles nos nulos
    cmds.parent(FinalControl, FinalControlNull)
    cmds.parent(BaseControl, BaseControlNull)

    #Mover nulos para anklel(pé) e hip joints
    cmds.delete(cmds.parentConstraint(RIGJointFinal3, FinalControlNull))
    cmds.delete(cmds.parentConstraint(RIGJoint1, BaseControlNull))

    #Depois de girados, colocar o constraint do controle no joint
    cmds.parentConstraint(BaseControl, RIGJoint1)
    cmds.orientConstraint(FinalControl, RIGJointFinal3)

    #Depois de criados, girar os nulls antes de criar uma hierarquia entre eles
    cmds.rotate('90deg', 0, 0, joint2 + "_Control")

    #E por fim de tudo isso, freeze transformations para zerar tudo
    cmds.makeIdentity(apply=True, rotate=True, translate=True,
                      scale=True)  #Duvids
    cmds.parent(FinalControlNull, BaseControlNull)

    # Criar o IK
    #sj= startJoint    ee= endEffector(Um end effector ou um joint que tera um effector)  p=priotiry  w= weight do Ik
    principalIk = cmds.ikHandle(sj=RIGJoint1[0],
                                ee=RIGJointFinal3[0],
                                solver="ikRPsolver",
                                p=1,
                                w=1,
                                n="ik_Principal_RPS" + RenameChars)
    cmds.parent(
        "ik_Principal_RPS" + RenameChars,
        FinalControl)  #Parentear o IK_RPS noFinalControl (do pé ou mão)

    # Criar o controle do poleVector(joelho/cotovelo) e dar constraint no IK
    PoleControl = cmds.nurbsSquare(n='poleVector_Control' + RenameChars)
    PoleControlNull = cmds.group(empty=True, n="pole_POS" + RenameChars)

    cmds.parent(PoleControl, PoleControlNull)
    cmds.rotate('90deg', 0, 0, "pole_POS" + RenameChars)

    cmds.delete(cmds.parentConstraint(RIGJointMeio2, PoleControlNull))

    cmds.move(moveX, 3, moveZ, 'poleVector_Control' + RenameChars)
    cmds.poleVectorConstraint('poleVector_Control' + RenameChars,
                              'ik_Principal_RPS' + RenameChars)

    cmds.makeIdentity(apply=True, rotate=True, translate=True, scale=True)

    #Criar atributo Twist no controle, e setar no comando twist do IK rps (como se fosse setDrivenKey)
    cmds.select(BaseControl)
    cmds.addAttr(
        sn="tw",
        longName="Twist",
        attributeType='float',
        r=True,
        w=True,
        h=False,
        k=True
    )  # sn= shortName  h= hidden (hidden in UI)   r= readable(ler conexões com o atributo)   w= writable(fazer conexões com o atributo)   k= keyable(create keys in animations)
    cmds.connectAttr(joint1 + "_Control.Twist",
                     "ik_Principal_RPS" + RenameChars + '.twist')

    cmds.select(FinalControl)  #RIGJointPeitoPe
    cmds.addAttr(sn='d_m',
                 ln='Dobra_Meio',
                 at='float',
                 r=True,
                 w=True,
                 h=False,
                 k=True)  #min value= min e max value= max
    cmds.connectAttr(joint2 + "_Control.Dobra_Meio", 'peito_pe' + RenameChars +
                     '.rotateY')  # ARRUMAR OS NOMEEEEES

    cmds.select(FinalControl)  #RIGJointPeitoPe
    cmds.addAttr(sn='g_m',
                 ln='Gira_Meio',
                 at='float',
                 r=True,
                 w=True,
                 h=False,
                 k=True)  #min value= min e max value= max
    cmds.connectAttr(joint2 + "_Control.Gira_Meio",
                     'peito_pe' + RenameChars + '.rotateZ')

    cmds.select(FinalControl)  #RIGJointPeitoPe
    cmds.addAttr(sn='d_p',
                 ln='Dobra_Ponta',
                 at='float',
                 r=True,
                 w=True,
                 h=False,
                 k=True)
    cmds.connectAttr(joint2 + "_Control.Dobra_Ponta",
                     'ponta_pe' + RenameChars + '.rotateY')

    #Criar os Parents Constraints para mover os joints skinados
    cmds.select(SKINJoint1)
    mel.eval("pickWalk -d down;")
    SKINJoint2 = cmds.ls(selection=True)
    mel.eval("pickWalk -d down;")
    SKINJoint3 = cmds.ls(selection=True)

    cmds.parentConstraint(RIGJoint1, SKINJoint1, mo=True)
    cmds.parentConstraint(RIGJointMeio2, SKINJoint2, mo=True)
    cmds.parentConstraint(RIGJointFinal3, SKINJoint3, mo=True)
示例#56
0
def Controllers():
    charName = cmds.textFieldGrp(NameInput, q=True, text=True)
    lengthY = locXYZ[1][1] - locXYZ[0][1]
    lengthZ = abs(locXYZ[0][2]) + abs(locXYZ[1][2])
    legY = locXYZ[0][1] - locXYZ[5][1]
    side = ['_L_', '_R_']
    nb = [1, -1]
    for i in range(len(side)):
        cmds.ikHandle(n=charName + '_Leg' + side[i] + 'ikHandle',
                      sj=charName + side[i] + 'thigh_Jnt_01',
                      ee=charName + side[i] + 'ankie_Jnt_01')
        cmds.spaceLocator(n=charName + '_poleVector' + side[i] + 'leg',
                          p=(nb[i] * locXYZ[4][0] - legY * 0.005,
                             locXYZ[4][1] + legY * 0.05, locXYZ[4][2]))
        cmds.xform(centerPivots=1)
        # aims the pole vector of 1 at 2.
        cmds.poleVectorConstraint(charName + '_poleVector' + side[i] + 'leg',
                                  charName + '_Leg' + side[i] + 'ikHandle')
        cmds.move(nb[i] * lengthY * 0.75,
                  -lengthY * 0.75,
                  charName + '_poleVector' + side[i] + 'leg',
                  moveXY=True)
        cmds.setAttr(charName + '_Leg' + side[i] + 'ikHandle.twist',
                     nb[i] * 90)
        cmds.ParentConstraint(charName + 'controllerfoot',
                              charName + '_poleVector' + side[i] + 'leg')
        cmds.parent(charName + '_poleVector' + side[i] + 'leg',
                    charName + '_Leg' + side[i] + 'ikHandle',
                    relative=True)
        cmds.ikHandle(n=charName + '_Foot' + side[i] + 'ball_ikHandle',
                      sj=charName + side[i] + 'ankie' + '_Jnt_01',
                      ee=charName + side[i] + 'ball' + '_Jnt_01')
        cmds.ikHandle(n=charName + '_Foot' + side[i] + 'toe_ikHandle',
                      sj=charName + side[i] + 'ball' + '_Jnt_01',
                      ee=charName + side[i] + 'toe' + '_Jnt_01')
        cmds.group(charName + '_Leg' + side[i] + 'ikHandle',
                   n=charName + '_Foot' + side[i] + 'heelPeel')
        #change pivot position
        Xpos = cmds.getAttr(charName + '_Foot' + side[i] +
                            'ball_ikHandle.translateX')
        Ypos = cmds.getAttr(charName + '_Foot' + side[i] +
                            'ball_ikHandle.translateY')
        Zpos = cmds.getAttr(charName + '_Foot' + side[i] +
                            'ball_ikHandle.translateZ')
        cmds.move(Xpos,
                  Ypos,
                  Zpos,
                  charName + '_Foot' + side[i] + 'heelPeel.scalePivot',
                  charName + '_Foot' + side[i] + 'heelPeel.rotatePivot',
                  absolute=True)
        cmds.group(charName + '_Foot' + side[i] + 'ball_ikHandle',
                   charName + '_Foot' + side[i] + 'toe_ikHandle',
                   n=charName + '_Foot' + side[i] + 'toeTap')
        cmds.move(Xpos,
                  Ypos,
                  Zpos,
                  charName + '_Foot' + side[i] + 'toeTap.scalePivot',
                  charName + '_Foot' + side[i] + 'toeTap.rotatePivot',
                  absolute=True)
        cmds.group(charName + '_Foot' + side[i] + 'ball_ikHandle',
                   charName + '_Foot' + side[i] + 'toeTap',
                   n=charName + '_Foot' + side[i] + 'TipToe')
        cmds.group(n=charName + '_Foot' + side[i] + '1', em=True)
        cmds.parent(charName + '_Foot' + side[i] + 'heelPeel',
                    charName + '_Foot' + side[i] + 'TipToe',
                    charName + '_Foot' + side[i] + '1',
                    relative=True)
        cmds.move(Xpos,
                  Ypos,
                  Zpos,
                  charName + '_Foot' + side[i] + '1.scalePivot',
                  charName + '_Foot' + side[i] + '1.rotatePivot',
                  absolute=True)
        Xpos = cmds.getAttr(charName + '_Foot' + side[i] +
                            'ball_ikHandle.translateX')
        Ypos = cmds.getAttr(charName + '_Foot' + side[i] +
                            'ball_ikHandle.translateY')
        Zpos = cmds.getAttr(charName + '_Foot' + side[i] +
                            'ball_ikHandle.translateZ')
        CreateCtr(charName + '_Foot' + side[i] + 'Crl',
                  charName + '_Foot' + side[i] + '1', (Xpos, Ypos, Zpos),
                  (lengthY / 60 * 10, lengthY / 60 * 10, lengthY / 60 * 16),
                  (0, 0, 0))
    #left Arm
    for i in range(len(side)):
        cmds.ikHandle(n=charName + '_Arm' + str(side[i]) + 'ikHandle',
                      sj=charName + str(side[i]) + 'shoulder' + '_Jnt_02',
                      ee=charName + str(side[i]) + 'wrist' + '_Jnt_01')
        cmds.CreateNURBSCircle()
        cmds.rename('nurbsCircle1', charName + '_Elbow' + str(side[i]) + 'Crl')
        cmds.move(nb[i] * locXYZ[2][0], locXYZ[2][1], locXYZ[2][2] * 30)
        cmds.scale(2, 2, 3)
        cmds.rotate(90, 0, 0)
        cmds.move(nb[i] * locXYZ[2][0],
                  locXYZ[2][1],
                  locXYZ[2][2],
                  charName + '_Elbow' + str(side[i]) + 'Crl.scalePivot',
                  charName + '_Elbow' + str(side[i]) + 'Crl.rotatePivot',
                  absolute=True)
        cmds.makeIdentity(apply=True)
        cmds.xform(centerPivots=1)
        cmds.poleVectorConstraint(
            charName + '_Elbow' + str(side[i]) + 'Crl',
            charName + '_Arm' + str(side[i]) + 'ikHandle')
        #left Arm controller
        CreateCtr(charName + '_Arm' + side[i] + 'Crl',
                  charName + '_Arm' + side[i] + 'ikHandle',
                  (nb[i] * locXYZ[3][0], locXYZ[3][1], locXYZ[3][2]),
                  (lengthY / 60 * 5, lengthY / 60 * 5, lengthY / 60 * 8),
                  (0, 0, nb[i] * 30))
    #spline
    cmds.parent(charName + '_R_shoulder_Jnt_01', w=True)
    cmds.parent(charName + '_L_shoulder_Jnt_01', w=True)
    cmds.select(d=True)
    cmds.select(charName + '_spline_Jnt_03')
    cmds.DisconnectJoint(charName + '_spline_Jnt_03')
    cmds.rename(charName + '_spline_Jnt_03', charName + '_neck_Jnt_00')
    cmds.rename('joint1', charName + '_spline_Jnt_03')
    cmds.rename(charName + '_root' + '_Jnt_01', charName + '_spline_Jnt_00')
    cmds.parent(charName + '_R_hip_Jnt_01', w=True)
    cmds.parent(charName + '_L_hip_Jnt_01', w=True)
    cmds.select(d=True)
    cmds.joint(p=(locXYZ[0][0], locXYZ[0][1], locXYZ[0][2]),
               n=charName + '_root' + '_Jnt_01')
    cmds.parent(charName + '_L_hip_Jnt_01')
    cmds.select(charName + '_root' + '_Jnt_01')
    cmds.parent(charName + '_R_hip_Jnt_01')
    cmds.curve(n=charName + '_SplineIK_Crv_01',
               p=[(locXYZ[0][0], locXYZ[0][1], locXYZ[0][2]),
                  (0.0, locXYZ[0][1] + lengthY * 0.43,
                   locXYZ[0][2] + lengthZ * 0.43),
                  (0.0, locXYZ[0][1] + lengthY * 0.8,
                   locXYZ[0][2] + lengthZ * 0.18),
                  (locXYZ[1][0], locXYZ[1][1], locXYZ[1][2])])
    cmds.ikHandle(n=charName + 'SplineIK_01',
                  sj=charName + '_spline_Jnt_00',
                  ee=charName + '_spline_Jnt_03',
                  curve=charName + '_SplineIK_Crv_01',
                  sol='ikSplineSolver',
                  createCurve=False,
                  parentCurve=False)
    for i in range(4):
        cmds.select(charName + '_SplineIK_Crv_01' + '.cv[' + str(i) + ']')
        cmds.cluster(n='cluster_' + str(i + 1))
    CreateCtr(charName + '_Spline_Ctrl_01', 'cluster_1Handle',
              (0, locXYZ[0][1] * 1.05, 0),
              (lengthY / 60 * 25, lengthY / 60 * 25, lengthY / 60 * 25),
              (0, 0, 0))
    cmds.parentConstraint(charName + '_Spline_Ctrl_01',
                          charName + '_root_Jnt_01',
                          maintainOffset=True)
    CreateCtr(charName + '_Chest_Ctrl_01', 'cluster_4Handle',
              (0, locXYZ[1][1], 0),
              (lengthY / 60 * 25, lengthY / 60 * 25, lengthY / 60 * 25),
              (0, 0, 0))
    for i in range(len(side)):
        cmds.parentConstraint(charName + '_Chest_Ctrl_01',
                              charName + side[i] + 'shoulder_Jnt_01',
                              maintainOffset=True)
        cmds.parent(charName + '_Arm' + side[i] + 'Crl_grp',
                    charName + '_Chest_Ctrl_01')
        cmds.parent(charName + '_Elbow' + side[i] + 'Crl',
                    charName + '_Chest_Ctrl_01')
    CreateCtr(charName + '_Chest_Ctrl_02', 'cluster_2Handle',
              (0, (locXYZ[0][1] + locXYZ[1][1]) / 2, 0),
              (lengthY / 60 * 20, lengthY / 60 * 20, lengthY / 60 * 20),
              (0, 0, 0))
    cmds.parentConstraint(charName + '_Chest_Ctrl_01',
                          charName + '_neck_Jnt_00',
                          maintainOffset=True,
                          w=1)
    cmds.parentConstraint(charName + '_Chest_Ctrl_01',
                          'cluster_3Handle',
                          maintainOffset=True,
                          weight=0.5)
    cmds.parentConstraint(charName + '_Chest_Ctrl_01',
                          charName + '_Chest_Ctrl_02_grp',
                          maintainOffset=True,
                          weight=0.5)
    cmds.parentConstraint(charName + '_Spline_Ctrl_01',
                          charName + '_Chest_Ctrl_02_grp',
                          maintainOffset=True,
                          weight=0.5)
    cmds.CreateNURBSCircle()
    cmds.rename('nurbsCircle1', charName + '_Hip_Ctrl_01')
    cmds.move(0, locXYZ[0][1], 0)
    cmds.scale(lengthY / 60 * 30, lengthY / 60 * 30, lengthY / 60 * 30)
    cmds.makeIdentity(apply=True)
    cmds.parentConstraint(charName + '_Hip_Ctrl_01',
                          charName + '_Spline_Ctrl_01',
                          maintainOffset=True,
                          weight=0.5)
    cmds.parentConstraint(charName + '_Hip_Ctrl_01',
                          charName + '_Chest_Ctrl_01',
                          maintainOffset=True,
                          weight=0.5)
    #clean
    for i in range(len(side)):
        cmds.parent(charName + side[i] + 'shoulder_Jnt_01',
                    charName + '_Joints_01')
        cmds.parent(charName + '_Chest_Ctrl_0' + str(i + 1) + '_grp',
                    charName + '_Controls_01')
        cmds.parent(charName + '_Foot' + side[i] + '1',
                    charName + '_Controls_01')
        cmds.parent(charName + '_Foot' + side[i] + 'Crl_grp',
                    charName + '_Controls_01')
        cmds.parent(charName + '_Arm' + side[i] + 'ikHandle',
                    charName + '_ikHandle_01')
        cmds.parent('cluster_' + str(i + 1) + 'Handle',
                    charName + '_ikHandle_01')
        cmds.parent('cluster_' + str(i + 3) + 'Handle',
                    charName + '_ikHandle_01')
    cmds.parent(charName + 'SplineIK_01', charName + '_ikHandle_01')
    cmds.parent(charName + '_SplineIK_Crv_01', charName + '_ikHandle_01')
    cmds.parent(charName + '_neck_Jnt_00', charName + '_Joints_01')
    cmds.parent(charName + '_root_Jnt_01', charName + '_Joints_01')
    cmds.parent(charName + '_spline_Jnt_00', charName + '_Joints_01')
    cmds.parent(charName + '_Spline_Ctrl_01_grp', charName + '_Controls_01')
    cmds.parent(charName + '_Hip_Ctrl_01', charName + '_Controls_01')
示例#57
0
def createRig(upperVertexList,
              lowerVertexList,
              prefix='L_',
              rigPartName='EyeLid',
              rigScale=1.0,
              eyeJoint='',
              numCtrl=5,
              ):

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

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

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

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

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

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

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

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

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

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

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

        upperEyeLidParentJntList.append(parentJoint)

    cmds.select(cl=1)

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

        cmds.select(cl=1)

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

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

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

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

        cmds.select(cl=1)

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

        cmds.parent(ikHandle[0], eyelidLoc)

        upperEyelidLocList.append(eyelidLoc)

    cmds.select(cl=1)

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

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

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

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

    # make each locator attach to the curve

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

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

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

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

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

        cmds.select(cl=1)

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

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

    cmds.select(cl=1)

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

    eachADD = 1.0 / (numCtrl - 1)

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

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

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

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

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

        upperControlJointList.append(newJnt)

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

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

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

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

        upperJntCtrlGrpList.append(ctrl.Off)

    cmds.select(cl=1)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        lowerEyeLidParentJntList.append(parentJoint)

    cmds.select(cl=1)

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

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

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

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

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

        cmds.select(cl=1)

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

        cmds.parent(ikHandle[0], eyelidLoc)

        lowerEyelidLocList.append(eyelidLoc)

    cmds.select(cl=1)

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

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

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

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

    # make each locator attach to the curve

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

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

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

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

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

        cmds.select(cl=1)

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

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

    cmds.select(cl=1)

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

    eachADD = 1.0 / (numCtrl - 1)

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

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

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

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

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

        lowerControlJointList.append(newJnt)

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

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

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

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

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

        lowerJntCtrlGrpList.append(ctrl.Off)

    cmds.select(cl=1)

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

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

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

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

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

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

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

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

    # final
    cmds.parent(upperLidRigModule.topGrp, eyeLidRigModule.topGrp)
    cmds.parent(lowerLidRigModule.topGrp, eyeLidRigModule.topGrp)
示例#58
0
    def buildFKSpine(self):
	
	#find the number of spine bones from the skeleton settings
	spineJoints = self.getSpineJoints()
	fkControls = []
	parent = None
	
	for joint in spineJoints:
	    if joint == "spine_01":
		#add space switcher node to base of spine
		spaceSwitcherFollow = cmds.group(empty = True, name = joint + "_space_switcher_follow")
		constraint = cmds.parentConstraint(joint, spaceSwitcherFollow)[0]
		cmds.delete(constraint)
		spaceSwitcher = cmds.duplicate(spaceSwitcherFollow, name = joint + "_space_switcher")[0]
		cmds.parent(spaceSwitcher, spaceSwitcherFollow)
		
	    #create an empty group in the same space as the joint
	    group = cmds.group(empty = True, name = joint + "_anim_grp")
	    constraint = cmds.parentConstraint(joint, group)[0]
	    cmds.delete(constraint)
	    
	    #create an additional layer of group that has zeroed attrs
	    offsetGroup = cmds.group(empty = True, name = joint + "_anim_offset_grp")
	    constraint = cmds.parentConstraint(joint, offsetGroup)[0]
	    cmds.delete(constraint)
	    cmds.parent(offsetGroup, group)
	    
	    #create a control object in the same space as the joint
	    control = utils.createControl("circle", 45, joint + "_anim")
	    tempDupe = cmds.duplicate(control)[0]
	    constraint = cmds.parentConstraint(joint, control)[0]
	    cmds.delete(constraint)
	    fkControls.append(control)
	    
	    
	    #parent the control object to the group
	    cmds.parent(control, offsetGroup)
	    constraint = cmds.orientConstraint(tempDupe, control, skip = ["x", "z"])[0]
	    cmds.delete(constraint)
	    cmds.makeIdentity(control, t = 1, r = 1, s = 1, apply = True)

	    
	    #setup hierarchy
	    if parent != None:
		cmds.parent(group, parent, absolute = True)
		
	    else:
		cmds.parent(group, spaceSwitcher)
		cmds.parent(spaceSwitcherFollow, "body_anim")
		
		
	    #set the parent to be the current spine control
	    parent = control
	    
	    #clean up
	    cmds.delete(tempDupe)
	    
	    for attr in [".v"]:
		cmds.setAttr(control + attr, lock = True, keyable = False)
		
	    #set the control's color
	    cmds.setAttr(control + ".overrideEnabled", 1)
	    cmds.setAttr(control + ".overrideColor", 18)
	    

	return fkControls
示例#59
0
def edo_addFacialCtrlCmd(ctrlName,parent='',onlyFrame=0,sfix='_CTRL'):
    #ctrlName='test'
    #sfix='_CONNECT'
    #parent=''
    print ctrlName
    if cmds.objExists(ctrlName+'_FRAME'):
        cmds.confirmDialog( title='Confirm', message=ctrlName+sfix + ' .. has already existed in this scene!', button=['got it'] )
        return False
    curve=cmds.curve(d=1,p=[(-1,1,0),(-1,-1,0),(1,-1,0),(1,1,0),(-1,1,0)],k=[0,1,2,3,4])
    curve_zy=cmds.curve(d=1,p=[(-1,0.2,0),(-1,-1,0),(1,-1,0),(1,0.2,0),(-1,0.2,0)],k=[0,1,2,3,4])
    curve_fy=cmds.curve(d=1,p=[(-1,1,0),(-1,-0.2,0),(1,-0.2,0),(1,1,0),(-1,1,0)],k=[0,1,2,3,4])
    curve_zx=cmds.curve(d=1,p=[(-1,1,0),(-1,-1,0),(0.2,-1,0),(0.2,1,0),(-1,1,0)],k=[0,1,2,3,4])
    curve_fx=cmds.curve(d=1,p=[(-0.2,1,0),(-0.2,-1,0),(1,-1,0),(1,1,0),(-0.2,1,0)],k=[0,1,2,3,4])
    curve_zyfy=cmds.curve(d=1,p=[(-1,0.2,0),(-1,-0.2,0),(1,-0.2,0),(1,0.2,0),(-1,0.2,0)],k=[0,1,2,3,4])
    curve_zxfx=cmds.curve(d=1,p=[(-0.2,1,0),(-0.2,-1,0),(0.2,-1,0),(0.2,1,0),(-0.2,1,0)],k=[0,1,2,3,4])
    curve_zyfyfx=cmds.curve(d=1,p=[(-0.2,0.2,0),(-0.2,-0.2,0),(1,-0.2,0),(1,0.2,0),(-0.2,0.2,0)],k=[0,1,2,3,4])
    curve_zyfyzx=cmds.curve(d=1,p=[(-1,0.2,0),(-1,-0.2,0),(0.2,-0.2,0),(0.2,0.2,0),(-1,0.2,0)],k=[0,1,2,3,4])
    curve_zxfxfy=cmds.curve(d=1,p=[(-0.2,1,0),(-0.2,-0.2,0),(0.2,-0.2,0),(0.2,1,0),(-0.2,1,0)],k=[0,1,2,3,4])
    curve_zxfxzy=cmds.curve(d=1,p=[(-0.2,0.2,0),(-0.2,-1,0),(0.2,-1,0),(0.2,0.2,0),(-0.2,0.2,0)],k=[0,1,2,3,4])
    cmds.rename(curve,ctrlName+'_FRAME')
    cmds.rename(curve_zy,ctrlName+'_FRAME_lockzy')
    cmds.rename(curve_fy,ctrlName+'_FRAME_lockfy')
    cmds.rename(curve_zx,ctrlName+'_FRAME_lockzx')
    cmds.rename(curve_fx,ctrlName+'_FRAME_lockfx')
    cmds.rename(curve_zyfy,ctrlName+'_FRAME_lockzyfy')
    cmds.rename(curve_zxfx,ctrlName+'_FRAME_lockzxfx')
    cmds.rename(curve_zyfyfx,ctrlName+'_FRAME_lockzyfyfx')
    cmds.rename(curve_zyfyzx,ctrlName+'_FRAME_lockzyfyzx')
    cmds.rename(curve_zxfxzy,ctrlName+'_FRAME_lockzxfxzy')
    cmds.rename(curve_zxfxfy,ctrlName+'_FRAME_lockzxfxfy')
    allframe=[ctrlName+'_FRAME',ctrlName+'_FRAME_lockzy',ctrlName+'_FRAME_lockfy',ctrlName+'_FRAME_lockzx',ctrlName+'_FRAME_lockfx',ctrlName+'_FRAME_lockzyfy',ctrlName+'_FRAME_lockzxfx',ctrlName+'_FRAME_lockzyfyzx',ctrlName+'_FRAME_lockzyfyfx',ctrlName+'_FRAME_lockzxfxzy',ctrlName+'_FRAME_lockzxfxfy',]
    cmds.addAttr(ctrlName+'_FRAME',ln='up',at='double',min=0)
    cmds.setAttr(ctrlName+'_FRAME.up',keyable=1)
    cmds.addAttr(ctrlName+'_FRAME',ln='dn',at='double',min=0)
    cmds.setAttr(ctrlName+'_FRAME.dn',keyable=1)
    cmds.addAttr(ctrlName+'_FRAME',ln='lf',at='double',min=0)
    cmds.setAttr(ctrlName+'_FRAME.lf',keyable=1)
    cmds.addAttr(ctrlName+'_FRAME',ln='rt',at='double',min=0)
    cmds.setAttr(ctrlName+'_FRAME.rt',keyable=1)
    cmds.addAttr(ctrlName+'_FRAME',ln='lfup',at='double',min=0)
    cmds.setAttr(ctrlName+'_FRAME.lfup',keyable=1)
    cmds.addAttr(ctrlName+'_FRAME',ln='rtup',at='double',min=0)
    cmds.setAttr(ctrlName+'_FRAME.rtup',keyable=1)
    cmds.addAttr(ctrlName+'_FRAME',ln='lfdn',at='double',min=0)
    cmds.setAttr(ctrlName+'_FRAME.lfdn',keyable=1)
    cmds.addAttr(ctrlName+'_FRAME',ln='rtdn',at='double',min=0)
    cmds.setAttr(ctrlName+'_FRAME.rtdn',keyable=1)
    cmds.addAttr(ctrlName+'_FRAME',ln='fourAxis_up',at='double',min=0)
    cmds.setAttr(ctrlName+'_FRAME.fourAxis_up',keyable=1)
    cmds.addAttr(ctrlName+'_FRAME',ln='fourAxis_dn',at='double',min=0)
    cmds.setAttr(ctrlName+'_FRAME.fourAxis_dn',keyable=1)
    cmds.addAttr(ctrlName+'_FRAME',ln='fourAxis_lf',at='double',min=0)
    cmds.setAttr(ctrlName+'_FRAME.fourAxis_lf',keyable=1)
    cmds.addAttr(ctrlName+'_FRAME',ln='fourAxis_rt',at='double',min=0)
    cmds.setAttr(ctrlName+'_FRAME.fourAxis_rt',keyable=1)
    #
    cmds.addAttr(ctrlName+'_FRAME',ln='curveType',dt='string')
    cmds.setAttr(ctrlName+'_FRAME.curveType',sfix,type='string')
    cmds.setAttr(ctrlName+'_FRAME.curveType',e=1,l=1)
    #
    cmds.createNode('transform',n='GRP_'+ctrlName+'_FRAME')
    cmds.parent(allframe,'GRP_'+ctrlName+'_FRAME')
    curve=cmds.curve(d=1,p=[(-1,1,0),(-1,3,0),(-2,3,0),(0,5,0),(2,3,0),(1,3,0),(1,1,0),(4,4,0),(1,1,0),(3,1,0),(3,2,0),(5,0,0),(3,-2,0),(3,-1,0),(1,-1,0),(4,-4,0),(1,-1,0),(1,-3,0),(2,-3,0),(0,-5,0),(-2,-3,0),(-1,-3,0),(-1,-1,0),(-4,-4,0),(-1,-1,0),(-3,-1,0),(-3,-2,0),(-5,0,0),(-3,2,0),(-3,1,0),(-1,1,0),(-4,4,0),(-1,1,0)],k=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32])
    cmds.rename(curve,ctrlName+sfix)
    cmds.setAttr(ctrlName+sfix+'Shape.overrideEnabled',1)
    cmds.setAttr(ctrlName+sfix+'Shape.ovc',17)
    cmds.setAttr(ctrlName+sfix+'.sx',0.05)
    cmds.setAttr(ctrlName+sfix+'.sy',0.05)
    cmds.setAttr(ctrlName+sfix+'.sy',0.05)
    cmds.transformLimits(ctrlName+sfix,etx=(1,1),tx=(-1,1))
    cmds.transformLimits(ctrlName+sfix,ety=(1,1),ty=(-1,1))
    cmds.transformLimits(ctrlName+sfix,etz=(1,1),tz=(0,0))
    cmds.makeIdentity(ctrlName+sfix,apply=1,t=1,r=1,s=1,n=0)
    cmds.group(ctrlName+sfix,n='GRP_'+ctrlName+sfix,p=ctrlName+'_FRAME')
    ##==================

    #=======addReferenceAttribute=======
    cmds.addAttr(ctrlName+sfix,ln='frameSelectAble',at='enum',en='normal:template:reference:')
    cmds.setAttr(ctrlName+sfix+'.frameSelectAble',e=1,k=0,cb=0)
    cmds.setAttr(ctrlName+sfix+'.frameSelectAble',2)
    for frame in allframe:
        #frame=allframe[0]
        cmds.setAttr(frame+'Shape.overrideEnabled',1)
        cmds.connectAttr(ctrlName+sfix+'.frameSelectAble',frame+'Shape.overrideDisplayType',f=1)
        if not frame==ctrlName+'_FRAME':
            cmds.parent(frame,ctrlName+'_FRAME')
    
    if not parent=='':
        cmds.parent('GRP_'+ctrlName+'_FRAME',parent)
    cmds.select(cl=1)
    edo_addAttrBoundaryBox(ctrlName,sfix)
    
    if onlyFrame==1:
        return True
    cmds.createNode('multiplyDivide',n=ctrlName+'_upmult_Xinverse')
    cmds.connectAttr(ctrlName+sfix+'.tx',ctrlName+'_upmult_Xinverse.input2X',f=1)
    cmds.setAttr(ctrlName+'_upmult_Xinverse.input1X',-1)
    cmds.createNode('clamp',n=ctrlName+'_upclamp_PXrange')
    cmds.connectAttr(ctrlName+'_upmult_Xinverse.outputX',ctrlName+'_upclamp_PXrange.inputR',f=1)
    cmds.setAttr(ctrlName+'_upclamp_PXrange.minR',0)
    cmds.setAttr(ctrlName+'_upclamp_PXrange.maxR',1)
    cmds.createNode('clamp',n=ctrlName+'_upclamp_NXrange')
    cmds.connectAttr(ctrlName+sfix+'.tx',ctrlName+'_upclamp_NXrange.inputR',f=1)
    cmds.setAttr(ctrlName+'_upclamp_NXrange.minR',0)
    cmds.setAttr(ctrlName+'_upclamp_NXrange.maxR',1)
    cmds.createNode('plusMinusAverage',n=ctrlName+'_upplus_Xplus')
    cmds.connectAttr(ctrlName+'_upclamp_NXrange.outputR',ctrlName+'_upplus_Xplus.input1D[0]',f=1)
    cmds.connectAttr(ctrlName+'_upclamp_PXrange.outputR',ctrlName+'_upplus_Xplus.input1D[1]',f=1)
    cmds.createNode('reverse',n=ctrlName+'_upreverse_X')
    cmds.connectAttr(ctrlName+'_upplus_Xplus.output1D',ctrlName+'_upreverse_X.inputX',f=1)
    cmds.createNode('clamp',n=ctrlName+'_upclamp_PYrange')
    cmds.connectAttr(ctrlName+sfix+'.ty',ctrlName+'_upclamp_PYrange.inputR',f=1)
    cmds.setAttr(ctrlName+'_upclamp_PYrange.minR',0)
    cmds.setAttr(ctrlName+'_upclamp_PYrange.maxR',1)
    cmds.createNode('multiplyDivide',n=ctrlName+'_upScale')
    cmds.connectAttr(ctrlName+'_upclamp_PYrange.outputR',ctrlName+'_upScale.input1X',f=1)
    cmds.connectAttr(ctrlName+'_upreverse_X.outputX',ctrlName+'_upScale.input2X',f=1)
    cmds.createNode('clamp',n=ctrlName+'_upclamp_finalrange')
    cmds.connectAttr(ctrlName+'_upScale.outputX',ctrlName+'_upclamp_finalrange.inputR',f=1)
    cmds.setAttr(ctrlName+'_upclamp_finalrange.minR',0)
    cmds.setAttr(ctrlName+'_upclamp_finalrange.maxR',1)
    cmds.connectAttr(ctrlName+'_upclamp_finalrange.outputR',ctrlName+'_FRAME.up',f=1)
    ##==================    
    cmds.createNode('multiplyDivide',n=ctrlName+'_dnmult_Yinverse')
    cmds.connectAttr(ctrlName+sfix+'.ty',ctrlName+'_dnmult_Yinverse.input2X',f=1)
    cmds.setAttr(ctrlName+'_dnmult_Yinverse.input1X',-1)
    cmds.createNode('clamp',n=ctrlName+'_dnclamp_PYrange')
    cmds.connectAttr(ctrlName+'_dnmult_Yinverse.outputX',ctrlName+'_dnclamp_PYrange.inputR',f=1)
    cmds.setAttr(ctrlName+'_dnclamp_PYrange.minR',0)
    cmds.setAttr(ctrlName+'_dnclamp_PYrange.maxR',1)
    cmds.createNode('multiplyDivide',n=ctrlName+'_dnScale')
    cmds.connectAttr(ctrlName+'_dnclamp_PYrange.outputR',ctrlName+'_dnScale.input1X',f=1)
    cmds.connectAttr(ctrlName+'_upreverse_X.outputX',ctrlName+'_dnScale.input2X',f=1)
    cmds.createNode('clamp',n=ctrlName+'_dnclamp_finalrange')
    cmds.connectAttr(ctrlName+'_dnScale.outputX',ctrlName+'_dnclamp_finalrange.inputR',f=1)
    cmds.setAttr(ctrlName+'_dnclamp_finalrange.minR',0)
    cmds.setAttr(ctrlName+'_dnclamp_finalrange.maxR',1)
    cmds.connectAttr(ctrlName+'_dnclamp_finalrange.outputR',ctrlName+'_FRAME.dn',f=1)
    
    
    ##==================    
    cmds.createNode('multiplyDivide',n=ctrlName+'_lfmult_Yinverse')
    cmds.connectAttr(ctrlName+sfix+'.ty',ctrlName+'_lfmult_Yinverse.input2X',f=1)
    cmds.setAttr(ctrlName+'_lfmult_Yinverse.input1X',-1)
    cmds.createNode('clamp',n=ctrlName+'_lfclamp_PYrange')
    cmds.connectAttr(ctrlName+'_lfmult_Yinverse.outputX',ctrlName+'_lfclamp_PYrange.inputR',f=1)
    cmds.setAttr(ctrlName+'_lfclamp_PYrange.minR',0)
    cmds.setAttr(ctrlName+'_lfclamp_PYrange.maxR',1)
    cmds.createNode('clamp',n=ctrlName+'_lfclamp_NYrange')
    cmds.connectAttr(ctrlName+sfix+'.ty',ctrlName+'_lfclamp_NYrange.inputR',f=1)
    cmds.setAttr(ctrlName+'_lfclamp_NYrange.minR',0)
    cmds.setAttr(ctrlName+'_lfclamp_NYrange.maxR',1)
    cmds.createNode('plusMinusAverage',n=ctrlName+'_lfplus_Yplus')
    cmds.connectAttr(ctrlName+'_lfclamp_NYrange.outputR',ctrlName+'_lfplus_Yplus.input1D[0]',f=1)
    cmds.connectAttr(ctrlName+'_lfclamp_PYrange.outputR',ctrlName+'_lfplus_Yplus.input1D[1]',f=1)
    cmds.createNode('reverse',n=ctrlName+'_lfreverse_Y')
    cmds.connectAttr(ctrlName+'_lfplus_Yplus.output1D',ctrlName+'_lfreverse_Y.inputX',f=1)
    cmds.createNode('multiplyDivide',n=ctrlName+'_lfmult_Xinverse')
    cmds.connectAttr(ctrlName+sfix+'.tx',ctrlName+'_lfmult_Xinverse.input2X',f=1)
    cmds.setAttr(ctrlName+'_lfmult_Xinverse.input1X',-1)
    cmds.createNode('clamp',n=ctrlName+'_lfclamp_PXrange')
    cmds.connectAttr(ctrlName+'_lfmult_Xinverse.outputX',ctrlName+'_lfclamp_PXrange.inputR',f=1)
    cmds.setAttr(ctrlName+'_lfclamp_PXrange.minR',0)
    cmds.setAttr(ctrlName+'_lfclamp_PXrange.maxR',1)
    cmds.createNode('multiplyDivide',n=ctrlName+'_lfScale')
    cmds.connectAttr(ctrlName+'_lfclamp_PXrange.outputR',ctrlName+'_lfScale.input1X',f=1)
    cmds.connectAttr(ctrlName+'_lfreverse_Y.outputX',ctrlName+'_lfScale.input2X',f=1)
    cmds.createNode('clamp',n=ctrlName+'_lfclamp_finalrange')
    cmds.connectAttr(ctrlName+'_lfScale.outputX',ctrlName+'_lfclamp_finalrange.inputR',f=1)
    cmds.setAttr(ctrlName+'_lfclamp_finalrange.minR',0)
    cmds.setAttr(ctrlName+'_lfclamp_finalrange.maxR',1)
    cmds.connectAttr(ctrlName+'_lfclamp_finalrange.outputR',ctrlName+'_FRAME.lf',f=1)
    
    ##==================    
    cmds.createNode('clamp',n=ctrlName+'_rtclamp_PXrange')
    cmds.connectAttr(ctrlName+sfix+'.tx',ctrlName+'_rtclamp_PXrange.inputR',f=1)
    cmds.setAttr(ctrlName+'_rtclamp_PXrange.minR',0)
    cmds.setAttr(ctrlName+'_rtclamp_PXrange.maxR',1)
    cmds.createNode('multiplyDivide',n=ctrlName+'_rtScale')
    cmds.connectAttr(ctrlName+'_rtclamp_PXrange.outputR',ctrlName+'_rtScale.input1X',f=1)
    cmds.connectAttr(ctrlName+'_lfreverse_Y.outputX',ctrlName+'_rtScale.input2X',f=1)
    cmds.createNode('clamp',n=ctrlName+'_rtclamp_finalrange')
    cmds.connectAttr(ctrlName+'_rtScale.outputX',ctrlName+'_rtclamp_finalrange.inputR',f=1)
    cmds.setAttr(ctrlName+'_rtclamp_finalrange.minR',0)
    cmds.setAttr(ctrlName+'_rtclamp_finalrange.maxR',1)
    cmds.connectAttr(ctrlName+'_rtclamp_finalrange.outputR',ctrlName+'_FRAME.rt',f=1)
    
    ##==================
    cmds.createNode('multiplyDivide',n=ctrlName+'_lfupmult')
    cmds.connectAttr(ctrlName+'_lfclamp_NYrange.outputR',ctrlName+'_lfupmult.input1X',f=1)
    cmds.connectAttr(ctrlName+'_upclamp_PXrange.outputR',ctrlName+'_lfupmult.input2X',f=1)
    cmds.connectAttr(ctrlName+'_lfupmult.outputX',ctrlName+'_FRAME.lfup',f=1)

    ##==================
    cmds.createNode('multiplyDivide',n=ctrlName+'_rtupmult')
    cmds.connectAttr(ctrlName+'_lfclamp_NYrange.outputR',ctrlName+'_rtupmult.input1X',f=1)
    cmds.connectAttr(ctrlName+'_upclamp_NXrange.outputR',ctrlName+'_rtupmult.input2X',f=1)
    cmds.connectAttr(ctrlName+'_rtupmult.outputX',ctrlName+'_FRAME.rtup',f=1)
    
    ##==================
    cmds.createNode('multiplyDivide',n=ctrlName+'_lfdnmult')
    cmds.connectAttr(ctrlName+'_lfclamp_PYrange.outputR',ctrlName+'_lfdnmult.input1X',f=1)
    cmds.connectAttr(ctrlName+'_upclamp_PXrange.outputR',ctrlName+'_lfdnmult.input2X',f=1)
    cmds.connectAttr(ctrlName+'_lfdnmult.outputX',ctrlName+'_FRAME.lfdn',f=1)
  
    ##==================
    cmds.createNode('multiplyDivide',n=ctrlName+'_rtdnmult')
    cmds.connectAttr(ctrlName+'_lfclamp_PYrange.outputR',ctrlName+'_rtdnmult.input1X',f=1)
    cmds.connectAttr(ctrlName+'_upclamp_NXrange.outputR',ctrlName+'_rtdnmult.input2X',f=1)
    cmds.connectAttr(ctrlName+'_rtdnmult.outputX',ctrlName+'_FRAME.rtdn',f=1)
    
    #=======4Aixs=====================
    cmds.connectAttr(ctrlName+'_lfclamp_NYrange.outputR',ctrlName+'_FRAME.fourAxis_up',f=1)
    cmds.connectAttr(ctrlName+'_lfclamp_PYrange.outputR',ctrlName+'_FRAME.fourAxis_dn',f=1)
    cmds.connectAttr(ctrlName+'_upclamp_NXrange.outputR',ctrlName+'_FRAME.fourAxis_rt',f=1)
    cmds.connectAttr(ctrlName+'_upclamp_PXrange.outputR',ctrlName+'_FRAME.fourAxis_lf',f=1)
    cmds.select(cl=1)
示例#60
0
    def _setup_stretch(self):
        # ==================stretchSpine setup=============================
        # create a curveInfo node to get the curve length
        curveInfoNode = cmd.arclen(self.spineCurve, constructionHistory=True)
        curveInfoNode = cmd.rename(curveInfoNode, self.spineCurve + 'Info')

        # Calculate stretch factor
        stretchMDnode = cmd.shadingNode('multiplyDivide', asUtility=True, name='spineIKstretchy_MD')
        cmd.connectAttr(curveInfoNode + '.arcLength', stretchMDnode + '.input1.input1X')
        nonScaleLength = cmd.getAttr(curveInfoNode + '.arcLength')

        # original curve length = nonscale length * global scale
        originalLengthMD = cmd.shadingNode('multiplyDivide', asUtility=True, name='spineCurveOriginalLength_MD')
        cmd.setAttr(originalLengthMD + '.input1X', nonScaleLength)
        if self.globalScale == 1:
            cmd.setAttr(originalLengthMD + '.input2X', 1)
        else:
            cmd.connectAttr(self.globalScale, originalLengthMD + '.input2X')

        originalLength = originalLengthMD + '.outputX'
        cmd.connectAttr(originalLength, stretchMDnode + '.input2X')
        cmd.setAttr(stretchMDnode + '.operation', 2)

        # create a switch for stretch
        condition = cmd.shadingNode('condition', asUtility=True, name='stretch_condition')
        cmd.connectAttr(stretchMDnode + '.output.outputX', condition + '.colorIfTrue.colorIfTrueR')
        cmd.setAttr(condition + '.operation', 0)
        cmd.setAttr(condition + '.firstTerm', 1)  # this attr goes into the switch (stretchy ON/OFF)
        cmd.setAttr(condition + '.secondTerm', 1)

        # attributes: stretchSpine:
        cmd.addAttr(self.upperCtrl, ln='stretchSpine', at='bool', dv=1, keyable=True)
        cmd.connectAttr(self.upperCtrl + '.stretchSpine', condition + '.firstTerm')

        # ==================hook the output value from condition node to joints==================
        # end effector (end joint) no need to stretch, exclude from joint list
        self.stretchJnts = self.joints[:len(self.joints) - 1]
        self.jntPMAdict = {}
        for joint in self.stretchJnts:
            jntPMAnode = cmd.shadingNode('plusMinusAverage', asUtility=True, name=joint + '_spine_compression_PMA')
            cmd.connectAttr(condition + '.outColorR', jntPMAnode + '.input1D[0]', force=True)
            cmd.connectAttr(jntPMAnode + '.output1D', joint + '.sx', f=True)
            self.jntPMAdict[joint] = jntPMAnode

        # =========================twist fix=============================
        ikHandle = self.ikSpine[0]
        cmd.setAttr(ikHandle + '.dTwistControlEnable', 1)
        cmd.setAttr(ikHandle + '.dWorldUpType', 4)
        cmd.setAttr(ikHandle + '.dWorldUpVectorX', 1)
        cmd.setAttr(ikHandle + '.dWorldUpVectorY', 0)
        cmd.setAttr(ikHandle + '.dWorldUpVectorEndX', 1)
        cmd.setAttr(ikHandle + '.dWorldUpVectorEndY', 0)
        cmd.connectAttr(self.lowerCtrl + '.xformMatrix', ikHandle + '.dWorldUpMatrix', f=True)
        cmd.connectAttr(self.upperCtrl + '.xformMatrix', ikHandle + '.dWorldUpMatrixEnd', f=True)

        cmd.makeIdentity(self.joints[0], apply=True, r=True)

        # ==========================warning box==========================
        # create warning box material:
        warningLambert = cmd.shadingNode('lambert', asShader=True, name='warningBox_material')
        sg = cmd.sets(renderable=True, noSurfaceShader=True, empty=True, name=warningLambert + 'SG')
        cmd.connectAttr(warningLambert + '.outColor', sg + '.surfaceShader', f=True)
        cmd.setAttr(warningLambert + '.transparency', 0.6, 0.6, 0.6)

        # set color change:
        cmd.addAttr(self.upperCtrl, ln='scaleFactor', at='float', dv=0, keyable=False)

        cmd.setAttr(self.upperCtrl + '.scaleFactor', 1.5)
        cmd.setAttr(warningLambert + '.color', 1, 0, 0, type='double3')
        cmd.setDrivenKeyframe(warningLambert + '.colorR', currentDriver=self.upperCtrl + '.scaleFactor')
        cmd.setDrivenKeyframe(warningLambert + '.colorG', currentDriver=self.upperCtrl + '.scaleFactor')
        cmd.setDrivenKeyframe(warningLambert + '.colorB', currentDriver=self.upperCtrl + '.scaleFactor')

        cmd.setAttr(self.upperCtrl + '.scaleFactor', 0.6)
        cmd.setDrivenKeyframe(warningLambert + '.colorR', currentDriver=self.upperCtrl + '.scaleFactor')
        cmd.setDrivenKeyframe(warningLambert + '.colorG', currentDriver=self.upperCtrl + '.scaleFactor')
        cmd.setDrivenKeyframe(warningLambert + '.colorB', currentDriver=self.upperCtrl + '.scaleFactor')

        cmd.setAttr(self.upperCtrl + '.scaleFactor', 1)
        cmd.setAttr(warningLambert + '.color', 0, 1, 0, type='double3')
        cmd.setDrivenKeyframe(warningLambert + '.colorR', cd=self.upperCtrl + '.scaleFactor')
        cmd.setDrivenKeyframe(warningLambert + '.colorG', cd=self.upperCtrl + '.scaleFactor')
        cmd.setDrivenKeyframe(warningLambert + '.colorB', cd=self.upperCtrl + '.scaleFactor')

        cmd.connectAttr(stretchMDnode + '.outputX', self.upperCtrl + '.scaleFactor')

        # assign material to warningbox
        for ctrl in [self.upperCtrl, self.lowerCtrl]:
            shapes = cmd.listRelatives(ctrl, shapes=True)
            for box in shapes:
                if cmd.ls(box, showType=True)[1] == 'mesh':
                    cmd.setAttr(box + '.castsShadows', 0)
                    cmd.setAttr(box + '.receiveShadows', 0)
                    cmd.setAttr(box + '.motionBlur', 0)
                    cmd.setAttr(box + '.primaryVisibility', 0)
                    cmd.setAttr(box + '.smoothShading', 0)
                    cmd.setAttr(box + '.visibleInReflections', 0)
                    cmd.setAttr(box + '.visibleInRefractions', 0)
                    cmd.select(box, r=True)
                    cmd.sets(e=True, forceElement=sg)
                    cmd.connectAttr(self.upperCtrl + '.stretchSpine', box + '.visibility')