예제 #1
0
    def __init__(self, uiinfo):
        # Get our joint lists from a json file.
        data_path = os.environ["AR_DATA"] + 'data/rig/head.json'
        # Use our readJson function
        data = utils.readJson(data_path)
        # Load the json into a dictionary
        self.module_info = json.loads( data )
        
        # Make a new dictionary to store information about the arm rig.
        self.rig_info = {}

        # Here we will see if we have a selection to get new positions from.
        if len(cmds.ls(sl=True, type='joint')) == numjnts :
            self.rig_info['seljnts']=cmds.ls(sl=True, type='joint')
            positions = []
            for s in self.rig_info['seljnts']:
                positions.append(cmds.xform(s, q=True, ws=True, t=True))
            self.rig_info['positions']=positions

            # Get the joint orientations
            self.rig_info['parent'] = cmds.listRelatives(self.rig_info['seljnts'][0], p=True)[0]
            cmds.parent(self.rig_info['seljnts'][0], w=True)
            orients = []
            for j in self.rig_info['seljnts']:
                orients.append(cmds.getAttr("%s.jointOrient" % j))
            self.rig_info['orients'] = orients
            cmds.parent(self.rig_info['seljnts'][0], self.rig_info['parent'])

        else:
            self.rig_info['positions']=self.module_info['positions']

        self.instance = uiinfo[0]

        # Run rig_arm function
        self.install()
예제 #2
0
파일: scene.py 프로젝트: ewerybody/melDrop
def orderNextTo(objects, target):
    '''
    places 'objects'/[objects] next to 'target' in hierarchy and ordering

    I found most of the time I use the get/setOrder stuff to relocate objs to another
    with parenting and if in world and hierarchy Nr and all that shit.. this does it inline
    '''
    if not isinstance(objects, list):
        objects = [objects]
    handledObjs = []
    targetParent = m.listRelatives(target, parent=True, fullPath=True)
    targetNr = getOrder(target)
    # handle each object on its own no matter how its parented
    for o in objects:
        oParent = m.listRelatives(o, parent=1, fullPath=1)
        if oParent != targetParent:
            if targetParent:
                o = m.parent(o, targetParent)[0]
            else:
                o = m.parent(o, world=1)[0]
        # else if in same hierarchy already decrease count if obj is before target
        elif getOrder(o) <= targetNr:
            targetNr -= 1
        handledObjs.append(o)
    setOrder(handledObjs, targetNr + 1)
    m.select(handledObjs)
    return handledObjs
예제 #3
0
    def createLocators(self):
        #create list of loc names (self.name)
        for i in range(len(self.jointList)):
            self.locList.append("%s_%s_Loc"%(self.jointList[i],self.limbName))

        #check that these don't exist already
        if (cmds.objExists(self.locList[0])):
            cmds.error("these limb locators exists already!")
        else:

            #fill dictionary - assign values from list
            self.locPos = {}
            for j in range(len(self.locList)):
                self.locPos[self.locList[j]] = self.locPosValues[j]

            #create the locs
            for key in self.locPos.keys():
                thisLoc = cmds.spaceLocator(n=key)
                cmds.move(self.locPos[key][0], self.locPos[key][1], self.locPos[key][2], thisLoc)

            #parent them together (from list of loc names)
            for k in range((len(self.locList)-1),0,-1):
                cmds.parent(self.locList[k], self.locList[k-1])

######### make this true only for the arms. . . or figure out how to extract which rot this should be
            #rotate second joint to just get a preferred angle
            cmds.setAttr("%s.ry"%self.locList[1], -5)
예제 #4
0
def createJoints(prefix, lytObs, *args):
    print "CreateJoints"

    cmds.select(d=True)

    ik_joints = []

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

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


    lytLen = len(lytObs)

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

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


    return ik_joints  
예제 #5
0
    def setupIKCtrl(self, x, IKHandle):

        ############# MODIFY FOR INHERITANCE  #############
        side = self.prefixList[x]
        thisChain = self.IKChains[x]

        #create a control for the ik
        name = "%s_%s_IK_CTRL"%(side, self.limbName)
        if x==0:
            IKCtrl = rig.createControl(name, "cube", self.jAxis1, "blue")
        if x==1:
            IKCtrl = rig.createControl(name, "cube", self.jAxis1, "red")
        self.IKCtrls.append(IKCtrl)
        #strip to rotate and translate
        rig.stripToRotateTranslate(IKCtrl)

        #G.O. control
        rig.groupOrient(thisChain[2], IKCtrl, self.groupSuffix)

        #orient constraint joint 2 (wrist ankle) to control
        cmds.orientConstraint(IKCtrl, thisChain[2])

        #parent ik handle to control
        cmds.parent(IKHandle, IKCtrl)

        return IKCtrl
예제 #6
0
파일: shape.py 프로젝트: auqeyjf/glTools
def unparent(shape):
	'''
	Unparent shape nodes from a source parent
	@param shape: Shape or transform to unparent shapes from
	@type shape: str
	'''
	# Checks
	if not mc.objExists(shape):
		raise Exception('Object "'+shape+'" does not exist!!')
	
	# Get shapes
	if mc.ls(shape,type='transform'):
		transform = shape
		shapes = mc.listRelatives(shape,s=True,pa=True)
	else:
		transform = mc.listRelatives(shape,p=True,pa=True)[0]
		shapes = [shape]
	
	# Create shape holder
	shapeHolder = transform+'Shapes'
	if not mc.objExists(shapeHolder): shapeHolder = mc.createNode('transform',n=shapeHolder)
	targetXform = mc.xform(transform,q=True,ws=True,m=True)
	mc.xform(shapeHolder,ws=True,m=targetXform)
	
	# Unparent shapes
	for shape in shapes:
		mc.parent(shape,shapeHolder,s=True,r=True)
	
	# Return Result
	return shapeHolder
예제 #7
0
파일: shape.py 프로젝트: eddiehoyle/link
    def create(self, parent_transform, style):
        """Create shape"""

        self.parent = parent_transform

        # Add style
        curve_data = Style()[style]
        for curve in curve_data:
            temp = cmds.curve(name="temp_curve", d=1, p=curve['points'], k=curve['knot'])

            # Parent curve under transform
            shapes = cmds.listRelatives(temp, shapes=True)
            for shape_index, shape in enumerate(shapes):
                cmds.parent(shape, parent_transform, shape=True, r=True)

                # Rename shape to be tidy
                new_shape = cmds.rename(shape, "%s%s" % (self.name, shape_index))
                self.nodes.append(new_shape)

            # Remove temp transform
            cmds.delete(temp)

        # Set colors
        self.set_color(name.get_position(self.parent))

        # Match values
        self.scale_shapes(self.scale)
        self.rotate_shapes(self.rotate)

        # Clear selection
        cmds.select(cl=True)
예제 #8
0
파일: Util.py 프로젝트: darkuress/arFace
    def mirrorJoints(self, topJoint = '', prefix = ['l_', 'r_']):
        """
        mirroring joint, top node needs to contain 'l_' as prefix
        """

        lPrefix = prefix[0]
        rPrefix = prefix[1]
        
        cmds.select(cl = True)
        cmds.joint(n = 'temp_jnt')
        cmds.select(topJoint, r = True)
        cmds.select('temp_jnt', tgl = True)
        self.toggleSelect(topJoint, 'temp_jnt')
        cmds.parent()
        
        cmds.select(topJoint, r = True)
        cmds.mirrorJoint(mirrorYZ = True, mirrorBehavior  = True, myz = True, searchReplace =  prefix)
        
        rJoint = rPrefix + topJoint.split(lPrefix)[-1]
        cmds.select(topJoint, rJoint)
        cmds.parent(w = True)
        
        cmds.delete('temp_jnt')
        
        return rJoint
예제 #9
0
def buildAnnotation( obj, text='' ):
	'''
	like the distance command above, this is a simple wrapper for creating annotation nodes,
	and having the nodes you actually want returned to you.  whoever wrote these commands
	should be shot.  with a large gun

	returns a 3 tuple containing the start transform, end transform, and annotation shape node
	'''
	obj = str( obj )  #cast as string just in case we've been passed a PyNode instance

	rand = random.randint
	end = spaceLocator()[ 0 ]
	shape = annotate( end, p=(rand(0, 1000000), rand(1000000, 2000000), 2364), tx=text )

	start = listRelatives( shape, p=True, pa=True )[ 0 ]
	endShape = listRelatives( end, s=True, pa=True )[ 0 ]

	delete( parentConstraint( obj, end ) )
	for ax in Axis.AXES[ :3 ]:
		setAttr( '%s.t%s' % (start, ax), 0 )

	setAttr( '%s.v' % endShape, 0 )
	setAttr( '%s.v' % endShape, lock=True )
	cmd.parent( end, obj )

	return start, end, shape
예제 #10
0
def build(numBindJoints=6, numSpans=None, name='', numSkinJoints=3, width=None):
    '''
    builds a nurbs ribbon
    If width is not specified, width will be set to numBindJoints
    If numSpans is not specified, it will be set to numBindJoints
    
    '''
    if not width:
        width = numBindJoints
    if not numSpans:
        numSpans = numBindJoints
    
    main_grp = cmds.group(empty=1, name=(name + '_grp'))
    plane = cmds.nurbsPlane(axis=(0, 1, 0), ch=0, lengthRatio=(1.0 / width), w=width, u=numSpans, name=(name + '_nurbsPlane'))[0]
    cmds.parent(plane, main_grp)
    
    # Creat Skin joints
    skinJoints = []
    skinJointPositions = common.pointsAlongVector( start=[width*.5, 0, 0], end=[width*-.5, 0, 0], divisions=(numSkinJoints-1) )
    for index in range(len(skinJointPositions)):
        cmds.select(main_grp)
        j = cmds.joint(position = skinJointPositions[index], name=(name + '_' + str(index) + '_jnt'))
        skinJoints.append(j)
        
    # Add skinning to ribbon
    cmds.skinCluster(skinJoints, plane, tsb=1, name=(plane + '_skinCluster'))
    cmds.setAttr(plane+'.inheritsTransform', 0)
    
    # Add follicles
    for index in range(numBindJoints):
        f = rivet.build( mesh=plane, paramU=(1.0 / (numBindJoints-1) * index), paramV=0.5, name=(name + '_' + str(index)))
        cmds.parent(f, main_grp)
        j = cmds.joint(name=(name + '_' + str(index) + '_bnd'))
예제 #11
0
파일: LightSkeleton.py 프로젝트: akkey/maya
def set_knee_IK():
    # メッセージ
    cmds.inViewMessage(amg="<hl>「指のコントローラー設置」</hl>を押してください。", pos="midCenter", fade=True, fit=1, fst=4000, fts=20)
    # 座標取得
    positionR = cmds.xform("Knee_R", q=True, ws=True, t=True)
    locatorNameR = "Knee_R_Locator"
    # ロケーター設置
    cmds.spaceLocator(p=(positionR[0], positionR[1], positionR[2] + 3.8), n=locatorNameR)
    knee_ik_add("Hip_R", "Ankle_R", "Knee_R_Effector", positionR, locatorNameR)

    # 座標取得
    positionL = cmds.xform("Knee_L", q=True, ws=True, t=True)
    locatorNameL = "Knee_L_Locator"
    # ロケーター設置
    cmds.spaceLocator(p=(positionL[0], positionL[1], positionL[2] + 3.8), n=locatorNameL)
    knee_ik_add("Hip_L", "Ankle_L", "Knee_L_Effector", positionL, locatorNameL)

    # つま先のIK実行
    toe_ik_add("Ankle_R", "MiddleToe2_R", "Ankle_R_Effector")
    toe_ik_add("Ankle_L", "MiddleToe2_L", "Ankle_L_Effector")

    # 足のコントローラー、 座標取得
    toePositionR = cmds.xform("MiddleToe1_R", q=True, ws=True, t=True)
    toePositionL = cmds.xform("MiddleToe1_L", q=True, ws=True, t=True)
    foot_controller("foot_R_controller", toePositionR[0])
    foot_controller("foot_L_controller", toePositionL[0])

    # コントローラー内にエフェクター移動
    cmds.parent("Ankle_L_Effector", "foot_L_controller")
    cmds.parent("Knee_L_Effector", "foot_L_controller")
    cmds.parent("Ankle_R_Effector", "foot_R_controller")
    cmds.parent("Knee_R_Effector", "foot_R_controller")

    # 親子関係移動
    cmds.parent("Knee_R_Locator", "Knee_L_Locator", "foot_R_controller", "foot_L_controller", "main_controller")
def main():
	mm.eval('selectCurveCV("all");')
	sel = mc.ls(sl=1, fl=1)
	grpname = (sel[0].split('.'))
	grpname = grpname[0]+"_grp"
	grp = mc.group(em=1, n=grpname)
	
	for i in sel:
		iname = i.replace('[', '')
		iname = iname.replace(']','')
		iname = iname.replace('.','_')
		
		locname = iname+"_loc"
		clusname = iname+"_clus"	
		
		mc.select(i, r=1)
		print "here"
		cluster = mc.cluster(n=clusname)
	
		location = mc.xform(cluster, q=1, ws=1, sp=1)
		print location
		locator = mc.spaceLocator(n=locname, p=(location[0], location[1], location[2]))
		mc.xform(locator, cp=1)
		set_vis = clusname+"Handle.visibility"
		mc.setAttr(set_vis, 0)
		mc.parent(cluster, locator)
		mc.parent(locator, grp)
		
		shape = mc.listRelatives(locator)
		mc.setAttr((shape[0]+".overrideEnabled"),1)
		mc.setAttr((shape[0]+".overrideColor"),17)
예제 #13
0
    def _setup_wire_deformer(self, mesh, wire, wirebase, curve,
                             parent, complexity):
        """Setup the wire deformer. If complexity is 1 or higher call this
        function recursively to create a wire deformer on the nurbs surface.

        @param mesh(string): PolyMesh used to wire deform
        @param wire(string): Descriptive part of the name of the wire deformer
        @param wirebase(string): Descriptive part of the name of the base wire
        @param curve(string): Curve used for wireTool deformer
        @param parent(string): Parent node of the wire setup
        @param complexity(uint): complexity level value
        """
        w = wire
        wb = wirebase
        cmds.wire(mesh, w=curve, dds=[0, 10000], n=w, foc=False)
        cmds.rename(cmds.listConnections('%s.baseWire[0]' % w)[0], wb)
        if not cmds.listRelatives(curve, p=True) == [self.wire_grp]:
            cmds.parent(curve, wb, self.wire_grp)
        # end if
        wbs = cmds.listRelatives(wb, ad=True, type='shape')[0]
        cs = cmds.listRelatives(curve, ad=True, type='shape')[0]
        cmds.setAttr('%s.rotation' % w, 0)
        # connect to showHistory
        cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % w)
        cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % wb)
        cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % wbs)
        cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % cs)
        if complexity:
            cmds.duplicate(self.curve, n=self.nrbcurve)
            return self._setup_wire_deformer(self.surface, self.nrbwire,
                                             self.nrbwirebase, self.nrbcurve,
                                             self.parent, 0)
예제 #14
0
파일: legSetup.py 프로젝트: darkuress/arNew
    def legCleanup(self):
        for lr in self.lrPrefix:
            #- hide heel pivot
            cmds.setAttr('%sheel_PivotPosition.visibility' %lr, 0)

            #- placing extra control
            cmds.select('%sleg_extra_ctl_grp' %lr, r = True)
            cmds.select('%sankle_jnt' %lr, tgl = True)
            cmds.parent()
            
            #- hide attribute
            cmds.setAttr('%sleg_pv_ctl.visibility' %lr, keyable = False, channelBox = False)
            cmds.setAttr('%sleg_ctl.visibility' %lr, keyable = False, channelBox = False)
            
            #- clean up hierarchy
            self.util.group(['%sik_hip_jnt' %lr, '%sfk_hip_jnt' %lr], '%sfkik_leg_jnt_grp' %lr)
            self.util.group(['%ship_jnt' %lr, '%sfkik_leg_jnt_grp' %lr], '%sleg_jnt_grp' %lr)
            
            #- hide stretchIK locator
            cmds.setAttr('%sstretch_leg_grp.visibility' %lr, 0)
                        
        self.util.group(['l_leg_jnt_grp', 'r_leg_jnt_grp'], 'leg_jnt_grp')    
        children = ['l_leg_pv_ctl_grp', 'r_leg_pv_ctl_grp',
                    'l_fk_hip_ctl_grp', 'r_fk_hip_ctl_grp',
                    'l_leg_ctl_grp', 'r_leg_ctl_grp']
        self.util.group(children, 'leg_ctl_grp')
        self.util.group(['l_stretch_leg_grp', 'r_stretch_leg_grp'], 'stretch_leg_grp')
        self.util.group(['l_heel_PivotPosition', 'r_heel_PivotPosition', 'stretch_leg_grp'], 'leg_misc_grp')    
        
        
            
예제 #15
0
파일: arm.py 프로젝트: jonntd/Rigganator
 def create_ik_arm_stretch(self):
     """Creates the IK stretch setup."""
     arm_dist, start_loc, end_loc = self.c.distance_node(self.guides['upperArm'], self.guides['hand'])
     arm_dist = cmds.rename(arm_dist, '%s_%s_%s' % (self.side, 'arm', self.nc.distance))
     start_loc = cmds.rename(start_loc, '%s_%s_%s' % (self.side, 'armLengthStart', self.nc.locator))
     end_loc = cmds.rename(end_loc, '%s_%s_%s' % (self.side, 'armLengthEnd', self.nc.locator))
     cmds.parent(end_loc, self.controls['handik'])
     cmds.parent(arm_dist, self.top_grp)
     driver = '%sShape.distance' % arm_dist
     if self.side == 'R':
         mult = cmds.shadingNode('multiplyDivide', asUtility=True)
         mult = cmds.rename(mult, '%s_%s_stretch_negative_MDN' % (self.side, 'arm'))
         cmds.connectAttr('%sShape.distance' % arm_dist, '%s.input1X' % mult, f=True)
         cmds.setAttr('%s.input2X' % mult, -1)
         driver = '%s.outputX' % mult
     # END if
     upper_arm_len = cmds.getAttr('%s.tx' % self.ik_jnts[1])
     fore_arm_len = cmds.getAttr('%s.tx' % self.ik_jnts[2])
     sum_len = upper_arm_len + fore_arm_len
     cmds.setDrivenKeyframe('%s.translateX' % self.ik_jnts[1], cd=driver,
                            dv=sum_len, itt='linear', ott='linear')
     cmds.setDrivenKeyframe('%s.translateX' % self.ik_jnts[1], cd=driver,
                            dv=sum_len*2, v=upper_arm_len*2, itt='linear', ott='linear')
     cmds.setDrivenKeyframe('%s.translateX' % self.ik_jnts[2], cd=driver,
                            dv=sum_len, itt='linear', ott='linear')
     cmds.setDrivenKeyframe('%s.translateX' % self.ik_jnts[2], cd=driver,
                            dv=sum_len*2, v=fore_arm_len*2, itt='linear', ott='linear')
     cmds.setAttr('%s_translateX.postInfinity' % self.ik_jnts[1], 1)
     cmds.setAttr('%s_translateX.postInfinity' % self.ik_jnts[2], 1)
     # stretch the result joints
     curve = '%s_%s_%s' % (self.side, 'upperArm', self.nc.curve)
     self.stretch_result_joints(curve, 'upperArm', self.upper_arm_jnts)
     curve = '%s_%s_%s' % (self.side, 'foreArm', self.nc.curve)
     self.stretch_result_joints(curve, 'foreArm', self.fore_arm_jnts)
예제 #16
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)
예제 #17
0
파일: dave.py 프로젝트: jonntd/Rigganator
    def _finger_hydraulics(self):
        """Connects the finger hydraulics."""
        for side in ['L', 'R']:
            for finger in ['pointer', 'middle', 'ring']:
                start_jnt = '%s_%sBase_result_%s' % (side, finger, self.nc.joint)
                end_jnt = '%s_%s1_result_%s' % (side, finger, self.nc.joint)

                if finger == 'ring':
                    finger = 'pinky'
                # END if

                start_hydraulic = '%s_%sHydraulicsStart_%s_%s' % (side, finger, self.nc.joint, self.nc.group)
                mid_hydraulic = '%s_%sHydraulicsMid_%s_%s' % (side, finger, self.nc.joint, self.nc.group)
                end_hydraulic = '%s_%sHydraulicsEnd_%s_%s' % (side, finger, self.nc.joint, self.nc.group)

                cmds.select(cl=True)
                start_offset = cmds.group(n='%s_%sBaseOffset_%s' % (side, finger, self.nc.group), empty=True)
                cmds.select(cl=True)
                end_offset = cmds.group(n='%s_%s2Offset_%s' % (side, finger, self.nc.group), empty=True)

                self.c.snap_a_to_b(start_offset, start_hydraulic)
                self.c.snap_a_to_b(end_offset, end_hydraulic)
                cmds.parent(start_offset, start_jnt)
                cmds.parent(end_offset, end_jnt)

                cmds.parent(start_hydraulic, start_offset)
                cmds.parent(end_hydraulic, end_offset)

                try:
                    cmds.parent(mid_hydraulic, '%s_hand_%s' % (side, self.nc.group))
                except Exception as err:
                    print err
