Ejemplo n.º 1
0
def uiCmd_createSplineJointEachSpans( *args ):
    
    selections = cmds.ls( sl=1 )
    curve = selections[0]
    curveShape = cmds.listRelatives( curve, s=1 )[0]
    
    minValue = cmds.getAttr( curveShape+'.minValue' )
    maxValue = cmds.getAttr( curveShape+'.maxValue' )
    
    spans    = cmds.getAttr( curveShape+'.spans' )
    
    paramRange = maxValue - minValue
    eachParamRate = paramRange / spans
    
    infos = []
    
    for i in range( 0, spans+1 ):
        info = cmds.createNode( 'pointOnCurveInfo' )
        cmds.connectAttr( curveShape+'.local', info+'.inputCurve' )
        cmds.setAttr( info+'.parameter', eachParamRate*i )
        infos.append( info )
    
    cmds.select( d=1 )
    jnts = [ cmds.joint() ]
    for i in range( spans ):
        cmds.select( jnts[-1] )
        jnt = cmds.joint()
        jnts.append( jnt )
        
        distNode = cmds.createNode( 'distanceBetween' )
        cmds.connectAttr( infos[i]+'.position', distNode+'.point1' )
        cmds.connectAttr( infos[i+1]+'.position', distNode+'.point2' )
        cmds.connectAttr( distNode+'.distance', jnt+'.tx' )

    cmds.ikHandle( sj=jnts[0], ee=jnts[-1], sol='ikSplineSolver', ccv=False, pcv=False, curve=curveShape )
Ejemplo n.º 2
0
def ik_stretch(ikhnd):
    '''

    '''
    jts = cmds.ikHandle(ikhnd, q=True, jl=True)
    cu_s = cmds.ikHandle(ikhnd, q=True, c=True)
    cu = cmds.listRelatives(cu_s, p=1)[0]
    cmds.addAttr(ikhnd, longName='ik_stretch', k=1, defaultValue=1.0, minValue=0.0, maxValue=1.)

    dcu = cmds.duplicate(cu, n=cu + '_base_scale')[0]
    dcu_s = cmds.listRelatives(dcu, c=1)[0]

    cf = cmds.createNode('curveInfo')
    dcf = cmds.createNode('curveInfo')
    bl = cmds.createNode('blendTwoAttr')
    md = cmds.createNode('multiplyDivide')

    cmds.connectAttr(cu_s + '.worldSpace', cf + '.inputCurve')
    cmds.connectAttr(dcu_s + '.worldSpace', dcf + '.inputCurve')
    cmds.connectAttr(dcf + '.arcLength', bl + '.input[0]')
    cmds.connectAttr(cf + '.arcLength', bl + '.input[1]')
    cmds.connectAttr(ikhnd + '.ik_stretch', bl + '.attributesBlender')
    cmds.connectAttr(bl + '.output', md + '.input1X')

    cmds.setAttr(md + '.input2X', cmds.getAttr(cf + '.arcLength'), l=1)
    cmds.setAttr(md + '.operation', 2)
    cmds.setAttr(dcu + '.v', 0)

    for j in jts:
        cmds.connectAttr(md + '.outputX', j + '.sx')

    return dcu
Ejemplo n.º 3
0
 def __init__(self, curve_sel, vertex_list):
     self.curve_sel = curve_sel
     self.verts = vertex_list
     self.find_length = Find_Out()
             
     self.link_length = self.find_length.edge_length(self.verts)
     self.chain_length = self.find_length.curve_length(self.curve_sel)
     self.link_total = int(self.chain_length/self.link_length)
     
     cmds.duplicate(self.curve_sel, n = 'buildCurve')
     cmds.rebuildCurve('buildCurve', ch = 1, rpo = 1, rt = 0, end = 1, kr = 2, kep = 1, kt = 0, kcp = 0, s = self.link_total/2, d = 3, tol = 0.01 )
     
     self.num_cv = int(cmds.getAttr ('buildCurve.degree'))+ (cmds.getAttr ('buildCurve.spans'))
     
     for dummy_cv in range(self.num_cv):
         dummy_cv_pos = (cmds.getAttr ('buildCurve.cv['+ str(dummy_cv) +']'))
         
         if dummy_cv == 0:
             cmds.joint(n=self.curve_sel+'_jointRoot',p = dummy_cv_pos[0])
         elif dummy_cv == self.num_cv - 1:
             cmds.joint(n=self.curve_sel+'_jointEnd', p = dummy_cv_pos[0])
         else:
             cmds.joint(n=self.curve_sel+'_joint_'+(str(dummy_cv)),p = dummy_cv_pos[0])    
     
     cmds.delete('buildCurve')        
     cmds.ikHandle( sj = (self.curve_sel+'_jointRoot'), ee = (self.curve_sel+'_jointEnd'), c = self.curve_sel,
             sol = 'ikSplineSolver', scv = 0, pcv = 0, ccv = 0, ns = 4)       
Ejemplo n.º 4
0
def switchToIK( control, ikHandle=None, poleControl=None, onCmd=None, offCmd=None ):
	'''
	this proc will align the IK controller to its fk chain
	flags used:
	-control   this is the actual control being used to move the ikHandle - it is assumed to be the same object as the ikHandle, but if its different (ie if the ikHandle is constrained to a controller) use this flag
	-pole      tells the script the name of the pole controller - if there is no pole vector control, leave this flag out
	-ikHandle  this flag specifies the name of the ikHandle to work on
	-onCmd     this flag tells the script what command to run to turn the ik handle on - it is often left blank because its assumed we're already in ik mode
	-offCmd    this flag holds the command to turn the ik handle off, and switch to fk mode
	NOTE: if the offCmd isn't specified, it defaults to:  if( `getAttr -se ^.ikb` ) setAttr ^.ikb 1;

	symbols to use in cmd strings:
	 ^  refers to the ikHandle
	 #  refers to the control object

	example:
	zooAlignIK "-control somObj -ikHandle ikHandle1 -offCmd setAttr #.fkMode 0";
	'''
	if ikHandle is None:
		ikHandle = control

	if callable( onCmd ):
		onCmd( control, ikHandle, poleControl )

	joints = cmd.ikHandle( ikHandle, q=True, jl=True )
	effector = cmd.ikHandle( ikHandle, q=True, ee=True )
	effectorCtrl = listConnections( '%s.tx' % effector, d=False )[ 0 ]

	mel.zooAlign( "-src %s -tgt %s" % (effectorCtrl, control) )
	if poleControl is not None and objExists( poleControl ):
		pos = mel.zooFindPolePosition( "-start %s -mid %s -end %s" % (joints[ 0 ], joints[ 1 ], effectorCtrl) )
		move( pos[0], pos[1], pos[2], poleControl, a=True, ws=True, rpr=True )

	if callable( offCmd ):
		offCmd( control, ikHandle, poleControl )
Ejemplo n.º 5
0
 def RMIdentifyIKJoints(self,ikHandle):
     endEffector = cmds.ikHandle(ikHandle, q = True, endEffector = True)
     EndJoint = RMRigTools.RMCustomPickWalk (endEffector, 'joint', 1, Direction = "up")
     EndJoint = RMRigTools.RMCustomPickWalk (EndJoint[len(EndJoint)-1], 'joint', 1)
     EndJoint = EndJoint[1]
     StartJoint = cmds.ikHandle(ikHandle, q = True, startJoint = True)
     return RMRigTools.FindInHieararchy (StartJoint, EndJoint)
Ejemplo n.º 6
0
    def _create_reverse_setup(self):
        
        # Create Ik handles
        ball_ik, ball_effector = cmds.ikHandle(sj=self.joint_detail['ankle'], ee=self.joint_detail['ball'], sol="ikSCsolver")
        tip_ik, tip_effector = cmds.ikHandle(sj=self.joint_detail['ball'], ee=self.joint_detail['tip'], sol="ikSCsolver")

        self.ik_detail['ball'] = ball_ik
        self.ik_detail['tip'] = tip_ik
Ejemplo n.º 7
0
def build(startJoint,endJoint,solver='ikSCsolver',curve='',ikSplineOffset=0.0,prefix=''):
	'''
	INPUTS:
	@input startJoint: Start joint for the IK handle
	@inputType startJoint: str
	@input endJoint: End joint for the IK handle
	@inputType endJoint: str
	@input solver: IK Solver to use
	@inputType solver: str
	@input curve: Input curve for splineIK
	@inputType curve: str
	@input ikSplineOffset: Offset value for ikSplineSolver
	@inputType ikSplineOffset: float
	@input prefix: Name prefix for all builder created nodes
	@inputType prefix: str
	'''
	# Check joints
	if not mc.objExists(startJoint): raise Exception('Joint '+startJoint+' does not exist!!')
	if not mc.objExists(endJoint): raise Exception('Joint '+endJoint+' does not exist!!')
	
	# Check solver type
	ikType = ['ikSplineSolver','ikSCsolver','ikRPsolver','ik2Bsolver']
	if not ikType.count(solver):
		raise Exception('Invalid ikSlover type specified ("'+solver+ '")!!')
	
	# Check curve
	createCurve = False
	if solver == ikType[0]: # solver = ikSplineSolver
		if not mc.objExists(curve):
			createCurve = True
	
	# Extract name prefix from joint name
	if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(startJoint)
	
	mc.select(cl=True)
	
	#-----------------
	# Create ikHandle
	ik = []
	if solver == ikType[0]:
		# Spline IK solver
		ik = mc.ikHandle(sj=startJoint,ee=endJoint,sol=solver,curve=curve,ccv=createCurve,pcv=False)
	else:
		# Chain IK solver
		ik = mc.ikHandle(sj=startJoint,ee=endJoint,sol=solver)
	
	# Clear selection (to avoid printed warning message)
	mc.select(cl=True)
	
	# Rename ikHandle and endEffector
	ikHandle = str(mc.rename(ik[0],prefix+'_ikHandle'))
	ikEffector = str(mc.rename(ik[1],prefix+'_ikEffector'))
	
	# Set ikHandle offset value
	mc.setAttr(ikHandle+'.offset',ikSplineOffset)
	
	# Return result
	return ikHandle