예제 #18
0
    def mirror_chain(self, side = None):
        #create one temporary joint at the origin
        tmp_jnt = cmds.joint(position = [0, 0, 0])

        #parent the chain to that joint
        cmds.parent(self.fk_joint_names[0], tmp_jnt)

        #mirror the chain and rename the mirrored side
        if side == 'L':
            self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'R'))
        elif side == 'l':
            self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'r'))
        elif side == 'R':
            self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'L'))
        elif side == 'r':
            self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'l'))
        else:
            self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1)

        #unparent the chain and delete the temporary joint
        cmds.parent(self.fk_joint_names[0], self.mirrored_fk_joint_names[0], world = 1)        
        cmds.delete(tmp_jnt)

        cmds.select(clear = 1)        
        return self.mirrored_fk_joint_names
예제 #19
0
    def mirror_chain(self, side = None):
        #create one temporary joint at the origin
        tmp_jnt = cmds.joint(position = [0, 0, 0])

        #parent the chain to that joint
        cmds.parent(self.ik_joint_names[0], tmp_jnt)

        #mirror the chain and rename the mirrored side
        if side == 'L':
            self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'R'))
        elif side == 'l':
            self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'r'))
        elif side == 'R':
            self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'L'))
        elif side == 'r':
            self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'l'))
        else:
            self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1)

        #unparent the chain and delete the temporary joint
        cmds.parent(self.ik_joint_names[0], self.mirrored_ik_joint_names[0], world = 1)        
        cmds.delete(tmp_jnt)

        cmds.select(clear = 1)

        #rename the side of the mirrored effector correctly and store the ik and effector in a list
        mirrored_ik  = self.mirrored_ik_joint_names[0][0] + self.ik_handle_names[-1][1:]
        mirrored_eff = cmds.rename(self.mirrored_ik_joint_names[-1], self.mirrored_ik_joint_names[0][0] + self.ik_handle_names[-1][1:])
        self.mirrored_ik_handle_names = [mirrored_ik, mirrored_eff]
        self.mirrored_ik_joint_names.pop(-1)
예제 #20
0
파일: leg.py 프로젝트: jonntd/japeto
    def rig(self):
        if super(Leg,self).rig():
            return True

        #create pelvis control
        pelvisCtrl = \
            control.create(name = self.pelvisJoint.replace('_%s' % common.JOINT, ''),
                    type = 'cube',
                    parent = self.controlsGrp,
                    color = common.SIDE_COLOR[self._getSide()])
        #end loop

        common.setColor(pelvisCtrl, color = common.SIDE_COLOR[self._getSide()])
        pelvisCtrlZero = common.getParent(pelvisCtrl)
        transform.matchXform(self.pelvisJoint, pelvisCtrlZero, type = 'pose')
        cmds.parentConstraint(pelvisCtrl, self.pelvisJoint, mo = True)

        #parent fkCtrls under the pelvis control
        cmds.parent(common.getParent(self.controls['fk'][0]), pelvisCtrl)

        #parent constraint ik/fk joints to the pelvis control
        cmds.parentConstraint(self.pelvisJoint,self.joints['ik'][0], mo = True)
        cmds.parentConstraint(self.pelvisJoint, self.joints['target'][0], mo = True)

        #add joints to the joints dictionary
        self.joints['fk'].insert(0, self.pelvisJoint)

        #add controls to the control dictionary
        self.controls['fk'].insert(0,pelvisCtrl)


        self.hookRoot.pop(0)
        self.hookRoot.insert(0, pelvisCtrlZero)
예제 #21
0
    def install_custom(self, joints, moduleGrp, moduleContainer):
        joint = joints[1]
        name = "globalControl"
        
        controlObjectInstance = controlObject.ControlObject()
        globalControlInfo = controlObjectInstance.create(name, "cubeLocator.ma", self, lod=1, translation=True, rotation=True, globalScale=True, spaceSwitching=True)
        globalControl = globalControlInfo[0]
        globalControl_rootParent = globalControlInfo[1]
        
        # Position and orient control object
        pos = cmds.xform(joint, q=True, worldSpace=True, translation=True)
        orient = cmds.xform(joint, q=True, worldSpace=True, rotation=True)
        
        cmds.xform(globalControl, worldSpace=True, absolute=True, translation=pos)
        cmds.xform(globalControl, worldSpace=True, absolute=True, rotation=orient)
        """ Try freezing transforms """
        #cmds.makeIdentity(globalControl, apply=True, t=True, r=False, s=False)
        
        cmds.parent(globalControl_rootParent, moduleGrp, absolute=True)
        
        cmds.connectAttr(joint+".rotateOrder", globalControl+".rotateOrder")
        
        parentConstraint = cmds.parentConstraint(globalControl, joint, maintainOffset=False, n=joint+"_parentConstraint")[0]
        scaleConstraint = cmds.scaleConstraint(globalControl, joint, maintainOffset=False, n=joint+"_scaleConstraint")[0]

        utils.addNodeToContainer(moduleContainer, [parentConstraint, scaleConstraint])
예제 #22
0
    def StardardFeetFK(self, StandarFeetPointsDic, FeetControl = None):
        Side = self.NameConv.RMGetFromName(self.StandardFeetPointsDic["feet"][0],"Side")
        self.rootFKJoints , StandardFeetFKJoints = self.StandardReverseFeetJointStructure( StandarFeetPointsDic)

        StandardFeetFKJoints = self.NameConv.RMRenameSetFromName(StandardFeetFKJoints,"FK" , "Name" , mode = "add")
        
        FootIn  = self.StandardFeetPointsDic["limitIn"]
        FootOut = self.StandardFeetPointsDic["limitOut"]
        FootBK  = self.StandardFeetPointsDic["limitBack"]
        Length  = RMRigTools.RMPointDistance(self.StandardFeetPointsDic["feet"][2] , FootBK)

        if not FeetControl:
            self.FirstLimbFeetResetControl, FeetControl = RMRigShapeControls.RMCircularControl(StandardFeetFKJoints[0] ,radius =  Length, name = "FKFeetControl")

        self.FeetControl = FeetControl

        SecondLimbfeetResetControl , SecondLimbFeetControl = RMRigShapeControls.RMCircularControl(StandardFeetFKJoints[1] ,radius =  Length, name = "FKTipFeetControl")

        cmds.parentConstraint(FeetControl, StandardFeetFKJoints[0], mo = True)
        cmds.parentConstraint(SecondLimbFeetControl, StandardFeetFKJoints[1], mo = True)
        cmds.parentConstraint(StandardFeetFKJoints[0], SecondLimbfeetResetControl, mo = True)

        cmds.parent(SecondLimbfeetResetControl,FeetControl )
        RMRigTools.RMLockAndHideAttributes(FeetControl,"000111000h")
        RMRigTools.RMLockAndHideAttributes(SecondLimbFeetControl,"000111000h")

        self.StandardFeetFKJoints = StandardFeetFKJoints
        self.SecondLimbFeetControl = SecondLimbFeetControl
        self.SecondLimbControlResetPoint = SecondLimbfeetResetControl
def bt_moveObjToCamera():
    
    #Check for hotkey and make if possible
    bt_checkCtrFHotkey()

    activePanel = cmds.getPanel(wf=1)
    if "model" in activePanel:
        activeCamera = cmds.modelEditor(activePanel,q=1,camera=1)   
    else:
        cmds.error ('No active panel/camera to frame to')    
         
    selected = cmds.ls(sl=1)
    
    locator = cmds.spaceLocator()
    cmds.select(activeCamera,add=1)
    cmds.parent(r=1)
    cmds.move(0,0,-5,locator,r=1,os=1)
    location = cmds.xform(q=1,t=1,ws=1)
    
    for object in selected:
        cmds.move(location[0],location[1],location[2],object,ws=1,a=1)
        #cmds.move(location[0],location[1],location[2],'pCube1',ws=1,a=1)
        
    cmds.delete(locator)   
    cmds.select(selected,r=1)
예제 #24
0
	def create_module(self, moduleType):
		# new module dialog
		moduleName, ok = QtGui.QInputDialog().getText(self, 'Add ' + moduleType + ' Module', 'Enter module name:', QtGui.QLineEdit.Normal, moduleType)

		if ok and moduleName != "":

			# If module with name is exist
			if cmds.objExists(moduleName+":main"):
				QtGui.QMessageBox.information(self, "Warning", "This module is exist.")
			else:
				# add module to list
				item = QtGui.QListWidgetItem(moduleName)
				self.modules_listWidget.addItem(item)
				self.modules_listWidget.setCurrentItem(item)
				
				# import module  
				cmds.file("G:/Projects New/AnimaCord/pk_rig/%s/%s_rig.mb" %(moduleType,moduleType), r=True, type="mayaBinary", namespace=moduleName)
				cmds.file("G:/Projects New/AnimaCord/pk_rig/%s/%s_rig.mb" %(moduleType,moduleType), importReference=True )
				cmds.parent(moduleName+":main", characterRoot)
				
				# set module name
				cmds.setAttr(moduleName+":main.moduleName", moduleName, type="string")
				
				cmds.hide(moduleName+":controls")
				cmds.select(moduleName+":main_poser")
				
				self.update_modules_list()
예제 #25
0
def createTwistJoints(joint, numTwistJoints, offsetAxis="x", prefix=""):
    """
	"""
    # Check joint
    if not mc.objExists(joint):
        raise Exception("Joint " + joint + " does not exist!")

        # Check prefix
    if not prefix:
        prefix = glTools.utils.stringUtils.stripSuffix(joint)

    # Get joint length
    jointEnd = mc.listRelatives(joint, c=True)[0]
    jointLen = mc.getAttr(jointEnd + ".t" + offsetAxis)
    jointOffset = jointLen / (numTwistJoints - 1)

    # Create twist joints
    twistJoints = []
    for i in range(numTwistJoints):

        alphaInd = glTools.utils.stringUtils.alphaIndex(i, upper=True)

        # Duplicate joint
        twistJoint = mc.duplicate(joint, po=True, n=prefix + "_twist" + alphaInd + "_jnt")[0]
        mc.parent(twistJoint, joint)

        # Position joint
        mc.setAttr(twistJoint + ".t" + offsetAxis, jointOffset * i)

        # Append twist joint list
        twistJoints.append(twistJoint)

        # Return result
    return twistJoints
예제 #26
0
파일: ikhandle.py 프로젝트: jonntd/Public
    def ikRPsolver(self, 
                    startJoint = None, 
                    endEffector = None, 
                    side = None, 
                    name = None, 
                    suffix = None,
                    parent = None,
                    hide = False):
        #--- do the proper naming checks
        self.__check_ik_name(startJoint = startJoint, endEffector = endEffector, 
                           side = side, name = name, suffix = suffix)

        #--- create the ik_handle
        ik = cmds.ikHandle(startJoint = startJoint, endEffector = endEffector, 
                           name = self.ik_name, solver = 'ikRPsolver')

        #--- rename the effector
        eff = cmds.rename(ik[-1], ik[0] + 'EFF')

        #--- store the ik_handle and effector in a list to return
        ik_handle = [ik[0], eff]

        #--- parent the ik_handle under the specified parent
        if parent:
            cmds.parent(ik_handle[0], parent)

        #--- hide the ik handle
        if hide:
            cmds.setAttr(ik_handle[0] + '.v', 0)

        cmds.select(clear = 1)
        return ik_handle
예제 #27
0
    def __setup_final_meshes(self):
        #--- this method setups the final meshes
        if 'FINAL' in self.mesh:
            if cmds.objExists(self.mesh):
                self.final_mesh = self.mesh
            else:
                self.final_mesh = cmds.duplicate(self.mesh)
                cmds.parent(self.final_mesh, self.sf_final_meshes)
                final_name = cmds.rename(self.final_mesh,
                                         self.mesh)
                self.final_mesh = final_name
        else:
            if cmds.objExists(self.mesh + 'FINAL'):
                self.final_mesh = self.mesh + 'FINAL'
            else:
                self.final_mesh = cmds.duplicate(self.mesh)
                cmds.parent(self.final_mesh, self.sf_final_meshes)
                final_name = cmds.rename(self.final_mesh,
                                         self.mesh + 'FINAL')
                self.final_mesh = final_name

        if cmds.objExists(self.mesh + '_BSP'):
            #--- setup blendShape deformer
            self.final_bsp = self.mesh + '_BSP'
            cmds.setAttr(self.final_bsp + '.' + self.mesh, 1)
            cmds.setAttr(self.mesh + '.v', 0)
        else:
            if 'FINAL' in self.mesh:
                self.mesh = self.mesh.split('FINAL')[0]
            self.final_bsp = cmds.blendShape(self.mesh,
                                             self.final_mesh,
                                             name = self.mesh + '_BSP')[0]
            cmds.setAttr(self.final_bsp + '.' + self.mesh, 1)
            cmds.setAttr(self.mesh + '.v', 0)
예제 #28
0
 def exportRig(self):
     """ will export SH and Geo found in the geo folder """
     # rig and geo should not be referenced
     # find SH, delete constraints, parent to world
     # find geo folder parent to world
     # select SH and geo folder and export as fbx to fbx folder
     pymelLogger.debug( 'Starting rig export' )
     export = 0
     for rig in self.rootList:
         if cmds.objExists(rig): 
             # check if geo folder also exists
             if cmds.objExists(self.geo):
                 self._delConstraints(rig)  
                 cmds.parent(rig, w=1)
                 cmds.parent(self.geo, w=1)
                 cmds.select(rig,self.geo, r=1)
                 #print rig, self.geo
                 if self._fbxExport( 2 ):
                     cmds.confirmDialog(m='FBX Rig Exported', button='Ok')
                 pymelLogger.debug( 'Finished rig export' )
                 export = 1
                 break
             else: 
                 pymelLogger.error( 'No geo folder has been found' )
     if export == 0 : pymelLogger.error( 'No Rig Exported. Note: Referenced Rigs Will Not Export' )
예제 #29
0
def createSplineCurveInfo( curve, number, **options ):
    
    crvShape = cmds.listRelatives( curve, s=1 )
    if not crvShape: return None
    crvShape = crvShape[0]
    
    splineNode = cmds.createNode( 'splineCurveInfo', n=curve+'_spline' )
    cmds.connectAttr( crvShape+'.local', splineNode+'.inputCurve' )
    
    if number <= 1:
        return None
    elif number > 1:
        eachRate = 1.0/(number-1)
        for i in range( number ):
            cmds.setAttr( splineNode+'.parameter[%d]' % i, eachRate*i+0.001 )
            
    for i in range( number-1 ):
        trNode = cmds.createNode( 'transform' )
        cmds.connectAttr( splineNode+'.output[%d].position' % i, trNode+'.t' )
        cmds.connectAttr( splineNode+'.output[%d].rotate' % i, trNode+'.r' )
        cmds.parent( trNode, curve )
        cmds.setAttr( trNode+'.dh', 1 )
        cmds.setAttr( trNode+'.dla', 1 )
    
    return splineNode
예제 #30
0
파일: ueExport.py 프로젝트: jonntd/dmptools
def exportSelection(selection, filepath):    
    # combine if selection is more than 1 mesh
    if len(selection) > 1:
        selection = modeling.combine()
    # get asset name
    base = os.path.basename(filepath)
    assetname = os.path.splitext(base)[0]
    
    # create groups
    cmds.select(clear=True)
    main_group = cmds.group(n=assetname, empty=True)
    geo_group = cmds.group(n=assetname+'_main', empty=True, p=main_group)
    lod0_group = cmds.group(n=assetname+'_lod0', empty=True, p=geo_group)
    col_group = cmds.group(n=assetname+'_collision', empty=True, p=main_group)
    
    # parent the geo to the lod0 group
    cmds.parent(selection, lod0_group)
    # create the collision
    collision = cmds.duplicate(selection)
    cmds.parent(collision, col_group)

    # rename meshes
    cmds.rename(selection, 'part_state0')
    cmds.rename(collision, 'part_state0_Mesh1')

    # select main group
    cmds.select(main_group, r=True)
    
    # set fbx settings
    mel.eval('FBXExportFileVersion "FBX201300"') 
    #mel.eval('FBXConvertUnitString "m"')
    mel.eval('FBXExportSmoothingGroups -v true')
    mel.eval('FBXExportUpAxis "Y"')
    # export selection
    mel.eval('FBXExport -f "'+filepath+'" -s')
예제 #31
0
def createLoc():
	head= 2
	mc.spaceLocator(n = 'FootLeftLoc')
	mc.scale(0.3,0.3,0.3)
	mc.move(1,0,1)
	mc.color(rgb=(0,0,1))
	
	mc.spaceLocator(n = 'ToeLeftLoc')
	mc.scale(0.2,0.2,0.2)
	mc.move(1,0,2)
	mc.color(rgb=(0,0,1))
	mc.parent('ToeLeftLoc','FootLeftLoc')
	
	mc.spaceLocator(n = 'AnkleLeftLoc')
	mc.move(1,head*0.5,0)
	mc.scale(0.2,0.2,0.2)
	mc.color(rgb=(0.5,0,0))
	mc.parent('FootLeftLoc','AnkleLeftLoc')
	
	mc.spaceLocator(n = 'KneeLeftLoc')
	mc.move(1,head*2,0)
	mc.scale(0.3,0.3,0.3)
	mc.color(rgb=(0.5,0.2,0))
	mc.parent('AnkleLeftLoc' ,  'KneeLeftLoc')
	
	mc.spaceLocator(n = 'ThighLeftLoc')
	mc.move(1,head*4,0)
	mc.scale(0.4,0.4,0.4)
	mc.color(rgb=(0.5,0.2,0.5))
	mc.parent('KneeLeftLoc' ,'ThighLeftLoc')
		
	mc.spaceLocator(n = 'NeckLoc')
	mc.move(0,head*6.5,0)
	mc.scale(0.2,0.2,0.2)
	mc.color(rgb=(0,0.2,0.5))
	
	mc.spaceLocator(n = 'RootLoc')
	mc.move(0,head*4,0)
	mc.scale(0.2,0.2,0.2)
	mc.color(rgb=(0,0.2,0.5))
	
	mc.spaceLocator(n = 'Spine0Loc')
	mc.move(0,head*4.5,0)
	mc.scale(0.2,0.2,0.2)
	mc.color(rgb=(0,0.2,0.5))
	
	mc.spaceLocator(n = 'Spine1Loc')
	mc.move(0,head*5.0,0)
	mc.scale(0.2,0.2,0.2)
	mc.color(rgb=(0,0.2,0.5))
	
	mc.spaceLocator(n = 'Spine2Loc')
	mc.move(0,head*5.5,0)
	mc.scale(0.2,0.2,0.2)
	mc.color(rgb=(0,0.2,0.5))
	
	mc.spaceLocator(n = 'Spine3Loc')
	mc.move(0,head*6,0)
	mc.scale(0.2,0.2,0.2)
	mc.color(rgb=(0,0.2,0.5))
	
	mc.spaceLocator(n = 'ShoulderLeftLoc')
	mc.move(head,head*6.5,0)
	mc.scale(0.2,0.2,0.2)
	mc.color(rgb=(0,0.2,0.5))
	
	mc.spaceLocator(n = 'ClavicleLoc')
	mc.move(head*0.3,head*6.6,0)
	mc.scale(0.2,0.2,0.2)
	mc.color(rgb=(0,0.2,0.5))
		
	mc.spaceLocator(n = 'ElbowLeftLoc')
	mc.move(head*2.5,head*6.5,0)
	mc.scale(0.2,0.2,0.2)
	mc.color(rgb=(0,0.2,0.5))
	
	mc.spaceLocator(n = 'WristLeftLoc')
	mc.move(head*3.7,head*6.5,0)
	mc.scale(0.2,0.2,0.2)
	mc.color(rgb=(0,0.2,0.5))
		
	mc.spaceLocator(n = 'IndexLeftLoc3')
	mc.move(head*4.4,head*6.5,0)
	mc.scale(0.1,0.1,0.1)
	mc.color(rgb=(0,0.2,0.5))
	
	mc.spaceLocator(n = 'IndexLeftLoc0')
	fingerEnd = mc.getAttr('IndexLeftLoc3.tx')
	wrist = mc.getAttr('WristLeftLoc.tx')
	halfhand = wrist+(fingerEnd - wrist)*0.5
	mc.move(halfhand,head*6.5,0)
	mc.scale(0.05,0.05,0.05)
	
	mc.spaceLocator(n = 'IndexLeftLoc1')
	fingerEnd = mc.getAttr('IndexLeftLoc3.tx')
	middlefingerRoot = mc.getAttr('IndexLeftLoc0.tx')
	
	halfmiddleFinger = middlefingerRoot + (fingerEnd - middlefingerRoot)*0.5
	mc.move(halfmiddleFinger,head*6.5,0)
	mc.scale(0.05,0.05,0.05)
	
	mc.spaceLocator(n = 'IndexLeftLoc2')
	fingerEnd = mc.getAttr('IndexLeftLoc3.tx')
	IndexLeftLoc1 = mc.getAttr('IndexLeftLoc1.tx')
	halfmiddleSecondFinger = IndexLeftLoc1 + (fingerEnd - IndexLeftLoc1)*0.5
	mc.move(halfmiddleSecondFinger,head*6.5,0)
	mc.scale(0.05,0.05,0.05)
			
	mc.select('IndexLeftLoc0','IndexLeftLoc1','IndexLeftLoc2','IndexLeftLoc3')
	mc.move(0,0,0.2,r = True)


	mc.spaceLocator(n = 'HeadLoc')
	mc.move(0,head*7,0)
	mc.scale(0.5,0.5,0.5)
	mc.color(rgb=(0,0.2,0.5))
	
	mc.spaceLocator(n = 'HeadEndLoc')
	mc.move(0,head*8,0)
	mc.scale(0.7,0.7,0.7)
	mc.color(rgb=(0,0,2))


	#other fingers besides index
	for i in range(3):
		mc.select('IndexLeftLoc0','IndexLeftLoc1','IndexLeftLoc2','IndexLeftLoc3')
		mc.duplicate()
		mc.move(0,0,-0.2*(i+1),r = True)

	for j in range(4):
		mc.rename('IndexLeftLoc' + str(j+4),'MiddleLeftLoc' + str(j))
	for j in range(4,8):
		mc.rename('IndexLeftLoc' + str(j+4),'RingLeftLoc' + str(j-4))
	for j in range(8,12):
		mc.rename('IndexLeftLoc' + str(j+4),'PinkieLeftLoc' + str(j-8))
	
	#thumb
	mc.select('IndexLeftLoc0','IndexLeftLoc1','IndexLeftLoc2')
	mc.duplicate()
	mc.move(0,0,0.2,r = True)
	for j in range(3):
		mc.rename('IndexLeftLoc' + str(j+4),'ThumbLeftLoc' + str(j))	
	for i in range(1,3):
		mc.parent('ThumbLeftLoc' +  str(3-i),'ThumbLeftLoc' +  str(2-i) )
	
	for each in ('PinkieLeft','RingLeft','MiddleLeft','IndexLeft'):
		for i in range(1,4):
			mc.parent(each + 'Loc' +  str(4-i),each + 'Loc' +  str(3-i) )

	mc.parent('WristLeftLoc' ,'ElbowLeftLoc')
	mc.parent('ElbowLeftLoc','ShoulderLeftLoc')
	for each in ('MiddleLeftLoc0','IndexLeftLoc0','ThumbLeftLoc0','RingLeftLoc0','PinkieLeftLoc0'):
		mc.parent(each,'WristLeftLoc')