Ejemplo n.º 8
0
	def createListRig(self, list,nameElement,ikHandleBase=None):
		for index in range(len(list)):
			tuplePoint = list[index]
			cmds.joint(p=tuplePoint,name=nameElement + str(index))
			cmds.ikHandle( sj=ikHandleBase ,ee=nameElement + "0")
			cmds.select(nameElement + str(index))
		for index in range(len(list)-1) :
			cmds.select(nameElement + str(index+1))
			cmds.ikHandle(sj=nameElement + str(index))
Ejemplo n.º 9
0
    def ikSplineSolver(self, 
                         startJoint = None, 
                         endEffector = None, 
                         curve = 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
        if curve == None:
            ik = cmds.ikHandle(startJoint = startJoint, 
                                endEffector = endEffector, 
                                createCurve = True, 
                                name = self.ik_name, solver = 'ikSplineSolver')
        else:
            if cmds.objExists(curve):
                ik = cmds.ikHandle(startJoint = startJoint, 
                                    endEffector = endEffector, 
                                    curve = curve, createCurve = False, 
                                    name = self.ik_name, solver = 'ikSplineSolver')
            else:
                raise Exception('There is no specified curve: ' + curve )

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

        #--- store the ik_handle and effector in a list to return
        ik_handle = []
        if curve == None:
            #--- rename the automated curve
            crv = cmds.rename(ik[-1], ik[0] + 'CRV')
            ik_handle = [ik[0], eff, crv]
        else:
            ik_handle = [ik[0], eff, curve]

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

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

        cmds.select(clear = 1)
        return ik_handle
    #end def ikSplineSolver()
#end class IkHandle()
Ejemplo n.º 10
0
Archivo: leg.py Proyecto: chirs/studio5
def make_joint():
    """
    Create a few joints
    """

    cmds.select(d=True)
    cmds.joint(p=(0, 0, 0), name="joint1")
    cmds.joint(p=(0, 4, 0), name="joint2")
    cmds.joint("joint1", e=True, zso=True, oj="xyz")
    cmds.joint(p=(0, 8, -1), name="joint3")
    cmds.joint("joint2", e=True, zso=True, oj="xyz")
    cmds.joint(p=(2, 9, 3), name="joint4")
    cmds.joint("joint3", e=True, zso=True, oj="xyz")

    cmds.ikHandle(n="tendon", sj="joint1", ee="joint4", p=2, w=0.5)
Ejemplo n.º 11
0
 def setupIK(self, ikChain):
     # setup IK:
     """
     setup an ik on the input list
     :param ikChain: list of joint chain to set an ik on
     """
     handle = cmd.ikHandle(n=ikChain[0] + '_ikHandle', sj=ikChain[0], ee=ikChain[-1], sol='ikRPsolver', s=0)
Ejemplo n.º 12
0
 def create_ik_setup(self):
     """@todo: insert doc for create_ik_setup"""
     # ik arm, hand
     ik_arm = cmds.ikHandle(sj=self.ik_jnts[0], ee=self.ik_jnts[2], sol='ikRPsolver')
     cmds.rename(ik_arm[1], '%s_%s_%s' % (self.side, 'arm', self.nc.effector))
     ik_arm = cmds.rename(ik_arm[0], '%s_%s_%s' % (self.side, 'arm', self.nc.ikhandle))
     ik_hand = cmds.ikHandle(sj=self.ik_jnts[2], ee=self.ik_jnts[3])
     cmds.rename(ik_hand[1], '%s_%s_%s' % (self.side, 'arm', self.nc.effector))
     ik_hand = cmds.rename(ik_hand[0], '%s_%s_%s' % (self.side, 'hand', self.nc.ikhandle))
     cmds.parent(ik_arm, ik_hand, self.controls['handik'])
     self.create_ik_arm_stretch()
     pv = cmds.poleVectorConstraint(self.controls['elbow'], ik_arm, weight=1)
     self.create_elbow_pin()
     # twist switch
     cmds.connectAttr('%s.twist' % self.controls['hand'], '%s_%s_%s.dTwistControlEnable' % (self.side, 'upperArm', self.nc.ikhandle), f=True)
     cmds.connectAttr('%s.twist' % self.controls['hand'], '%s_%s_%s.dTwistControlEnable' % (self.side, 'foreArm', self.nc.ikhandle), f=True)
Ejemplo n.º 13
0
def  MakeJntAndIKs(side):
    """
    选择两圈眼球上的线,生成骨骼和ik,side的值例如:R_In or R_Out
    ps: 选择骨骼链的子物体,打组,centerPivot,在原点生成一个骨点,用组约束骨点,正确命名,然后将IK组分别放到对应骨点下边。
    """    
    lx_start=mc.xform('loc_eyeCenter01',q=1,ws=1,t=1)
    lx_mouthPnt= mc.filterExpand(sm=31)
    mc.select (cl=1)
    lx_Jnts=[]
    lx_IKs = []
    for i in lx_mouthPnt :
        lx_end=mc.xform(i,q=1,ws=1,t=1)
        lx_stJnt=mc.joint (n=("Jnt_"+side+"_st"),p=(lx_start[0],lx_start[1],lx_start[2]),radius=0.1)
        lx_edJnt=mc.joint (n=("Jnt_"+side+"_ed"),p=(lx_end[0],lx_end[1],lx_end[2]),radius=0.1)        
        lx_scik =mc.ikHandle (n=("scik_"+side+str(01)),sj=lx_stJnt,ee=lx_edJnt,sol="ikSCsolver")
        #mc.setAttr((str(lx_scik[0]) +".visibility") ,0)
        mc.select(cl=1)
        lx_Jnts.append(lx_stJnt)
        lx_IKs .append(lx_scik[0])
    mc.select(lx_Jnts,r=1)
    mc.group(n=("grp_Jnts"+side))
    
    mc.select(lx_IKs,r=1)
    mc.group(n=("grp_iks"+side))
    mc.setAttr((str("grp_iks"+side) +".visibility") ,0)
    
#3.选择眼皮曲线,执行脚本,生成
    def  MakeEyeLidJnts(cuvs):
        
        
Ejemplo n.º 14
0
 def setupIK(self):
     #Create shoulder 
     self.m_shoulderCtrl = cmds.spaceLocator(
         n=self.m_joints.m_shoulder.replace("_JNT", "_LOC")
         )[0]
     # Add to controls
     rc.addToControlDict(self.m_allControls, "%s_IKShoulder" %(self.m_baseName), self.m_shoulderCtrl)
     rc.addToLayer(self.m_sceneData, "hidden", self.m_shoulderCtrl)
     rc.orientControl(self.m_shoulderCtrl, self.m_joints.m_shoulder)
     rg.add3Groups(self.m_shoulderCtrl, ["_SDK", "_CONST", "_0"])
     cmds.parent(self.m_shoulderCtrl+"_0", self.m_group, r=1)
     cmds.pointConstraint(
         self.m_shoulderCtrl, 
         self.m_joints.m_shoulder, 
         mo=1
         )
     desiredName = self.m_wristCtrl.replace("_CTRL", "_IK")
     self.m_ikHandle = cmds.ikHandle(
         n = desiredName, 
         sj = self.m_joints.m_shoulder, 
         ee = self.m_joints.m_wrist, 
         sol = "ikRPsolver", 
         see = True
         )[0]
     # deselect so we don't get errors
     cmds.select(d=1)
     rc.addToLayer(self.m_sceneData, "hidden", [self.m_ikHandle])
     cmds.parent(self.m_ikHandle, self.m_wristCtrl)
     self.setupPoleVec()
Ejemplo n.º 15
0
    def _setup(self):
        sj = self.joints[0]
        ej = self.joints[-1]

        self.spineCurve = 'curve_bindSpine'
        # setup IK
        ikSpine = cmd.ikHandle(sj=sj, ee=ej, name='ikHandle_bindSpine', sol='ikSplineSolver', createCurve=True,
                               ns=2)
        cmd.rename(ikSpine[2], self.spineCurve)

        # clusters
        clusterReturn = general.clusterCurve(self.spineCurve, 'cluster_spineIK')
        clusters = clusterReturn[0]
        clusterGrp = clusterReturn[1]

        # ==================controllers setup=============================
        if self.upperCtrl == None:
            self.upperCtrl = self._drawCtrl('ctrl_upperTorso', self.joints[-2])
        if self.lowerCtrl == None:
            self.lowerCtrl = self._drawCtrl('ctrl_lowerTorso', self.joints[1])

        for i in [0, 1]:
            cmd.parentConstraint(self.lowerCtrl, clusters[i], mo=True)
        for i in [2, 3, 4]:
            cmd.parentConstraint(self.upperCtrl, clusters[i], mo=True)
    def testAnimIKRW(self):

        name = createJoints()
        handleName = MayaCmds.ikHandle(sj=name, ee='joint4')[0]
        MayaCmds.currentTime(1, update=True)
        MayaCmds.setKeyframe(handleName, breakdown=0, hierarchy='none', controlPoints=False, shape=False)
        MayaCmds.currentTime(16, update=True)
        MayaCmds.move(-1.040057, -7.278225, 6.498725, r=True)
        MayaCmds.setKeyframe(handleName, breakdown=0, hierarchy='none', controlPoints=False, shape=False)

        self.__files.append(util.expandFileName('testAnimIKRW.abc'))
        self.__files.append(util.expandFileName('testAnimIKRW01_08.abc'))
        self.__files.append(util.expandFileName('testAnimIKRW09-16.abc'))

        # write to files
        MayaCmds.AbcExport(j='-fr 1 8 -root %s -f %s' % (name, self.__files[-2]))
        MayaCmds.AbcExport(j='-fr 9 16 -root %s -f %s' % (name, self.__files[-1]))
        MayaCmds.select(name)
        MayaCmds.group(name='original')

        subprocess.call(self.__abcStitcher + self.__files[-3:])

        # read from file
        MayaCmds.AbcImport(self.__files[-3], mode='import')

        # make sure the translate and rotation are the same
        nodes1 = ["|original|joint1", "|original|joint1|joint2", "|original|joint1|joint2|joint3", "|original|joint1|joint2|joint3|joint4"]
        nodes2 = ["|joint1", "|joint1|joint2", "|joint1|joint2|joint3", "|joint1|joint2|joint3|joint4"]

        for t in range(1, 25):
            MayaCmds.currentTime(t, update=True)
            for i in range(0, 4):
                self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tx'), MayaCmds.getAttr(nodes2[i]+'.tx'), 4)
                self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.ty'), MayaCmds.getAttr(nodes2[i]+'.ty'), 4)
                self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tz'), MayaCmds.getAttr(nodes2[i]+'.tz'), 4)
Ejemplo n.º 17
0
 def surfJnts(name, pairL):
     jntPairs = []
     iks = []
     j = 0
     for pair in pairL:
         jnts = []
         i = 0
         suff = ['_root', '_aim', '_up']
         for point in pair:
             cmds.select(point)
             pos = cmds.xform(point, q=True, t=True, ws=True)
             jnts.append(place.joint(0, name + str(j) + suff[i] + '_jnt', pad=2, rpQuery=False)[0])
             i = i + 1
         j = j + 1
         # parent ik joints
         cmds.parent(jnts[1], jnts[0])
         # orient ik joints
         cmds.joint(jnts[0], e=True, oj='zyx', secondaryAxisOrient='yup')
         jnt.ZeroJointOrient(jnts[1])
         # orient up vector jnt
         cmds.parent(jnts[2], jnts[0])
         jnt.ZeroJointOrient(jnts[2])
         cmds.parent(jnts[2], w=True)
         # append pairs to list
         jntPairs.append(jnts)
         # ik
         ikhndl = cmds.ikHandle(sj=jnts[0], ee=jnts[1], sol='ikRPsolver', sticky='sticky')[0]
         cmds.setAttr(ikhndl + '.visibility', False)
         cmds.poleVectorConstraint(jnts[2], ikhndl)
         iks.append(ikhndl)
         # cleanup
         place.cleanUp(jnts[0], SknJnts=True)
         place.cleanUp(jnts[2], SknJnts=True)
         place.cleanUp(ikhndl, World=True)
     return jntPairs, iks
Ejemplo n.º 18
0
    def setup(self):

        #duplicate given joints
        cmds.duplicate( self.oldJoint1, n=self.dupJoint1, po=True )
        cmds.duplicate( self.oldJoint2, n=self.dupJoint2, po=True )
        cmds.parent( self.dupJoint2, self.dupJoint1 )
        cmds.parent(self.dupJoint1, w=True)

        #create rp ik
        ik = cmds.ikHandle(
            sol='ikRPsolver',
            sj=self.dupJoint1,
            ee=self.dupJoint2,
            n=self.ik
        )[0]

        #zero pole vectors
        cmds.setAttr("{0}.poleVectorX".format(self.ik), 0)
        cmds.setAttr("{0}.poleVectorY".format(self.ik), 0)
        cmds.setAttr("{0}.poleVectorZ".format(self.ik), 0)

        #parent to bindJoint
        cmds.select( self.oldJoint1)
        clav = cmds.pickWalk(d='Up')
        cmds.parent( self.ik, self.oldJoint1)
        cmds.parent( self.dupJoint1, clav )

        #hide ik
        cmds.setAttr( '{0}.v'.format(ik), 0 )

        # hide them they ugly
        cmds.setAttr( "{0}.v".format(self.dupJoint1), 0)
        cmds.setAttr( "{0}.v".format(self.dupJoint2), 0)
Ejemplo n.º 19
0
 def create_ik_setup(self):
     """Creates the IK setup."""
     ik = cmds.ikHandle(sj=self.result_jnts[0], ee=self.result_jnts[1])
     cmds.rename(ik[1], '%s_%s_%s' % (self.side, 'shoulder', self.nc.effector))
     ik = cmds.rename(ik[0], '%s_%s_%s' % (self.side, 'shoulder', self.nc.ikhandle))
     cmds.parent(ik, self.controls['ik'])
     self.create_ik_stretch()
Ejemplo n.º 20
0
    def createToeIk(self, ball, toe, iksSolver, footCtrl, *args):
        """ Create an Ik Solver """
        solverName = toe.replace("ikPJnt_", "toeSolver_")
        iktSolver = cmds.ikHandle(n=solverName, sj=ball, ee=toe, sol="ikRPsolver")

        """ Create attributes on the foot control """
        attributes = ("toe_roll", "toe_twist", "toe_bank")
        cmds.select(footCtrl)
        for attr in attributes:  
            cmds.addAttr(shortName=attr, longName=attr, defaultValue=0, k=True)
        cmds.select(d=True)

        """ Create a group at the toe """
        groupName = toe.replace("ikPJnt_", "grp_ik_")
        grpPos = cmds.xform(toe, q=True, t=True, ws=True)
        toeGrp = cmds.group(name=groupName, em=True, p=footCtrl[0])

        cmds.select(toeGrp)
        cmds.xform(toeGrp, t=grpPos, ws=True) 
        cmds.select(d=True)
        #cmds.parent(toeGrp, footCtrl)
        #cmds.parent(iktSolver, footCtrl)
        #cmds.parent(iksSolver, toeGrp)
        #cmds.parent(iktSolver, toeGrp)
        cmds.connectAttr(footCtrl[0]+".toe_roll", toeGrp+".rotateX")
        cmds.connectAttr(footCtrl[0]+".toe_twist", toeGrp+".rotateY")
        cmds.connectAttr(footCtrl[0]+".toe_bank", toeGrp+".rotateZ")
Ejemplo n.º 21
0
    def create_ik(jnt_start, jnt_end, type = 'RPS', up_vec = [0,1,0], name = '_IKH', create_curve = True, curve=None, reparent_curve = False, freeze_joints = True):
        '''
        Desc:
        Create ikhandle between defined start and end joint

        Parameter:
        jnt_start = start joint
        jnt_end = end joint
        type = ikh type
        up_vec = user defined up vector
        name = ikh member name

        Return:
        Ik handle node created by procedure
        '''
        solver = None
        if type == 'RPS':
            solver = 'ikRPsolver'
            name = '_IKH'
        elif type == 'SCS':
            solver = 'ikSCsolver'
            name = '_IKH'
        elif type == 'SS':
            solver = 'ikSplineSolver'
            name == 'IKHS'
        ikh = cmds.ikHandle(name = name, sj = jnt_start, ee = jnt_end, solver = solver, createCurve=create_curve, curve=curve, freezeJoints = freeze_joints, parentCurve = reparent_curve)
        return ikh
Ejemplo n.º 22
0
    def get_polar_position(self, handle):
        """Get pole position."""
        joints = cmds.ikHandle(handle, jl=True, q=True)
        joints.append(cmds.listRelatives(joints[-1], c=1)[0])

        j1 = cmds.xform(joints[0], q=1, ws=1, t=1)
        j2 = cmds.xform(joints[1], q=1, ws=1, t=1)
        j3 = cmds.xform(joints[2], q=1, ws=1, t=1)

        vec1 = om.MVector(j1)
        vec2 = om.MVector(j2)
        vec3 = om.MVector(j3)

        first_last = vec3 - vec1
        first_second = vec2 - vec1

        dot = first_second * first_last
        cast = float(dot) / float(first_last.length())
        first_last_normal = first_last.normal()
        cast_vec = first_last_normal * cast

        point = (first_second - cast_vec) * 3
        pole_pos = point + vec2
        pole_offset = om.MVector(cmds.xform(self.polar, q=1, rp=1))
        return(pole_pos - pole_offset)
Ejemplo n.º 23
0
def j_BodyFix():
    # Get The Goal Joint position 
    position = dict()
    dupJnt = ['ShoulderPart2_L','Elbow_L','ElbowPart1_L','HipPart2_L','Knee_L','KneePart1_L']
    for jnt in dupJnt:
        position[jnt] =mc.xform(jnt,ws=1,t=1,q=1)
        
    # Create  Joint  And Ikhandle From position
    newJnt = []
    na =1;
    for j in dupJnt: 
        if mc.objExists(('Fix'+j)):
            mc.select(('Fix'+j),r=1)
            break;
        newJnt.append(mc.joint(n=('Fix'+j),p=position[j],radius=1.75))
        if na%3==0:        
        # Create IKHandle With ikRPsolver , Then Mirror With IkHandle
            mc.joint(newJnt[0],e=1,zso=1,oj='xyz',sao='yup')
            mc.joint(newJnt[1],e=1,zso=1,oj='xyz',sao='yup')
            mc.setAttr('%s.jointOrient'%newJnt[2],0,0,0)
            ikhand = mc.ikHandle(name=('rpik_'+newJnt[1]+'01'),sj=newJnt[0],ee=newJnt[2],sol = 'ikSCsolver')
            mc.setAttr('%s.v'%ikhand[0],0)
            # mirrorJoint -mirrorYZ -mirrorBehavior -searchReplace "_L" "_R";
            mc.mirrorJoint(newJnt[0],mirrorYZ =1,mirrorBehavior =1,searchReplace=('_L','_R'))
            mc.parent(ikhand[0],j)
            mc.parent((re.sub('_L',"_R",ikhand[0])),(re.sub('_L','_R',j)))
            mc.parent(newJnt[0],dupJnt[na-3])
            mc.parent((re.sub("_L","_R",newJnt[0])),(re.sub('_L','_R',dupJnt[na-3])))
            newJnt = []       
            mc.select(clear=1)
        na=na+1; 
Ejemplo n.º 24
0
    def create_ik(self):
        """Ik spline"""

        # Create curve
        tmp_curve = curve.create_from_nodes(self.joints, name=name.set_suffix(self.name, 'ikCrv'), degree=3)
        self.curve = curve.rebuild_curve(tmp_curve, 3)[0]

        start_joint, end_joint = self.ik_joints[0], self.ik_joints[-1]
        logger.info("Creating Ik using nodes: %s" % self.joints)
        self.ik, self.effector = cmds.ikHandle(name=name.set_suffix(self.name, 'ikh'), sj=start_joint, ee=end_joint, curve=self.curve, createCurve=False, sol="ikSplineSolver", ns=3)

        # Add to setups
        self.setups.extend([self.ik, self.curve])

        # Set attrs
        cmds.setAttr("%s.dTwistControlEnable" % self.ik, 1)
        cmds.setAttr("%s.dWorldUpAxis" % self.ik, 1)
        cmds.setAttr("%s.dWorldUpType" % self.ik, 4)
        cmds.setAttr("%s.dWorldUpVector" % self.ik, 1.0, 0.0, 0.0, type="float3")
        cmds.setAttr("%s.dWorldUpVectorEnd" % self.ik, 1.0, 0.0, 0.0, type="float3")

        # Turn on cvs
        cmds.select(self.curve, r=True)
        cmds.toggle(cv=True)

        # Create clusters
        clusters = OrderedDict()
        clusters['bot'] = cmds.cluster(["%s.cv[0]" % self.curve, "%s.cv[1]" % self.curve])[1]
        clusters['mid'] = cmds.cluster(["%s.cv[2]" % self.curve, "%s.cv[3]" % self.curve])[1]
        clusters['top'] = cmds.cluster(["%s.cv[4]" % self.curve, "%s.cv[5]" % self.curve])[1]
        
        xform.match_pivot(start_joint, clusters['bot'])
        xform.match_pivot(end_joint, clusters['top'])

        self.clusters = clusters
Ejemplo n.º 25
0
    def create_ik_setup(self):
        """Creates the IK setup."""
        ik = cmds.ikHandle(sj=self.result_jnts[0], ee=self.result_jnts[-1], sol='ikSplineSolver', ns=1)
        cmds.rename(ik[1], '%s_%s_%s' % (self.side, 'neck', self.nc.effector))
        curve = cmds.rename(ik[2], '%s_%s_%s' % (self.side, 'neck', self.nc.curve))
        cmds.setAttr('%s.inheritsTransform' % curve, 0)
        ik = cmds.rename(ik[0], '%s_%s_%s' % (self.side, 'neck', self.nc.ikhandle))
        cmds.select(self.additional_jnts, curve)
        cmds.skinCluster(tsb=True)
        cmds.parent(ik, self.top_grp)

        cmds.setAttr('%s.dTwistControlEnable' % ik, 1)
        cmds.setAttr('%s.dWorldUpType' % ik, 4)
        cmds.setAttr('%s.dWorldUpAxis' % ik, 4)
        cmds.setAttr('%s.dWorldUpVectorY' % ik, -1)
        cmds.setAttr('%s.dWorldUpVectorEndY' % ik, 1)
        cmds.setAttr('%s.dWorldUpVectorEndZ' % ik, -1)
        cmds.connectAttr('%s.worldMatrix[0]' % self.additional_jnts[0], '%s.dWorldUpMatrix' % ik, f=True)
        cmds.connectAttr('%s.worldMatrix[0]' % self.additional_jnts[1], '%s.dWorldUpMatrixEnd' % ik, f=True)
        self.head_grp = cmds.group(self.controls['head'])
        self.head_grp = cmds.rename(self.head_grp, '%s_head_CTL_%s' % (self.side, self.nc.group))
        cmds.parent(self.head_grp, self.top_grp)
        self.c.move_pivot_to(self.guides['neckEnd'][0], self.guides['neckEnd'][1], self.guides['neckEnd'][2], self.head_grp)
        cmds.parentConstraint(self.controls['head'], self.additional_jnts[-1], mo=True, weight=1)
        cmds.orientConstraint(self.controls['head_rot'], self.result_jnts[-1], mo=True, weight=1)
Ejemplo n.º 26
0
    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
Ejemplo n.º 27
0
def bdRigIkArm(side):
    ikChainStart = bdBuildDrvChain(side,'ik')
    ikChainJoints = cmds.listRelatives(ikChainStart, ad=True,type='joint')
    ikChainJoints.reverse()
    ikBones = ikChainStart + ikChainJoints
    print ikBones
    armIk = cmds.ikHandle(sol= 'ikRPsolver',sticky='sticky', startJoint=ikBones[0],endEffector = ikBones[2],name = side + '_arm_ikHandle')
    handIk = cmds.ikHandle(sol= 'ikSCsolver',sticky='sticky', startJoint=ikBones[2],endEffector = ikBones[3],name = side + '_hand_ikHandle')
    ikHandlesGrp = cmds.group([armIk[0],handIk[0]],n=side + '_arm_ikHandles_grp')
    wristPos = cmds.xform(ikBones[2],q=True,ws=True,t=True)
    cmds.move(wristPos[0], wristPos[1], wristPos[2], [ikHandlesGrp + '.scalePivot',ikHandlesGrp + '.rotatePivot'])
    pvAnim = cmds.ls(side + '_elbow_ik_anim', type='transform')[0]
    if pvAnim:
        cmds.poleVectorConstraint(pvAnim,armIk[0])
    
    ikAnimCtrl = cmds.ls(side + '_hand_ik_anim',type='transform')[0] 
    cmds.parentConstraint(ikAnimCtrl, ikHandlesGrp)
Ejemplo n.º 28
0
def chain_on_curve(name,num_j=12):
    curvs = get_curve()
    jt_grp = cmds.group(em=True,name='%s\#' %name)
    for cu in curvs:
        jts = chain(cu,num_j,'chain_joint')
        ikhnd=cmds.ikHandle(sj=jts[0], ee=jts[-1], c=cu, ccv=False, sol='ikSplineSolver',pcv=0)      
        cmds.parent(jts[0],jt_grp)
        cmds.delete(ikhnd)
Ejemplo n.º 29
0
 def create_ik_setup(self):
     """Creates the IK setup."""
     ik_leg = cmds.ikHandle(sj=self.ik_jnts[0], ee=self.ik_jnts[2], sol='ikRPsolver')
     cmds.rename(ik_leg[1], '%s_%s_%s' % (self.side, 'leg', self.nc.effector))
     ik_leg = cmds.rename(ik_leg[0], '%s_%s_%s' % (self.side, 'leg', self.nc.ikhandle))
     ik_foot = cmds.ikHandle(sj=self.ik_jnts[2], ee=self.ik_jnts[3])
     cmds.rename(ik_foot[1], '%s_%s_%s' % (self.side, 'foot', self.nc.effector))
     ik_foot = cmds.rename(ik_foot[0], '%s_%s_%s' % (self.side, 'foot', self.nc.ikhandle))
     ik_ball = cmds.ikHandle(sj=self.ik_jnts[3], ee=self.ik_jnts[4])
     cmds.rename(ik_ball[1], '%s_%s_%s' % (self.side, 'ball', self.nc.effector))
     ik_ball = cmds.rename(ik_ball[0], '%s_%s_%s' % (self.side, 'ball', self.nc.ikhandle))
     cmds.parent(ik_leg, ik_foot, self.controls['ik'])
     self.create_ik_stretch()
     cmds.poleVectorConstraint(self.controls['knee'], ik_leg, weight=1)
     self.create_knee_pin()
     self._reverse_foot([ik_leg, ik_foot, ik_ball])
     self._foot_attributes([ik_leg, ik_foot, ik_ball])
Ejemplo n.º 30
0
def createIK(side, part, IKstartJoint, IKendJoint):
	print "In Create IK"

	IKName = side + part + "_ikHandle"
	IK_handle = cmds.ikHandle(n=IKName, sj=IKstartJoint, ee=IKendJoint, sol="ikRPsolver")
	cmds.select(cl=True)

	return IK_handle
Ejemplo n.º 31
0
    def build_ik(self):
        # use ik auto create curve with 2 span (5 cvs), exclude the root joint
        cmds.ikHandle(startJoint=self.jnt_list[1],
                      endEffector=self.jnt_list[-1],
                      name=self.ik_name,
                      createCurve=1,
                      parentCurve=False,
                      roc=1,
                      solver='ikSplineSolver',
                      simplifyCurve=1,
                      numSpans=2)
        cmds.rename('curve1', self.ik_curve)

        cmds.cluster(self.ik_curve + '.cv[0:1]', name=self.cluster_list[0])
        cmds.cluster(self.ik_curve + '.cv[2]', name=self.cluster_list[1])
        cmds.cluster(self.ik_curve + '.cv[3:4]', name=self.cluster_list[-1])

        cmds.setAttr(self.ik_name + '.visibility', 0)  # hide ik
        cmds.parent(self.ik_name, self.ctrl_grp)
Ejemplo n.º 32
0
def SK_findAllIKJoints():
    AllIkJnts = []
    AllIkHandes = rig.ls(type='ikHandle')
    for handle in AllIkHandes:
        startJnt = rig.ikHandle(handle, q=True, sj=True)
        endJnt = rig.listConnections(rig.ikHandle(handle, q=True, ee=True),
                                     d=False,
                                     s=True,
                                     type='joint')[0]
        AllIkJnts.append(startJnt)
        AllIkJnts.append(endJnt)
        while (True):
            temUpJnt = rig.listRelatives(endJnt, p=True, type='joint')[0]
            if (startJnt == temUpJnt):
                break
            else:
                endJnt = temUpJnt
                AllIkJnts.append(endJnt)
    return AllIkJnts
Ejemplo n.º 33
0
def create_spine(start_joint, end_joint, lower_control, upper_control, name='spine'):
    spline_chain, original_chain = shortcuts.duplicate_chain(start_joint, end_joint, prefix='ikSpine_')

    # Create the spline ik
    ikh, effector, curve = cmds.ikHandle(
        name='{0}_ikh'.format(name), solver='ikSplineSolver',
        startJoint=spline_chain[0], endEffector=spline_chain[-1], parentCurve=False,
        simplifyCurve=False)
    effector = cmds.rename(effector, '{0}_eff'.format(name))
    curve = cmds.rename(curve, '{0}_crv'.format(name))

    # Create the joints to skin the curve
    curve_start_joint = cmds.duplicate(start_joint, parentOnly=True, name='{0}CurveStart_jnt'.format(name))
    cmds.parent(curve_start_joint, lower_control)
    curve_end_joint = cmds.duplicate(end_joint, parentOnly=True, name='{0}CurveEnd_jnt'.format(name))
    cmds.parent(curve_end_joint, upper_control)

    # Skin curve
    cmds.skinCluster(curve_start_joint, curve_end_joint, curve, name='{0}_scl'.format(name), tsb=True)

    # Create stretch network
    curve_info = cmds.arclen(curve, constructionHistory=True)
    mdn = cmds.createNode('multiplyDivide', name='{0}Stretch_mdn'.format(name))
    cmds.connectAttr('{0}.arcLength'.format(curve_info), '{0}.input1X'.format(mdn))
    cmds.setAttr('{0}.input2X'.format(mdn), cmds.getAttr('{0}.arcLength'.format(curve_info)))
    cmds.setAttr('{0}.operation'.format(mdn), 2)  # Divide

    # Connect to joints
    for joint in spline_chain[1:]:
        tx = cmds.getAttr('{0}.translateX'.format(joint))
        mdl = cmds.createNode('multDoubleLinear', name='{0}Stretch_mdl'.format(joint))
        cmds.setAttr('{0}.input1'.format(mdl), tx)
        cmds.connectAttr('{0}.outputX'.format(mdn), '{0}.input2'.format(mdl))
        cmds.connectAttr('{0}.output'.format(mdl), '{0}.translateX'.format(joint))

    # Setup advanced twist
    cmds.setAttr('{0}.dTwistControlEnable'.format(ikh), True)
    cmds.setAttr('{0}.dWorldUpType'.format(ikh), 4)  # Object up
    cmds.setAttr('{0}.dWorldUpAxis'.format(ikh), 0)  # Positive Y Up
    cmds.setAttr('{0}.dWorldUpVectorX'.format(ikh), 0)
    cmds.setAttr('{0}.dWorldUpVectorY'.format(ikh), 1)
    cmds.setAttr('{0}.dWorldUpVectorZ'.format(ikh), 0)
    cmds.setAttr('{0}.dWorldUpVectorEndX'.format(ikh), 0)
    cmds.setAttr('{0}.dWorldUpVectorEndY'.format(ikh), 1)
    cmds.setAttr('{0}.dWorldUpVectorEndZ'.format(ikh), 0)
    cmds.connectAttr('{0}.worldMatrix[0]'.format(lower_control), '{0}.dWorldUpMatrix'.format(ikh))
    cmds.connectAttr('{0}.worldMatrix[0]'.format(upper_control), '{0}.dWorldUpMatrixEnd'.format(ikh))

    # Constrain original chain back to spline chain
    for ik_joint, joint in zip(spline_chain, original_chain):
        if joint == end_joint:
            cmds.pointConstraint(ik_joint, joint, mo=True)
            cmds.orientConstraint(upper_control, joint, mo=True)
        else:
            cmds.parentConstraint(ik_joint, joint)
Ejemplo n.º 34
0
def build(tailRootJoint="Jt_tail", tailCurve="tail_SpIK_CV", base=None):

    tailRootCtrl = Control(prefix=removePrefix(tailRootJoint),
                           scale=8,
                           translateTo=tailRootJoint,
                           rotateTo=tailRootJoint,
                           parent=base.controlGrp,
                           lockChannels=["t", "s"])

    cmds.parentConstraint(cmds.listRelatives(tailRootJoint,
                                             p=True,
                                             type="joint")[0],
                          tailRootCtrl.Off,
                          mo=True)

    tailJoints = listJointHierarchy(tailRootJoint)
    # cluster tail curve.
    tailCurveCvs = cmds.ls(tailCurve + ".cv[*]", fl=1)
    tailCurveClusters = []

    for i in range(len(tailCurveCvs)):
        cluster = cmds.cluster(tailCurveCvs[i],
                               n=tailCurve + "_cluster%d" % i)[1]
        tailCurveClusters.append(cluster)

    cmds.parent(tailCurve, base.noTransformGrp)
    tailControls = []
    for i in range(len(tailCurveCvs)):
        ctrl = Control(prefix="tail" + "%s" % i,
                       translateTo=tailCurveClusters[i],
                       scale=3,
                       parent=base.controlGrp,
                       shape="octahedron")
        ctrl.adjustControlPosition(x=0, y=8, z=0)
        cmds.parentConstraint(tailRootCtrl.C, ctrl.Off, mo=True)
        tailControls.append(ctrl)

    for i in range(len(tailCurveCvs)):
        cmds.parent(tailCurveClusters[i], tailControls[i].C)

    tailIk = cmds.ikHandle(n=tailCurve + '_ikhandle',
                           sol='ikSplineSolver',
                           sj=tailJoints[0],
                           ee=tailJoints[-1],
                           c=tailCurve,
                           ccv=0,
                           parentCurve=0)[0]

    cmds.parent(tailIk, base.ikGrp)

    twistAt = 'twist'
    cmds.addAttr(tailControls[-1].C, ln=twistAt, k=1)
    cmds.connectAttr(tailControls[-1].C + ".%s" % twistAt, "%s.twist" % tailIk)
    cmds.hide(tailControls[0].Off)
    cmds.hide(tailCurveClusters)
Ejemplo n.º 35
0
 def createSplineIK(self,
                    crv=None,
                    autoCrvSpans=0,
                    rootOnCrv=True,
                    parent=None):
     ## ik creation
     if crv:
         ik = cmds.ikHandle(sj=self.sj,
                            ee=self.ej,
                            sol='ikSplineSolver',
                            c=crv,
                            ccv=False)
         self.crv = crv
     else:
         if autoCrvSpans:
             scv = True
         else:
             scv = False
         ik = cmds.ikHandle(sj=self.sj,
                            ee=self.ej,
                            sol='ikSplineSolver',
                            ccv=True,
                            scv=scv,
                            ns=autoCrvSpans)
         self.crv = cmds.rename(
             ik[2],
             utils.setupName(self.name, obj='nurbsCrv', side=self.side))
     self.hdl = cmds.rename(
         ik[0], utils.setupName(self.name, obj='ikHandle', side=self.side))
     self.eff = cmds.rename(
         ik[1], utils.setupName(self.name, obj='ikEffector',
                                side=self.side))
     self.grp = utils.newNode('group',
                              name=self.name,
                              side=self.side,
                              parent=parent).name
     cmds.parent(self.hdl, self.crv, self.grp)
     cmds.setAttr('{}.it'.format(self.crv), 0)
     grpCP = cmds.xform(self.hdl, q=1, t=1, ws=1)
     cmds.xform(self.grp, piv=grpCP, ws=1)
     ## set effected joints
     self.jnts = utils.getChildrenBetweenObjs(self.sj, self.ej)
Ejemplo n.º 36
0
    def create(self):
        '''
        This method will be used to construct the ikfk system.
        '''
        if not self._ikJointList:
            super(IkFkFoot, self).create()

        ankleConnections = mc.listConnections("{0}.tx".format(
            self._ikJointList[0]),
                                              source=False,
                                              destination=True)
        if ankleConnections:
            effectors = mc.ls(ankleConnections, type='ikEffector')
            if effectors:
                self.ankleHandle = mc.listConnections(
                    "{}.handlePath[0]".format(effectors[0]),
                    source=False,
                    destination=True)[0]

        # gathering all the pivots into one list.
        if not self.pivotList:
            self.pivotList = mc.listRelatives(self.anklePivot, ad=True)
            self.pivotList.reverse()

        if not self._handles:
            self._handles.append(
                mc.ikHandle(sj=self._ikJointList[0],
                            ee=self._ikJointList[1],
                            sol="ikSCsolver",
                            name="{0}_hdl".format(self._ikJointList[1]))[0])
            self._handles.append(
                mc.ikHandle(sj=self._ikJointList[1],
                            ee=self._ikJointList[2],
                            sol="ikSCsolver",
                            name="{0}_hdl".format(self._ikJointList[2]))[0])

        # parent the handles to the pivot
        mc.parent(self._handles[1], self.pivotList[-1])
        if mc.objExists(self.ankleHandle):
            mc.parent(self.ankleHandle, self.pivotList[-2])

        mc.parent(self._handles[0], self.pivotList[-2])
Ejemplo n.º 37
0
 def setupIK(self, ikChain):
     # setup IK:
     """
     setup an ik on the input list
     :param ikChain: list of joint chain to set an ik on
     """
     handle = cmd.ikHandle(n=ikChain[0] + '_ikHandle',
                           sj=ikChain[0],
                           ee=ikChain[-1],
                           sol='ikRPsolver',
                           s=0)
Ejemplo n.º 38
0
def buildIKLimb(ik_joints, ik_ctrl, pv_ctrl, constrain_last_jnt=True):
    'create ik handle and connect to ik controllers'

    ik_handlename = ik_joints[0] + "h"
    ik_handle = mc.ikHandle(sj=ik_joints[0],
                            ee=ik_joints[2],
                            name=ik_handlename)[0]
    mc.poleVectorConstraint(pv_ctrl, ik_handle)
    if constrain_last_jnt:
        mc.pointConstraint(ik_ctrl, ik_handle, mo=True)
        mc.orientConstraint(ik_ctrl, ik_joints[2], mo=True)
Ejemplo n.º 39
0
	def rig_leg(self):
		cmds.select(d=True)
		#Create IK Joints
		self.rig_info['IKjoints'] = utils.createJoint(self.module_info['IKjoints'], self.rig_info['position'], self.instance)
		
		#Create FK Joints
		self.rig_info['FKjoints'] = utils.createJoint(self.module_info['FKjoints'], self.rig_info['position'], self.instance)
		
		#Create RIG Joints
		self.rig_info['RIGjoints'] = utils.createJoint(self.module_info['RIGjoints'], self.rig_info['position'], self.instance)

		#Create IK Rig
		#IK Handle
		#IKcontrols': ["s_legPV_CTRL", "s_leg_ikHandle", "s_legIK_CTRL"]
		ikHandleName = self.module_info['IKcontrols'][1].replace('s_', self.instance)
		self.rig_info['IKhandle'] = cmds.ikHandle(n=ikHandleName, sj=self.rig_info['IKjoints'][0], ee=self.rig_info['IKjoints'][2], p=2, w=1 )

		IKcontrolName = self.module_info['IKcontrols'][0].replace('s_', self.instance)
		self.rig_info['IKcontrol'] = utils.createControl([[self.rig_info['position'][2], IKcontrolName]])[0]

		PVpos = utils.calculatePVposition([self.rig_info['IKjoints'][0], self.rig_info['IKjoints'][1], self.rig_info['IKjoints'][2]])

		self.rig_info['PVctrlInfo'] = utils.createControl([[PVpos, self.module_info['IKcontrols'][0]]])[0]

		# Make a control for leg settings
		self.rig_info['setcontrol']=utils.createControl([[self.rig_info['position'][2], 'ctrl_settings']])[0]
		cmds.addAttr(self.rig_info['setcontrol'][1], ln='IK_FK', at="enum", en="FK:IK:", k=True )

		#parent ikHandle to ctrl
		cmds.parent(self.rig_info['IKhandle'][0], self.rig_info['IKcontrol'][1])

		#PV constraint
		cmds.poleVectorConstraint(self.rig_info['PVctrlInfo'][1], self.rig_info['IKhandle'][0])

		#orient constraint leg ik_endLeg to endLeg_ctrl
		cmds.orientConstraint(self.rig_info['IKcontrol'][1], self.rig_info['IKjoints'][2], mo=True)

		#Create FK rig
		self.rig_info['FKcontrols'] = utils.createControl([[self.rig_info['position'][0], self.module_info['FKcontrols'][0]],
		[self.rig_info['position'][1], self.module_info['FKcontrols'][1]],
		[self.rig_info['position'][2], self.module_info['FKcontrols'][2]]])

		#Parent FK controls
		cmds.parent(self.rig_info['FKcontrols'][2][0], self.rig_info['FKcontrols'][1][1])
		cmds.parent(self.rig_info['FKcontrols'][1][0], self.rig_info['FKcontrols'][0][1])


		# Connect Ik and Fk to Rig joints
		switchattr = self.rig_info['setcontrol'][0] + ".IK_FK"
		utils.connectThroughBC(self.rig_info['IKjoints'], self.rig_info['FKjoints'], self.rig_info['RIGjoints'], self.instance, switchattr )


		# Constrain fk joints to controls.
		[cmds.parentConstraint(self.rig_info['FKcontrols'][i][1], self.rig_info['FKjoints'][i]) for i in range(len(self.rig_info['FKcontrols']))]
Ejemplo n.º 40
0
 def _create_ik_handle(self):
     ik_chain = self.chain_b.get()
     ik_handle, effector = cmds.ikHandle(startJoint=ik_chain[0],
                                         endEffector=ik_chain[-1],
                                         solver="ikSpringSolver")
     self.ik_handle.set(ik_handle)
     cmds.parent(ik_handle, self.extras_group.get())
     cmds.poleVectorConstraint(self.ik_pv_ctl.get(), ik_handle)
     mop.dag.matrix_constraint(self.ik_end_ctl.get(),
                               ik_handle,
                               maintain_offset=True)
Ejemplo n.º 41
0
def createIKs():
    mc.ikHandle(n='R_Arm_IK',
                sj='R_Shoulder_BIND',
                ee='R_Wrist_BIND',
                p=2,
                w=.5)
    mc.ikHandle(n='L_Arm_IK',
                sj='L_Shoulder_BIND',
                ee='L_Wrist_BIND',
                p=2,
                w=.5)
    mc.ikHandle(n='R_Foot_IK', sj='R_Hip_BIND', ee='R_Ankle_BIND', p=2, w=.5)
    mc.ikHandle(n='L_Foot_IK', sj='L_Hip_BIND', ee='L_Ankle_BIND', p=2, w=.5)
Ejemplo n.º 42
0
def ikChainBuild(scaleIK, HandleName):
    
    masterIkHandle = cmds.ikHandle(sj=ogChain[0] + "_ik", ee=ogChain[2] + "_ik", sol="ikRPsolver", n=side + HandleName + "_ikHandle")
    cmds.setAttr(masterIkHandle[0] + ".visibility", 0)
    
    if HandleName == "Arm": 
        #print ("scaleController", scaleField_UI)
        armIk(scaleIK, masterIkHandle, HandleName)
    else:   
        #print ("scaleController", scaleField_UI)
        legIK(scaleIK, masterIkHandle, HandleName)
Ejemplo n.º 43
0
def createIkSpine(startEff, endEff):
    [ikhandle, eff, crv] = cmds.ikHandle(startJoint=startEff,
                                         endEffector=endEff,
                                         solver="ikSplineSolver",
                                         simplifyCurve=False)
    ikhandle = cmds.rename(ikhandle, IKSPINEHANDLE)
    crv = cmds.rename(crv, IKSPINECURVE)
    cmds.setAttr(ikhandle + ".dTwistControlEnable", True)
    cmds.setAttr(ikhandle + ".dWorldUpType", 4)
    # then manually set forward axis to x, up axis to y, chest control for the end, spine control for the starting point
    return crv
Ejemplo n.º 44
0
def createSpline(start, end, curve, *args):
    ik = cmds.ikHandle(n='ikTail_spline',
                       sj=start,
                       ee=end,
                       c=curve,
                       sol='ikSplineSolver',
                       ccv=False,
                       rootOnCurve=True,
                       parentCurve=False)[0]
    cmds.setAttr('{}.v'.format(ik), 0)
    return ik
Ejemplo n.º 45
0
def CreateIkH():
    Name = cmds.textFieldGrp(NameTextFG, q=1, tx=1)
    selJnt = cmds.ls(Name + "*_joint1", type='joint')  ####------------------creating ikHandle------------------####
    IKCtlAmnt = cmds.intSliderGrp(IKCtlintSG, q=1, v=1)
    for i in SelHi_(selJnt):
        ikHLst = cmds.ikHandle(n=Naming_([i], 'joint', 'ikH')[0][0], sj=i[0], ee=i[-1], sol='ikSplineSolver',
                               ns=IKCtlAmnt - 1)
        crvName = ikHLst[2]
        cmds.select(crvName)
        cmds.rename(ikHLst[0] + '_crv')
    print ('*ikHandle �ㅻ컯�꾩æ^______^*')
Ejemplo n.º 46
0
def two_joint_ik(startJoint=None, endEffector=None, ikParent=None):
    """
    @type  startJoint: string
    @param startJoint: specify the startJoint

    @type  endEffector: string
    @param endEffector: specify the endEffector

    @type  ikParent: string
    @param ikParent: specify the parent of the ikHandle
    """
    #--- startJoint
    assert startJoint, "Please specify an existing startJoint!"
    assert cmds.objExists(startJoint), "Please specify an existing startJoint!"
    #--- endEffector
    assert endEffector, "Please specify an existing endEffector!"
    assert cmds.objExists(
        endEffector), "Please specify an existing endEffector!"
    #--- endParent
    assert ikParent, "Please specify an existing parent for the ikHandle!"
    assert cmds.objExists(ikParent), "Please specify an existing parent node!"

    #--- create joint chain
    child = cmds.listRelatives(startJoint, type='transform')
    if not child or not child[0] == endEffector:
        attribute.lock_attributes(endEffector, ['t', 'r', 's'], False)
        cmds.parent(endEffector, startJoint)
        attribute.lock_attributes(endEffector, ['t', 'r', 's'])
        attribute.lock_attributes(startJoint, ['r'], False)

    #--- compose name
    ikname = ikParent.split('_')[0] + '_' + ikParent.split('_')[1] + '_IKH'
    ikeff = ikParent.split('_')[0] + '_' + ikParent.split('_')[1] + '_EFF'

    #--- create ikHandle
    ik = cmds.ikHandle(startJoint=startJoint,
                       endEffector=endEffector,
                       solver='ikSCsolver',
                       name=ikname)
    eff = cmds.rename(ik[1], ikeff)
    ik.pop(1)
    ik.append(eff)

    #--- parent to ikParent
    cmds.parent(ik[0], ikParent)
    cmds.setAttr(ik[0] + '.t', 0, 0, 0)
    cmds.setAttr(ik[0] + '.r', 0, 0, 0)

    #--- cleanup
    for i in [ik[0], ik[1], 'ikSCsolver']:
        cmds.setAttr(i + '.ihi', 0)
        attribute.lock_all(i)

    return ik
Ejemplo n.º 47
0
    def create_ik(self):
        ik_hdl_grp = mc.createNode("transform",
                                   n=self.prefix + 'HdlOffset_grp')
        self.ik_hdl = mc.ikHandle(n=self.prefix + 'Main_hdl',
                                  sol='ikRPsolver',
                                  sj=self.ikChain[0],
                                  ee=self.ikChain[-1])[0]
        mc.parent(self.ik_hdl, ik_hdl_grp)
        mc.parent(ik_hdl_grp, self.ik_ctrl.C)

        return {'ik_hdl': self.ik_hdl, 'ik_hdl_grp': ik_hdl_grp}
Ejemplo n.º 48
0
    def create_controler(self):

        self.greate_controler('circle', 6, joint_list, 'tail')
        self.greate_controler('sphere', 13, joint_list, 'tail')

        for x in range(self.cycle_num):
            cmds.parent(self.sphere_NUL_list[x], self.circle_CON_list[x])

        cmds.ikHandle(sj=self.joint_list[0],
                      ee=self.joint_list[-1],
                      c=self.sel_curve,
                      n=self.splitName + '_HDL',
                      sol='ikSplineSolver',
                      ccv=0,
                      roc=0,
                      pcv=0)

        for x in range(self.cycle_num):
            cmds.parentConstraint(self.sphere_CON_list[x],
                                  self.LOC_NUL_list[x])
Ejemplo n.º 49
0
 def setup_ik(self):
     # Create ik handle and constraints
     armIK_ctl = self.side + "armIK_ctl"
     arm_ik_hdl = cmds.ikHandle(
         sj = self.ik_jnts[0], ee = self.ik_jnts[2], sol = "ikRPsolver", \
         n = self.ik_jnts[0].replace("jnt", "hdl"))
     cmds.poleVectorConstraint(self.side + "armPV_ctl", arm_ik_hdl[0])
     cmds.parentConstraint(armIK_ctl, arm_ik_hdl[0], mo=1)
     # May need to change parent constraint on group
     cmds.parent(arm_ik_hdl[0], self.rig_grp)
     cmds.orientConstraint(armIK_ctl, self.ik_jnts[2], mo=0)
Ejemplo n.º 50
0
def createSplineIK(jointChain, handleNum):

    splineIk = cmds.ikHandle(solver='ikSplineSolver',
                             startJoint=jointChain[0],
                             endEffector=jointChain[len(jointChain) - 1],
                             name='spl_spline_IK_#',
                             numSpans=handleNum - 2)
    splineIkHandle = splineIk[0]
    splineCurve = splineIk[2]
    splineCurve = cmds.rename(splineCurve, 'spl_spline_CRV_#')

    return splineIkHandle, splineCurve
Ejemplo n.º 51
0
    def __initialSetup(self):
        # get last name string of the chain
        self.ikh = cmds.ikHandle(sj=self.startJointChain, ee=self.lastChild,
                                 sol='ikSplineSolver', scv=False, pcv=False,
                                 n='self.ikh_{0}Spline_01_{1}'.format(self.name, self.side))


        # Rebuild curve with desired cv count
        self.crvName = cmds.rebuildCurve(self.ikh[2], rpo=1, rt=0, end=1,
                                         kr=0, kcp=0, kep=1, kt=0,
                                         s=self.numberOfCtrls - 2, d=3, tol=0.01)
        self.effector = cmds.rename('effector1', '{0}_{1}_effector'.format(self.side, self.name))


        # cluster setup
        num = 1
        numLst = ['0:1']
        numLst.extend(range(2,  self.numberOfCtrls-1))
        numLst.append('{0}:{1}'.format(str(self.numberOfCtrls - 1), str(self.numberOfCtrls)))

        for cv in numLst:
            clus = cmds.cluster('{0}.cv[{1}]'.format(self.ikh[2], str(cv)))

            # if first two points
            if cv == '0:1':
                # find the first point position on curve
                startPnt = cmds.xform(self.ikh[2] + '.cv[0]', q=True, t=True)
                # positioned the cluster to the Start point
                cmds.xform(clus, piv=(startPnt))

            # if last two points
            if cv == '{0}:{1}'.format(str(self.numberOfCtrls - 1), str(self.numberOfCtrls)):
                # find the end point position on curve
                endPnt = cmds.xform('{0}.cv[{1}]'.format(self.ikh[2], str(self.numberOfCtrls)), q=True, t=True)
                # positioned the cluster to the End point
                cmds.xform(clus, piv=(endPnt))

            self.clustName = cmds.rename(clus[1], 'cls_{0}_{1}_{2}'.format(self.name, str(num), self.side))
            self.__adjGrp()
            num += 1

            # creating joints to replace cluster as base
            jntNames = cmds.joint(name= 'jnt_cluster{0}_{1}_{2}'.format(self.name, str(num-1), self.side))
            self.jntClusGrp.append(jntNames)

            # rotate for control
            if self.rotateControl:
                cmds.setAttr(jntNames+'.r'+self.rotateControl.keys()[0], self.rotateControl.values()[0])

            # find the cluster position
            bah=cmds.parentConstraint(self.clustName, jntNames, sr=['x','y','z'])
            cmds.delete(bah)
            cmds.parentConstraint(jntNames, self.clustName, sr=['x','y','z'],mo=True)
Ejemplo n.º 52
0
def mmIkHandle(*args):

    sels = cmds.ls(sl=1)

    handles = []
    for sel in sels:
        selChildren = cmds.listRelatives(sel, c=1, ad=1)
        lastChild = selChildren[0]

        handle = cmds.ikHandle(sj=sel, ee=lastChild, sol='ikRPsolver')

    handles.append(handle)
Ejemplo n.º 53
0
 def create_ik_spline(self):
     #----------------check setting here, crv should have 3 or 4 spans?  Root twist mode
     splHandle, splEffector, splCrv = cmds.ikHandle(
         startJoint=self.jntList[0],
         ee=self.jntList[-1],
         sol="ikSplineSolver",
         numSpans=2,
         rootTwistMode=True,
         parentCurve=False,
         name="{0}_IK".format(self.name))
     splCrv = cmds.rename(splCrv, "{0}_ikSpl_CRV".format(self.name))
     return (splHandle, splEffector, splCrv)
Ejemplo n.º 54
0
	def createIKControl(self):
		joint1Pos = mc.xform(self.ikJoints[0], q = True, ws = True, t = True)
		joint2Pos = mc.xform(self.ikJoints[1], q = True, ws = True, t = True)
		joint3Pos = mc.xform(self.ikJoints[2], q = True, ws = True, t = True)

		startV = OpenMaya.MVector(joint1Pos[0] ,joint1Pos[1],joint1Pos[2])
		midV = OpenMaya.MVector(joint2Pos[0] ,joint2Pos[1],joint2Pos[2])
		endV = OpenMaya.MVector(joint3Pos[0] ,joint3Pos[1],joint3Pos[2])

		startEnd = endV - startV
		startMid = midV - startV

		dotP = startMid * startEnd

		proj = float(dotP) / float(startEnd.length())

		startEndN = startEnd.normal()

		projV = startEndN * proj

		arrowV = startMid - projV

		arrowV*= 10

		finalV = arrowV + midV

		poleVectorControl = mc.spaceLocator(n = self.jointNames[1] + "_PV_CTL")[0]

		mc.xform(poleVectorControl , ws =1 , t= (finalV.x , finalV.y ,finalV.z))
		mc.makeIdentity(poleVectorControl, apply=True, t=1, r=1, s=1, n=0)

		ikHandle = mc.ikHandle(sj = self.ikJoints[0], ee = self.ikJoints[2], sol = "ikRPsolver")[0]

		self.ikControlObject = mc.circle(nr = (0, 0, 1), c = (0,0,0), r = 10, name = self.jointNames[2]+"_IK_CTL")[0]

		# mc.xform(self.ikControlObject, worldSpace=True, translation=mc.xform(self.ikJoints[2], query = True, worldSpace = True, translation = True))

		mc.makeIdentity(self.ikControlObject, apply=True, t=1, r=1, s=1, n=0)

		ikControlOffsetGroup = mc.group(self.ikControlObject, n = self.ikControlObject.replace('_CTL', 'Offset_GRP'))
		ikControlGroup = mc.group(ikControlOffsetGroup, n = self.ikControlObject.replace('_CTL', '_GRP'))

		mc.parent(ikControlGroup, self.ikJoints[2])
		mc.makeIdentity(ikControlGroup, t = 1, r = 1, s = 1)
		mc.parent(ikControlGroup, world=True)
		mc.orientConstraint(self.ikControlObject, self.ikJoints[2], mo=False)

		mc.parent(ikHandle, self.ikControlObject)

		poleVector = mc.poleVectorConstraint(poleVectorControl, ikHandle)

		self.ikControls.append(self.ikControlObject)
		self.ikControls.append(poleVectorControl)
Ejemplo n.º 55
0
def createArmJoints():
    joints = []
    global ikarmL  #make global for later constraints
    global ikarmR  #make global for later constraints
    mc.select(clear=True)
    #get pos of locators and add Joints to them
    for i in armJointsL:
        print i
        pos = mc.pointPosition(i)
        print pos
        joints.append(mc.joint(p=pos, n=str(i)))
        mc.color(ud=5)
    #orient spineJoints and then nub
    mc.joint(joints[0], e=True, oj="xyz", sao="yup", ch=True, zso=True)
    mc.joint(joints[2], e=True, o=[0, 0, 0])
    ikarmL = mc.ikHandle(sj=joints[0], ee=joints[2], solver="ikRPsolver")
    mc.color(ikarmL, rgb=(1, .55, 0))
    AJL[:] = joints[:]
    #print ikarmL

    joints[:] = []
    mc.select(clear=True)
    for i in armJointsR:
        print i
        pos = mc.pointPosition(i)
        print pos
        joints.append(mc.joint(p=pos, n=str(i)))
        mc.color(ud=5)

    #orient spineJoints and then nub
    mc.joint(joints[0], e=True, oj="xyz", sao="yup", ch=True, zso=True)
    mc.joint(joints[2], e=True, o=[0, 0, 0])
    ikarmR = mc.ikHandle(sj=joints[0], ee=joints[2], solver="ikRPsolver")
    mc.color(ikarmR, rgb=(1, .55, 0))
    AJR[:] = joints[:]

    mc.select(clear=True)

    print "armJointsL: " + str(armJointsL)
    print "armJointsR: " + str(armJointsR)
Ejemplo n.º 56
0
def uiCmd_createSplineJointEachSpans(*args):

    selections = cmds.ls(sl=1)
    curve = selections[0]
    curveShape = cmds.listRelatives(curve, s=1)[0]

    minValue = cmds.getAttr(curveShape + '.minValue')
    maxValue = cmds.getAttr(curveShape + '.maxValue')

    spans = cmds.getAttr(curveShape + '.spans')

    paramRange = maxValue - minValue
    eachParamRate = paramRange / spans

    infos = []

    for i in range(0, spans + 1):
        info = cmds.createNode('pointOnCurveInfo')
        cmds.connectAttr(curveShape + '.local', info + '.inputCurve')
        cmds.setAttr(info + '.parameter', eachParamRate * i)
        infos.append(info)

    cmds.select(d=1)
    jnts = [cmds.joint()]
    for i in range(spans):
        cmds.select(jnts[-1])
        jnt = cmds.joint()
        jnts.append(jnt)

        distNode = cmds.createNode('distanceBetween')
        cmds.connectAttr(infos[i] + '.position', distNode + '.point1')
        cmds.connectAttr(infos[i + 1] + '.position', distNode + '.point2')
        cmds.connectAttr(distNode + '.distance', jnt + '.tx')

    cmds.ikHandle(sj=jnts[0],
                  ee=jnts[-1],
                  sol='ikSplineSolver',
                  ccv=False,
                  pcv=False,
                  curve=curveShape)
Ejemplo n.º 57
0
def switchToIK(control,
               ikHandle=None,
               poleControl=None,
               onCmd=None,
               offCmd=None):
    '''
	this proc will align the IK controller to its fk chain
	flags used:
	-control   this is the actual control being used to move the ikHandle - it is assumed to be the same object as the ikHandle, but if its different (ie if the ikHandle is constrained to a controller) use this flag
	-pole      tells the script the name of the pole controller - if there is no pole vector control, leave this flag out
	-ikHandle  this flag specifies the name of the ikHandle to work on
	-onCmd     this flag tells the script what command to run to turn the ik handle on - it is often left blank because its assumed we're already in ik mode
	-offCmd    this flag holds the command to turn the ik handle off, and switch to fk mode
	NOTE: if the offCmd isn't specified, it defaults to:  if( `getAttr -se ^.ikb` ) setAttr ^.ikb 1;

	symbols to use in cmd strings:
	 ^  refers to the ikHandle
	 #  refers to the control object

	example:
	zooAlignIK "-control somObj -ikHandle ikHandle1 -offCmd setAttr #.fkMode 0";
	'''
    if ikHandle is None:
        ikHandle = control

    if callable(onCmd):
        onCmd(control, ikHandle, poleControl)

    joints = cmd.ikHandle(ikHandle, q=True, jl=True)
    effector = cmd.ikHandle(ikHandle, q=True, ee=True)
    effectorCtrl = listConnections('%s.tx' % effector, d=False)[0]

    mel.zooAlign("-src %s -tgt %s" % (effectorCtrl, control))
    if poleControl is not None and objExists(poleControl):
        pos = mel.zooFindPolePosition("-start %s -mid %s -end %s" %
                                      (joints[0], joints[1], effectorCtrl))
        move(pos[0], pos[1], pos[2], poleControl, a=True, ws=True, rpr=True)

    if callable(offCmd):
        offCmd(control, ikHandle, poleControl)
Ejemplo n.º 58
0
def armIk(armIkScale, armikHandle, pvName):

    ikHandJoint = cmds.joint(n=side + "hand_ik")
    cmds.delete(cmds.parentConstraint(ogChain[2] + "_ik", ikHandJoint))
    cmds.makeIdentity(ikHandJoint, a = 1, t = 1, r = 1, s = 0)
    if side == "l_":
        cmds.move(10,0,0, ikHandJoint, r=1, os=1)
    else:
        cmds.move(-10,0,0, ikHandJoint, r=1, os=1)
    cmds.parent(ikHandJoint, ogChain[2] + "_ik")
    handikHandle = cmds.ikHandle(sj=ogChain[2] + "_ik", ee=ikHandJoint, n=side + "hand_ikHandle", sol="ikSCsolver")
    cmds.parent(handikHandle[0], armikHandle[0])
    
    #create IK controller ---> CUBE
    crvIkCube = cmds.curve(d=1, p=[(-0.5, 0.5, -0.5), (0.5, 0.5, -0.5), (0.5, 0.5, 0.5),
                                    (-0.5, 0.5, 0.5), (-0.5, -0.5, 0.5), (-0.5, -0.5, -0.5),
                                    (-0.5, 0.5, -0.5), (-0.5, 0.5, 0.5), (-0.5, -0.5, 0.5),
                                    (0.5, -0.5, 0.5), (0.5, 0.5, 0.5), (0.5, 0.5, -0.5),
                                    (0.5, -0.5, -0.5), (0.5, -0.5, 0.5), (0.5, -0.5, -0.5), (-0.5, -0.5, -0.5)], 
                                    k=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5], n=side + "hand_ik_anim" )

    # Rename shape node                 
    shapeList = cmds.listRelatives(crvIkCube, s = True)
    cmds.rename(shapeList, crvIkCube + "Shape")
    
    crvIkCubeGrp = cmds.group(n=crvIkCube + "_grp")
    cmds.delete(cmds.parentConstraint(ogChain[2] + "_ik", crvIkCubeGrp))

    cmds.color(crvIkCube, rgb=controllerColor)
    cmds.scale(armIkScale, armIkScale, armIkScale, crvIkCubeGrp)

    cmds.parent(armikHandle[0], crvIkCube)

    pvController = createSphere(nome= side+pvName+"_PV")

    findPoleVector(loc=pvController, targetHandle=armikHandle[0])

    cmds.addAttr(pvController, at="enum", enumName = "------", ln="Attributes", k=1, r=1)
    cmds.addAttr(pvController, ln="Follow", k=1, r=1, min=0, max=1)
    cmds.addAttr(pvController, ln="Follow_Clav_Hand", k=1, r=1, min=0, max=1, dv=0.5)

    # Parent ikController and PV under _rig_GRP
    cmds.parent(crvIkCubeGrp, pvController + "_grp" ,rigGrp)
    
    #set SDK visibility
    sdkDriver = switcherLoc[0] + ".FKIK_Mode"
    cmds.setAttr(sdkDriver, 0)
    cmds.setDrivenKeyframe(crvIkCubeGrp + ".visibility", cd=sdkDriver, v=0, dv=0)
    cmds.setDrivenKeyframe(pvController + "_grp.visibility", cd=sdkDriver, v=0, dv=0)
    cmds.setAttr(sdkDriver, 1)
    cmds.setDrivenKeyframe(crvIkCubeGrp + ".visibility", cd=sdkDriver, v=1, dv=1)
    cmds.setDrivenKeyframe(pvController + "_grp.visibility", cd=sdkDriver, v=1, dv=1)