예제 #32
0
def _buildRearEmitter(name='',
                      boatName='',
                      splashParticleName='',
                      rearAnimatable='',
                      presetName=None):
    """
    New builder for rear nParticle Emitter
    Checks if the NPARTICLE_EMITTLERS_hrc exists or not too

    @param name: The name of the new emitter
    @param splashParticleName: The name of the nParticleShape node for the splash
    @type name:  String
    @type splashParticleName: String
    """
    if not cmds.objExists('nPARTICLE_EMITTERS_hrc'):
        cmds.group(n='nPARTICLE_EMITTERS_hrc', em=True)

    debug(None,
          method='_buildRearEmitter',
          message='name: %s' % name,
          verbose=False)
    cmds.select(
        clear=True
    )  ## Because if you have anything selected maya may freak out it's the wrong damn thing.. f**k you maya seriously!

    ## Build the emitter
    emitter = cmds.emitter(name=name)
    emitter[0] = cmds.ls(emitter[0], long=True)[0]

    if presetName:
        pathToPreset = '%s/%s' % (CONST.EMITTERBASEPRESETPATH, presetName)
        debug(None,
              method='_buildRearEmitter',
              message='emitter: %s' % emitter,
              verbose=False)
        debug(None,
              method='_buildRearEmitter',
              message='pathToPreset: %s' % pathToPreset,
              verbose=False)

        ## Apply the preset to the emitter
        try:
            mel.eval('applyPresetToNode "%s" "" "" "%s" 1;' %
                     (emitter[0], pathToPreset))
            debug(None,
                  method='_buildRearEmitter',
                  message='Mel preset applied to %s: %s' %
                  (emitter[0], pathToPreset),
                  verbose=False)
        except RuntimeError:
            pass

    ## Now parent it
    try:
        emitter[0] = cmds.parent(emitter[0], 'nPARTICLE_EMITTERS_hrc')[0]
    except:
        pass

    ## Connect the emitter to the particles
    _connect_NParticleShape_to_NParticleEmitter(
        particleShapeNode=splashParticleName, emitter=emitter[0])

    ## Now do the expression for the rear emitter
    expStringList = [
        'float $minSpeed = %s.minSpeed;\n' % rearAnimatable,
        'float $maxSpeed = %s.maxSpeed;\n' % rearAnimatable,
        'float $speed = %s:world_ctrl.speed;\n' % boatName,
        'float $curve = smoothstep($minSpeed, $maxSpeed, $speed);\n',
        'float $rateMuliplier = %s.rateMultiplier;\n' % rearAnimatable,
        'float $splashMaxSpeed = %s.splashMaxSpeed;\n' % rearAnimatable,
        '\n',
        'if (%s.useSpeed == 1)\n' % rearAnimatable,
        '{\n\t',
        '%s.rate = $rateMuliplier * $curve;\n\t\t' % emitter[0],
        '\n\t\t',
        'float $emitterSpeed = $splashMaxSpeed * $curve;\n\t\t',
        'if ($emitterSpeed == 0)\n\t\t',
        '{\n\t\t\t',
        '$emitterSpeed = 0.1;\n\t\t',
        '}\n\t\t',
        '%s.alongAxis = $emitterSpeed;\n' % emitter[0],
        '}\n',
        'else\n',
        '{\n\t',
        '%s.rate = $rateMuliplier;\n\t' % emitter[0],
        '%s.alongAxis = $splashMaxSpeed;\n' % emitter[0],
        '}\n',
    ]
    ## Check if the expression already exists in the scene, if so delete it
    # utils.checkExpressionExists('%s_rearEmitter' % boatName)

    ## Build new expression
    cmds.expression(emitter[0],
                    n='%s_rearEmitter' % boatName,
                    string=utils.processExpressionString(expStringList))

    ## Connect some attributes
    if not cmds.isConnected('%s.randomSpeed' % rearAnimatable,
                            '%s.speedRandom' % emitter[0]):
        cmds.connectAttr('%s.randomSpeed' % rearAnimatable,
                         '%s.speedRandom' % emitter[0])
    if not cmds.isConnected('%s.randomDirection' % rearAnimatable,
                            '%s.randomDirection' % emitter[0]):
        cmds.connectAttr('%s.randomDirection' % rearAnimatable,
                         '%s.randomDirection' % emitter[0])

    return emitter[0]
예제 #33
0
def _buildSideSplashEmitter(name='',
                            boatName='',
                            splashParticleName=[],
                            boatIntersectCurveShape='',
                            sideAnimatable='',
                            presetName=None):
    """
    New builder for sideSplash nParticle Emitter
    Checks if the NPARTICLE_EMITTLERS_hrc exists or not too

    @param name: The name of the new emitter
    @param splashParticleName: List of the names of nParticleShape nodes to connect to the emitter
    @param boatIntersectCurveShape: The name of the intersection curve to emit from.
    @type name:  String
    @type splashParticleName: List
    @type boatIntersectCurveShape: String
    """
    if not cmds.objExists('nPARTICLE_EMITTERS_hrc'):
        cmds.group(n='nPARTICLE_EMITTERS_hrc', em=True)

    debug(None,
          method='_buildSideSplashEmitter',
          message='name: %s' % name,
          verbose=False)

    # Get base flat surface
    lineCurve = cmds.curve(name='%s_extrudeCurve' % name,
                           degree=1,
                           point=[(-0.01, 0, 0), (0.01, 0, 0)])
    flatSurface = cmds.extrude(lineCurve,
                               boatIntersectCurveShape,
                               name='%s_flatSurface' % name,
                               constructionHistory=True,
                               range=False,
                               polygon=0,
                               useComponentPivot=1,
                               fixedPath=True,
                               useProfileNormal=True,
                               extrudeType=2,
                               reverseSurfaceIfPathReversed=True)[0]
    cmds.rebuildSurface(flatSurface,
                        constructionHistory=True,
                        replaceOriginal=True,
                        rebuildType=0,
                        endKnots=1,
                        keepCorners=False,
                        spansU=1,
                        degreeU=1,
                        spansV=100,
                        degreeV=3)

    # Offset upwards curve from surface
    offsetUp = cmds.offsetCurve('%s.u[0.5]' % flatSurface,
                                name='%s_offsetUp' % name,
                                distance=0,
                                constructionHistory=True,
                                range=0,
                                subdivisionDensity=1)[0]
    cmds.rebuildCurve(offsetUp,
                      constructionHistory=False,
                      replaceOriginal=True,
                      end=1,
                      keepRange=0,
                      keepControlPoints=True,
                      degree=1)
    cmds.setAttr('%s.translateY' % offsetUp, 0.01)

    # Offset from upwards curve with distance and translate down to get the 45 degree angle
    offset_distance = -0.01
    offsetOut = cmds.offsetCurve(offsetUp,
                                 name='%s_offsetOut' % name,
                                 distance=offset_distance,
                                 constructionHistory=True,
                                 range=0,
                                 subdivisionDensity=1)[0]
    cmds.setAttr('%s.translateY' % offsetOut, offset_distance)

    # Finally, loft a non-flipping surface solution (45 degree angle of the boat)
    noFlipSurface = cmds.loft(offsetUp,
                              offsetOut,
                              degree=1,
                              constructionHistory=True,
                              range=0,
                              polygon=0,
                              sectionSpans=1)[0]
    noFlipSurface = cmds.rename(noFlipSurface, '%s_noFlipSurface' % name)

    ## Build the emitter
    emitter = cmds.emitter(noFlipSurface,
                           name='%s_emitter' % name,
                           type='surface')

    # Create closestPointOnSurface for acceleration expression where front more acceleration
    cPoS = cmds.createNode('closestPointOnSurface', name='%s_cPoS' % name)
    cmds.connectAttr('%s.worldSpace' % noFlipSurface, '%s.inputSurface' % cPoS)

    ## Build the emitter group if it doesn't already exist
    emitterGroup = '%s_hrc' % name
    if not cmds.objExists(emitterGroup):
        cmds.group(lineCurve,
                   flatSurface,
                   offsetUp,
                   offsetOut,
                   noFlipSurface,
                   emitter[0],
                   n=emitterGroup)
    debug(None,
          method='_buildSideSplashEmitter',
          message='emitterName: %s' % emitter[1],
          verbose=False)

    ## Check if a custom preset has been assigned via the func flags for the emitter, if not use the default preset...
    if presetName:
        pathToPreset = '%s/%s' % (CONST.EMITTERBASEPRESETPATH, presetName)
        debug(None,
              method='_buildSideSplashEmitter',
              message='pathToPreset: %s' % pathToPreset,
              verbose=False)
        mel.eval('applyPresetToNode "%s" "" "" "%s" 1;' %
                 (emitter[1], pathToPreset))

    ## Now parent it
    try:
        cmds.parent(emitterGroup, 'nPARTICLE_EMITTERS_hrc')
    except:
        pass

    ## Connect the emitter to the particles
    debug(None,
          method='_buildSideSplashEmitter',
          message='Connected %s: %s' % (splashParticleName, emitter[1]),
          verbose=False)
    for each in splashParticleName:
        _connect_NParticleShape_to_NParticleEmitter(particleShapeNode=each,
                                                    emitter=emitter[1])

    ## Now do the expression for the side emitter
    if 'IntersectCurveRight' in emitter[1]:
        direction = 'R'
    else:
        direction = 'L'

    expStringList = [
        'float $minSpeed = %s.minSpeed;\n' % sideAnimatable,
        'float $maxSpeed = %s.maxSpeed;\n' % sideAnimatable,
        'float $speed = %s:world_ctrl.speed;\n' % boatName,
        'float $curve = smoothstep($minSpeed, $maxSpeed, $speed);\n',
        'float $rateMuliplier = %s.rateMultiplier%s;\n' %
        (sideAnimatable, direction),
        'float $splashMaxSpeed = %s.splashMaxSpeed%s;\n' %
        (sideAnimatable, direction),
        '\n',
        'if (%s.useSpeed == 1)\n' % sideAnimatable,
        '{\n\t',
        '%s.rate = $rateMuliplier * $curve;\n' % emitter[1],
        '\n\t\t',
        'float $emitterSpeed = $splashMaxSpeed * $curve;\n\t\t',
        'if ($emitterSpeed == 0)\n\t\t',
        '{\n\t\t\t',
        '$emitterSpeed = 0.1;\n\t\t',
        '}\n\t\t',
        '%s.speed = $emitterSpeed;\n' % emitter[1],
        '}\n',
        'else\n',
        '{\n\t',
        '%s.rate = $rateMuliplier;\n\t' % emitter[1],
        '%s.speed = $splashMaxSpeed;\n' % emitter[1],
        '}\n',
    ]
    ## Check if the expression already exists in the scene, if so delete it
    utils.checkExpressionExists('%s_sideSplashEmitter' % boatName)

    ## Build new expression
    cmds.expression(emitter[1],
                    n='%s_sideSplashEmitter' % emitter[1],
                    string=utils.processExpressionString(expStringList))

    ## Connect some attributes
    if not cmds.isConnected('%s.normalSpeed%s' % (sideAnimatable, direction),
                            '%s.normalSpeed' % emitter[1]):
        cmds.connectAttr('%s.normalSpeed%s' % (sideAnimatable, direction),
                         '%s.normalSpeed' % emitter[1])
    if not cmds.isConnected('%s.randomSpeed%s' % (sideAnimatable, direction),
                            '%s.speedRandom' % emitter[1]):
        cmds.connectAttr('%s.randomSpeed%s' % (sideAnimatable, direction),
                         '%s.speedRandom' % emitter[1])

    return cPoS
예제 #34
0
         smdName = util.names.nodeName('softMod', baseName)
 else:
     smdName = util.names.nodeName('softMod', baseName)
         
 vtxPlug = mesh
 mesh = mel.eval('plugNode("{0}")'.format(str(vtxPlug)))
 if vtxPlug != mesh:
     softModPos = cmds.xform(vtxPlug, ws=1, t=1, q=1)
 else:
     softModPos = cmds.xform(mesh, ws=1, rp=1, q=1)
 
 # Piv ctl
 softModCenterCtlGrp = cmds.createNode('transform',
     n=util.names.nodeName('transform', '{0}PivotGrp'.format(baseName)))
 softModCenterCtl = cmds.spaceLocator(n=util.names.nodeName('transform', '{0}Pivot'.format(baseName)))[0]
 cmds.parent(softModCenterCtl, softModCenterCtlGrp)
 locatorShape = cmds.listRelatives(softModCenterCtl, children=1, type='locator')[0]
 grpParent = softModCenterCtlGrp
 
 # Soft Mod ctl
 softModCtlGrp = cmds.createNode('transform',
     n=util.names.nodeName('transform', '{0}Grp'.format(baseName)))
 softModCtl = cmds.circle(
     n=util.names.nodeName('transform', '{0}'.format(baseName)))[0]
 cmds.parent(softModCtl, softModCtlGrp)
 cmds.parent(softModCtlGrp, softModCenterCtl)
 
 meshConnections = cmds.listConnections('{0}.inMesh'.format(mesh), s=1, d=0, plugs=1)
 if attachToMesh and meshConnections:
     # Create a transform constrained to the mesh
     rivetGrp = cmds.createNode('transform',
예제 #35
0
def createParamTracker(selection = [],name = '',startVector = [1,0,0]):
    
    if not len(selection) == 2:
        om.MGlobal.displayError('Wrong Selection: select parent and driver.')
        
    else:
        parentObj = selection[0]
        drivingObj = selection[1]
        
        position = cmds.xform(drivingObj,q = True, ws = True,rp = True)
        rotation = cmds.xform(drivingObj,q = True, ws = True,rotation = True)
        
        paramTrackerGrp = cmds.group(empty = True,name = '%s_Grp'%name)
        cmds.move(position[0],position[1],position[2],paramTrackerGrp,ws = True)
        
        cmds.parentConstraint(parentObj,paramTrackerGrp,mo = True)
        
        null = cmds.group(name = '%s_Tracking_Null'%name,empty = True)
        nullGrp = cmds.group(n = '%s_Tracking_Grp'%name,empty = True)
        cmds.move(position[0],position[1],position[2],nullGrp,ws = True)
        #cmds.move(startVector[0],startVector[1],startVector[2],nullGrp,os = True)
        cmds.parent(null,nullGrp)
        cmds.parent(nullGrp, paramTrackerGrp)
        locator = cmds.spaceLocator(n = '%s_Tracking_Loc'%name)[0]
        cmds.parent(locator,nullGrp)
        pointOnSurfaceNode = cmds.createNode('closestPointOnSurface',name = '%s_POS'%name)
        plane = cmds.nurbsPlane(n = '%s_Tracking_Surface'%name,w = 2)[0]
        cmds.rotate(rotation[0],rotation[1],rotation[2],plane,ws = True)
        planeShape = cmds.listRelatives(plane,type = 'shape')[0]
        
        cmds.parent(null,paramTrackerGrp,r = True)
        cmds.parent(plane,paramTrackerGrp,r = True)
        
        cmds.move(startVector[0],startVector[1],startVector[2],null,os = True)
        cmds.parentConstraint(drivingObj,null,mo = True)
        
        cmds.connectAttr('%s.worldSpace[0]'%planeShape,'%s.inputSurface'%pointOnSurfaceNode)
        
        cmds.addAttr(locator,ln = 'uValue',at = 'double')
        cmds.setAttr('%s.uValue'%locator,e = True,keyable = True)
        
        cmds.addAttr(locator,ln = 'vValue',at = 'double')
        cmds.setAttr('%s.vValue'%locator,e = True,keyable = True)
        
        cmds.connectAttr('%s.parameterU'%pointOnSurfaceNode,'%s.uValue'%locator)
        cmds.connectAttr('%s.parameterV'%pointOnSurfaceNode,'%s.vValue'%locator)
        
        decomposeMatrix = cmds.createNode('decomposeMatrix',n = '%s_DM'%name)
        cmds.connectAttr('%s.worldMatrix[0]'%locator,'%s.inputMatrix'%decomposeMatrix)
        cmds.connectAttr('%s.outputTranslate'%decomposeMatrix,'%s.inPosition'%pointOnSurfaceNode)
        
        rivetNodes = cmds.kSurfaceRivetCmd(s = planeShape)
        cmds.rename(rivetNodes[0],'%s_Rivet'%name)
        cmds.rename(rivetNodes[1],'%s_Rivet_Loc'%name)
        
        rivetNodes[0] = '%s_Rivet'%name
        rivetNodes[1] = '%s_Rivet_Loc'%name
        closestPointOnSurface = cmds.createNode('closestPointOnSurface',n = '%s_CPS'%name)
        cmds.connectAttr('%s.outputTranslate'%decomposeMatrix, '%s.inPosition'%closestPointOnSurface)
        cmds.connectAttr('%s.worldSpace[0]'%planeShape,'%s.inputSurface'%closestPointOnSurface)
        cmds.connectAttr('%s.result.parameterU'%closestPointOnSurface,'%s.uValue'%rivetNodes[0])
        cmds.connectAttr('%s.result.parameterV'%closestPointOnSurface,'%s.vValue'%rivetNodes[0])
예제 #36
0
def Arm_R():
    Scale_Guide = cmds.xform('Guide_Ctrl_Master', ws=True, q=True, s=True)[0]
    #J_Clavicle_R#
    translate_Guide_Clavicle_R = cmds.xform('Loc_Guide_Clavicle_R',
                                            ws=True,
                                            q=True,
                                            t=True)
    rot_Guide_Clavicle_R = cmds.xform('Loc_Guide_Clavicle_R',
                                      ws=True,
                                      q=True,
                                      ro=True)
    J_Clavicle_R = cmds.joint(n=('J_Clavicle_R'),
                              p=translate_Guide_Clavicle_R,
                              rad=.7 * Scale_Guide)
    cmds.mirrorJoint(myz=True, mb=True)
    cmds.delete('J_Clavicle_R')
    Rename_FK = mel.eval('searchReplaceNames("_R1","_R","all")')
    cmds.select(d=True)
    Z_J_Clavicle_R = cmds.group(n=("Z_J_Clavicle_R"), em=True)
    translate_J_Clavicle_R = cmds.xform('J_Clavicle_R',
                                        ws=True,
                                        q=True,
                                        t=True)
    rot_J_Clavicle_R = cmds.xform('J_Clavicle_R', ws=True, q=True, ro=True)
    emparentarTrans_J_Clavicle_R = cmds.xform(Z_J_Clavicle_R,
                                              ws=True,
                                              t=translate_J_Clavicle_R)
    emparentarRot_J_Clavicle_R = cmds.xform(Z_J_Clavicle_R,
                                            ws=True,
                                            ro=rot_J_Clavicle_R)
    cmds.parent(J_Clavicle_R, Z_J_Clavicle_R)
    cmds.select(d=True)
    #R_Clavicle_CTL#
    translate_Clavicle_R = cmds.xform('J_Clavicle_R', ws=True, q=True, t=True)
    rot_Clavicle_R = cmds.xform('J_Clavicle_R', ws=True, q=True, ro=True)
    emparentarTrans_Clavicle_R = cmds.xform('P_R_Clavicle_CTL',
                                            ws=True,
                                            t=translate_Clavicle_R)
    emparentarRot_Clavicle_R = cmds.xform('P_R_Clavicle_CTL',
                                          ws=True,
                                          ro=rot_Clavicle_R)
    cmds.parentConstraint('R_Clavicle_CTL', 'J_Clavicle_R', mo=True)
    cmds.select(d=True)
    ##Joints Arm_R##
    #J_ARM_R#
    trans_Guide_Arm_R = cmds.xform('Loc_Guide_Arm_R', ws=True, q=True, t=True)
    translate_Guide_ForeArm_R = cmds.xform('Loc_Guide_ForeArm_R',
                                           ws=True,
                                           q=True,
                                           t=True)
    translate_Guide_Hand_R = cmds.xform('Loc_Guide_Hand_R',
                                        ws=True,
                                        q=True,
                                        t=True)
    Joint_Arm_Neutral_R = cmds.joint(n='J_Arm_Neutral_R',
                                     p=trans_Guide_Arm_R,
                                     rad=1 * Scale_Guide)
    Joint_ForeArm_Neutral_R = cmds.joint(n='J_ForeArm_Neutral_R',
                                         p=translate_Guide_ForeArm_R,
                                         rad=1 * Scale_Guide)
    Joint_Hand_Neutral_R = cmds.joint(n='J_Hand_Neutral_R',
                                      p=translate_Guide_Hand_R,
                                      rad=1 * Scale_Guide)
    OJ_Joint_Arm_Neutral_R = cmds.joint('J_Arm_Neutral_R',
                                        e=True,
                                        zso=True,
                                        oj='xzy',
                                        sao='zup')
    OJ_Joint_ForeArm_Neutral_R = cmds.joint('J_ForeArm_Neutral_R',
                                            e=True,
                                            zso=True,
                                            oj='xzy',
                                            sao='zup')
    OJ_Joint_Hand_Neutral_R = cmds.joint('J_Hand_Neutral_R',
                                         e=True,
                                         zso=True,
                                         oj='xzy',
                                         sao='zup')
    joX_Hand_R = cmds.setAttr("J_Hand_Neutral_R.jointOrientX", 0)
    joY_Hand_R = cmds.setAttr("J_Hand_Neutral_R.jointOrientY", 0)
    joZ_Hand_R = cmds.setAttr("J_Hand_Neutral_R.jointOrientZ", 0)
    cmds.select(Joint_Arm_Neutral_R)
    cmds.mirrorJoint(myz=True, mb=True)
    cmds.delete('J_Arm_Neutral_R')
    Rename_FK = mel.eval('searchReplaceNames("_R1","_R","all")')
    cmds.select(d=True)
    rot_J_Arm_Neutral_R = cmds.xform('J_Arm_Neutral_R',
                                     ws=True,
                                     q=True,
                                     ro=True)
    trans_J_Arm_Neutral_R = cmds.xform('J_Arm_Neutral_R',
                                       ws=True,
                                       q=True,
                                       t=True)
    Z_J_Arm = cmds.group(n='Z_J_Arm_Neutral_R', em=True)
    P_J_Arm = cmds.group(n='P_J_Arm_Neutral_R')
    emparentarTrans = cmds.xform('P_J_Arm_Neutral_R',
                                 ws=True,
                                 t=trans_J_Arm_Neutral_R)
    emparentarRot = cmds.xform('P_J_Arm_Neutral_R',
                               ws=True,
                               ro=rot_J_Arm_Neutral_R)
    P_J_Arm_Neutral_R_Z_J_Arm_Neutral_R = cmds.parent('J_Arm_Neutral_R',
                                                      'Z_J_Arm_Neutral_R')
    cmds.select(d=True)
    Activar_color = cmds.setAttr('P_J_Arm_Neutral_R.overrideEnabled', 1)
    Blanco = cmds.setAttr('P_J_Arm_Neutral_R.overrideColor', 16)
    #duplicate the originaR chain
    Duplicar_a_FK = cmds.duplicate(P_J_Arm, rc=True)
    Duplicar_a_IK = cmds.duplicate(P_J_Arm, rc=True)
    #rename the chain
    Rename_FK = mel.eval('searchReplaceNames("_Neutral_R1","_FK_R","all")')
    Rename_IK = mel.eval('searchReplaceNames("_Neutral_R2","_IK_R","all")')
    #Change color Herarchy FK_IK
    Activar_color = cmds.setAttr(('P_J_Arm_FK_R.overrideEnabled'), 1)
    Azul = cmds.setAttr('P_J_Arm_FK_R.overrideColor', 6)
    Activar_color = cmds.setAttr('P_J_Arm_IK_R.overrideEnabled', 1)
    Amarillo = cmds.setAttr('P_J_Arm_IK_R.overrideColor', 17)

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

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

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

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

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

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

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

    fun('rotate')
    fun('translate')
    #Cons_Orient_Ik_Hand_J_Hand_R
    cmds.duplicate('J_Hand_IK_R', n='Eff_J_Hand_IK_R')
    cmds.move(Scale_Guide * (-2),
              0,
              0,
              'Eff_J_Hand_IK_R',
              r=True,
              os=True,
              wd=True)
    cmds.parent('Eff_J_Hand_IK_R', 'J_Hand_IK_R')
    cmds.ikHandle(n='IkHandle_Wrist_R',
                  sj='J_Hand_IK_R',
                  ee='Eff_J_Hand_IK_R',
                  sol='ikSCsolver')
    cmds.parent('IkHandle_Wrist_R', 'R_IK_Arm_CTL')
    cmds.hide('IkHandle_Wrist_R')
    cmds.select(cl=True)
    Parent_Cons_FK_Ctrl_J_Ik_Arm = cmds.parentConstraint('R_FK_Arm_CTL',
                                                         'J_Arm_IK_R',
                                                         mo=True)
    Herarchy_Switch_Arm_R_J_Hand_Neutral_R = cmds.parent(
        'P_R_SwitchArm_CTL', 'J_Hand_Neutral_R')
    translate_J_ForeArm_Ik_R = cmds.xform('J_ForeArm_IK_R',
                                          ws=True,
                                          q=True,
                                          t=True)
    translate_Ctrl_Polevector_Arm_R = cmds.xform('R_PolevectorArm_CTL',
                                                 ws=True,
                                                 q=True,
                                                 t=True)
    #CVPv_IK_R#
    Cv_Polevector_Arm_R = cmds.curve(n='Cv_Polevector_Arm_R',
                                     d=1,
                                     p=[(translate_J_ForeArm_Ik_R),
                                        (translate_Ctrl_Polevector_Arm_R)],
                                     k=(0, 1))
    Z_Cvv_Polevector_Arm_R = cmds.group(n=("Z_Cv_Polevector_Arm_R"), em=True)
    Herarchy_CV_Grp = cmds.parent('Cv_Polevector_Arm_R',
                                  "Z_Cv_Polevector_Arm_R")
    lineWidth_Cv_Polevector_Arm_R = cmds.setAttr(
        Cv_Polevector_Arm_R + ".lineWidth", 2)
    OvE_Cv_Polevector_Arm_R = cmds.setAttr(
        Cv_Polevector_Arm_R + ".overrideEnabled", 1)
    OvDT_Cv_Polevector_Arm_R = cmds.setAttr(
        Cv_Polevector_Arm_R + ".overrideDisplayType", 2)
    cmds.select(d=True)
    J_CV_0_ARM_R = cmds.joint(p=translate_J_ForeArm_Ik_R, n="J_Cv_0_Arm_R")
    Grp_J_CV_0_ARM_R = cmds.group(n='Z_J_Cv_0_Arm_R')
    cmds.select(d=True)
    J_CV_1_ARM_R = cmds.joint(p=translate_Ctrl_Polevector_Arm_R,
                              n="J_Cv_1_Arm_R")
    Grp_J_CV_1_ARM_R = cmds.group(n='Z_J_Cv_1_Arm_R')
    cmds.select(d=True)
    Skin_J_Cvs = cmds.skinCluster('J_Cv_0_Arm_R',
                                  'J_Cv_1_Arm_R',
                                  'Cv_Polevector_Arm_R',
                                  dr=4)
    Parent_J_CV_Arm_R_J_ForeArm_IK_R = cmds.parent(Grp_J_CV_0_ARM_R,
                                                   'J_ForeArm_IK_R')
    Parent_J_CV_Arm_R_J_ForeArm_IK_R = cmds.parent(Grp_J_CV_1_ARM_R,
                                                   'R_PolevectorArm_CTL')
    cmds.select(d=True)
    #Create Node_Vis_Arm_R#
    Node_Reverse_Vis_Arm_R = cmds.shadingNode('reverse',
                                              au=True,
                                              n='R_Vis_Arm_R')
    Node_MD_Vis_Arm_R = cmds.shadingNode('multiplyDivide',
                                         au=True,
                                         n='MD_Vis_Arm_R')
    Operation_MD_Vis_Arm_R = cmds.setAttr(Node_MD_Vis_Arm_R + '.operation',
                                          2,
                                          k=True)
    Set_2X_Node_MD_Vis_Arm_R = cmds.setAttr(Node_MD_Vis_Arm_R + '.input2X',
                                            10,
                                            k=True)
    #Conect Vis_Arm_R#
    Switch_MD_Arm_R = cmds.connectAttr('R_SwitchArm_CTL.Switch_FK_IK',
                                       Node_MD_Vis_Arm_R + '.input1X')
    MD_R_Arm_R = cmds.connectAttr(Node_MD_Vis_Arm_R + '.outputX',
                                  Node_Reverse_Vis_Arm_R + '.inputX')
    R_Ctrl_FK_Arm_R = cmds.connectAttr(Node_Reverse_Vis_Arm_R + '.outputX',
                                       'P_R_FK_ForeArm_CTL.visibility')
    R_J_FK_Arm_R = cmds.connectAttr(Node_Reverse_Vis_Arm_R + '.outputX',
                                    'P_J_Arm_FK_R.visibility')
    MD_Ctrl_IK_Arm_R = cmds.connectAttr(Node_MD_Vis_Arm_R + '.outputX',
                                        'P_R_IK_Arm_CTL.visibility')
    MD_PV_IK_Arm_R = cmds.connectAttr(Node_MD_Vis_Arm_R + '.outputX',
                                      'R_PolevectorArm_CTL.visibility')
    MD_CV_PV_IK_Arm_R = cmds.connectAttr(Node_MD_Vis_Arm_R + '.outputX',
                                         'Z_Cv_Polevector_Arm_R.visibility')
    MD_J_IK_Arm_R = cmds.connectAttr(Node_MD_Vis_Arm_R + '.outputX',
                                     'P_J_Arm_IK_R.visibility')
예제 #37
0
def freezeCombo(combo):
    """ Freeze a combo so you can change the upstream combos and shapes
    without affecting the result that you sculpted for the given combo

    In practice, this snapshots the combo, then live-reads the upstream
    shapes from the main blendshape and builds an up-to-date combo. The
    difference between these two meshes is added back into the combo shape
    """
    simplex = combo.simplex

    tweakShapeGroups = []
    fullGeos = []
    ppFilter = []

    # disconnect the controller from the operator
    with disconnected(simplex.DCC.op) as sliderCnx:

        for shapeIdx, pp in enumerate(combo.prog.pairs):
            tVal = pp.value
            freezeShape = pp.shape
            if freezeShape.isRest:
                continue

            # zero all the sliders
            cnx = sliderCnx[simplex.DCC.op]
            for a in six.itervalues(cnx):
                cmds.setAttr(a, 0.0)

            # set the combo values
            for pair in combo.pairs:
                cmds.setAttr(cnx[pair.slider.thing], pair.value * tVal)

            tweakPairs = []
            for shape in simplex.shapes[1:]:  # skip the restShape
                shapeVal = cmds.getAttr(shape.thing)
                if abs(shapeVal) > 0.0001:
                    tweakPairs.append((shape, shapeVal))

            # Extract this fully-on shape
            fullGeo = cmds.duplicate(simplex.DCC.mesh,
                                     name="{0}_Freeze".format(
                                         freezeShape.name))[0]
            fullGeos.append(fullGeo)

            # Clean any orig shapes for now
            interObjs = cmds.ls(cmds.listRelatives(fullGeo, shapes=True),
                                intermediateObjects=True)
            cmds.delete(interObjs)

            tweakShapeGroups.append(tweakPairs)
            ppFilter.append(pp)

    simplex.DCC.primeShapes(combo)

    shapePlugFmt = (
        ".inputTarget[{meshIdx}].inputTargetGroup[{shapeIdx}].inputTargetItem[6000]"
    )
    endPlugs = [
        ".inputRelativePointsTarget",
        ".inputRelativeComponentsTarget",
        ".inputPointsTarget",
        ".inputComponentsTarget",
        "",
    ]
    shapeNode = simplex.DCC.shapeNode
    helpers = []
    for geo, tweakPairs, pp in zip(fullGeos, tweakShapeGroups, ppFilter):

        # build the basicBS node
        bbs = cmds.deformer(geo, type="basicBlendShape")[0]
        helpers.append(bbs)
        idx = 0

        for shape, val in tweakPairs:
            if shape == freezeShape:
                continue
            # connect the output shape.thing to the basicBS

            # Create an empty shape. Do it like this to get the automated renaming stuff
            gDup = cmds.duplicate(geo,
                                  name="{0}_DeltaCnx".format(shape.name))[0]
            # The 4th value must be 1.0 so the blendshape auto-names
            cmds.blendShape(bbs, edit=True, target=(geo, idx, gDup, 1.0))
            cmds.blendShape(bbs, edit=True, weight=(idx, -val))
            cmds.delete(gDup)

            # Connect the shape plugs
            inPlug = bbs + shapePlugFmt
            inPlug = inPlug.format(meshIdx=0, shapeIdx=idx)

            shapeIdx = simplex.DCC.getShapeIndex(shape)
            outPlug = shapeNode + shapePlugFmt
            outPlug = outPlug.format(meshIdx=0, shapeIdx=shapeIdx)

            # Must connect the individual child plugs rather than the top
            # because otherwise the input geometry plug overrides these deltas
            for ep in endPlugs:
                cmds.connectAttr(outPlug + ep, inPlug + ep)

            idx += 1

        # Connect the basicBS back into freezeShape
        freezeShapeIdx = simplex.DCC.getShapeIndex(pp.shape)
        freezeShapeTarget = shapeNode + shapePlugFmt + ".inputGeomTarget"
        freezeShapeTarget = freezeShapeTarget.format(meshIdx=0,
                                                     shapeIdx=freezeShapeIdx)
        cmds.connectAttr(geo + ".outMesh", freezeShapeTarget)

        gShapes = cmds.listRelatives(geo, shapes=True)
        if True:
            # Hide the frozen shapenode under the ctrl as an intermediate shape
            for gs in gShapes:
                cmds.setAttr(gs + ".intermediateObject", 1)
                nn = cmds.parent(gs,
                                 simplex.DCC.ctrl,
                                 shape=True,
                                 relative=True)
                helpers.extend(nn)

            # Get rid of the extra transform object
            cmds.delete(geo)
        else:
            helpers.extend(cmds.listRelatives(geo, shapes=True))

    # keep track of the shapes under the ctrl object
    combo.freezeThing = helpers
예제 #38
0
def particleLocators(particle,
                     bakeSimulation=False,
                     rotate=False,
                     scale=False,
                     start=0,
                     end=-1,
                     prefix=''):
    """
    """
    # Check Particle
    if not cmds.objExists(particle):
        raise Exception('Object "' + nParticle +
                        '" is not a valid particle or nParticle object!')

    # Check Prefix
    if not prefix: prefix = particle

    # Get particle count
    count = cmds.getAttr(particle + '.count')
    if not count: raise Exception('Invalid particle count! (' + count + ')')

    # Create locators
    partiLocs = [
        cmds.spaceLocator(n=prefix + '_loc' + str(i))[0] for i in range(count)
    ]
    partiLocsGrp = prefix + '_locGrp'
    if not cmds.objExists(partiLocsGrp):
        partiLocsGrp = cmds.group(em=True, n=partiLocsGrp)
    cmds.parent(partiLocs, partiLocsGrp)

    # For each particle, set locator position
    for i in range(count):
        pt = cmds.pointPosition(particle + '.pt[' + str(i) + ']')
        cmds.setAttr(partiLocs[i] + '.t', *pt)
        if rotate:
            rt = cmds.particle(particle, q=True, at='rotatePP', id=i)
            cmds.setAttr(partiLocs[i] + '.r', *rt)
        if scale:
            sc = cmds.particle(particle, q=True, at='scalePP', id=i)
            cmds.setAttr(partiLocs[i] + '.s', *sc)

    # Bake Simulation
    if (bakeSimulation):

        # Append particle expression
        expStr = '\n\n//--\n'
        expStr += 'int $id = id;\n'
        expStr += 'vector $pos = pos;\n'
        expStr += 'string $loc = ("' + prefix + '_loc"+$id);\n'
        expStr += 'if(`objExists $loc`){'
        expStr += '\t move -a ($pos.x) ($pos.y) ($pos.z) $loc;\n'
        if rotate:
            expStr += '\tvector $rot = rotatePP;\n'
            expStr += '\t rotate -a ($rot.x) ($rot.y) ($rot.z) $loc;\n'
        if scale:
            expStr += '\tvector $scl = scalePP;\n'
            expStr += '\t scale -a ($scl.x) ($scl.y) ($scl.z) $loc;\n'
        expStr += '}'

        # Old expression string
        oldRadStr = cmds.dynExpression(particle, q=True, s=True, rad=True)

        # Apply particle expression
        cmds.dynExpression(particle, s=oldRadStr + expStr, rad=True)

        # Bake to keyframes
        if end < start:
            start = cmds.playbackOptions(q=True, min=True)
            end = cmds.playbackOptions(q=True, max=True)
        bakeAttrs = ['tx', 'ty', 'tz']
        if rotate: bakeAttrs.extend(['rx', 'ry', 'rz'])
        if scale: bakeAttrs.extend(['sx', 'sy', 'sz'])
        cmds.bakeSimulation(partiLocs, at=bakeAttrs, t=(start, end))

        # Restore particle expression
        cmds.dynExpression(particle, s=oldRadStr, rad=True)
예제 #39
0
def BtoT():
	global jnt
	ben = many[j]
	tjo = mc.listRelatives(ben)
	twi = tjo[0]
	if '_L' in '{}'.format(ben):
		a = ben.split('_bend_L')
		for i in get:
			if a[0] in i:
				if '_L' in '{}'.format(i):
					if 'bend' not in '{}'.format(i):
						if 'twist' not in '{}'.format(i):
							jnt = i
	elif '_R' in '{}'.format(ben):
		a = ben.split('_bend_R')
		for i in get:
			if a[0] in i:
				if '_R' in '{}'.format(i):
					if 'bend' not in '{}'.format(i):
						if 'twist' not in '{}'.format(i):
							jnt = i
	else:
		a = ben.split('_bend')
		for i in get:
			if a[0] in i:
				if '_L' not in '{}'.format(i):
					if '_R' not in '{}'.format(i):
						if 'bend' not in '{}'.format(i):
							if 'twist' not in '{}'.format(i):
								jnt = i
	
	if bant >= 1:
		for i in baim:
			if jnt in i:
				roop()

	#create node
	aim = mc.createNode('aimConstraint', n='{}_afterSplitTwistDriver'.format(jnt))
	mc.select('{}'.format(aim), r=True)
	mc.addAttr(ln='bend', nc=3, at='double3')
	mc.addAttr(ln='twist', nc=3, at='double3')
	for i in range(3):
		mc.addAttr(ln='bend{}'.format(xyz[i]), at='doubleAngle', p='bend', k=True)
		mc.addAttr(ln='twist{}'.format(xyz[i]), at='doubleAngle', p='twist', k=True)

	oc1 = mc.createNode('orientConstraint', n='{}_afterSplitTwist'.format(jnt))
	oc2 = mc.createNode('orientConstraint', n='{}_rot'.format(jnt))
	oc3 = mc.createNode('orientConstraint', n='{}_twistRot'.format(jnt))
	pb1 = mc.createNode('pairBlend', n='{}_weightedTwist'.format(jnt))
	mc.addAttr(ln='inRot2', nc=3, at='double3', w=False)
	for i in range(3):
		mc.addAttr(ln='inRot2{}'.format(xyz[0]), at='doubleAngle', p='inRot2', w=False)

	pb2 = mc.createNode('pairBlend', n='{}_rotSafeRot'.format(jnt))
	pb3 = mc.createNode('pairBlend', n='{}_twistRotSafeRot'.format(jnt))

	grp = mc.group('{}'.format(oc1),'{}'.format(oc2),'{}'.format(oc3), n='{}_BendTwist'.format(jnt))
	mc.parent('{}'.format(aim), '{}'.format(jnt))
	mc.parent('{}'.format(grp), '{}'.format(jnt))
	mc.setAttr('{}.visibility'.format(grp), 0)


	#setAttr
	mc.setAttr('{}.target[0].targetTranslateX'.format(aim), 1)
	mc.setAttr('{}.worldUpType'.format(aim), 4)
	mc.setAttr('{}.interpType'.format(oc2), 2)
	mc.setAttr('{}.interpType'.format(oc3), 2)
	mc.setAttr('{}.rotateMode'.format(pb2), 2)
	mc.setAttr('{}.rotateMode'.format(pb3), 2)
	mc.setAttr('{}.rotInterpolation'.format(pb2), 1)
	mc.setAttr('{}.rotInterpolation'.format(pb3), 1)
	for i in range(3):
		mc.setAttr('{0}.translate{1}'.format(aim, xyz[i]), 0)


	#connectAttr
	mc.connectAttr('{}.constraintRotate'.format(aim), '{}.bend'.format(aim))
	mc.connectAttr('{}.constraintRotate'.format(aim), '{}.constraintJointOrient'.format(oc1))
	mc.connectAttr('{}.constraintRotate'.format(oc1), '{}.twist'.format(aim))
	mc.connectAttr('{}.matrix'.format(aim), '{}.target[0].targetParentMatrix'.format(aim))
	mc.connectAttr('{}.matrix'.format(aim), '{}.target[0].targetParentMatrix'.format(oc1))
	mc.connectAttr('{}.bend'.format(aim), '{}.target[0].targetJointOrient'.format(oc2))
	mc.connectAttr('{}.twist'.format(aim), '{}.inRotate1'.format(pb1))
	mc.connectAttr('{}.inRot2'.format(pb1), '{}.inRotate2'.format(pb1))
	mc.connectAttr('{}.outRotate'.format(pb1), '{}.target[0].targetRotate'.format(oc2))
	mc.connectAttr('{}.constraintRotate'.format(oc2), '{}.inRotate2'.format(pb2))
	mc.connectAttr('{}.constraintRotate'.format(oc2), '{}.constraintJointOrient'.format(oc3))
	mc.connectAttr('{}.rotate'.format(jnt), '{}.target[0].targetRotate'.format(oc3))
	mc.connectAttr('{}.constraintRotate'.format(oc3), '{}.inRotate2'.format(pb3))
	mc.connectAttr('{}.twistWeight'.format(twi), '{}.weight'.format(pb1))
	for i in range(3):
		mc.connectAttr('{0}.rotate{1}'.format(jnt, xyz[i]), '{0}.rotate{1}'.format(aim, xyz[i]))
		mc.connectAttr('{0}.translate{1}'.format(jnt, xyz[i]), '{0}.translate{1}'.format(ben, xyz[i]))
		mc.connectAttr('{0}.scale{1}'.format(jnt, xyz[i]), '{0}.scale{1}'.format(ben, xyz[i]))
		mc.connectAttr('{0}.shear{1}'.format(jnt, she[i]), '{0}.shear{1}'.format(ben, she[i]))
		mc.connectAttr('{0}.scale{1}'.format(ben, xyz[i]), '{0}.scale{1}'.format(twi, xyz[i]))
		mc.connectAttr('{0}.outRotate{1}'.format(pb2, xyz[i]), '{0}.rotate{1}'.format(ben, xyz[i]))
		mc.connectAttr('{0}.outRotate{1}'.format(pb3, xyz[i]), '{0}.rotate{1}'.format(twi, xyz[i]))

	roop()
예제 #40
0
파일: clavicle.py 프로젝트: jonntd/glTools
def build(startJoint,
          endJoint,
          clavOrient='',
          ctrlRotate=(0, 0, 0),
          prefix=''):
    '''
	@param startJoint: Clavicle start joint
	@type startJoint: str
	@param endJoint: Clavicle end joint
	@type endJoint: str
	@param scaleAttr: Global character scale attribute
	@type scaleAttr: str
	@param clavOrient: Clavicle orient transform
	@type clavOrient: str
	@param clavOrient: Rotate clavicle control shape
	@type clavOrient: list or tuple
	@param prefix: Name prefix for new nodes
	@type prefix: str
	'''

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

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

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

    scaleAxis = 'x'

    rotateCtrlScale = 0.5
    transCtrlScale = 0.2

    blendAttr = 'stretchToControl'

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

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

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

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

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

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

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

    mc.select(cl=True)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    # Define control list
    ctrlList = [clavRotateCtrl, clavTransCtrl]

    return [module, attachJoint]
예제 #41
0
    def testExportProxyShapes(self):
        import AL.usdmaya

        tempFile = tempfile.NamedTemporaryFile(
            suffix=".usda",
            prefix="AL_USDMayaTests_exportProxyShape_",
            delete=False)
        tempFile.close()

        mc.createNode("transform", n="world")
        mc.createNode("transform", n="geo", p="world")

        # create one proxyShape with a time offset
        mc.select(clear=1)
        proxyShapeNode = mc.AL_usdmaya_ProxyShapeImport(
            file="{}/sphere2.usda".format(os.environ.get('TEST_DIR')))[0]
        proxyShape = AL.usdmaya.ProxyShape.getByName(proxyShapeNode)
        proxyParentNode1 = mc.listRelatives(proxyShapeNode,
                                            fullPath=1,
                                            parent=1)[0]
        proxyParentNode1 = mc.parent(proxyParentNode1, "geo")[0]
        print(proxyParentNode1)
        # force the stage to load
        stage = proxyShape.getUsdStage()
        self.assertTrue(stage)

        # check that, with no time offset or scalar, we get the rotateZ values set
        # in the .usda
        sphereShape1Prim = stage.GetPrimAtPath("/pSphere1/pSphereShape1")
        sphereShape1Maya = proxyShape.makeUsdTransformChain(sphereShape1Prim)

        rotateZUsd = sphereShape1Prim.GetAttribute("xformOp:rotateZ")
        rotateZMaya = '{}.rotateZ'.format(sphereShape1Maya)
        expected_unaltered_rotate_z = {
            -1: 0,
            0: 0,
            2: 180,
            4: 360,
            5: 360,
        }
        for stage_time, expected_rotate in expected_unaltered_rotate_z.items():
            self.assertAlmostEqual(expected_rotate, rotateZUsd.Get(stage_time))
            mc.currentTime(stage_time)
            self.assertAlmostEqual(expected_rotate, mc.getAttr(rotateZMaya))

        timeOffset = 40
        timeScalarAL = 2
        mc.setAttr(proxyShapeNode + ".timeOffset", timeOffset)
        mc.setAttr(proxyShapeNode + ".timeScalar", timeScalarAL)

        # Now check that, with the time offset + scalar applied, we get
        # values at different times - note that the proxy shape interprets
        # a "timeScalar = 2" to mean the shape is fast-forwarded twice as fast,
        # so:
        #    layer_time = (maya_time - offset) * scalarAL
        #    maya_time = layer_time / scalarAL + offset
        expected_retimed_rotate_z = {
            39: 0,
            40: 0,
            41: 180,
            42: 360,
            43: 360,
        }
        for stage_time, expected_rotate in expected_retimed_rotate_z.items():
            mc.currentTime(stage_time)
            self.assertAlmostEqual(expected_rotate, mc.getAttr(rotateZMaya))

        # if we don't remove this, the reference gets made at:
        #     /world/geo/AL_usdmaya_Proxy/AL_usdmaya_ProxyShape
        # instead of the (collapsed):
        #     /world/geo/AL_usdmaya_Proxy
        proxyShape.removeUsdTransformChain(sphereShape1Prim)

        # create another proxyShape with a few session layer edits
        mc.select(clear=1)
        proxyShapeNode2 = mc.AL_usdmaya_ProxyShapeImport(
            file="{}/sphere2.usda".format(os.environ.get('TEST_DIR')))[0]
        proxyShape2 = AL.usdmaya.ProxyShape.getByName(proxyShapeNode2)
        proxyParentNode2 = mc.listRelatives(proxyShapeNode2,
                                            fullPath=1,
                                            parent=1)[0]
        proxyParentNode2 = mc.parent(proxyParentNode2, "geo")[0]
        print(proxyParentNode2)
        # force the stage to load
        stage2 = proxyShape2.getUsdStage()
        self.assertTrue(stage2)

        session = stage2.GetSessionLayer()
        stage2.SetEditTarget(session)
        extraPrimPath = "/pExtraPrimPath"
        firstSpherePath = "/pSphereShape1"
        secondSpherePath = "/pSphereShape2"
        stage2.DefinePrim("/pSphere1" + extraPrimPath)
        existingSpherePath = "/pSphere1" + secondSpherePath
        self.assertTrue(stage2.GetPrimAtPath(existingSpherePath))
        stage2.DefinePrim(existingSpherePath).SetActive(False)

        mc.select("world")
        mc.usdExport(f=tempFile.name)

        resultStage = Usd.Stage.Open(tempFile.name)
        self.assertTrue(resultStage)
        rootLayer = resultStage.GetRootLayer()

        refPrimPath = "/world/geo/" + proxyParentNode1
        refPrimPath2 = "/world/geo/" + proxyParentNode2
        print("Ref Prim Path 1: " + refPrimPath)
        print("Ref Prim Path 2: " + refPrimPath2)
        print("Resulting stage contents:")
        print(rootLayer.ExportToString())

        # Check proxyShape1
        # make sure references were created and that they have correct offset + scale
        refSpec = rootLayer.GetPrimAtPath(refPrimPath)
        self.assertTrue(refSpec)
        self.assertTrue(refSpec.hasReferences)
        refs = refSpec.referenceList.GetAddedOrExplicitItems()
        self.assertEqual(refs[0].layerOffset,
                         Sdf.LayerOffset(timeOffset, 1.0 / timeScalarAL))

        # and check that the animated values are properly offset
        resultSphereShape1Prim = resultStage.GetPrimAtPath(refPrimPath +
                                                           firstSpherePath)
        rotateZUsd = resultSphereShape1Prim.GetAttribute("xformOp:rotateZ")
        for stage_time, expected_rotate in expected_retimed_rotate_z.items():
            self.assertAlmostEqual(expected_rotate, rotateZUsd.Get(stage_time))

        # Check proxyShape2
        # make sure the session layer was properly grafted on
        refPrim2 = resultStage.GetPrimAtPath(refPrimPath2)
        self.assertTrue(refPrim2.IsValid())
        self.assertEqual(refPrim2.GetTypeName(), "Xform")
        self.assertEqual(refPrim2.GetSpecifier(), Sdf.SpecifierDef)

        refSpec2 = rootLayer.GetPrimAtPath(refPrimPath2)
        self.assertTrue(refSpec2)
        self.assertTrue(refSpec2.hasReferences)
        # ref root should be a defined xform on the main export layer also
        self.assertEqual(refSpec2.typeName, "Xform")
        self.assertEqual(refSpec2.specifier, Sdf.SpecifierDef)

        spherePrimPath = refPrimPath2 + secondSpherePath
        spherePrim = resultStage.GetPrimAtPath(spherePrimPath)
        self.assertTrue(spherePrim.IsValid())
        self.assertFalse(spherePrim.IsActive())
        # check that the proper specs are being created
        specOnExportLayer = rootLayer.GetPrimAtPath(spherePrimPath)
        self.assertEqual(specOnExportLayer.specifier, Sdf.SpecifierOver)

        os.remove(tempFile.name)
예제 #42
0
    def install(self):
        if cmds.objExists(self.module_info['rootname'][0].replace('s_', self.instance)+'_M_GRP') == True:
            return 
        # Create a master group
        self.rig_info['mastergrp'] = cmds.group(n=self.module_info['rootname'][0].replace('s_', self.instance)+'_M_GRP', em=True)
        cmds.xform(self.rig_info['mastergrp'], ws=True, t=self.rig_info['positions'][0])
        # Create a world group
        self.rig_info['worldgrp'] = cmds.group(n=self.module_info['rootname'][0].replace('s_', self.instance)+'_W_GRP', em=True)
        cmds.xform(self.rig_info['worldgrp'], ws=True, t=self.rig_info['positions'][0])
        # Create a local group
        self.rig_info['localgrp'] = cmds.group(n=self.module_info['rootname'][0].replace('s_', self.instance)+'_L_GRP', em=True)
        cmds.xform(self.rig_info['localgrp'], ws=True, t=self.rig_info['positions'][0])

        cmds.parent(self.rig_info['worldgrp'], self.rig_info['mastergrp'])
        cmds.parent(self.rig_info['localgrp'], self.rig_info['mastergrp'])

        cmds.select(d=True)

        #Try duplicate joint method
        self.rig_info['ikjnts']=utils.duplicateJoints(self.rig_info['seljnts'], self.module_info['ikjnts'], self.instance)
        cmds.parent(self.rig_info['ikjnts'][0], self.rig_info['localgrp'])

        self.rig_info['fkjnts']=utils.duplicateJoints(self.rig_info['seljnts'], self.module_info['fkjnts'], self.instance)
        cmds.parent(self.rig_info['fkjnts'][0], self.rig_info['localgrp'])

        self.rig_info['rigjnts']=utils.duplicateJoints(self.rig_info['seljnts'], self.module_info['rigjnts'], self.instance)
        cmds.parent(self.rig_info['rigjnts'][0], self.rig_info['localgrp'])
        
        # Make a control for arm settings
        lockattrs = (['.tx', '.ty', '.tz', '.rx', '.ry', '.rz', '.sx', '.sy', '.sz'])
        setctrlname = self.module_info["settingscontrol"][0].replace('s_', self.instance)
        self.rig_info['setcontrol']=utils.createControl([[self.rig_info['positions'][2], setctrlname, 'SettingsControl.ma', lockattrs]])[0]
        cmds.addAttr(self.rig_info['setcontrol'][1], shortName='IK_FK', longName='Ik_Fk', defaultValue=1, min=0, max=1, k=True)
        cmds.addAttr(self.rig_info['setcontrol'][1], shortName='stretch', longName='Stretchy', defaultValue=0, min=0, max=1, k=True)
        cmds.addAttr(self.rig_info['setcontrol'][1], shortName='Root_Length', longName='Root_Length', defaultValue=0, min=-5, max=5, k=True)
        cmds.addAttr(self.rig_info['setcontrol'][1], shortName='End_Length', longName='End_Length', defaultValue=0, min=-5, max=5, k=True)
        cmds.parent(self.rig_info['setcontrol'][2], self.rig_info['localgrp'])

        # Connect Ik and Fk to Rig joints
        switchattr = self.rig_info['setcontrol'][1] + '.IK_FK'
        self.rig_info['bcnodes'] = utils.connectThroughBC(self.rig_info['ikjnts'], self.rig_info['fkjnts'], self.rig_info['rigjnts'], self.instance, switchattr )
        
        # Create Ik Rig
        lockattrs = (['.sx', '.sy', '.sz'])
        ikctrlname = self.module_info["ikcontrols"][0].replace('s_', self.instance)
        self.rig_info['ikcontrol']=utils.createControl([[self.rig_info['positions'][2], ikctrlname, 'HandControl.ma', lockattrs]])[0]
        cmds.parent(self.rig_info['ikcontrol'][2], self.rig_info['localgrp'])
        
        lockattrs = (['.rx', '.ry', '.rz', '.sx', '.sy', '.sz'])
        pvpos = utils.calculatePVPosition([self.rig_info['ikjnts'][0], self.rig_info['ikjnts'][1], self.rig_info['ikjnts'][2]])
        pvctrlname = self.module_info["ikcontrols"][2].replace('s_', self.instance)
        self.rig_info['pvcontrol']=utils.createControl([[[pvpos[0], pvpos[1], pvpos[2]], pvctrlname, 'PVControl.ma', lockattrs]])[0]
        tmpcon = cmds.orientConstraint(self.rig_info['ikjnts'][1], self.rig_info['pvcontrol'][0], mo=False)
        cmds.delete(tmpcon)
        cmds.select(self.rig_info['pvcontrol'][0])
        #cmds.move(-5, z=True, r=True)
        cmds.parent(self.rig_info['pvcontrol'][2], self.rig_info['localgrp'])

        # Generate a name for the ik handle using self.instance
        ikhname = self.module_info["ikcontrols"][1].replace('s_', self.instance)
        # Create Stretchy IK
        pmas = 1
        pvMA = self.instance + "PV"
        self.rig_info['ikinfo']=utils.createStretchyIk(self.rig_info['ikjnts'], self.rig_info['rigjnts'], self.rig_info['ikcontrol'], 
            ikhname, pvctrlname, self.instance, False, pmas, pvMA, '.tx', self.rig_info['setcontrol'])

        # Parent ikh to ctrl
        cmds.parent(self.rig_info['ikinfo'][0], self.rig_info['ikcontrol'][1])
        cmds.parent(self.rig_info['ikinfo'][1], self.rig_info['localgrp'])
        for each in self.rig_info['ikinfo'][2]:
            try:
                cmds.parent(each, self.rig_info['worldgrp'])
            except: pass
    
        # orient constrain ik_wrist to ctrl
        cmds.orientConstraint(self.rig_info['ikcontrol'][1], self.rig_info['ikjnts'][2], mo=True)

        # Create FK rig   
        lockattrs = (['.sx', '.sy', '.sz'])
        self.rig_info['fkcontrols'] = utils.createControl([
        [self.rig_info['positions'][0], self.module_info["fkcontrols"][0].replace('s_', self.instance), 'RectangleControl.ma', lockattrs],
        [self.rig_info['positions'][1], self.module_info["fkcontrols"][1].replace('s_', self.instance), 'RectangleControl.ma', lockattrs],
        [self.rig_info['positions'][2], self.module_info["fkcontrols"][2].replace('s_', self.instance), 'RectangleControl.ma', lockattrs]])

        # Orient the fk controls to the fk joints
        for i in range(len(self.rig_info['fkcontrols'])):
            tc =  cmds.parentConstraint(self.rig_info['fkjnts'][i], self.rig_info['fkcontrols'][i][0], mo=False)
            cmds.delete(tc)
        # Parent fk controls      
        cmds.parent(self.rig_info['fkcontrols'][2][2], self.rig_info['fkcontrols'][1][1])
        cmds.parent(self.rig_info['fkcontrols'][1][2], self.rig_info['fkcontrols'][0][1])
        cmds.parent(self.rig_info['fkcontrols'][0][2], self.rig_info['localgrp'])
      
        # Constrain fk joints to controls.
        [cmds.parentConstraint(self.rig_info['fkcontrols'][i][1], self.rig_info['fkjnts'][i], mo=True) for i in range(len(self.rig_info['fkcontrols']))]
예제 #43
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")
예제 #44
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
import maya.cmds as cmds

sels = cmds.ls(sl=1)

for i in range(len(sels) - 1):
    selP = cmds.listRelatives(sels[i], p=1, f=1)
    if selP:
        cmds.parent(selP[0], sels[i + 1])
    else:
        cmds.parent(sels[i], sels[i + 1])
 def cleanup(self, *args, **kwargs):
     root=self.root
     #blow away constraints
     const=mc.ls(type="constraint")
     if const:
         mc.delete(const)
     
     #kill display layers
     dispLayers=mc.ls(type="displayLayer")
     if dispLayers:
         mc.delete(dispLayers)
     
     #flatten geometry hierarchy
     if mc.objExists(self.geoGrp):
         geo=[]
         for obj in mc.listRelatives(self.geoGrp, ad=1):
             if mc.objectType(obj)=="mesh" and self.getParent(self.getParent(obj))!=self.geoGrp:
                 geo.append(self.getParent(obj)[0])
         geo=list(set(geo))
         try:
             mc.parent(geo, self.geoGrp)
         except:
             print "Can't parent %s to %s"%(geo, self.geoGrp)
             pass
         #delete non mesh groups in geo group
         geoChildren=mc.listRelatives(self.geoGrp, c=1)
         for dag in geoChildren:
             meshes=None
             children=mc.listRelatives(dag, c=1)
             if children:
                 for child in children:
                     if mc.objectType(child)=="mesh":
                         meshes=child
             if not meshes:
                 mc.delete(dag)
     else:
         mc.group(em=1, n=self.geoGrp)
         mc.parent(mc.listRelatives(mc.ls(type="mesh"), p=1), self.geoGrp)
     
     #clean out root and move joints and geo into root
     if mc.objExists(root)!=1:
         mc.group(em=1, n=root)
     else:
         mc.parent(mc.listRelatives(root, c=1), w=1)
     
     mc.parent(self.geoGrp, root)
     
     mc.lockNode(self.jntGrp, l=0)
     mc.parent(self.jntGrp, root)
     
     safeList=mc.listRelatives(root, ad=1)
     safeList.append(root)
     
     killList=mc.ls(dag=1)
     for i in safeList:
         try:
             killList.remove(i)
         except:
             pass
     
     mc.delete(killList)
예제 #47
0
def CreateJoints():
    charName = cmds.textFieldGrp(NameInput, q=True, text=True)
    if charName == "":
        print("Write your character name")
    else:
        #Create directory
        listDirectory = [['_Joints_', '_Controls_', '_ikHandle_'],
                         '_GlobalControl_', '_Geo_']
        cmds.group(em=True, n=charName + '_Main_01')
        for i in range(len(listDirectory) - 1):
            cmds.group(em=True, n=charName + listDirectory[i + 1] + '01')
            cmds.parent(charName + listDirectory[i + 1] + '01',
                        charName + '_Main_01')
        for i in range(len(listDirectory[0])):
            cmds.group(em=True, n=charName + listDirectory[0][i] + '01')
            cmds.parent(charName + listDirectory[0][i] + '01',
                        charName + listDirectory[1] + '01')
        cmds.select(d=True)
        global locXYZ
        locXYZ = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0],
                  [0, 0, 0]]
        for i in range(len(list)):
            locXYZ[i][0] = cmds.getAttr('Loc_' + list[i] + '.translateX')
            print('translateX calcule done')
            locXYZ[i][1] = cmds.getAttr('Loc_' + list[i] + '.translateY')
            print('translateY calcule done')
            locXYZ[i][2] = cmds.getAttr('Loc_' + list[i] + '.translateZ')
            print('translateZ calcule done')
        #total length between root and neck
        lengthY = locXYZ[1][1] - locXYZ[0][1]
        lengthZ = abs(locXYZ[0][2]) + abs(locXYZ[1][2])
        #length between root and toe
        legY = locXYZ[0][1] - locXYZ[5][1]
        lengthY = locXYZ[1][1] - locXYZ[0][1]
        lengthZ = abs(locXYZ[0][2]) + abs(locXYZ[1][2])
        #length between root and toe
        legY = locXYZ[0][1] - locXYZ[5][1]
        cmds.joint(p=(locXYZ[0][0], locXYZ[0][1], locXYZ[0][2]),
                   n=charName + '_root' + '_Jnt_01')

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

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

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

        #place leg joint
        cmds.select(d=True)
        cmds.joint(charName + '_root' + '_Jnt_01',
                   p=(locXYZ[0][0] + lengthY * 0.08, locXYZ[0][1],
                      locXYZ[0][2] - lengthZ / 3.9),
                   n=charName + '_L' + '_hip' + '_Jnt_01')
        PlaceJoint(charName + '_L' + '_hip' + '_Jnt_01',
                   locXYZ[0][0] + lengthY * 0.21, locXYZ[0][1] + legY * 0.03,
                   locXYZ[0][2] - lengthZ / 1.86,
                   charName + '_L' + '_thigh' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_L' + '_thigh' + '_Jnt_01',
                   locXYZ[4][0] - legY * 0.005, locXYZ[4][1] + legY * 0.05,
                   locXYZ[4][2], charName + '_L' + '_knee' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_L' + '_knee' + '_Jnt_01',
                   locXYZ[4][0] + legY * 0.005, locXYZ[4][1] - legY * 0.05,
                   locXYZ[4][2] - legY * 0.03,
                   charName + '_L' + '_knee' + '_Jnt_02', 'x')
        PlaceJoint(
            charName + '_L' + '_knee' + '_Jnt_02',
            locXYZ[5][0] - locXYZ[4][0] * 0.3,
            locXYZ[5][1] + locXYZ[4][1] * 0.17,
            locXYZ[4][2] - legY * 0.03 - (locXYZ[5][2] - locXYZ[4][2]) / 6,
            charName + '_L' + '_ankie' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_L' + '_ankie' + '_Jnt_01',
                   (locXYZ[5][0] - locXYZ[4][0] * 0.3 + locXYZ[5][0]) / 2,
                   locXYZ[5][1], locXYZ[4][2] + locXYZ[5][2] / 1.9,
                   charName + '_L' + '_ball' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_L' + '_ball' + '_Jnt_01', locXYZ[5][0],
                   locXYZ[5][1], locXYZ[5][2],
                   charName + '_L' + '_toe' + '_Jnt_01', 'x')
        cmds.joint(charName + '_L' + '_toe' + '_Jnt_01',
                   e=True,
                   oj='none',
                   ch=True,
                   zso=True)