Ejemplo n.º 59
0
def create_ik_setup(controls, joints):
    """Creates an IK rig setup.

    Args:
        controls (list): control objects.
        joints (list): ik joint objects.

    Returns:
        str: ikHandle name
    """

    root_control, pole_control, goal_control = controls

    handle, effector = cmds.ikHandle(sj=joints[0],
                                     ee=joints[-1],
                                     sol='ikRPsolver')
    cmds.setAttr('{}.hiddenInOutliner'.format(handle), True)
    cmds.orientConstraint(goal_control, joints[-1], mo=True)
    cmds.parent(handle, goal_control)

    # connect root control to ik joint offset group
    ik_joints_offset = cmds.listRelatives(joints[0], p=True)[0]
    cmds.parentConstraint(root_control, ik_joints_offset, mo=True)
    cmds.scaleConstraint(root_control, ik_joints_offset, mo=True)

    # connect twisting and pole vector control
    cmds.addAttr(goal_control, ln='twist', at='float', k=True)
    cmds.connectAttr('{}.twist'.format(goal_control),
                     '{}.twist'.format(handle))

    cmds.poleVectorConstraint(pole_control, handle)

    # add curve that points elbow to pole control
    crv = cmds.curve(p=[[0, 0, 0], [0, 1, 0]], d=1)
    cmds.connectAttr('{}.visibility'.format(pole_control),
                     '{}.visibility'.format(crv))
    lock_hide_attrs(
        crv, attrs=['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])
    cmds.setAttr('{}.overrideEnabled'.format(crv), True)
    cmds.setAttr('{}.overrideDisplayType'.format(crv), 2)
    decomp_joint = cmds.createNode('decomposeMatrix')
    decomp_control = cmds.createNode('decomposeMatrix')
    cmds.connectAttr('{}.worldMatrix'.format(joints[1]),
                     '{}.inputMatrix'.format(decomp_joint))
    cmds.connectAttr('{}.worldMatrix'.format(pole_control),
                     '{}.inputMatrix'.format(decomp_control))
    cmds.connectAttr('{}.outputTranslate'.format(decomp_joint),
                     '{}.controlPoints[0]'.format(crv))
    cmds.connectAttr('{}.outputTranslate'.format(decomp_control),
                     '{}.controlPoints[1]'.format(crv))

    return handle, crv
Ejemplo n.º 60
0
    def create(self, distanceNode, powRate=1):

        eachParam = (self._maxParam - self._minParam) / (self._infoNum - 1)

        eachInfos = []

        for i in range(self._infoNum):

            info = cmds.createNode('pointOnCurveInfo',
                                   n=self._curveShape + '_info%d' % i)
            cmds.connectAttr(self._curveShape + '.local', info + '.inputCurve')
            cmds.setAttr(info + '.parameter', eachParam * i + self._minParam)
            eachInfos.append(info)

        cmds.setAttr(info + '.parameter', self._maxParam - 0.0001)

        cmds.select(d=1)

        joints = []
        for i in range(self._infoNum):
            joints.append(cmds.joint(p=[i, 0, 0]))

        handle, effector = cmds.ikHandle(sj=joints[0],
                                         ee=joints[-1],
                                         sol='ikSplineSolver',
                                         ccv=False,
                                         pcv=False,
                                         curve=self._curveShape)

        distNodes = []
        for i in range(self._infoNum - 1):

            firstInfo = eachInfos[i]
            secondInfo = eachInfos[i + 1]
            targetJoint = joints[i + 1]

            distNode = cmds.createNode('distanceBetween')
            distNodes.append(distNode)

            cmds.connectAttr(firstInfo + '.position', distNode + '.point1')
            cmds.connectAttr(secondInfo + '.position', distNode + '.point2')

            if distanceNode:
                cmds.connectAttr(distNode + '.distance', targetJoint + '.tx')
            else:
                cmds.setAttr(targetJoint + '.tx',
                             cmds.getAttr(distNode + '.distance'))

        if not distanceNode:
            cmds.delete(distNodes)

        return handle, joints