예제 #48
0
    def sqGenerateMuscleLocators(self, *args):
        muscleLoaded = True
        if not cmds.pluginInfo('MayaMuscle.mll', query=True, loaded=True):
            muscleLoaded = False
            try:
                cmds.loadPlugin('MayaMuscle.mll')
                muscleLoaded = True
            except:
                print "Error: Can not load the Maya Muscle plugin!"
                pass
        if muscleLoaded:
            minIndex = 0
            minPosX = 1000000000000000  # just to avoid non centered characters
            minPosId = 0
            vertexPairList = []
            muscleLocatorList = []
            for e, edgeName in enumerate(self.edgeList):
                tempCompList = cmds.polyListComponentConversion(edgeName,
                                                                fromEdge=True,
                                                                toVertex=True)
                tempExpList = cmds.filterExpand(tempCompList,
                                                selectionMask=31,
                                                expand=True)
                vertexPairList.append(tempExpList)

                edgePosA = cmds.xform(tempExpList[0],
                                      query=True,
                                      worldSpace=True,
                                      translation=True)[0]
                edgePosB = cmds.xform(tempExpList[1],
                                      query=True,
                                      worldSpace=True,
                                      translation=True)[0]
                if edgePosA < minPosX:
                    minIndex = e
                    minPosX = edgePosA
                    minPosId = 0
                if edgePosB < minPosX:
                    minIndex = e
                    minPosX = edgePosB
                    minPosId = 1

            usedIndexList = []
            usedIndexList.append(minIndex)

            lastIndexUp = minIndex
            lastIndexDown = 0

            upEdgeList = []
            upEdgeList.append(self.edgeList[minIndex])
            downEdgeList = []
            for i in range(0, len(vertexPairList) - 1):
                if not i == minIndex:
                    if vertexPairList[i][0] in vertexPairList[minIndex][
                            minPosId] or vertexPairList[i][
                                1] in vertexPairList[minIndex][minPosId]:
                        downEdgeList.append(self.edgeList[i])
                        usedIndexList.append(i)
                        lastIndexDown = i

            for i in range(0, self.maxIter - 2):
                for j in range(0, len(vertexPairList)):
                    if not j in usedIndexList:
                        if vertexPairList[j][0] in vertexPairList[
                                lastIndexUp] or vertexPairList[j][
                                    1] in vertexPairList[lastIndexUp]:
                            upEdgeList.append(self.edgeList[j])
                            usedIndexList.append(j)
                            lastIndexUp = j
                            break
                for j in range(0, len(vertexPairList)):
                    if not j in usedIndexList:
                        if vertexPairList[j][0] in vertexPairList[
                                lastIndexDown] or vertexPairList[j][
                                    1] in vertexPairList[lastIndexDown]:
                            downEdgeList.append(self.edgeList[j])
                            usedIndexList.append(j)
                            lastIndexDown = j
                            break

            upMinusDown = len(upEdgeList) - len(downEdgeList)
            downMinusUp = len(downEdgeList) - len(upEdgeList)

            if upMinusDown > 1:
                for i in range(0, upMinusDown):
                    if not len(upEdgeList) == (self.maxIter - 3):
                        downEdgeList.append(upEdgeList[len(upEdgeList) - 1])
                        upEdgeList = upEdgeList[:-1]
            if downMinusUp > 1:
                for i in range(0, downMinusUp):
                    if not len(upEdgeList) == (self.maxIter - 3):
                        upEdgeList.append(downEdgeList[len(downEdgeList) - 1])
                        downEdgeList = downEdgeList[:-1]

            upEdgeList = upEdgeList[:self.maxIter - 1]
            downEdgeList = downEdgeList[:self.maxIter - 1]

            for k in range(0, self.maxIter - 2):
                cmds.select([upEdgeList[k], downEdgeList[k]])
                #                cmds.refresh()
                #                cmds.pause(seconds=1)
                mel.eval("cMuscleSurfAttachSetup();")
                msa = cmds.rename("StickLips_" + str(k) + "_MSA")
                cmds.disconnectAttr(msa + "Shape.outRotate", msa + ".rotate")
                cmds.setAttr(msa + ".rotateX", 0)
                cmds.setAttr(msa + ".rotateY", 0)
                cmds.setAttr(msa + ".rotateZ", 0)
                muscleLocatorList.append(msa)
                cmds.parent(self.clusterList[k], msa, absolute=True)
예제 #49
0
파일: bumbleBee.py 프로젝트: mappp7/tools
 def create_skin_joint(self):
     tempJoint_rootList = [
         'R_template_clavicle_JNT', 'C_template_root_JNT',
         'C_template_neck1_JNT', 'L_template_clavicle_JNT',
         'L_template_hip_JNT', 'R_template_hip_JNT', 'C_template_tail1_JNT'
     ]
     for x in tempJoint_rootList:
         IKJoint = x.replace('template', 'IK')
         cmds.select(IKJoint, hi=1)
         IKJointList = cmds.ls(sl=1)
         DJointList = cmds.duplicate(x, renameChildren=1)
         for y in range(len(DJointList)):
             skinJoint = cmds.rename(
                 DJointList[y], DJointList[y].replace('template',
                                                      'Skin')[0:-1])
             cmds.parentConstraint(IKJointList[y], skinJoint)
     cmds.parent('C_Skin_neck1_JNT', 'C_Skin_chest_JNT')
     cmds.parent('L_Skin_clavicle_JNT', 'C_Skin_chest_JNT')
     cmds.parent('R_Skin_clavicle_JNT', 'C_Skin_chest_JNT')
     cmds.parent('L_Skin_hip_JNT', 'C_Skin_root_JNT')
     cmds.parent('R_Skin_hip_JNT', 'C_Skin_root_JNT')
     cmds.parent('C_Skin_root_JNT', 'SkinJoint_GRP')
     cmds.parent('C_Skin_tail1_JNT', 'C_Skin_root_JNT')
예제 #50
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')
예제 #51
0
def update_scene(set_container, containers, current_data, new_data, new_file):
    """Updates the hierarchy, assets and their matrix

    Updates the following withing the scene:
        * Setdress hierarchy alembic
        * Matrix
        * Parenting
        * Representations

    It removes any assets which are not present in the new build data

    Args:
        set_container (dict): the setdress container of the scene
        containers (list): the list of containers under the setdress container
        current_data (dict): the current build data of the setdress
        new_data (dict): the new build data of the setdres

    Returns:
        processed_containers (list): all new and updated containers

    """

    from pype.hosts.maya.lib import DEFAULT_MATRIX, get_container_transforms

    set_namespace = set_container['namespace']

    # Update the setdress hierarchy alembic
    set_root = get_container_transforms(set_container, root=True)
    set_hierarchy_root = cmds.listRelatives(set_root, fullPath=True)[0]
    set_hierarchy_reference = cmds.referenceQuery(set_hierarchy_root,
                                                  referenceNode=True)
    new_alembic = new_file.replace(".json", ".abc")
    assert os.path.exists(new_alembic), "%s does not exist." % new_alembic
    with unlocked(cmds.listRelatives(set_root, ad=True, fullPath=True)):
        cmds.file(new_alembic,
                  loadReference=set_hierarchy_reference,
                  type="Alembic")

    identity = DEFAULT_MATRIX[:]

    processed_namespaces = set()
    processed_containers = list()

    new_lookup = _instances_by_namespace(new_data)
    old_lookup = _instances_by_namespace(current_data)
    for container in containers:
        container_ns = container['namespace']

        # Consider it processed here, even it it fails we want to store that
        # the namespace was already available.
        processed_namespaces.add(container_ns)
        processed_containers.append(container['objectName'])

        if container_ns in new_lookup:
            root = get_container_transforms(container, root=True)
            if not root:
                log.error("Can't find root for %s", container['objectName'])
                continue

            old_instance = old_lookup.get(container_ns, {})
            new_instance = new_lookup[container_ns]

            # Update the matrix
            # check matrix against old_data matrix to find local overrides
            current_matrix = cmds.xform(root,
                                        query=True,
                                        matrix=True,
                                        objectSpace=True)

            original_matrix = old_instance.get("matrix", identity)
            has_matrix_override = not matrix_equals(current_matrix,
                                                    original_matrix)

            if has_matrix_override:
                log.warning("Matrix override preserved on %s", container_ns)
            else:
                new_matrix = new_instance.get("matrix", identity)
                cmds.xform(root, matrix=new_matrix, objectSpace=True)

            # Update the parenting
            if old_instance.get("parent", None) != new_instance["parent"]:

                parent = to_namespace(new_instance['parent'], set_namespace)
                if not cmds.objExists(parent):
                    log.error("Can't find parent %s", parent)
                    continue

                # Set the new parent
                cmds.lockNode(root, lock=False)
                root = cmds.parent(root, parent, relative=True)
                cmds.lockNode(root, lock=True)

            # Update the representation
            representation_current = container['representation']
            representation_old = old_instance['representation']
            representation_new = new_instance['representation']
            has_representation_override = (representation_current !=
                                           representation_old)

            if representation_new != representation_current:

                if has_representation_override:
                    log.warning(
                        "Your scene had local representation "
                        "overrides within the set. New "
                        "representations not loaded for %s.", container_ns)
                    continue

                # We check it against the current 'loader' in the scene instead
                # of the original data of the package that was loaded because
                # an Artist might have made scene local overrides
                if new_instance['loader'] != container['loader']:
                    log.warning(
                        "Loader is switched - local edits will be "
                        "lost. Removing: %s", container_ns)

                    # Remove this from the "has been processed" list so it's
                    # considered as new element and added afterwards.
                    processed_containers.pop()
                    processed_namespaces.remove(container_ns)
                    api.remove(container)
                    continue

                # Check whether the conversion can be done by the Loader.
                # They *must* use the same asset, subset and Loader for
                # `api.update` to make sense.
                old = io.find_one({"_id": io.ObjectId(representation_current)})
                new = io.find_one({"_id": io.ObjectId(representation_new)})
                is_valid = compare_representations(old=old, new=new)
                if not is_valid:
                    log.error("Skipping: %s. See log for details.",
                              container_ns)
                    continue

                new_version = new["context"]["version"]
                api.update(container, version=new_version)

        else:
            # Remove this container because it's not in the new data
            log.warning("Removing content: %s", container_ns)
            api.remove(container)

    # Add new assets
    all_loaders = api.discover(api.Loader)
    for representation_id, instances in new_data.items():

        # Find the compatible loaders
        loaders = api.loaders_from_representation(all_loaders,
                                                  representation_id)
        for instance in instances:

            # Already processed in update functionality
            if instance['namespace'] in processed_namespaces:
                continue

            container = _add(instance=instance,
                             representation_id=representation_id,
                             loaders=loaders,
                             namespace=set_container['namespace'],
                             root=set_root)

            # Add to the setdress container
            cmds.sets(container, addElement=set_container['objectName'])

            processed_containers.append(container)

    return processed_containers
예제 #52
0
파일: bumbleBee.py 프로젝트: mappp7/tools
    def etc_set(self):
        ### attribute
        # sup con vis
        for x in range(8):
            cmds.addAttr(TP.AA['PL'][x],
                         ln='sub_con_vis',
                         at='enum',
                         en='off:on:')
            cmds.setAttr(TP.AA['PL'][x] + '.sub_con_vis', e=1, keyable=1)
            cmds.connectAttr(TP.AA['PL'][x] + '.sub_con_vis',
                             TP.AA['CL'][x] + '.visibility')
        # FK / IK switch
        for x in range(2):
            switchCon = controllerShape(TP.conVis['key'][x][0] + '_CON',
                                        'cross', 'yellow')
            switchNul = cmds.group(switchCon,
                                   n=TP.conVis['key'][x][0] + '_NUL')
            cmds.delete(cmds.pointConstraint(TP.conVis['key'][x][1],
                                             switchNul))
            cmds.parent(switchNul, TP.conVis['key'][x][1])
            cmds.move(5, 0, 0, ws=1, r=1)
            cmds.addAttr(switchCon,
                         ln=TP.conVis['attr'][0],
                         at='enum',
                         en='off:on:')
            cmds.setAttr(switchCon + '.' + TP.conVis['attr'][0],
                         e=1,
                         keyable=1)
            cmds.addAttr(switchCon,
                         ln=TP.conVis['attr'][1],
                         at='enum',
                         en='off:on:')
            cmds.setAttr(switchCon + '.' + TP.conVis['attr'][1],
                         e=1,
                         keyable=1)
        for x in range(2):
            top_list = TP.conVis['vis'][x]
            for y in top_list:
                for z in y:
                    if len(y) == 1:
                        cmds.connectAttr(
                            TP.conVis['key'][x][0] + '_CON.' +
                            TP.conVis['attr'][0], z + '.visibility')
                    else:
                        cmds.connectAttr(
                            TP.conVis['key'][x][0] + '_CON.' +
                            TP.conVis['attr'][1], z + '.visibility')
                    cmds.setAttr(TP.conVis['key'][x][0] + '_CON.IK_con_vis', 1)
        ### Parent node
        cmds.group(p='noneTransform_GRP', em=1, n='locator_GRP')
        cmds.parent(TP.noneTrans_list, 'locator_GRP')
        cmds.parent(TP.attach_list, 'attach_GRP')
        cmds.parent(TP.auxillary_list, 'auxillary_GRP')
        cmds.parent(TP.neck_list, 'C_neck_GRP')
        cmds.parent(TP.spine_list, 'C_spine_GRP')
        cmds.parent(TP.L_foreLeg_list, 'L_foreLeg_GRP')
        cmds.parent(TP.R_foreLeg_list, 'R_foreLeg_GRP')
        cmds.parent(TP.L_hindLeg_list, 'L_hindLeg_GRP')
        cmds.parent(TP.R_hindLeg_list, 'R_hindLeg_GRP')
        cmds.parent(TP.tail_list, 'C_tail_GRP')
        cmds.delete(TP.delete_list)
        cmds.select(TP.noneTrans_list, r=1)
        cmds.select('templateJoint_GRP', tgl=1)
        cmds.select(TP.hide_list, tgl=1)
        cmds.select(TP.hide_list2, tgl=1)
        cmds.HideSelectedObjects()

        ### Rotate controler
        self.controlerRotate(TP.rotate_con_list_A, 0, 0, -90)
        self.controlerRotate(TP.rotate_con_list_B, -90, 0, 0)

        ### controler Color
        for x in TP.R_con_list:
            conShapeName = cmds.listRelatives(x, s=1)[0]
            cmds.setAttr(conShapeName + '.overrideEnabled', 1)
            cmds.setAttr(conShapeName + '.overrideColor', 13)
        for x in TP.switch_con_list:
            conShapeName = cmds.listRelatives(x, s=1)[0]
            cmds.setAttr(conShapeName + '.overrideEnabled', 1)
            cmds.setAttr(conShapeName + '.overrideColor', 14)

        ### controler Scale
        for x in TP.scale_con_list:
            scale_value = 2
            CRV_shape_name = cmds.listRelatives(x, s=1)[0]
            CRV_span_num = cmds.getAttr(CRV_shape_name + '.spans')
            cmds.select(x + '.cv[0:%s]' % (CRV_span_num))
            cmds.scale(scale_value, scale_value, scale_value, r=1)

        ### controler Parent
        for x in range(2):
            PL = TP.parent_list['PL'][x]
            for y in TP.parent_list['CL'][x]:
                cmds.parentConstraint(PL, y, mo=1)
        ### hindLeg Parent
        cmds.setAttr('L_rig_hip_JNT.inheritsTransform', 0)
        cmds.setAttr('R_rig_hip_JNT.inheritsTransform', 0)
        itemList = ['.sx', '.sy', '.sz']
        for x in TP.targetjointList:
            for y in itemList:
                cmds.connectAttr('place_CON.globalScale', x + y)
예제 #53
0
    def testParentToProxyShape(self):

        # Load a file with a USD hierarchy at least 2-levels deep.
        with OpenFileCtx("simpleHierarchy.ma"):

            # Create scene items for the proxy shape and the sphere.
            shapeSegment = mayaUtils.createUfePathSegment(
                "|mayaUsdProxy1|mayaUsdProxyShape1")
            shapePath = ufe.Path([shapeSegment])
            shapeItem = ufe.Hierarchy.createItem(shapePath)

            spherePath = ufe.Path([
                shapeSegment,
                usdUtils.createUfePathSegment("/pCylinder1/pCube1/pSphere1")
            ])
            sphereItem = ufe.Hierarchy.createItem(spherePath)

            # get the USD stage
            stage = mayaUsd.ufe.getStage(str(shapeSegment))

            # check GetLayerStack behavior
            self.assertEqual(stage.GetEditTarget().GetLayer(),
                             stage.GetRootLayer())

            # The sphere is not a child of the proxy shape.
            shapeHier = ufe.Hierarchy.hierarchy(shapeItem)
            shapeChildren = shapeHier.children()
            self.assertNotIn("pSphere1", childrenNames(shapeChildren))

            # Get its world space transform.
            sphereT3d = ufe.Transform3d.transform3d(sphereItem)
            sphereWorld = sphereT3d.inclusiveMatrix()
            sphereWorldListPre = matrixToList(sphereWorld)

            # Parent sphere to proxy shape in absolute mode (default), using UFE
            # path strings.Expect the exception happens
            cmds.parent(
                "|mayaUsdProxy1|mayaUsdProxyShape1,/pCylinder1/pCube1/pSphere1",
                "|mayaUsdProxy1|mayaUsdProxyShape1")

            # Confirm that the sphere is now a child of the proxy shape.
            shapeChildren = shapeHier.children()
            self.assertIn("pSphere1", childrenNames(shapeChildren))

            # Undo: the sphere is no longer a child of the proxy shape.
            cmds.undo()

            shapeChildren = shapeHier.children()
            self.assertNotIn("pSphere1", childrenNames(shapeChildren))

            # Redo: confirm that the sphere is again a child of the proxy shape.
            cmds.redo()

            shapeChildren = shapeHier.children()
            self.assertIn("pSphere1", childrenNames(shapeChildren))

            # Confirm that the sphere's world transform has not changed.  Must
            # re-create the item, as its path has changed.
            sphereChildPath = ufe.Path(
                [shapeSegment,
                 usdUtils.createUfePathSegment("/pSphere1")])
            sphereChildItem = ufe.Hierarchy.createItem(sphereChildPath)
            sphereChildT3d = ufe.Transform3d.transform3d(sphereChildItem)

            sphereWorld = sphereChildT3d.inclusiveMatrix()
            assertVectorAlmostEqual(self,
                                    sphereWorldListPre,
                                    matrixToList(sphereWorld),
                                    places=6)

            # Undo.
            cmds.undo()

            shapeChildren = shapeHier.children()
            self.assertNotIn("pSphere1", childrenNames(shapeChildren))
예제 #54
0
def groundConstraint(mesh, obj):
    name = mesh + '_' + obj

    # 1 create a CPOM node and connect input
    # ############################################################
    # create input position locator and closest point locator:
    pos = cmd.xform(obj, q=True, translation=True, ws=True)
    colLoc = cmd.spaceLocator(n=name + '_collisionLoc')[0]
    cmd.xform(colLoc, translation=pos, ws=True)
    ctrlLoc = cmd.spaceLocator(n=name + '_ctrlLoc', p=pos)[0]
    cmd.xform(ctrlLoc, cp=True)

    cmd.parent(colLoc, ctrlLoc)

    # closest point on mesh node:
    CPOM = cmd.shadingNode('closestPointOnMesh',
                           asUtility=True,
                           n=name + '_CPOM')

    # connect ground mesh to CPOM
    meshShape = cmd.listRelatives(mesh, shapes=True)[0]
    cmd.connectAttr(meshShape + '.worldMesh[0]', CPOM + '.inMesh')
    cmd.connectAttr(meshShape + '.worldMatrix[0]', CPOM + '.inputMatrix')

    # connect ctrl locator and collision locator to CPOM
    # decompose ctrlLoc
    if cmd.pluginInfo('decomposeMatrix', q=True, loaded=True) == False:
        cmd.loadPlugin('decomposeMatrix')

    colLocDM = cmd.shadingNode('decomposeMatrix',
                               asUtility=True,
                               n=colLoc + '_decomposeMatrix')
    cmd.connectAttr(colLoc + '.worldMatrix', colLocDM + '.inputMatrix')
    cmd.connectAttr(colLocDM + '.outputTranslate', CPOM + '.inPosition')
    # ############################################################

    # 2, fix rotation: make obj rotates on surface: normal constraint
    #############################################################
    # create vector product nodes:
    ax_x = cmd.shadingNode('vectorProduct', asUtility=True, n=name + 'ax_x')
    ax_z = cmd.shadingNode('vectorProduct', asUtility=True, n=name + 'ax_z')
    for node in [ax_x, ax_z]:
        cmd.setAttr(node + '.operation', 2)  #cross product
        cmd.setAttr(node + '.normalizeOutput', 1)  #normalize output

    # normal from CPOM --> vector product nodes
    cmd.setAttr(ax_z + '.input1X', 1)
    cmd.connectAttr(CPOM + '.result.normal', ax_z + '.input2')

    cmd.connectAttr(CPOM + '.result.normal', ax_x + '.input1')
    cmd.connectAttr(ax_z + '.output', ax_x + '.input2')

    # create a 4X4 matrix
    fourbyfour = cmd.shadingNode('fourByFourMatrix',
                                 asUtility=True,
                                 n=name + '_fourByFourMatrix')

    # connect translate/rotate output to matrix
    cmd.connectAttr(ax_x + '.outputX', fourbyfour + '.in00')
    cmd.connectAttr(ax_x + '.outputY', fourbyfour + '.in01')
    cmd.connectAttr(ax_x + '.outputZ', fourbyfour + '.in02')

    cmd.connectAttr(CPOM + '.result.normalX', fourbyfour + '.in10')
    cmd.connectAttr(CPOM + '.result.normalY', fourbyfour + '.in11')
    cmd.connectAttr(CPOM + '.result.normalZ', fourbyfour + '.in12')

    cmd.connectAttr(ax_z + '.outputX', fourbyfour + '.in20')
    cmd.connectAttr(ax_z + '.outputY', fourbyfour + '.in21')
    cmd.connectAttr(ax_z + '.outputZ', fourbyfour + '.in22')

    cmd.connectAttr(CPOM + '.result.positionX', fourbyfour + '.in30')
    cmd.connectAttr(CPOM + '.result.positionY', fourbyfour + '.in31')
    cmd.connectAttr(CPOM + '.result.positionZ', fourbyfour + '.in32')
    #############################################################

    # 3, detect if collision is happening
    #############################################################
    # create the difference matrix
    diffMatrix = cmd.shadingNode('multMatrix',
                                 asUtility=True,
                                 n=name + '_diffMatrix')
    # connect output from 4X4 and colLoc inverse worldMatrix to diffMatrix
    cmd.connectAttr(fourbyfour + '.output', diffMatrix + '.matrixIn[0]')
    cmd.connectAttr(colLoc + '.worldInverseMatrix[0]',
                    diffMatrix + '.matrixIn[1]')

    # decompose diffMatrix and create a condition node
    diffMatrixDM = cmd.shadingNode('decomposeMatrix',
                                   asUtility=True,
                                   n=diffMatrix + '_decomposeMatrix')
    cmd.connectAttr(diffMatrix + '.matrixSum', diffMatrixDM + '.inputMatrix')

    # condition: if diffMatrixDM.ty<0, then collision not happen (true=happe, false = not happen)
    condition = cmd.shadingNode('condition',
                                asUtility=True,
                                n=name + '_condition')
    cmd.setAttr(condition + '.operation', 2)  #greater than
    cmd.setAttr(condition + '.colorIfTrueR', 1)
    cmd.setAttr(condition + '.colorIfFalseR', 0)

    cmd.connectAttr(diffMatrixDM + '.outputTranslate.outputTranslateY',
                    condition + '.firstTerm')

    # blending: collision happen----> collide weight =1, collision not happen---> collide weight =0:
    blend = cmd.shadingNode('pairBlend', asUtility=True, n=name + '_blend')
    cmd.connectAttr(condition + '.outColorR', blend + '.weight')

    # blend ctrl loc and collision loc:
    # decompose ctrlLoc
    ctrlLocDM = cmd.shadingNode('decomposeMatrix',
                                asUtility=True,
                                n=ctrlLoc + '_decomposeMatrix')
    cmd.connectAttr(ctrlLoc + '.worldMatrix', ctrlLocDM + '.inputMatrix')

    # decompose 4X4
    fourbyfourDM = cmd.shadingNode('decomposeMatrix',
                                   asUtility=True,
                                   n=fourbyfour + '_decomposeMatrix')
    cmd.connectAttr(fourbyfour + '.output', fourbyfourDM + '.inputMatrix')

    # blend:
    cmd.connectAttr(ctrlLocDM + '.outputTranslate', blend + '.inTranslate1')
    cmd.connectAttr(ctrlLocDM + '.outputRotate', blend + '.inRotate1')
    cmd.connectAttr(fourbyfourDM + '.outputTranslate', blend + '.inTranslate2')
    cmd.connectAttr(fourbyfourDM + '.outputRotate', blend + '.inRotate2')
    ########################################################################

    # 5. offset obj position(contact)
    ########################################################################
    offsetMatrix = cmd.shadingNode('multMatrix',
                                   asUtility=True,
                                   n=name + 'offsetMatrix')
    cmd.connectAttr(diffMatrix + '.matrixSum', offsetMatrix + '.matrixIn[0]')
    cmd.connectAttr(ctrlLoc + '.worldMatrix[0]', offsetMatrix + '.matrixIn[1]')

    cmd.connectAttr(offsetMatrix + '.matrixSum',
                    fourbyfourDM + '.inputMatrix',
                    force=True)

    # 5. connect result to obj
    ########################################################################
    objGrp = cmd.group(obj, n=obj + '_collision_Grp', r=True)
    cmd.connectAttr(blend + '.outTranslate', objGrp + '.translate')
    cmd.connectAttr(blend + '.outRotate', objGrp + '.rotate')

    return (ctrlLoc, colLoc, objGrp)
예제 #55
0
    def testParentAbsoluteMultiMatrixOp(self):
        """Test parent -absolute on prim with a transform stack with multiple matrix ops."""

        cmds.file(new=True, force=True)

        # Create a scene with an xform and a capsule.
        import mayaUsd_createStageWithNewLayer

        mayaUsd_createStageWithNewLayer.createStageWithNewLayer()
        proxyShapePathStr = '|stage1|stageShape1'
        stage = mayaUsd.lib.GetPrim(proxyShapePathStr).GetStage()
        xformPrim = stage.DefinePrim('/Xform1', 'Xform')
        capsulePrim = stage.DefinePrim('/Capsule1', 'Capsule')
        xformXformable = UsdGeom.Xformable(xformPrim)
        capsuleXformable = UsdGeom.Xformable(capsulePrim)

        proxyShapePathSegment = mayaUtils.createUfePathSegment(
            proxyShapePathStr)

        # Translate and rotate the xform.
        xformPath = ufe.Path(
            [proxyShapePathSegment,
             usdUtils.createUfePathSegment('/Xform1')])
        xformItem = ufe.Hierarchy.createItem(xformPath)

        sn = ufe.GlobalSelection.get()
        sn.clear()
        sn.append(xformItem)

        cmds.move(0, -5, 0, r=True, os=True, wd=True)
        cmds.rotate(0, -90, 0, r=True, os=True, fo=True)

        self.assertEqual(
            xformXformable.GetXformOpOrderAttr().Get(),
            Vt.TokenArray(("xformOp:translate", "xformOp:rotateXYZ")))

        sn.clear()

        capsulePath = ufe.Path([
            proxyShapePathSegment,
            usdUtils.createUfePathSegment('/Capsule1')
        ])
        capsuleItem = ufe.Hierarchy.createItem(capsulePath)

        # Add 3 matrix transform ops to the capsule.
        # matrix A: tx  5, ry 90
        # matrix B: ty 10, rz 90
        # matrix C: tz 15, rx 90
        op = capsuleXformable.AddTransformOp(opSuffix='A')
        matrixValA = Gf.Matrix4d(0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 5, 0, 0,
                                 1)
        op.Set(matrixValA)
        op = capsuleXformable.AddTransformOp(opSuffix='B')
        matrixValB = Gf.Matrix4d(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 0, 10, 0,
                                 1)
        op.Set(matrixValB)
        op = capsuleXformable.AddTransformOp(opSuffix='C')
        matrixValC = Gf.Matrix4d(1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 15,
                                 1)
        op.Set(matrixValC)

        matrixOps = [
            "xformOp:transform:A", "xformOp:transform:B", "xformOp:transform:C"
        ]
        matrixValues = {
            "xformOp:transform:A": matrixValA,
            "xformOp:transform:B": matrixValB,
            "xformOp:transform:C": matrixValC
        }

        self.assertEqual(capsuleXformable.GetXformOpOrderAttr().Get(),
                         Vt.TokenArray(matrixOps))

        # Capture the current world space transform of the capsule.
        capsuleT3d = ufe.Transform3d.transform3d(capsuleItem)
        capsuleWorldPre = matrixToList(capsuleT3d.inclusiveMatrix())

        # We will run the parenting test 3 times, targeting each matrix op in
        # turn.
        for matrixOp in matrixOps:
            os.environ['MAYA_USD_MATRIX_XFORM_OP_NAME'] = matrixOp

            # The xform currently has no children.
            xformHier = ufe.Hierarchy.hierarchy(xformItem)
            xformChildren = xformHier.children()
            self.assertEqual(len(xformChildren), 0)

            # Parent the capsule to the xform.
            cmds.parent(ufe.PathString.string(capsulePath),
                        ufe.PathString.string(xformPath))

            def checkParentDone():
                # The xform now has the capsule as its child.
                xformChildren = xformHier.children()
                self.assertEqual(len(xformChildren), 1)
                self.assertIn('Capsule1', childrenNames(xformChildren))

                # Confirm that the capsule has not moved in world space.  Must
                # re-create the prim and its scene item after path change.
                capsulePath = ufe.Path([
                    proxyShapePathSegment,
                    usdUtils.createUfePathSegment('/Xform1/Capsule1')
                ])
                capsulePrim = mayaUsd.ufe.ufePathToPrim(
                    ufe.PathString.string(capsulePath))
                capsuleXformable = UsdGeom.Xformable(capsulePrim)
                capsuleItem = ufe.Hierarchy.createItem(capsulePath)
                capsuleT3d = ufe.Transform3d.transform3d(capsuleItem)
                capsuleWorld = capsuleT3d.inclusiveMatrix()
                assertVectorAlmostEqual(self, capsuleWorldPre,
                                        matrixToList(capsuleWorld))

                # No change in the capsule's transform ops.
                self.assertEqual(capsuleXformable.GetXformOpOrderAttr().Get(),
                                 Vt.TokenArray(matrixOps))

                # Matrix ops that were not targeted did not change.
                for checkMatrixOp in matrixOps:
                    if checkMatrixOp == matrixOp:
                        continue
                    op = UsdGeom.XformOp(
                        capsulePrim.GetAttribute(checkMatrixOp))
                    self.assertEqual(
                        op.GetOpTransform(
                            mayaUsd.ufe.getTime(
                                ufe.PathString.string(capsulePath))),
                        matrixValues[checkMatrixOp])

            checkParentDone()

            # Undo: the xform no longer has a child, the capsule is still where
            # it has always been.
            cmds.undo()

            xformChildren = xformHier.children()
            self.assertEqual(len(xformChildren), 0)

            capsulePath = ufe.Path([
                proxyShapePathSegment,
                usdUtils.createUfePathSegment('/Capsule1')
            ])
            capsulePrim = mayaUsd.ufe.ufePathToPrim(
                ufe.PathString.string(capsulePath))
            capsuleXformable = UsdGeom.Xformable(capsulePrim)
            capsuleItem = ufe.Hierarchy.createItem(capsulePath)
            capsuleT3d = ufe.Transform3d.transform3d(capsuleItem)
            capsuleWorld = capsuleT3d.inclusiveMatrix()
            assertVectorAlmostEqual(self, capsuleWorldPre,
                                    matrixToList(capsuleWorld))
            self.assertEqual(capsuleXformable.GetXformOpOrderAttr().Get(),
                             Vt.TokenArray(matrixOps))

            # Redo: capsule still hasn't moved.
            cmds.redo()

            checkParentDone()

            # Go back to initial conditions for next iteration of loop.
            cmds.undo()
예제 #56
0
    def testAlreadyChild(self):
        '''Parenting an object to its current parent is a no-op.'''

        with OpenFileCtx("simpleHierarchy.ma"):
            shapeSegment = mayaUtils.createUfePathSegment(
                "|mayaUsdProxy1|mayaUsdProxyShape1")
            spherePath = ufe.Path([
                shapeSegment,
                usdUtils.createUfePathSegment("/pCylinder1/pCube1/pSphere1")
            ])
            sphereItem = ufe.Hierarchy.createItem(spherePath)
            cylinderShapePath = ufe.Path([
                shapeSegment,
                usdUtils.createUfePathSegment("/pCylinder1/pCylinderShape1")
            ])
            cylinderShapeItem = ufe.Hierarchy.createItem(cylinderShapePath)
            parentPath = ufe.Path(
                [shapeSegment,
                 usdUtils.createUfePathSegment("/pCylinder1")])
            parentItem = ufe.Hierarchy.createItem(parentPath)

            parent = ufe.Hierarchy.hierarchy(parentItem)
            childrenPre = parent.children()

            # get the USD stage
            stage = mayaUsd.ufe.getStage(str(shapeSegment))

            # check GetLayerStack behavior
            self.assertEqual(stage.GetEditTarget().GetLayer(),
                             stage.GetRootLayer())

            # The sphere is not a child of the cylinder
            self.assertNotIn("pSphere1", childrenNames(childrenPre))

            # The cylinder shape is a child of the cylinder
            self.assertIn("pCylinderShape1", childrenNames(childrenPre))

            # Parent the sphere and the cylinder shape to the cylinder.  This
            # is a no-op for the cylinder shape, as it's already a child of the
            # cylinder, and the sphere is parented to the cylinder.
            cmds.parent(ufe.PathString.string(spherePath),
                        ufe.PathString.string(cylinderShapePath),
                        ufe.PathString.string(parentPath))

            children = parent.children()
            self.assertEqual(len(childrenPre) + 1, len(children))
            self.assertIn("pSphere1", childrenNames(children))
            self.assertIn("pCylinderShape1", childrenNames(children))

            # Undo / redo
            cmds.undo()

            children = parent.children()
            self.assertEqual(len(childrenPre), len(children))
            self.assertNotIn("pSphere1", childrenNames(children))
            self.assertIn("pCylinderShape1", childrenNames(children))

            cmds.redo()

            children = parent.children()
            self.assertEqual(len(childrenPre) + 1, len(children))
            self.assertIn("pSphere1", childrenNames(children))
            self.assertIn("pCylinderShape1", childrenNames(children))
예제 #57
0
    def testParentAbsoluteSingleMatrixOp(self):
        """Test parent -absolute on prim with a single matrix op."""

        # Our test strategy is the following: we use the existing scene's cube
        # prim as reference, and set its local matrix onto a new prim that has
        # a single matrix op.  The cube prim is used as a reference.
        #
        # We then parent -absolute the new prim as well as the cube, and assert
        # that neither the new prim or the cube have moved in world space.

        # Create scene items for the cube, the cylinder, and the proxy shape.
        proxyShapePathStr = '|mayaUsdProxy1|mayaUsdProxyShape1'
        proxyShapePath = ufe.PathString.path(proxyShapePathStr)
        proxyShapeItem = ufe.Hierarchy.createItem(proxyShapePath)
        shapeSegment = mayaUtils.createUfePathSegment(proxyShapePathStr)
        cubePath = ufe.Path(
            [shapeSegment,
             usdUtils.createUfePathSegment("/cubeXform")])
        cubeItem = ufe.Hierarchy.createItem(cubePath)
        cylinderPath = ufe.Path(
            [shapeSegment,
             usdUtils.createUfePathSegment("/cylinderXform")])
        cylinderItem = ufe.Hierarchy.createItem(cylinderPath)

        # get the USD stage
        stage = mayaUsd.ufe.getStage(str(shapeSegment))

        # check GetLayerStack behavior
        self.assertEqual(stage.GetEditTarget().GetLayer(),
                         stage.GetRootLayer())

        # Create a capsule prim directly under the proxy shape
        proxyShapeContextOps = ufe.ContextOps.contextOps(proxyShapeItem)
        proxyShapeContextOps.doOp(['Add New Prim', 'Capsule'])

        capsulePath = ufe.PathString.path(proxyShapePathStr + ',/Capsule1')

        capsulePrim = mayaUsd.ufe.ufePathToPrim(
            ufe.PathString.string(capsulePath))
        capsuleXformable = UsdGeom.Xformable(capsulePrim)

        # The capsule is not a child of the cylinder.
        cylHier = ufe.Hierarchy.hierarchy(cylinderItem)
        cylChildren = cylHier.children()
        self.assertEqual(len(cylChildren), 1)

        # Add a single matrix transform op to the capsule.
        capsulePrim = mayaUsd.ufe.ufePathToPrim(
            ufe.PathString.string(capsulePath))
        capsuleXformable = UsdGeom.Xformable(capsulePrim)
        capsuleXformable.AddTransformOp()

        self.assertEqual(capsuleXformable.GetXformOpOrderAttr().Get(),
                         Vt.TokenArray(["xformOp:transform"]))

        # Delay creating the Transform3d interface until after we've added our
        # single matrix transform op, so that we get a UsdTransform3dMatrixOp.
        capsuleItem = ufe.Hierarchy.createItem(capsulePath)
        capsuleT3d = ufe.Transform3d.transform3d(capsuleItem)

        # The cube is a direct child of the proxy shape, whose transform is the
        # identity, so the cube's world and local space transforms are identical
        cubeT3d = ufe.Transform3d.transform3d(cubeItem)
        cubeLocal = cubeT3d.matrix()
        cubeWorld = cubeT3d.inclusiveMatrix()
        cubeWorldListPre = matrixToList(cubeWorld)

        # Set the capsule's transform to be the same as the cube's.
        capsuleT3d.setMatrix(cubeLocal)

        self.assertEqual(capsuleXformable.GetXformOpOrderAttr().Get(),
                         Vt.TokenArray(["xformOp:transform"]))

        capsuleLocal = capsuleT3d.matrix()
        capsuleWorld = capsuleT3d.inclusiveMatrix()
        capsuleWorldListPre = matrixToList(capsuleWorld)

        assertVectorAlmostEqual(self, matrixToList(cubeLocal),
                                matrixToList(capsuleLocal))
        assertVectorAlmostEqual(self, matrixToList(cubeWorld),
                                matrixToList(capsuleWorld))

        # Parent cube and capsule to cylinder in absolute mode (default), using
        # UFE path strings.
        cmds.parent("|mayaUsdProxy1|mayaUsdProxyShape1,/cubeXform",
                    "|mayaUsdProxy1|mayaUsdProxyShape1,/Capsule1",
                    "|mayaUsdProxy1|mayaUsdProxyShape1,/cylinderXform")

        # Confirm that the cube and capsule are now children of the cylinder.
        cylChildren = cylHier.children()
        self.assertEqual(len(cylChildren), 3)
        self.assertIn("cubeXform", childrenNames(cylChildren))
        self.assertIn("Capsule1", childrenNames(cylChildren))

        # Undo: cylinder no longer has children.
        cmds.undo()

        cylChildren = cylHier.children()
        self.assertEqual(len(cylChildren), 1)

        # Redo: confirm children are back.
        cmds.redo()

        cylChildren = cylHier.children()
        self.assertEqual(len(cylChildren), 3)
        self.assertIn("cubeXform", childrenNames(cylChildren))
        self.assertIn("Capsule1", childrenNames(cylChildren))

        # Confirm that the cube and capsule's world transform has not changed.
        # Must re-create the items, as their path has changed.
        cubeChildPath = ufe.Path([
            shapeSegment,
            usdUtils.createUfePathSegment("/cylinderXform/cubeXform")
        ])
        cubeChildItem = ufe.Hierarchy.createItem(cubeChildPath)
        cubeChildT3d = ufe.Transform3d.transform3d(cubeChildItem)
        capsuleChildPath = ufe.Path([
            shapeSegment,
            usdUtils.createUfePathSegment("/cylinderXform/Capsule1")
        ])
        capsuleChildItem = ufe.Hierarchy.createItem(capsuleChildPath)
        capsuleChildT3d = ufe.Transform3d.transform3d(capsuleChildItem)

        cubeWorld = cubeChildT3d.inclusiveMatrix()
        capsuleWorld = capsuleChildT3d.inclusiveMatrix()
        assertVectorAlmostEqual(self,
                                cubeWorldListPre,
                                matrixToList(cubeWorld),
                                places=6)
        assertVectorAlmostEqual(self,
                                capsuleWorldListPre,
                                matrixToList(capsuleWorld),
                                places=6)

        # Undo everything.
        cmds.undo()

        cylChildren = cylHier.children()
        self.assertEqual(len(cylChildren), 1)
예제 #58
0
    def testParentAbsoluteXformCommonAPI(self):
        """Test parent -absolute on prim with a USD common transform APIfallback Maya transform stack."""
        # Create a scene with an xform and a capsule.
        import mayaUsd_createStageWithNewLayer

        mayaUsd_createStageWithNewLayer.createStageWithNewLayer()
        proxyShapePathStr = '|stage1|stageShape1'
        stage = mayaUsd.lib.GetPrim(proxyShapePathStr).GetStage()
        xformPrim = stage.DefinePrim('/Xform1', 'Xform')
        capsulePrim = stage.DefinePrim('/Capsule1', 'Capsule')
        xformXformable = UsdGeom.Xformable(xformPrim)
        capsuleXformable = UsdGeom.Xformable(capsulePrim)

        proxyShapePathSegment = mayaUtils.createUfePathSegment(
            proxyShapePathStr)

        xformPath = ufe.Path(
            [proxyShapePathSegment,
             usdUtils.createUfePathSegment('/Xform1')])
        xformItem = ufe.Hierarchy.createItem(xformPath)
        capsulePath = ufe.Path([
            proxyShapePathSegment,
            usdUtils.createUfePathSegment('/Capsule1')
        ])
        capsuleItem = ufe.Hierarchy.createItem(capsulePath)

        # Give the capsule a common API single pivot.  This will match the
        # common API, but not the Maya API.
        capsuleXformable.AddTranslateOp(UsdGeom.XformOp.PrecisionFloat,
                                        "pivot")
        capsuleXformable.AddTranslateOp(UsdGeom.XformOp.PrecisionFloat,
                                        "pivot", True)

        self.assertEqual(
            capsuleXformable.GetXformOpOrderAttr().Get(),
            Vt.TokenArray(("xformOp:translate:pivot",
                           "!invert!xformOp:translate:pivot")))
        self.assertTrue(UsdGeom.XformCommonAPI(capsuleXformable))

        # Now set the transform on both objects.
        sn = ufe.GlobalSelection.get()
        sn.clear()
        sn.append(xformItem)

        cmds.move(5, 10, 15, r=True, os=True, wd=True)
        cmds.rotate(30, -30, 45, r=True, os=True, fo=True)

        sn.clear()
        sn.append(capsuleItem)

        cmds.move(-5, -10, -15, r=True, os=True, wd=True)
        cmds.rotate(-30, 60, -45, r=True, os=True, fo=True)

        capsuleT3d = ufe.Transform3d.transform3d(capsuleItem)
        capsuleWorld = capsuleT3d.inclusiveMatrix()
        capsuleWorldPre = matrixToList(capsuleWorld)

        # The xform currently has no children.
        xformHier = ufe.Hierarchy.hierarchy(xformItem)
        xformChildren = xformHier.children()
        self.assertEqual(len(xformChildren), 0)

        # Parent the capsule to the xform.
        cmds.parent(ufe.PathString.string(capsulePath),
                    ufe.PathString.string(xformPath))

        def checkParentDone():
            # The xform now has the capsule as its child.
            xformChildren = xformHier.children()
            self.assertEqual(len(xformChildren), 1)
            self.assertIn('Capsule1', childrenNames(xformChildren))

            # Confirm that the capsule has not moved in world space.  Must
            # re-create the prim and its scene item, as its path has changed.
            capsulePath = ufe.Path([
                proxyShapePathSegment,
                usdUtils.createUfePathSegment('/Xform1/Capsule1')
            ])
            capsulePrim = mayaUsd.ufe.ufePathToPrim(
                ufe.PathString.string(capsulePath))
            capsuleXformable = UsdGeom.Xformable(capsulePrim)
            capsuleItem = ufe.Hierarchy.createItem(capsulePath)
            capsuleT3d = ufe.Transform3d.transform3d(capsuleItem)
            capsuleWorld = capsuleT3d.inclusiveMatrix()
            assertVectorAlmostEqual(self,
                                    capsuleWorldPre,
                                    matrixToList(capsuleWorld),
                                    places=6)
            # Using setMatrixCmd() on a common transform API prim will set
            # translate, rotate, and scale.
            self.assertEqual(
                capsuleXformable.GetXformOpOrderAttr().Get(),
                Vt.TokenArray(("xformOp:translate", "xformOp:translate:pivot",
                               "xformOp:rotateXYZ", "xformOp:scale",
                               "!invert!xformOp:translate:pivot")))

        checkParentDone()

        # Undo: the xform no longer has a child, the capsule is still where it
        # has always been.
        cmds.undo()

        xformChildren = xformHier.children()
        self.assertEqual(len(xformChildren), 0)

        capsulePath = ufe.Path([
            proxyShapePathSegment,
            usdUtils.createUfePathSegment('/Capsule1')
        ])
        capsulePrim = mayaUsd.ufe.ufePathToPrim(
            ufe.PathString.string(capsulePath))
        capsuleXformable = UsdGeom.Xformable(capsulePrim)
        capsuleItem = ufe.Hierarchy.createItem(capsulePath)
        capsuleT3d = ufe.Transform3d.transform3d(capsuleItem)
        capsuleWorld = capsuleT3d.inclusiveMatrix()
        assertVectorAlmostEqual(self, capsuleWorldPre,
                                matrixToList(capsuleWorld))

        # Redo: capsule still hasn't moved.
        cmds.redo()

        checkParentDone()
예제 #59
0
    def testParentAbsolute(self):
        # Create scene items for the cube and the cylinder.
        shapeSegment = mayaUtils.createUfePathSegment(
            "|mayaUsdProxy1|mayaUsdProxyShape1")
        cubePath = ufe.Path(
            [shapeSegment,
             usdUtils.createUfePathSegment("/cubeXform")])
        cubeItem = ufe.Hierarchy.createItem(cubePath)
        cylinderPath = ufe.Path(
            [shapeSegment,
             usdUtils.createUfePathSegment("/cylinderXform")])
        cylinderItem = ufe.Hierarchy.createItem(cylinderPath)

        # get the USD stage
        stage = mayaUsd.ufe.getStage(str(shapeSegment))

        # check GetLayerStack behavior
        self.assertEqual(stage.GetEditTarget().GetLayer(),
                         stage.GetRootLayer())

        # The cube is not a child of the cylinder.
        cylHier = ufe.Hierarchy.hierarchy(cylinderItem)
        cylChildren = cylHier.children()
        self.assertEqual(len(cylChildren), 1)

        # Get its world space transform.
        cubeT3d = ufe.Transform3d.transform3d(cubeItem)
        cubeWorld = cubeT3d.inclusiveMatrix()
        cubeWorldListPre = matrixToList(cubeWorld)

        # Parent cube to cylinder in absolute mode (default), using UFE
        # path strings.
        cmds.parent("|mayaUsdProxy1|mayaUsdProxyShape1,/cubeXform",
                    "|mayaUsdProxy1|mayaUsdProxyShape1,/cylinderXform")

        # Confirm that the cube is now a child of the cylinder.
        cylChildren = cylHier.children()
        self.assertEqual(len(cylChildren), 2)
        self.assertIn("cubeXform", childrenNames(cylChildren))

        # Undo: the cube is no longer a child of the cylinder.
        cmds.undo()

        cylChildren = cylHier.children()
        self.assertEqual(len(cylChildren), 1)

        # Redo: confirm that the cube is again a child of the cylinder.
        cmds.redo()

        cylChildren = cylHier.children()
        self.assertEqual(len(cylChildren), 2)
        self.assertIn("cubeXform", childrenNames(cylChildren))

        # Confirm that the cube's world transform has not changed.  Must
        # re-create the item, as its path has changed.
        cubeChildPath = ufe.Path([
            shapeSegment,
            usdUtils.createUfePathSegment("/cylinderXform/cubeXform")
        ])
        cubeChildItem = ufe.Hierarchy.createItem(cubeChildPath)
        cubeChildT3d = ufe.Transform3d.transform3d(cubeChildItem)

        cubeWorld = cubeChildT3d.inclusiveMatrix()
        assertVectorAlmostEqual(self,
                                cubeWorldListPre,
                                matrixToList(cubeWorld),
                                places=6)

        # Cube world y coordinate is currently 0.
        self.assertAlmostEqual(cubeWorld.matrix[3][1], 0)

        # Move the parent
        ufe.GlobalSelection.get().append(cylinderItem)

        cmds.move(0, 10, 0, relative=True)

        # Get the world space transform again.  The y component should
        # have incremented by 10.
        cubeWorld = cubeChildT3d.inclusiveMatrix()
        self.assertAlmostEqual(cubeWorld.matrix[3][1], 10)

        # Undo everything.
        for i in range(2):
            cmds.undo()

        cylChildren = cylHier.children()
        self.assertEqual(len(cylChildren), 1)
예제 #60
0
    def testParentAbsoluteFallback(self):
        """Test parent -absolute on prim with a fallback Maya transform stack."""
        # Create a scene with an xform and a capsule.
        import mayaUsd_createStageWithNewLayer

        mayaUsd_createStageWithNewLayer.createStageWithNewLayer()
        proxyShapePathStr = '|stage1|stageShape1'
        stage = mayaUsd.lib.GetPrim(proxyShapePathStr).GetStage()
        xformPrim = stage.DefinePrim('/Xform1', 'Xform')
        capsulePrim = stage.DefinePrim('/Capsule1', 'Capsule')
        xformXformable = UsdGeom.Xformable(xformPrim)
        capsuleXformable = UsdGeom.Xformable(capsulePrim)

        proxyShapePathSegment = mayaUtils.createUfePathSegment(
            proxyShapePathStr)

        # Translate and rotate the xform and capsule to set up their initial
        # transform ops.
        xformPath = ufe.Path(
            [proxyShapePathSegment,
             usdUtils.createUfePathSegment('/Xform1')])
        xformItem = ufe.Hierarchy.createItem(xformPath)
        capsulePath = ufe.Path([
            proxyShapePathSegment,
            usdUtils.createUfePathSegment('/Capsule1')
        ])
        capsuleItem = ufe.Hierarchy.createItem(capsulePath)

        sn = ufe.GlobalSelection.get()
        sn.clear()
        sn.append(xformItem)

        cmds.move(0, 5, 0, r=True, os=True, wd=True)
        cmds.rotate(0, 90, 0, r=True, os=True, fo=True)

        self.assertEqual(
            xformXformable.GetXformOpOrderAttr().Get(),
            Vt.TokenArray(("xformOp:translate", "xformOp:rotateXYZ")))

        sn.clear()
        sn.append(capsuleItem)

        cmds.move(-10, 0, 8, r=True, os=True, wd=True)
        cmds.rotate(90, 0, 0, r=True, os=True, fo=True)

        # Add an extra rotate transform op.  In so doing, the capsule prim no
        # longer matches the Maya transform stack, so our parent -absolute
        # operation will be forced to append Maya fallback transform stack ops
        # to the capsule.
        capsuleXformable.AddRotateXOp()
        self.assertEqual(
            capsuleXformable.GetXformOpOrderAttr().Get(),
            Vt.TokenArray(
                ("xformOp:translate", "xformOp:rotateXYZ", "xformOp:rotateX")))

        capsuleT3d = ufe.Transform3d.transform3d(capsuleItem)
        capsuleWorld = capsuleT3d.inclusiveMatrix()
        capsuleWorldPre = matrixToList(capsuleWorld)

        # The xform currently has no children.
        xformHier = ufe.Hierarchy.hierarchy(xformItem)
        xformChildren = xformHier.children()
        self.assertEqual(len(xformChildren), 0)

        # Parent the capsule to the xform.
        cmds.parent(ufe.PathString.string(capsulePath),
                    ufe.PathString.string(xformPath))

        def checkParentDone():
            # The xform now has the capsule as its child.
            xformChildren = xformHier.children()
            self.assertEqual(len(xformChildren), 1)
            self.assertIn('Capsule1', childrenNames(xformChildren))

            # Confirm that the capsule has not moved in world space.  Must
            # re-create the prim and its scene item, as its path has changed.
            capsulePath = ufe.Path([
                proxyShapePathSegment,
                usdUtils.createUfePathSegment('/Xform1/Capsule1')
            ])
            capsulePrim = mayaUsd.ufe.ufePathToPrim(
                ufe.PathString.string(capsulePath))
            capsuleXformable = UsdGeom.Xformable(capsulePrim)
            capsuleItem = ufe.Hierarchy.createItem(capsulePath)
            capsuleT3d = ufe.Transform3d.transform3d(capsuleItem)
            capsuleWorld = capsuleT3d.inclusiveMatrix()
            assertVectorAlmostEqual(self, capsuleWorldPre,
                                    matrixToList(capsuleWorld))

            # The capsule's transform ops now have Maya fallback stack ops.  A
            # scale fallback op is added, even though it's uniform unit.
            self.assertEqual(
                capsuleXformable.GetXformOpOrderAttr().Get(),
                Vt.TokenArray(
                    ("xformOp:translate", "xformOp:rotateXYZ",
                     "xformOp:rotateX", "xformOp:translate:maya_fallback",
                     "xformOp:rotateXYZ:maya_fallback",
                     "xformOp:scale:maya_fallback")))

        checkParentDone()

        # Undo: the xform no longer has a child, the capsule is still where it
        # has always been, and the fallback transform ops are gone.
        cmds.undo()

        xformChildren = xformHier.children()
        self.assertEqual(len(xformChildren), 0)

        capsulePath = ufe.Path([
            proxyShapePathSegment,
            usdUtils.createUfePathSegment('/Capsule1')
        ])
        capsulePrim = mayaUsd.ufe.ufePathToPrim(
            ufe.PathString.string(capsulePath))
        capsuleXformable = UsdGeom.Xformable(capsulePrim)
        capsuleItem = ufe.Hierarchy.createItem(capsulePath)
        capsuleT3d = ufe.Transform3d.transform3d(capsuleItem)
        capsuleWorld = capsuleT3d.inclusiveMatrix()
        assertVectorAlmostEqual(self, capsuleWorldPre,
                                matrixToList(capsuleWorld))
        self.assertEqual(
            capsuleXformable.GetXformOpOrderAttr().Get(),
            Vt.TokenArray(
                ("xformOp:translate", "xformOp:rotateXYZ", "xformOp:rotateX")))

        # Redo: capsule still hasn't moved, Maya fallback ops are back.
        cmds.redo()

        checkParentDone()