Example #1
0
 def setUp(self):
     cmds.file(new=1, f=1)
     self.cube = cmds.polyCube()[0]
     for i in xrange(1,21,2):
         cmds.currentTime(i)
         pm.setAttr(self.cube + '.tx', i)
         pm.setKeyframe(self.cube + '.tx')
Example #2
0
def fixedSeed():
  sel = pm.selected()
  
  animStartTime = pm.playbackOptions(animationStartTime=1, q=1)
  animEndTime = pm.playbackOptions(animationEndTime=1, q=1)
    
  for attr in sel:
    animStartTime = pm.playbackOptions(animationStartTime=1, q=1)
    animEndTime = pm.playbackOptions(animationEndTime=1, q=1)
    
    xVal = attr.rotateX.get()
    yVal = attr.rotateY.get()
    zVal = attr.rotateZ.get()
  
    print animStartTime
    print animEndTime
    print xVal
    print yVal
    print zVal
      
    while animStartTime<=animEndTime:
      attr.rotateX.set(xVal+random.uniform(-.1,.1))
      attr.rotateY.set(yVal+random.uniform(-.1,.1))
      attr.rotateZ.set(zVal+random.uniform(-.1,.1))
      pm.setKeyframe(attribute="rotate", time=animStartTime)
      animStartTime+=1
 def testGDuplicateStandin(self):
     self.standIn = pm.ls('testStandin_standInCtrl')[0]
     pm.select(self.standIn)
     self.cc.duplicateStandin()
     pm.setKeyframe('controllerB.testSrc', t=1, v=1.5)
     self.cc.saveState()
     # now cache that standin too
     self.cc.cacheStandin()
Example #4
0
def rigCurveShapeControl( ctrl=None, attr=None, sampleParams=[0,1,2,3,4,5,6,7,8,9,10], container=False  ):
    '''
    스쿼시 스트레치시 그래프 에디터 커브로 쉐입을 조정하려고 만들어짐.

    powAttr = rigCurveShapeControl( ctrl='spinCtrl', attr='sideAxisScaleShape', sampleParams=range( len(joints) ) )

    @param ctrl:
    @param attr:
    @param sampleParams:
    @param container:
    @return: ctrl.results 어트리뷰트를 리턴함.
    @rtype: pm.Attribute
    '''
    if not ctrl:
        sel = pm.selected()
        if sel:
            ctrl = sel[0]
        else:
            return

    if not attr:
        attr = 'curveCtrl'
        ctrl.addAttr( attr, keyable=True )

    ctrl     = pm.PyNode(ctrl)
    ctrlAttr = pm.Attribute( ctrl.attr(attr) )

    # 애니메이션 커브 생성
    pm.setKeyframe( ctrlAttr, t=sampleParams[ 0], v=0)
    pm.setKeyframe( ctrlAttr, t=sampleParams[-1], v=0)
    pm. keyTangent( ctrlAttr, weightedTangents=True )
    pm. keyTangent( ctrlAttr, weightLock=False )
    pm. keyTangent( ctrlAttr, e=True, absolute=True, time=[sampleParams[ 0]], outAngle=77, outWeight=1 )
    pm. keyTangent( ctrlAttr, e=True, absolute=True, time=[sampleParams[-1]], inAngle=-77,  inWeight=1 )

    # frameCache노드로 애니메이션 커브의 각 포인트에서 값을 가져옴
    ctrl.addAttr( 'samples', multi=True, readable=True, indexMatters=False )
    ctrl.addAttr( 'results', multi=True, readable=True, indexMatters=False )

    frameCaches = []
    for i,param in enumerate(sampleParams):
        ctrl.samples[i].set( param )

        frameCache = pm.createNode( 'frameCache' )
        pm.connectAttr( ctrlAttr, frameCache.stream)
        pm.connectAttr( ctrl.samples[i], frameCache.varyTime )
        pm.connectAttr( frameCache.varying, ctrl.results, na=True)

        frameCaches.append(frameCache)

    # container Setting : wip
    if container:
        cont = pm.container( type='dagContainer', addNode=frameCaches )
        cont.blackBox.set(True)

    return ctrl.results
Example #5
0
def model_screenshot(selected=True, debug=False, centerCam=False):
	meshes = pm.ls(sl=True)
	cam = pm.camera(n='tempCam')
	hfv=cam[1].getHorizontalFieldOfView()
	vfv=cam[1].getVerticalFieldOfView()
	grp = pm.group(em=True, n='tempCamOffset_GRP')
	
	#Determine the selection
	if selected==False:
		meshes = [mesh.getParent() for mesh in pm.ls(type=pm.nt.Mesh)]
	print meshes
	boundingBox = pm.polyEvaluate(meshes, b=True)
	
	#Determine the positions of the bounding box as variables
	xmin=boundingBox[0][0]
	xmax=boundingBox[0][1]
	ymin=boundingBox[1][0]
	ymax=boundingBox[1][1]
	zmin=boundingBox[2][0]
	zmax=boundingBox[2][1]
	
	#get the midpoints (these are also the object center!)
	zmid=(zmin+zmax)/2
	ymid=(ymin+ymax)/2
	xmid=(xmin+xmax)/2
	
	# Create locators to visualize the bounding box
	locators=[]
	locators.append(pm.spaceLocator(n='xmin',p=[xmin,ymid,zmid]))
	locators.append(pm.spaceLocator(n='xmax',p=[xmax,ymid,zmid]))
	locators.append(pm.spaceLocator(n='ymin',p=[xmid,ymin,zmid]))
	locators.append(pm.spaceLocator(n='ymax',p=[xmid,ymax,zmid]))
	locators.append(pm.spaceLocator(n='zmin',p=[xmid,ymid,zmin]))
	locators.append(pm.spaceLocator(n='zmax',p=[xmid,ymid,zmax]))
	
	#Determine the furthest distance needed from the object
	h_dist=(math.tan(hfv)*abs(xmin-xmax)) + abs(zmin-zmax)
	zh_dist=(math.tan(vfv)*abs(zmin-zmax)) + abs(zmin-zmax)
	zv_dist=(math.tan(vfv)*abs(zmin-zmax)) + abs(zmin-zmax)
	v_dist=(math.tan(vfv)*abs(ymin-ymax)) + abs(zmin-zmax) #this will never be used, always going to be shortest.
	
	#set the camera distance etc for the bounding box.
	print h_dist,v_dist,zh_dist, zv_dist
	print max(h_dist,v_dist,zh_dist, zv_dist)
	cam[0].translateZ.set(max(h_dist,zh_dist,v_dist,zv_dist))
	cam[0].translateY.set(ymid)
	
	cam[0].setParent(grp)
	if debug:
		pm.delete(locators)
	if centerCam:
		grp.translate.set([zmid,0,xmid])
		pm.setKeyframe(grp.rotateY, t=pm.playbackOptions(q=True,ast=True), v=0)
		pm.setKeyframe(grp.rotateY, t=pm.playbackOptions(q=True,aet=True), v=360)
Example #6
0
    def test_RigCtrl(self):
        from classRigCtrl import RigCtrl
        from omtk.libs import libSerialization
        log.info("test_RigCtrl")
        foo = RigCtrl()
        foo.build()
        pymel.setKeyframe(foo.node)
        foo.unbuild()

        network = libSerialization.export_network(foo)
        pymel.select(network)
        foo.build()
Example #7
0
def bdCleanKeyframes():
    start = pm.playbackOptions(q=1,ast=1)
    end = pm.playbackOptions(q=1,aet=1)

    sel = pm.ls(sl=1,type='transform')

    for i in range(8,end-10,1):
        if not (i%4):
            print i
            pm.currentTime(i)
            pm.setKeyframe(sel,t=i)
        else:
            pm.cutKey(sel,clear=1,an='objects',iub=0,t=(i,i+1))
    def bdSwitchCBLidParent(self,newParent):
        selection = pm.ls(sl=1,type='transform')
        if selection:
            pass
        else:
            pm.warning('Nothing selected !!!')
            return
        if 'candybox_lid' in selection[0].name():
            candyboxLidCtrl = selection[0]
            try:
                currentParent = candyboxLidCtrl.attr('parent').get()
            except:
                pm.warning('Current selection has no Parent attribute, aborting!')
                return
            print currentParent 
            switchFrame = pm.currentTime(q=1)


            pm.currentTime(switchFrame-1,e=1)
            pm.setKeyframe(candyboxLidCtrl)
            pm.currentTime(switchFrame,e=1)

            hatPos = candyboxLidCtrl.getTranslation(space='world')
            hatRot = candyboxLidCtrl.getRotation(space='world')


            #World Parent
            if newParent == 0:
                print 'Candybox new parent: Candybox'
                candyboxLidCtrl.attr('parent').set(0)

            elif newParent == 2:
                print 'Candybox new  parent: Right Hand'

                candyboxLidCtrl.attr('parent').set(2)

            elif newParent == 1:
                print 'Candybox new  parent: Left Hand'

                candyboxLidCtrl.attr('parent').set(1)

            candyboxLidCtrl.setTranslation(hatPos,space='world')
            candyboxLidCtrl.setRotation(hatRot,space='world')


            pm.setKeyframe(candyboxLidCtrl )



        else:
            pm.warning('Select candybox_lid_ctrl')
def matchIkToFk(ikControl, ikPole, offset=100.0, msgAttr='fkjoints', autoKey=True):
    """
    Matches ikControl and ikPole Vector control to match the current pose of underlying
    fk duplicate joint chains
    Finds the fk joints using a previously created message connection to the attribute msgAttr
    """

    fkJoints = pmc.listConnections('{0}.{1}'.format(ikControl, msgAttr),
                                   destination=False, source=True)

    attr = pmc.listConnections('{0}.ikfk'.format(ikControl), destination=False,
                               source=True, plugs=True, scn=True)[0]
    switchControl = attr.node()
    switchAttr = attr.name(includeNode=False)

    frameBeforeCurrent = pmc.currentTime(q=True) - 1
    if autoKey:
        pmc.setKeyframe(switchControl, attribute=switchAttr, time=frameBeforeCurrent,
                        value=1, outTangentType='step')
        pmc.setKeyframe([ikControl, ikPole], time=frameBeforeCurrent, outTangentType='step')

        pmc.setKeyframe(switchControl, attribute=switchAttr, value=0, outTangentType='step')

    alignObjects(ikControl, fkJoints[-1])
    loc = getPoleVectorPosition(fkJoints, offset, curveGuide=False)
    alignObjects(ikPole, loc, position=True, rotation=False)
    pmc.delete(loc)

    if autoKey:
        pmc.setKeyframe([ikControl, ikPole], time=frameBeforeCurrent)

    pmc.headsUpMessage('BAMF!')
Example #10
0
 def insert_key(self, attr, value):
     '''
     # this inserts a key at the given position
     # take the attr to key and the position in time
     # attr example: 'pCube1.translateX'
     '''
     print attr, value.getValue(), attr, value.getValue()
     
     pm.setKeyframe('%s' % (attr), time= int(value.getValue()) )
     
     # reinvoking the create to add the uis for the new keys
     print 'recreating'
     pm.deleteUI(self.temp_layout)
     self.create()
Example #11
0
def animateSpotLights():
    spotLights=cmds.ls(type='spotLight')
    for spotL in spotLights:
        #lights turn off at this time
        randomFrameOff = random.randrange(530,535)
        step = 20
        randomFrameOn = randomFrameOff + step
        #lights turn on at this time
        randomFrameOn2 = random.randrange(900,905)
        randomFrameOff2 = randomFrameOn2 + step
        #set attributes for light turned off
        pm.setAttr(spotL + '.intensity',0)
        pm.setAttr(spotL + '.aiExposure',0)
        pm.setAttr(propLight + '.color',1, 0.897, 0.667)
        keyableAttributes = ['aiExposure','intensity']
        #keyframe it
        pm.setKeyframe(spotL,at=keyableAttributes,t=randomFrameOff)
        #set attributes for light turned on
        pm.setAttr(spotL + '.intensity',1)
        pm.setAttr(spotL + '.aiExposure',10)
        #keyframe it
        pm.setKeyframe(spotL,at=keyableAttributes,t=randomFrameOn)
        #keyframe the other time when it's time to turn off
        pm.setKeyframe(spotL,at=keyableAttributes, t=randomFrameOn2)
        #turn the lights off
        pm.setAttr(spotL + '.intensity',0)
        pm.setAttr(spotL + '.aiExposure',0)
        #keyframe it
        pm.setKeyframe(spotL,at=keyableAttributes, t=randomFrameOff2)
        print 'spot is animated out of this light!!!'
Example #12
0
    def slice(self, slices_in_x, slices_in_y):
        """slices all renderable cameras
        """
        # set render resolution
        self.unslice_scene()
        self.is_sliced = True
        self._store_data()

        sx = self.slices_in_x = slices_in_x
        sy = self.slices_in_y = slices_in_y

        # set render resolution
        d_res = pm.PyNode("defaultResolution")
        h_res = d_res.width.get()
        v_res = d_res.height.get()

        # this system only works when the
        d_res.aspectLock.set(0)
        d_res.pixelAspect.set(1)
        d_res.width.set(h_res / float(sx))
        d_res.pixelAspect.set(1)
        d_res.height.set(v_res / float(sy))
        d_res.pixelAspect.set(1)

        # use h_aperture to calculate v_aperture
        h_aperture = self.camera.getAttr('horizontalFilmAperture')

        # recalculate the other aperture
        v_aperture = h_aperture * v_res / h_res
        self.camera.setAttr('verticalFilmAperture', v_aperture)

        v_aperture = self.camera.getAttr('verticalFilmAperture')

        self.camera.setAttr('zoom', 1.0/float(sx))

        t = 0
        for i in range(sy):
            v_pan = v_aperture / (2.0 * sy) * (1 + 2 * i - sy)
            for j in range(sx):
                h_pan = h_aperture / (2.0 * sx) * (1 + 2 * j - sx)
                pm.currentTime(t)
                pm.setKeyframe(self.camera, at='horizontalPan', v=h_pan)
                pm.setKeyframe(self.camera, at='verticalPan', v=v_pan)
                t += 1

        self.camera.panZoomEnabled.set(1)
        self.camera.renderPanZoom.set(1)

        d_res.pixelAspect.set(1)
Example #13
0
def amcveRebuild(cvNew, cvSrcProfile):
	"""
	"""
	cvTrimmed = cvSrcProfile['cvTrimmed']
	cvBaseMod = cvSrcProfile['cvBaseMod']
	cvPortray = cvSrcProfile['cvPortray']
	cvFeature = cvSrcProfile['cvFeature']

	''' A. create animCurve '''
	# create same type of animation curve
	cvNew = pm.createNode(cvBaseMod['cvTyp'], n= cvNew)

	''' B. build curve base '''
	# whatever this animationCurve is time-base or float-base,
	# one of lists will be empty, just add them up.
	cvInp = cvPortray['Frame'] + cvPortray['Float']
	# set value to each keyframe
	for i, x in enumerate(cvInp):
		if cvTrimmed and (x < cvTrimmed[0] or x > cvTrimmed[1]):
			continue
		# whatever this animationCurve is time-base or float-base,
		# just set both, the one incorrect will take no effect.
		y = cvPortray['Value'][i]
		isBD = True if x in cvBaseMod['breaD'] else False
		pm.setKeyframe(cvNew, t= x, f= x, v= y, bd= isBD)

	''' C. inject curve feature '''
	cvNew.setPreInfinityType(cvBaseMod['prInf'])
	cvNew.setPostInfinityType(cvBaseMod['poInf'])
	weedT = cvBaseMod['weedT'][0]
	pm.keyTangent(cvNew, wt= weedT)
	if weedT:
		for i, x in enumerate(cvInp):
			if cvTrimmed and (x < cvTrimmed[0] or x > cvTrimmed[1]):
				continue
			WLock = cvFeature['WLock'][i]
			pm.keyTangent(cvNew, index= [i], wl= WLock)
	for i, x in enumerate(cvInp):
		if cvTrimmed and (x < cvTrimmed[0] or x > cvTrimmed[1]):
			continue
		pm.keyTangent(cvNew, index= [i], l= cvFeature['TLock'][i])
		pm.keyTangent(cvNew, index= [i], iw= cvFeature['InWet'][i])
		pm.keyTangent(cvNew, index= [i], ow= cvFeature['OuWet'][i])
		pm.keyTangent(cvNew, index= [i], ia= cvFeature['InAng'][i])
		pm.keyTangent(cvNew, index= [i], oa= cvFeature['OuAng'][i])
		pm.keyTangent(cvNew, index= [i], itt= cvFeature['InTyp'][i])
		pm.keyTangent(cvNew, index= [i], ott= cvFeature['OuTyp'][i])

	return cvNew
Example #14
0
def random():
  sel = pm.selected()
  
  animStartTime = pm.playbackOptions(animationStartTime=1, q=1)
  animEndTime = pm.playbackOptions(animationEndTime=1, q=1)
  
  
  
  while animStartTime<=animEndTime:
    for s in sel:
        s.translateX.set(s.translateX.get()+random.uniform(-.1,.1))
        s.translateY.set(s.translateY.get()+random.uniform(-.1,.1))
        s.translateZ.set(s.translateZ.get()+random.uniform(-.1,.1))
    pm.setKeyframe(attribute="translate", time=animStartTime)
    animStartTime+=1
Example #15
0
def copyAnim():
	selection = pm.ls(sl=True)
	if len(selection) != 2:
		pm.warning('Need exactly two objects to copy')
		return
	try:
		namespace = selection[0].namespace()
	except:
		namespace = ''
		
	print namespace
	holders = pm.ls('*_HOLDE*')
	if namespace != '':
		holders = pm.ls('*:*_HOLDE*')
	
	if holders:
		pm.delete(holders)

	source = selection[0]
	target = selection[1]
	
	pm.setKeyframe(source)
	pm.setKeyframe(target)
	
	sourceName = source.name()
	targetName = target.name()
	if namespace != '':
		sourceName =  source.stripNamespace()
		targetName =  target.stripNamespace()
		
	pm.select(cl=True)

	sourceAttr = pm.listAttr(source,k=True)
	sourceHolder = pm.group(n=namespace + sourceName + '_SOURCE_HOLDER')
	for attr in sourceAttr:
		attrType = source.attr(attr).type()
		pm.addAttr(sourceHolder,ln='__' + attr,nn=attr,at = attrType)
		sourceHolder.attr('__' + attr).set(source.attr(attr).get())
	
	pm.select(cl=True)
	targetAttr = pm.listAttr(target,k=True)
	targetHolder = pm.group(n=namespace + targetName + '_TARGET_HOLDER')
	for attr in targetAttr:
		attrType = target.attr(attr).type()
		pm.addAttr(targetHolder,ln='__' + attr,nn=attr,at = attrType)
		targetHolder.attr('__' + attr).set(target.attr(attr).get())
	
	pm.select([target,source])
Example #16
0
def keyAllChildren(op="set", jointsOnly=False): #set, cut, copy, paste
   selectedObjects = mc.ls(sl=True)
   targetObjects = mc.listRelatives( selectedObjects, ad=True ) + selectedObjects
   if(jointsOnly):
      targetObjects = mc.ls(targetObjects, type='joint')
   if(op=="set"):
      py.setKeyframe( targetObjects )
   elif(op=="cut"):
      py.cutKey( targetObjects )
   elif(op=="copy"):
      py.copyKey( targetObjects )
   elif(op=="paste"):
      py.pasteKey( targetObjects )   
   elif(op=="bake"):
      inTime=mc.playbackOptions(q=1,ast=1)
      outTime=mc.playbackOptions(q=1,aet=1)
      mc.bakeResults(targetObjects,simulation=1,sampleBy=1,time=(inTime,outTime))
Example #17
0
def amcveProfile(cvSrc, trim):
	"""
	"""
	cvSrc = pm.ls(cvSrc)[0]
	tiLen = []

	if trim:
		tiLen.append(pm.playbackOptions(q= 1, min= 1))
		tiLen.append(pm.playbackOptions(q= 1, max= 1))
		pm.undoInfo(ock= 1)
		pm.setKeyframe(cvSrc, insert= 1, t= tiLen, f= tiLen)
		pm.undoInfo(cck= 1)

	cvBaseMod = {
			'cvTyp' : pm.objectType(cvSrc),
			'prInf' : cvSrc.getPreInfinityType().key,
			'poInf' : cvSrc.getPostInfinityType().key,
			'weedT' : pm.keyTangent(cvSrc, q= 1, weightedTangents= 1),
			'breaD' : pm.keyframe(cvSrc, q= 1, breakdown= 1)
	}
	cvPortray = {
			'Frame' : pm.keyframe(cvSrc, q= 1, timeChange= 1),
			'Float' : pm.keyframe(cvSrc, q= 1, floatChange= 1),
			'Value' : pm.keyframe(cvSrc, q= 1, valueChange= 1)
	}
	cvFeature = {
			'TLock' : pm.keyTangent(cvSrc, q= 1, lock= 1),
			'WLock' : pm.keyTangent(cvSrc, q= 1, weightLock= 1),
			'InTyp' : pm.keyTangent(cvSrc, q= 1, inTangentType= 1),
			'OuTyp' : pm.keyTangent(cvSrc, q= 1, outTangentType= 1),
			'InWet' : pm.keyTangent(cvSrc, q= 1, inWeight= 1),
			'OuWet' : pm.keyTangent(cvSrc, q= 1, outWeight= 1),
			'InAng' : pm.keyTangent(cvSrc, q= 1, inAngle= 1),
			'OuAng' : pm.keyTangent(cvSrc, q= 1, outAngle= 1)
	}
	cvSrcProfile = {
			'cvTrimmed' : tiLen,
			'cvBaseMod' : cvBaseMod,
			'cvPortray' : cvPortray,
			'cvFeature' : cvFeature
	}
	if trim:
		pm.undo()

	return cvSrcProfile
    def storeAnimationAttrs(self):

        name = str(self.cube.name())
        atr = name + ".translateX"
        pm.setKeyframe(
                atr,
                t=1,
                v=10
                )
        pm.setKeyframe(
                atr,
                t=5,
                v=5
                )

        self.store.animationAttrs(
                [atr],
                self.cube
                )
        return name
Example #19
0
def mirrorAnim():
	selection = pm.ls(sl=True)
	if len(selection) != 2:
		pm.warning('Need exactly two objects to mirror')
		return

	try:
		namespace = selection[0].namespace()
	except:
		namespace = ''
		

	try:
		sourceHolder = pm.ls(namespace + '*_SOURCE_HOLDER')[0]
		targetHolder = pm.ls(namespace + '*_TARGET_HOLDER')[0]
	except:
		pm.warning('No holders found to mirror animations')
		return
	source = pm.ls(sourceHolder.name().replace('_SOURCE_HOLDER',''),type='transform')[0]
	target= pm.ls(targetHolder.name().replace('_TARGET_HOLDER',''),type='transform')[0]
	
	sourceHolderAttr = pm.listAttr(sourceHolder,ud=True)
	targetHolderAttr = pm.listAttr(targetHolder,ud=True)
	
	for attr in sourceHolderAttr:
		print attr
		reverse = 1
		if (attr.find('translateX') > 0) or (attr.find('rotateY') > 0) or (attr.find('KneeTwist') > 0) or (attr.find('rotateZ') > 0):
			reverse = -1
		target.attr(attr.replace('__','')).set(sourceHolder.attr(attr).get() * reverse)
		
	for attr in targetHolderAttr:
		reverse = 1
		if (attr.find('translateX') > 0) or (attr.find('rotateY') > 0) or (attr.find('KneeTwist') > 0) or (attr.find('rotateZ') > 0):
			reverse = -1		
		source.attr(attr.replace('__','')).set(targetHolder.attr(attr).get() * reverse)
		
	pm.delete([sourceHolder,targetHolder])

	pm.setKeyframe(source)
	pm.setKeyframe(target)
Example #20
0
def keys_sequential_visibility(transforms, additive=False):
    ''' Sets visibility keys in order on a given selection of objects, in selection order
    Args:
        transforms [pm.nt.Transform]: transforms to key
        additive (bool): if false we turn off the object again, so they blink in order, not stay on
    Returns (None)
    Usage:
        key_vis_in_sequence(pm.ls(sl=True, type='transform'))
    '''
    start_frame = pm.currentTime()
    current_frame = start_frame + 1
    
    for transform in transforms:
        pm.setKeyframe(transform.visibility,
                       v=0,
                       inTangentType='flat',
                       outTangentType='flat',
                       t=start_frame)
        pm.setKeyframe(transform.visibility,
                       v=1,
                       inTangentType='flat',
                       outTangentType='flat',
                       t=current_frame)
        if not additive:
            pm.setKeyframe(transform.visibility,
                           v=0,
                           inTangentType='flat',
                           outTangentType='flat',
                           t=current_frame+1)
        current_frame += 1
Example #21
0
def moveVerts(target=None, spread=1, time=1):
    if not target:
        target = s()

    for i in range(0,len(target)):
        # iterate through every vertex in the sphere           
        index = 1
        for v in target[i].vtx:
            # set initial position
            if(time > 1):
                py.setKeyframe(v, t=1)
            original = v.getPosition()

            # make a new position
            new_pos = [p + rnd(-spread, spread) for p in original]
            v.setPosition(new_pos)
            
            if(time > 1):
                py.setKeyframe(v, t=index)
            
            if(time > 1):
                v.setPosition(original)
                py.setKeyframe(v, t=index+time)
            
            index += 1
Example #22
0
def bdSwitchParent():
	selection = pm.ls(sl=1,type='transform')
	if selection:
		ctrl = selection[0]
		try:
			currentParent = ctrl.attr('Parent').get()
		except:
			pm.warning('Current selection has no Parent attribute, aborting!')
			return
		print currentParent 
		switchFrame = pm.currentTime(q=1)
		
	
		pm.currentTime(switchFrame-1,e=1)
		pm.setKeyframe(ctrl)
		pm.currentTime(switchFrame,e=1)

		#World Parent
		if currentParent == 1:
			print 'Frow World to hand'
			tempLoc = pm.spaceLocator(n='temp')
			tempCnstr = pm.parentConstraint(ctrl,tempLoc)
			pm.delete(tempCnstr)

			ctrl.attr('Parent').set(0)

			worldPos = tempLoc.getTranslation(space='world')
			worldRot = tempLoc.getRotation(space='world')


			ctrl.setTranslation(worldPos,space='world')
			ctrl.setRotation(worldRot,space='world')
			
			pm.delete(tempLoc)
			pm.setKeyframe(ctrl )

		else :
			print 'From hand to world'
			tempLoc = pm.spaceLocator(n='temp')
			tempCnstr = pm.parentConstraint(ctrl,tempLoc)
			pm.delete(tempCnstr)

			ctrl.attr('Parent').set(1)

			worldPos = tempLoc.getTranslation(space='world')
			worldRot = tempLoc.getRotation(space='world')


			ctrl.setTranslation(worldPos,space='world')
			ctrl.setRotation(worldRot,space='world')
			
			pm.delete(tempLoc)
			pm.setKeyframe(ctrl )


	else:
		pm.warning('Select a ticket ctrl or the pound bill ctrl')
Example #23
0
def animateWindowLights():
    winLights = cmds.listRelatives('okviriSvetlaSet', c=1)
    #iterate through all the mesh lights
    for winLight in winLights:
        y_random = random.randint(0,1)
        if y_random == 1:
            try:
                #make them a mesh light
                cmds.setAttr(winLight + '.aiTranslator','mesh_light',type='string')
            except RuntimeError:
                print "not given..."
            try:
                #get the random frame range where lights should animate
                #lights turn off at this time
                randomFrameOff = random.randrange(530,620)
                step = 1
                randomFrameOn = randomFrameOff + step
                #lights turn on at this time
                randomFrameOn2 = random.randrange(700,800)
                randomFrameOff2 = randomFrameOn2 + step
                #set attributes for light turned off
                pm.setAttr(winLight + '.intensity',0)
                pm.setAttr(winLight + '.aiExposure',0)
                pm.setAttr(winLight + '.lightVisible',1)
                pm.setAttr(winLight + '.color',1, 0.897, 0.667)
                keyableAttributes = ['aiExposure','intensity']
                #keyframe it
                pm.setKeyframe(winLight,at=keyableAttributes,t=randomFrameOff)
                #set attributes for light turned on
                pm.setAttr(winLight + '.intensity',1)
                pm.setAttr(winLight + '.aiExposure',15)
                #keyframe it
                pm.setKeyframe(winLight,at=keyableAttributes,t=randomFrameOn)
                #keyframe the other time when it's time to turn off
                pm.setKeyframe(winLight,at=keyableAttributes, t=randomFrameOn2)
                #turn the lights off
                pm.setAttr(winLight + '.intensity',0)
                pm.setAttr(winLight + '.aiExposure',0)
                #keyframe it
                pm.setKeyframe(winLight,at=keyableAttributes, t=randomFrameOff2)
                print 'made a mesh light out of this light!!!'
            except RuntimeError:
                pass
        else:
            pass
Example #24
0
def animatePropLights():
    allPropLights=cmds.ls('propLight*')
    for propLight in allPropLights:
        try:
            #make them a mesh light
            cmds.setAttr(propLight + '.aiTranslator','mesh_light',type='string')
        except RuntimeError:
            print "not given..."
        try:
            #get the random frame range where lights should animate
            #lights turn off at this time
            randomFrameOff = random.randrange(530,535)
            step = 20
            randomFrameOn = randomFrameOff + step
            #lights turn on at this time
            randomFrameOn2 = random.randrange(900,905)
            randomFrameOff2 = randomFrameOn2 + step
            #set attributes for light turned off
            pm.setAttr(propLight + '.intensity',0)
            pm.setAttr(propLight + '.aiExposure',0)
            pm.setAttr(propLight + '.lightVisible',1)
            #pm.setAttr(propLight + '.color',1, 0.897, 0.667)
            keyableAttributes = ['aiExposure','intensity']
            #keyframe it
            pm.setKeyframe(propLight,at=keyableAttributes,t=randomFrameOff)
            #set attributes for light turned on
            pm.setAttr(propLight + '.intensity',1)
            pm.setAttr(propLight + '.aiExposure',10)
            #keyframe it
            pm.setKeyframe(propLight,at=keyableAttributes,t=randomFrameOn)
            #keyframe the other time when it's time to turn off
            pm.setKeyframe(propLight,at=keyableAttributes, t=randomFrameOn2)
            #turn the lights off
            pm.setAttr(propLight + '.intensity',0)
            pm.setAttr(propLight + '.aiExposure',0)
            #keyframe it
            pm.setKeyframe(propLight,at=keyableAttributes, t=randomFrameOff2)
            print 'made a mesh light out of this light!!!'
        except RuntimeError:
            pass
Example #25
0
def CombineDeform(nodes, attributes, values, interval=10.0):

    #setting keyframes
    for attr in attributes:
        for value in values:
            currentTime = pm.currentTime()

            pm.currentTime(currentTime + interval, update=True)

            pm.setKeyframe(nodes, attribute=attr, value=(value/len(nodes)))

            for zeroAttr in attributes:
                if attr != zeroAttr:
                    pm.setKeyframe(nodes, attribute=zeroAttr, value=0)

            if attr == attributes[0]:
                pm.setKeyframe(nodes, attribute=attr, value=0,
                               time=currentTime - interval)

            if attr == attributes[-1]:
                pm.setKeyframe(nodes, attribute=attr, value=0,
                               time=currentTime + (interval * 2))
Example #26
0
def key_attr(attr, new_value=None, copy_previous=None):
    """
    Key given attr on previous and current frame.

    :param attr: Attribute to be keyed of type Attribute().
    :param new_value: Explicitly set key value on current frame.
    :param copy_previous: Explicitly copy previous key or value onto previous frame for a single-frame switch.
    """
    log.debug("Keying attr...")

    cur_time = pmc.currentTime(q=True)

    log.debug("Attr: {}".format(attr))
    log.debug("New value: {}".format(new_value))
    log.debug("Copy previous: {}".format(copy_previous))
    log.debug("Current time: {}".format(cur_time))

    if copy_previous:
        prev_key_time = pmc.findKeyframe(attr, which="previous")
        prev_key_value = attr.get(t=prev_key_time)
        prev_key = pmc.copyKey(attr, t=prev_key_time)

        log.debug("Previous key time: {}".format(prev_key_time))
        log.debug("Previous key value: {}".format(prev_key_value))

        # If a key did not exist
        if prev_key == 0:
            pmc.setKeyframe(attr, t=(cur_time - 1))
        # If a key exists
        elif prev_key == 1:
            pmc.pasteKey(attr, t=(cur_time - 1))
    else:
        pmc.setKeyframe(attr, t=(cur_time - 1))

    if new_value:
        pmc.setKeyframe(attr, t=cur_time, v=new_value)
        attr.set(new_value)
    else:
        pmc.setKeyframe(attr, t=cur_time)
    def add_target(self, aNewParent, firstSetup=False):
        """
        Add a new target to the space switch system
        """
        iNbTgt = len(self.nSwConst.getWeightAliasList())
        aExistTgt = self.nSwConst.getTargetList()

        for nParent in aNewParent:
            #Ensure that the parent doesn't already exist in the drivers list
            if not nParent in aExistTgt:
                #First, calculate the offset between the parent and the driven node
                vTrans = self._get_tm_offset(nParent, type="t")
                vRot = self._get_tm_offset(nParent, type="r")

                #Connect the new target manually in the parent constraint
                if (iNbTgt == 0):
                    self.nSwConst.addAttr(nParent.name() + "W" + str(iNbTgt), at="double", min=0, max=1, dv=1, k=True, h=False)
                else:
                    self.nSwConst.addAttr(nParent.name() + "W" + str(iNbTgt), at="double", min=0, max=1, dv=0, k=True, h=False)

                pymel.connectAttr(nParent.parentMatrix, self.nSwConst.target[iNbTgt].targetParentMatrix)
                pymel.connectAttr(nParent.scale, self.nSwConst.target[iNbTgt].targetScale)
                pymel.connectAttr(nParent.rotateOrder, self.nSwConst.target[iNbTgt].targetRotateOrder)
                pymel.connectAttr(nParent.rotate, self.nSwConst.target[iNbTgt].targetRotate)
                pymel.connectAttr(nParent.rotatePivotTranslate, self.nSwConst.target[iNbTgt].targetRotateTranslate)
                pymel.connectAttr(nParent.rotatePivot, self.nSwConst.target[iNbTgt].targetRotatePivot)
                pymel.connectAttr(nParent.translate, self.nSwConst.target[iNbTgt].targetTranslate)
                #Link the created attributes to the weight value of the target
                nConstTgtWeight = pymel.Attribute(self.nSwConst.name() + "." + nParent.name() + "W" + str(iNbTgt))
                pymel.connectAttr(nConstTgtWeight, self.nSwConst.target[iNbTgt].targetWeight)

                #Set the offset information
                self.nSwConst.target[iNbTgt].targetOffsetTranslate.targetOffsetTranslateX.set(vTrans[0])
                self.nSwConst.target[iNbTgt].targetOffsetTranslate.targetOffsetTranslateY.set(vTrans[1])
                self.nSwConst.target[iNbTgt].targetOffsetTranslate.targetOffsetTranslateZ.set(vTrans[2])
                self.nSwConst.target[iNbTgt].targetOffsetRotate.targetOffsetRotateX.set(vRot[0])
                self.nSwConst.target[iNbTgt].targetOffsetRotate.targetOffsetRotateY.set(vRot[1])
                self.nSwConst.target[iNbTgt].targetOffsetRotate.targetOffsetRotateZ.set(vRot[2])

                pymel.setKeyframe(nConstTgtWeight, t=0, ott="step")
                pymel.setKeyframe(self.nSwConst.target[iNbTgt].targetOffsetTranslate, t=0, ott="step")
                pymel.setKeyframe(self.nSwConst.target[iNbTgt].targetOffsetRotate, t=0, ott="step")
                self.aDrivers.append(nParent)
                self.aDriversSubName.append(nParent.name())
                iNbTgt += 1
            else:
                print("Warning: " + nParent.name() + " is already a driver for " + self.nDriven)
def matchFkToIk(fkControls, msgAttr='ikjoints', autoKey=True):
    """
    Matches fkControls to match the current pose of the underlying ik duplicate joint chains
    Finds the ik joints using a previously created message connection to the attribute msgAttr
    """

    ikJoints = None
    switchControl = None
    switchAttr = None
    for ctl in fkControls:
        if pmc.hasAttr(ctl, msgAttr):
            ikJoints = pmc.listConnections('{0}.{1}'.format(ctl, msgAttr),
                                           destination=False, source=True)

            attr = pmc.listConnections('{0}.ikfk'.format(ctl), destination=False,
                                       source=True, plugs=True, scn=True)[0]
            switchControl = attr.node()
            switchAttr = attr.name(includeNode=False)
            break

    if autoKey:
        frameBeforeCurrent = pmc.currentTime(q=True) - 1
        pmc.setKeyframe(switchControl, attribute=switchAttr, time=frameBeforeCurrent,
                        value=0, outTangentType='step')
        pmc.setKeyframe(fkControls, attribute='rotate', time=frameBeforeCurrent,
                        outTangentType='step')

        pmc.setKeyframe(switchControl, attribute=switchAttr, value=1, outTangentType='step')

    for ikj, ctl in izip(ikJoints, fkControls):
        alignObjects(ctl, ikj, position=False, rotation=True)

    if autoKey:
        pmc.setKeyframe(fkControls, attribute='rotate')

    pmc.headsUpMessage('BAMF!')
Example #29
0
def createAnimCurveUU(startVal, endVal, remapOldValToNewVal, driver):
    '''
    '''
    animCurveNd = pm.createNode('animCurveUU', name=driver.replace('.','_')+'_timewarp')
    
    pm.setKeyframe(animCurveNd, f=startVal, v=startVal)
    
    for oldVal, newVal in remapOldValToNewVal:
        pm.setKeyframe(animCurveNd, f=oldVal, v=newVal)
        
    pm.setKeyframe(animCurveNd, f=endVal, v=endVal)
    
    # reroute connections
    outgoing = driver.outputs(p=True)
    driver >> animCurveNd.input
    for eachCon in outgoing:
        animCurveNd.output >> eachCon
        
    return animCurveNd
Example #30
0
def animateHeartJnt(heartJnt,timeOffset=0):
    offsetMin = 0.005
    offsetMax = 0.015
    animLength=30
    pos = heartJnt.getTranslation(space='world')
    pos1 = [pos.x + random.uniform(offsetMin,offsetMax) , pos.y,pos.z]
    pos2 = [pos.x  , pos.y - random.uniform(offsetMin,offsetMax) ,pos.z]
    #pos3 = [pos.x - random.uniform(offsetMin,offsetMax) , pos.y - random.uniform(offsetMin,offsetMax) ,pos.z]
    '''
    pm.setKeyframe(heartJnt,attribute='translateX',t=0,value=pos[0])
    pm.setKeyframe(heartJnt,attribute='translateX',t=animLength/4,value=pos1[0])
    pm.setKeyframe(heartJnt,attribute='translateX',t=2*animLength/4,value=pos1[0])
    pm.setKeyframe(heartJnt,attribute='translateX',t=3*animLength/4,value=pos[0])
    pm.setKeyframe(heartJnt,attribute='translateX',t=animLength,value=pos[0])
    '''
    pm.setKeyframe(heartJnt,attribute='translateY',t=timeOffset,value=pos[1])
    pm.setKeyframe(heartJnt,attribute='translateY',t=timeOffset + animLength/2,value=pos2[1])
    #pm.setKeyframe(heartJnt,attribute='translateY',t=2*animLength/4,value=pos2[1])
    #pm.setKeyframe(heartJnt,attribute='translateY',t=3*animLength/4,value=pos2[1])
    pm.setKeyframe(heartJnt,attribute='translateY',t=timeOffset + animLength,value=pos[1])
Example #31
0
def leftHandMain(mayaFalse):
    #check
    if not pm.ls(
            'Locator_Pivot'
    ):  #first, perform a check to see if locatorMake() has been performed.
        pm.confirmDialog(title=u'SER 武器リグ', message=u'先ず、ピボット設定をしてください。')
        return

    #rest of rig start
    constrLoc = pm.spaceLocator(
        name="Locator_Constraint")  #creating locator to constraint the bone to

    weapJoint = pm.ls('*Joint_Weapon', type='joint')[0]
    pm.xform(
        constrLoc, ws=True, t=pm.xform(weapJoint, q=True, t=True, ws=True)
    )  #moving the newly created constraint locator to the translation position of the joint

    pm.parentConstraint(constrLoc, weapJoint, mo=False)
    controller_weapon = pm.circle(name='Controller_Weapon_Global',
                                  r=9,
                                  nr=[0, 1, 0])
    controller_weapon_local = pm.circle(name='Controller_Weapon_Local',
                                        r=7.5,
                                        nr=[0, 1, 0])
    controller_weapon_local_2 = pm.circle(name='Controller_Weapon_Local_2',
                                          r=5,
                                          nr=[0, 1, 0])
    controller_RH = pm.circle(name='Controller_Weapon_RightHand',
                              r=7,
                              nr=[0, 1, 0])
    pm.parent(controller_RH[0], controller_weapon_local_2[0],
              controller_weapon_local[0])

    pm.parent(controller_weapon_local[0], controller_weapon[0])

    pm.xform(controller_weapon,
             ws=True,
             t=pm.xform('Locator_Pivot', q=True, t=True, ws=True),
             ro=pm.xform('Locator_Pivot', q=True, ro=True, ws=True))
    pm.xform(controller_RH, ws=True, t=[0, -10, 0], relative=True)
    pm.delete(
        'Locator_Pivot'
    )  #deleting locator pivot after rig controllers have been created.
    pm.parent(constrLoc, controller_weapon_local_2[0])

    #create the extra effectors
    mel.eval('hikCreateAuxEffector Character1_Ctrl_RightWristEffector;'
             )  #calling left aux effector

    pm.parentConstraint(controller_RH[0],
                        'Character1_Ctrl_RightWristEffectorAux1',
                        mo=False)
    pm.setKeyframe('Character1_Ctrl_RightWristEffectorAux1')
    pm.setKeyframe('Character1_Ctrl_RightWristEffectorAux1',
                   v=1,
                   at='blendParent1',
                   itt='auto',
                   ott='step')

    pm.xform(controller_weapon[0],
             ws=True,
             translation=pm.xform('Helper_Weapon2',
                                  q=True,
                                  translation=True,
                                  ws=True),
             rotation=(90, 0, 90))
    pm.parentConstraint('Character1_Ctrl_LeftWristEffector',
                        controller_weapon[0],
                        mo=True,
                        name='Constraint_Weapon_Global')
    pm.setKeyframe('Controller_Weapon_Global')
    pm.setKeyframe('Controller_Weapon_Global',
                   v=1,
                   at='blendWeaponGlobal',
                   itt='auto',
                   ott='step')
Example #32
0
def keyGroup(model, groupSuffix):

    controlers = getControlers(model, groupSuffix)
    pm.setKeyframe(controlers)
Example #33
0
 def run(self):
     pm.setKeyframe(crab.utils.access.get_controls())
Example #34
0
    def paste(self, dataContent):
        '''
        Description            
            Function for set(paste) the animation curve value of maya objects.
                        
            :Type - class function                  
            :param  dataContent    <dict>    example {'mObect': {'attributes': {animation information}, 'namespace': 'Clifan:'}} 
            :return  None                
            :example to execute               
                from smartCopy import mayaAnim
                reload(mayaAnim)
                data = {}
                ma= mayaAnim.MayaAnim(objects=objects)
                ma.paste(dataContent=data)
        '''

        pymel.undoInfo(openChunk=True)

        objects = {}

        for eachObject in self._mObjects:

            if pymel.referenceQuery(eachObject, inr=True):
                currentNamespace = eachObject.namespace().encode()
                currentObject = eachObject.name().replace(
                    currentNamespace, '').encode()

                if currentObject not in dataContent:
                    continue
                objects.setdefault(currentObject, currentNamespace)

            else:
                if eachObject.name() not in dataContent:
                    continue

                objects.setdefault(eachObject.name().encode(), None)

        if not objects:
            warnings.warn(
                'sorry, your selected object can not find in the copy data.')
            return None

        startFrame = int(pymel.currentTime(q=1))

        for eachNode, eachNamespace in objects.iteritems():
            currentNode = '{}{}'.format(eachNamespace, eachNode)

            if not eachNamespace:
                currentNode = eachNode

            print '\n'

            for eachAttri, eachValue in dataContent[eachNode][
                    'attributes'].iteritems():

                if not pymel.objExists('{}.{}'.format(currentNode, eachAttri)):
                    continue

                pyNode = pymel.PyNode(currentNode)
                pyAttributes = pymel.PyNode('{}.{}'.format(
                    currentNode, eachAttri))

                animCurve = eachValue['animCurve']
                animCurveType = eachValue['animCurveType']
                weightTangent = eachValue['weightTangent']
                preInfinity = eachValue['preInfinity']
                postInfinity = eachValue['postInfinity']
                inTangentType = eachValue['inTangentType']
                outTangentType = eachValue['outTangentType']
                inAngle = eachValue['inAngle']
                outAngle = eachValue['outAngle']
                timeChange = eachValue['timeChange']
                valueChange = eachValue['valueChange']

                animCurves = pyAttributes.listConnections(d=False, s=True)

                if animCurves:
                    if animCurves[0].type() == 'animCurveTL' or animCurves[
                            0].type() == 'animCurveTA' or animCurves[0].type(
                            ) == 'animCurveTU':
                        currentAnimCurve = animCurves[0]
                else:
                    currentAnimCurve = pymel.createNode(
                        animCurveType, n=pyAttributes.name().replace('.', '_'))
                    currentAnimCurve.connectAttr('output', pyAttributes)

                pymel.keyTangent(currentAnimCurve, e=True,
                                 wt=weightTangent)  # Set weightTangent

                currentAnimCurve.setAttr('preInfinity',
                                         preInfinity)  # Set preInfinity
                currentAnimCurve.setAttr('postInfinity',
                                         postInfinity)  # Set postInfinity

                # Set frames and key
                for index in range(len(timeChange)):
                    precentage = float(valueChange[index]) * 100 / 100.00
                    currentFrame = (startFrame + timeChange[index]) - 1

                    pymel.setKeyframe(currentAnimCurve,
                                      time=float(currentFrame),
                                      value=precentage)
                    pymel.keyTangent(currentAnimCurve,
                                     e=1,
                                     t=(currentFrame, currentFrame),
                                     itt=inTangentType[index],
                                     ott=outTangentType[index])
                    pymel.keyTangent(currentAnimCurve,
                                     e=1,
                                     t=(currentFrame, currentFrame),
                                     ia=inAngle[index],
                                     oa=float(outAngle[index]))

                print eachNode, eachAttri, eachValue
        pymel.undoInfo(closeChunk=True)
Example #35
0
    def switch_space(self, vm, event_args):
        '''
        switch_space(self, vm, event_args)
        Event method to get the current frame and pass it to C#

        Args:
            vm (Freeform.Rigging.RigSwitcher.RigSwitcherVM): C# view model object sending the command
            event_args (SwitchSpaceEventArgs): EventArgs to store space to switch to, start and end frames
        '''
        # This could be moved to a being set on a UI event on combo box selection
        self.component = rigging.rig_base.Component_Base.create_from_network_node(
            self.index_rig_dict[event_args.Space].node)

        start_frame = event_args.StartFrame
        end_frame = event_args.EndFrame
        if start_frame > end_frame:
            return None

        if start_frame == end_frame:
            start_frame = int(pm.playbackOptions(q=True, ast=True))
            end_frame = int(pm.playbackOptions(q=True, aet=True))

        component_jnt = self.component.network.get(
            'skeleton').get_first_connection()
        component_network_list = rigging.skeleton.get_active_rig_network(
            component_jnt)

        constraint_attr_list = []
        for jnt in self.component.network.get('skeleton').get_connections():
            for constraint in list(set(
                    jnt.listConnections(type='constraint'))):
                constraint_attr_list.extend(
                    constraint.listAttr(ud=True, k=True))

        control_list = self.component.network.get('controls').get_connections()

        # Bake animation to the swapping component within the keyframe
        pm.refresh(su=True)
        autokey_state = pm.autoKeyframe(q=True, state=True)
        pm.autoKeyframe(state=False)
        try:
            # Bookend keys in the current rig component space
            if event_args.KeySwitch:
                self.component.match_to_skeleton([start_frame, end_frame],
                                                 True)

                pm.currentTime(start_frame - 1)
                pm.setKeyframe(constraint_attr_list)
                pm.setKeyframe(control_list)

                pm.currentTime(end_frame + 1)
                pm.setKeyframe(constraint_attr_list)
                pm.setKeyframe(control_list)

                # Key the switch to the new driving component
                pm.currentTime(start_frame)
                self.component.switch_current_component()
                pm.setKeyframe(constraint_attr_list)

                pm.currentTime(end_frame)
                self.component.switch_current_component()
                pm.setKeyframe(constraint_attr_list)
            else:
                self.component.switch_current_component()

        except Exception, e:
            exception_info = sys.exc_info()
            v1_core.exceptions.except_hook(exception_info[0],
                                           exception_info[1],
                                           exception_info[2])
Example #36
0
def switchFKIK(switcher_ctrl, key=True, match_only=False):
    """
    Moves the FK or IK controls to the transform of the other based on the FK_IK attribute on the switcher control.

    Args:
        switcher_ctrl (pm.nodetypes.Transform): Switcher control with attributes that hold all the FK IK information.

        key (boolean): If True, will set a key at the previous frame.

        match_only (boolean): If True, will match the FK/IK space, but will not switch the FK_IK attribute.
    """
    # check whether given node has all needed attributes to perform a switch, raise error if it does not.
    switcher_ctrl, transforms, fk_controls, ik_controls, reverses, fk_ik_value = switcher.getAllData(
        switcher_ctrl)
    current_frame = pm.currentTime(q=True)
    reverse_control_transforms = {}

    if not (fk_ik_value == 1 or fk_ik_value == 0):
        pm.warning(
            'FK IK attribute = {}, which is not a whole number, matching might be off!'
            .format(str(fk_ik_value)))

    # FK is being used, move IK to original joints
    if fk_ik_value <= 0.5:
        new_fk_ik_value = 1
        mid = pcu.getMedian(transforms)

        to_key = ik_controls + [switcher_ctrl] + reverses

        # if foot has banker attribute, set to banker's rotations to 0 and add it to key list
        if ik_controls[-1].hasAttr(pcfg.banker_attribute):
            banker_control = pm.PyNode(ik_controls[-1].attr(
                pcfg.banker_attribute).get())
            [
                banker_control.attr(r).set(0) for r in ['rx', 'ry', 'rz']
                if not banker_control.attr(r).isLocked()
            ]
            to_key.append(banker_control)

        if key:
            pm.setKeyframe(to_key, time=current_frame - 1)

        ik_controls[-1].volumetric.set(False)

        [reverse.r.set(0, 0, 0) for reverse in reverses]
        for transform, ik_control in reversed(
                list(zip(transforms, ik_controls))):

            # middle transform
            if transform == mid:
                translate, _, _, straight = xform.calculatePoleVector(
                    transforms[0], mid, transforms[-1], scale=2)
                ik_control.t.set(0, 0, 0) if straight else pm.xform(
                    ik_control, ws=True, t=translate)

            # end
            else:
                matrix = transform.worldMatrix.get()
                pm.xform(ik_control, ws=True, m=matrix)

    # IK is being used, move FK to original joints
    else:
        new_fk_ik_value = 0

        # storing reverse control transforms that will need to be set after matching IK chain
        for reverse in reverses:
            negated_ctrl = attribute.getMessagedReverseTarget(reverse)
            driven = attribute.getMessagedTarget(negated_ctrl)
            reverse_control_transforms[negated_ctrl] = driven.worldMatrix.get()

        if key:
            pm.setKeyframe(fk_controls + [switcher_ctrl] +
                           list(reverse_control_transforms),
                           time=current_frame - 1)

        # set the inner controls to their local space
        inner_start_index = int(len(fk_controls) / 2)
        for inner_ctrl in fk_controls[inner_start_index:]:
            switch(inner_ctrl)
            mayamath.zeroOut(inner_ctrl)

        # only match the real controls, not the inner ones
        for transform, fk_control in zip(transforms,
                                         fk_controls[:inner_start_index]):
            matrix = transform.worldMatrix.get()
            fk_control.volumetric.set(0)
            pm.xform(fk_control, ws=True, m=matrix)

    if not match_only:
        switcher_ctrl.attr(pcfg.fk_ik_attribute).set(new_fk_ik_value)

        if reverse_control_transforms:
            {
                pm.xform(transform, ws=True, m=matrix)
                for transform, matrix in reverse_control_transforms.items()
            }
def squishySplineIk(startLoc, endLoc):
    ikJoints = list()
    startJoint = pmc.createNode('joint')
    adv.alignObjects(startJoint, startLoc)

    endJoint = pmc.createNode('joint')
    adv.alignObjects(endJoint, endLoc)
    pmc.parent(endJoint, startJoint)

    startJoint.orientJoint('xzy', secondaryAxisOrient='zup')
    pmc.makeIdentity(endJoint, apply=True, jointOrient=True)

    Splitter.doSplit(startJoint, 10)

    ikJoints.append(startJoint)
    ikJoints.extend(reversed(startJoint.getChildren(ad=True, type='joint')))

    for i, ikj in enumerate(ikJoints):
        ikj.radius.set(2)
        ikj.rename('ikj_spine{0:02d}'.format(i))

    # Create second set of joints
    rigJoints = adv.makeDuplicateJoints(joints=ikJoints, search='ikj_', replace='local_rig_', connectBone=False)
    # HACK I haven't figured out how to create SDK nodes procedurally,
    # so making some dummy locs to make the curve I need
    a = pmc.createNode('transform')
    b = pmc.createNode('transform')

    pmc.setKeyframe(a.ty, t=0, value=2.5, inTangentType='flat', outTangentType='flat')
    pmc.setKeyframe(a.ty, t=10, value=0, inTangentType='flat', outTangentType='flat')
    pmc.keyTangent(a.ty, index=[0], inAngle=0)
    pmc.keyTangent(a.ty, index=[1], inAngle=-30)
    pmc.keyTangent(a.ty, index=[0], outAngle=0)
    pmc.keyTangent(a.ty, index=[1], outAngle=-30)

    animSquashCurve = a.ty.listConnections()[0]
    animSquashCurve.output.disconnect(a.ty)
    animSquashCurve.rename('squash_ramp')

    pmc.setKeyframe(a.tx, t=0, value=0, inTangentType='flat', outTangentType='flat')
    pmc.setKeyframe(a.tx, t=5, value=1, inTangentType='flat', outTangentType='flat')
    pmc.setKeyframe(a.tx, t=10, value=0, inTangentType='flat', outTangentType='flat')

    animTwistCurve = a.tx.listConnections()[0]
    animTwistCurve.output.disconnect(a.tx)
    animTwistCurve.rename('twist_ramp')

    pmc.delete(a, b)

    animControls = dict()
    animControls['lower_spine'] = adv.makeControlNode('ctl_lower_spine', targetObject=rigJoints[2], alignRotation=False)
    animControls['middle_spine'] = adv.makeControlNode('ctl_middle_spine')
    animControls['upper_spine'] = adv.makeControlNode('ctl_upper_spine', targetObject=rigJoints[-2],
                                                      alignRotation=False)

    animControls['lower_spine'][0].rotateOrder.set(adv.ROO_YXZ)
    animControls['middle_spine'][0].rotateOrder.set(adv.ROO_YXZ)
    animControls['upper_spine'][0].rotateOrder.set(adv.ROO_YXZ)

    pmc.pointConstraint(animControls['lower_spine'][0], animControls['upper_spine'][0],
                        animControls['middle_spine'][1], mo=False)

    pmc.orientConstraint(animControls['lower_spine'][0], animControls['upper_spine'][0],
                         animControls['middle_spine'][1], mo=False)

    splineIk = pmc.ikHandle(sj=ikJoints[0], ee=ikJoints[-1], sol='ikSplineSolver', parentCurve=False,
                            createCurve=True, simplifyCurve=True, numSpans=2, rootOnCurve=False, n='sik_spine')

    splineIkHandle = splineIk[0]
    spline = splineIk[2]
    spline.rename('crv_spine')
    clusterJoints = list()
    clusterJoints.append(pmc.createNode('joint', n='clj_spine0'))
    pmc.parentConstraint(animControls['lower_spine'][0], clusterJoints[-1])

    clusterJoints.append(pmc.createNode('joint', n='clj_spine1'))
    pmc.parentConstraint(animControls['middle_spine'][0], clusterJoints[-1])

    clusterJoints.append(pmc.createNode('joint', n='clj_spine2'))
    pmc.parentConstraint(animControls['upper_spine'][0], clusterJoints[-1])

    pmc.skinCluster(clusterJoints, spline, maximumInfluences=3)

    pmc.parentConstraint(animControls['lower_spine'][0], ikJoints[0], maintainOffset=True)

    for clj in clusterJoints:
        clj.radius.set(3)

    splineIkHandle.dTwistControlEnable.set(1)
    splineIkHandle.dWorldUpType.set(4)
    splineIkHandle.dWorldUpAxis.set(0)
    splineIkHandle.dWorldUpVector.set([0.0, 0.0, 1.0])
    splineIkHandle.dWorldUpVectorEnd.set([0.0, 0.0, 1.0])

    animControls['lower_spine'][0].worldMatrix[0].connect(splineIkHandle.dWorldUpMatrix)
    animControls['upper_spine'][0].worldMatrix[0].connect(splineIkHandle.dWorldUpMatrixEnd)

    normalizeNode = stretchySplineIk(splineIkHandle, useScale=True, globalScaleAttr='ctl_main.size')
    sqrtScale = pmc.createNode('multiplyDivide', n='sqrt_spine_scale')
    sqrtScale.operation.set(3)
    sqrtScale.input2X.set(0.5)
    normalizeNode.outputX.connect(sqrtScale.input1X)

    invScale = pmc.createNode('multiplyDivide', n='div_spine_inverse_scale')
    invScale.operation.set(2)
    invScale.input1X.set(1.0)
    sqrtScale.outputX.connect(invScale.input2X)

    jointGroups = list()
    for i, jnt in enumerate(rigJoints):
        preTransform = adv.zeroOut(jnt, 'pre')
        jointGroups.append(preTransform)

        ikNode = adv.zeroOut(jnt, 'hlp_ik')
        pmc.pointConstraint(ikJoints[i], ikNode)
        pmc.orientConstraint(ikJoints[i], ikNode)

        twistNode = adv.zeroOut(jnt, 'hlp_twist')
        twistCache = pmc.createNode('frameCache', n='frm_{0}_twist'.format(jnt))
        animTwistCurve.output.connect(twistCache.stream)
        twistCache.varyTime.set(i)

        rotateMultiplier = pmc.createNode('multiplyDivide', n='mul_{0}_twist'.format(jnt.shortName()))

        twistCache.varying.connect(rotateMultiplier.input2X)
        animControls['middle_spine'][0].rotateY.connect(rotateMultiplier.input1X)
        rotateMultiplier.outputX.connect(twistNode.rotateX)

        volumeCache = pmc.createNode('frameCache', n='frm_{0}_volume'.format(jnt.shortName()))
        animSquashCurve.output.connect(volumeCache.stream)
        volumeCache.varyTime.set(i)

        pow_ = pmc.createNode('multiplyDivide', n='pow_{0}'.format(jnt.shortName()))
        pow_.operation.set(3)
        invScale.outputX.connect(pow_.input1X)
        volumeCache.varying.connect(pow_.input2X)
        pow_.outputX.connect(jnt.scaleY)
        pow_.outputX.connect(jnt.scaleZ)

    pmc.group(animControls['lower_spine'][1], animControls['upper_spine'][1], animControls['middle_spine'][1],
              n='grp_spine_anim')
    pmc.group(splineIkHandle, spline, n='grp_spine_rig_systems')
    pmc.group(clusterJoints, startJoint, n='grp_spine_system_joints')
    pmc.group(jointGroups, n='grp_spine_bind_joints')

    return rigJoints
Example #38
0
 def run(self):
     pm.setKeyframe(crab.utils.access.get_controls(current_only=True))
def set_keyframe_with_time_editor(attr,
                                  inTangentType=None,
                                  outTangentType=None):
    """
    Set a keyframe, working around problems with the time editor.
    """
    def set_to_time_editor():
        keying_target = pm.timeEditorPanel('timeEditorPanel1TimeEd',
                                           q=True,
                                           keyingTarget=True)
        if not keying_target:
            return False

        # The time editor has weird native hooks for applying keyframes, which calls
        # teSetKeyFrameOnActiveLayerOrClip in teKeyingFunctions.mel.  It's very broken:
        # it looks at the channel box to see what to key, which causes it to key the wrong
        # attributes.  We can't just set what's shown in the channel box: that requires
        # changing the selection (which will screw with the graph editor), and we can't change
        # the selection and the channel box at the same time since the CB update is async.
        #
        # Instead, bypass all of that and set the key on the time editor layer directly.
        #
        # This means we can't control tangents on time editor clips, which sucks.
        keying_target = pm.ls(keying_target)[0]
        clip_id = keying_target.node().attr('clip[0].clipid').get()
        layer_id = keying_target.attr('layerId').get()
        is_layer = isinstance(keying_target.node(), pm.nodetypes.TimeEditorClip
                              ) and keying_target.attr('layerName').get() != ''
        if not is_layer:
            return False

        # timeEditorClipLayer doesn't take tangentType arguments like pm.setKeyframe, so we have
        # to work around this the long way by temporarily changing the default.
        old_in_tangent_type = pm.keyTangent(q=True, g=True,
                                            inTangentType=True)[0]
        old_out_tangent_type = pm.keyTangent(q=True,
                                             g=True,
                                             outTangentType=True)[0]
        if inTangentType is not None:
            pm.keyTangent(g=True, inTangentType=inTangentType)
        if outTangentType is not None:
            pm.keyTangent(g=True, outTangentType=outTangentType)

        try:
            # Set the key.
            pm.timeEditorClipLayer(e=True,
                                   clipId=clip_id,
                                   layerId=layer_id,
                                   setKeyframe=True,
                                   attribute=attr)
        finally:
            # Restore the tangent type.
            pm.keyTangent(g=True, inTangentType=old_in_tangent_type)
            pm.keyTangent(g=True, outTangentType=old_out_tangent_type)

        return True

    with maya_helpers.undo():
        if set_to_time_editor():
            return

        kwargs = {}
        if inTangentType is not None:
            kwargs['inTangentType'] = inTangentType
        if outTangentType is not None:
            kwargs['outTangentType'] = outTangentType
        pm.setKeyframe(attr, **kwargs)
Example #40
0
def characterizeBiped(*args):

    try:
        gCtl = pm.PyNode('global_C0_ctl')
        mocapAttach = att.addAttribute(gCtl,
                                       "mocapAttach",
                                       "float",
                                       1.0,
                                       minValue=0.0,
                                       maxValue=1.0)

    except:
        pm.displayWarning("global_C0_ctl: Is not in the scene")
        return

    # Align skeleton
    for a, b in zip(skelFK, gearFK):
        try:
            oA = pm.PyNode(a)
        except:
            pm.displayWarning(a + ": Is not in the scene")
        try:
            oB = pm.PyNode(b)
        except:
            pm.displayWarning(b + ": Is not in the scene")
        tra.matchWorldTransform(oB, oA)

    #constrain FK controls
    for a, b in zip(skelFK, gearFK):
        oA = pm.PyNode(a)
        oB = pm.PyNode(b)
        cns = pm.parentConstraint(oA, oB, mo=True)

        pb_node = pm.createNode("pairBlend")

        pm.connectAttr(cns + ".constraintRotateX", pb_node + ".inRotateX2")
        pm.connectAttr(cns + ".constraintRotateY", pb_node + ".inRotateY2")
        pm.connectAttr(cns + ".constraintRotateZ", pb_node + ".inRotateZ2")
        pm.connectAttr(pb_node + ".outRotateX", oB + ".rotateX", f=True)
        pm.connectAttr(pb_node + ".outRotateY", oB + ".rotateY", f=True)
        pm.connectAttr(pb_node + ".outRotateZ", oB + ".rotateZ", f=True)
        pm.setKeyframe(oB, at="rotateX")
        pm.setKeyframe(oB, at="rotateY")
        pm.setKeyframe(oB, at="rotateZ")

        pm.connectAttr(cns + ".constraintTranslateX",
                       pb_node + ".inTranslateX2")
        pm.connectAttr(cns + ".constraintTranslateY",
                       pb_node + ".inTranslateY2")
        pm.connectAttr(cns + ".constraintTranslateZ",
                       pb_node + ".inTranslateZ2")
        pm.connectAttr(pb_node + ".outTranslateX", oB + ".translateX", f=True)
        pm.connectAttr(pb_node + ".outTranslateY", oB + ".translateY", f=True)
        pm.connectAttr(pb_node + ".outTranslateZ", oB + ".translateZ", f=True)
        pm.setKeyframe(oB, at="translateX")
        pm.setKeyframe(oB, at="translateY")
        pm.setKeyframe(oB, at="translateZ")

        pm.connectAttr(mocapAttach, pb_node.attr("weight"))

    #align IK controls with FK controls
    for a, b in zip(alignIK, alignFK):
        oA = pm.PyNode(a)
        oB = pm.PyNode(b)
        tra.matchWorldTransform(oB, oA)
        if a in [u'arm_L0_upv_ctl', u'arm_R0_upv_ctl']:
            oA.attr("tz").set(-3)
        if a == u'arm_L0_ikcns_ctl':
            oA.attr("rx").set((oA.attr("rx").get() + 90))
        if a == u'arm_R0_ikcns_ctl':
            oA.attr("rx").set((oA.attr("rx").get() - 90))

    # constrain IK controls
    for a, b in zip(skelIK, gearIK):
        oA = pm.PyNode(a)
        oB = pm.PyNode(b)
        print b
        pb_node = pm.createNode("pairBlend")
        try:
            if b in [u'leg_L0_upv_ctl', u'leg_R0_upv_ctl']:
                att.lockAttribute(pm.PyNode(b), lock=False, keyable=True)
            if b in [
                    u'leg_L0_mid_ctl', u'leg_R0_mid_ctl', u'arm_L0_mid_ctl',
                    u'arm_R0_mid_ctl'
            ]:
                cns = pm.pointConstraint(oA, oB, mo=True)
            else:
                cns = pm.parentConstraint(oA, oB, mo=True)
            pm.connectAttr(cns + ".constraintRotateX", pb_node + ".inRotateX2")
            pm.connectAttr(cns + ".constraintRotateY", pb_node + ".inRotateY2")
            pm.connectAttr(cns + ".constraintRotateZ", pb_node + ".inRotateZ2")
            pm.connectAttr(pb_node + ".outRotateX", oB + ".rotateX", f=True)
            pm.connectAttr(pb_node + ".outRotateY", oB + ".rotateY", f=True)
            pm.connectAttr(pb_node + ".outRotateZ", oB + ".rotateZ", f=True)
            pm.setKeyframe(oB, at="rotateX")
            pm.setKeyframe(oB, at="rotateY")
            pm.setKeyframe(oB, at="rotateZ")
        except:
            cns = pm.pointConstraint(oA, oB, mo=True)

        pm.connectAttr(cns + ".constraintTranslateX",
                       pb_node + ".inTranslateX2")
        pm.connectAttr(cns + ".constraintTranslateY",
                       pb_node + ".inTranslateY2")
        pm.connectAttr(cns + ".constraintTranslateZ",
                       pb_node + ".inTranslateZ2")
        pm.connectAttr(pb_node + ".outTranslateX", oB + ".translateX", f=True)
        pm.connectAttr(pb_node + ".outTranslateY", oB + ".translateY", f=True)
        pm.connectAttr(pb_node + ".outTranslateZ", oB + ".translateZ", f=True)
        pm.setKeyframe(oB, at="translateX")
        pm.setKeyframe(oB, at="translateY")
        pm.setKeyframe(oB, at="translateZ")

        pm.connectAttr(mocapAttach, pb_node.attr("weight"))
Example #41
0
    def switch(self):
        """switches the pivot to the futurePivot
        """
        if not self._isSetup:
            return

        # get the current frame
        frame = pm.currentTime(q=True)

        # get the current position of the object
        current_object_pos = pm.xform(self._object, q=True, ws=True, t=True)

        current_pivot_pos = pm.xform(self._object, q=True, ws=True, piv=True)
        future_pivot_pos = pm.xform(self._futurePivot, q=True, ws=True, t=True)

        displacement = (future_pivot_pos[0] - current_pivot_pos[0],
                        future_pivot_pos[1] - current_pivot_pos[1],
                        future_pivot_pos[2] - current_pivot_pos[2])

        # move the pivot to the future_pivot
        pm.xform(self._object, ws=True, piv=future_pivot_pos[0:3])

        # set keyframes
        pm.setKeyframe(self._object, at="rotatePivotX", t=frame, ott="step")
        pm.setKeyframe(self._object, at="rotatePivotY", t=frame, ott="step")
        pm.setKeyframe(self._object, at="rotatePivotZ", t=frame, ott="step")

        pm.setKeyframe(self._object, at="scalePivotX", t=frame, ott="step")
        pm.setKeyframe(self._object, at="scalePivotY", t=frame, ott="step")
        pm.setKeyframe(self._object, at="scalePivotZ", t=frame, ott="step")

        # set pivot translations
        self._object.setAttr("rotatePivotTranslate", -1 * displacement)
        self._object.setAttr("scalePivotTranslate", -1 * displacement)

        # set keyframes
        pm.setKeyframe(self._object, at="rotatePivotTranslateX", t=frame,
                       ott="step")
        pm.setKeyframe(self._object, at="rotatePivotTranslateY", t=frame,
                       ott="step")
        pm.setKeyframe(self._object, at="rotatePivotTranslateZ", t=frame,
                       ott="step")

        pm.setKeyframe(self._object, at="scalePivotTranslateX", t=frame,
                       ott="step")
        pm.setKeyframe(self._object, at="scalePivotTranslateY", t=frame,
                       ott="step")
        pm.setKeyframe(self._object, at="scalePivotTranslateZ", t=frame,
                       ott="step")
    def bakeme(self, start, end, scene_scale):
        for i in range(
                start,
                end + 1,
        ):
            # updates the time and gets to camera attributes stored in the origcam object
            pm.currentTime(i, edit=True, update=True)

            # unpacks the object attributes into vaiables for readability
            mylens = self.camtoget.shape.focalLength.get()
            mysensorx = self.camtoget.shape.horizontalFilmAperture.get()
            mysensory = self.camtoget.shape.verticalFilmAperture.get()
            mytransx, mytransy, mytransz = pm.xform(self.camtoget.selection,
                                                    query=True,
                                                    ws=True,
                                                    t=True)
            myrotx, myroty, myrotz = pm.xform(self.camtoget.selection,
                                              query=True,
                                              ws=True,
                                              ro=True)

            # key the lens
            pm.setKeyframe(self.camtobake.shape, v=mylens, at="focalLength")
            # key sensor
            pm.setKeyframe(self.camtobake.shape,
                           v=mysensorx,
                           at="horizontalFilmAperture")
            pm.setKeyframe(self.camtobake.shape,
                           v=mysensory,
                           at="verticalFilmAperture")
            # key translates and mulitplies it by the scenescale
            pm.setKeyframe(self.camtobake.selection,
                           v=mytransx * scene_scale,
                           at="translateX")
            pm.setKeyframe(self.camtobake.selection,
                           v=mytransy * scene_scale,
                           at="translateY")
            pm.setKeyframe(self.camtobake.selection,
                           v=mytransz * scene_scale,
                           at="translateZ")
            # key rotates - rotation order ZXY
            pm.setKeyframe(self.camtobake.selection, v=myrotz, at="rotateZ")
            pm.setKeyframe(self.camtobake.selection, v=myrotx, at="rotateX")
            pm.setKeyframe(self.camtobake.selection, v=myroty, at="rotateY")
Example #43
0
    def setEmitter(self, startFrame=1):
        pm.setKeyframe(self.fluidEmitter, attribute='fluidDensityEmission', time=1, value=8)
        pm.setKeyframe(self.fluidEmitter, attribute='fluidDensityEmission', time=6, value=0)

        pm.setKeyframe(self.fluidEmitter, attribute='fluidHeatEmission', time=1, value=5)
        pm.setKeyframe(self.fluidEmitter, attribute='fluidHeatEmission', time=6, value=0)

        pm.setKeyframe(self.fluidEmitter, attribute='fluidFuelEmission', time=1, value=5)
        pm.setKeyframe(self.fluidEmitter, attribute='fluidFuelEmission', time=6, value=0)

        self.fluidEmitter.turbulence.set(6)
        self.fluidEmitter.turbulenceSpeed.set(0.25)
        self.fluidEmitter.detailTurbulence.set(1)
Example #44
0
def add_frame_sculpt(layer_node, anim=False, keyf=[1, 0, 0, 1]):
    """Add a sculpt frame to each selected layer

    Args:
        layer_node (dagNode list):  ist of Crank layer node to add the
            sculpt frame
        anim (bool, optional): if True, will keyframe the sculpt frame in the
        specified range.
        keyf (list, optional):  Keyframe range configuration. EaseIn, pre hold,
        post hold and ease out
    """
    objs = layer_node.layer_objects.inputs()
    bs_node = layer_node.layer_blendshape_node.inputs()

    # ensure other targets are set to false the edit flag

    # get current frame
    cframe = int(pm.currentTime(query=True))

    # get valid name. Check if frame is ducplicated in layer
    frame_name = "frame_{}".format(str(cframe))
    i = 1
    while layer_node.hasAttr(frame_name):
        frame_name = "frame_{}_v{}".format(str(cframe), str(i))
        i += 1

    # create frame master channel
    master_chn = attribute.addAttribute(layer_node,
                                        frame_name,
                                        "float",
                                        value=1,
                                        minValue=0,
                                        maxValue=1)

    # keyframe in range the master channel
    if anim:
        # current frame
        pm.setKeyframe(master_chn,
                       t=[cframe],
                       v=1,
                       inTangentType="linear",
                       outTangentType="linear")

        # pre and post hold
        pre_hold = keyf[1]
        if pre_hold:
            pm.setKeyframe(master_chn,
                           t=[cframe - pre_hold],
                           v=1,
                           inTangentType="linear",
                           outTangentType="linear")

        post_hold = keyf[2]
        if post_hold:
            pm.setKeyframe(master_chn,
                           t=[cframe + post_hold],
                           v=1,
                           inTangentType="linear",
                           outTangentType="linear")

        # ease in and out
        if keyf[0]:
            ei = pre_hold + keyf[0]
            pm.setKeyframe(master_chn,
                           t=[cframe - ei],
                           v=0,
                           inTangentType="linear",
                           outTangentType="linear")
        if keyf[3]:
            eo = post_hold + keyf[3]
            pm.setKeyframe(master_chn,
                           t=[cframe + eo],
                           v=0,
                           inTangentType="linear",
                           outTangentType="linear")

    for obj, bsn in zip(objs, bs_node):
        dup = pm.duplicate(obj)[0]
        bst_name = "_".join([obj.name(), frame_name])
        pm.rename(dup, bst_name)
        indx = bsn.weight.getNumElements()
        pm.blendShape(bsn,
                      edit=True,
                      t=(obj, indx, dup, 1.0),
                      ts=True,
                      tc=True,
                      w=(indx, 1))
        pm.delete(dup)
        pm.blendShape(bsn, e=True, rtd=(0, indx))
        # is same as: bs.inputTarget[0].sculptTargetIndex.set(3)
        pm.sculptTarget(bsn, e=True, t=indx)

        # connect target to master channel
        pm.connectAttr(master_chn, bsn.attr(bst_name))
Example #45
0
 def setVelocity(self):
     # self.fluidContainer.velocitySwirl.set(6) # al frame 1
     pm.setKeyframe(self.fluidContainer, attribute='velocitySwirl', time=1, value=6)
     #self.fluidContainer.velocitySwirl.set(2.5) # al frame 50
     pm.setKeyframe(self.fluidContainer, attribute='velocitySwirl', time=50, value=2.5)
     self.fluidContainer.velocityNoise.set(1)
Example #46
0
#connect ocio node to shader
ocio_node.output_color >> shader_node.outColor
pm.select(cl=True)

#set texture file
file_node.fileTextureName.set(texture_dir + '/' + texture_name)

#polyplane_transform_node, polyplane_shape_node
polyplane_transform_node, polyplane_shape_node = pm.polyPlane(
    n='ocio_test_polyplane',
    sx=10,
    sy=10,
    axis=(0, 1, 0),
    width=12.8,
    height=7.8)
pm.select(cl=True)
#connect plane to shader
pm.sets(shading_group_node, forceElement=polyplane_transform_node.name())
pm.select(cl=True)

#render_cam
render_cam_transform, render_cam_shape = pm.camera()
pm.select(cl=True)
pm.rename(render_cam_transform, 'render_cam')
render_cam_transform.translate.set(0, 13, 7)
render_cam_transform.rotate.set(-65, 0, 0)
pm.setKeyframe(render_cam_transform, s=False)
pm.lookThru(render_cam_transform)

#select ocio node at end
pm.select(ocio_node, r=True)
Example #47
0
#def run(self)
# animation step

pm.ls(regex='pSphere\d+', visible=True, r=True)
pm.delete()

sim = Clothsim(300, 300)
sim.setup()
sim.draw()

collision_sphere = pm.polySphere(sx=8, sy=8, r=1.0)
collision_sphere_name = collision_sphere[0]
pm.move(0, 2, 0, collision_sphere_name, ws=True)

NODES_LIST = pm.ls(regex='pSphere\d+', visible=True, r=True)
ATTRS_LIST = ("tx", "ty", "tz")
playbackStartTime = 1
playbackEndTime = 30
TIMES_LIST = [
    i for i in range(playbackStartTime, playbackEndTime + 1, SET_KEY_STEP)
]  #Creates the list 1,5,9,13,17,21...

pm.setKeyframe(NODES_LIST, attribute=ATTRS_LIST,
               time=TIMES_LIST)  #Set all the keys at the same time

pm.playbackOptions(ast=playbackStartTime,
                   aet=playbackEndTime,
                   max=playbackEndTime,
                   min=playbackStartTime)
Example #48
0
    def doRig(self):
        relaxOps1 = [[], [1], [.2, 1], [.2, .6, 1.0], [0.1, .33, .66, 1.0],
                     [.2, .4, .6, .8, 1.0]]
        relaxOps2 = [[], [-1], [-1, -.2], [-1.0, -.6, -.2],
                     [-1.0, -.66, -.33, -.1], [-1.0, -.8, -.6, -.4, -.2]]
        spreadOps = [[], [0], [-1, 1], [-1, -.1, 1], [-1, -.2, .3, 1],
                     [-1, -.4, -.1, .4, 1]]

        #thumb = [x for x in self.fingers if self.fingers[x]['fingerId'] == 0]
        thumb = []
        relax1 = relaxOps1[len(self.fingers) - len(thumb)]
        relax2 = relaxOps2[len(self.fingers) - len(thumb)]
        spread = spreadOps[len(self.fingers) - len(thumb)]

        if not self.guideMoveall:
            self.doGuide()

        cntrlName = self.moveallCntrlSetup['nameTempl']

        if pm.objExists(cntrlName):
            pm.delete(cntrlName)

        # esqueleto
        center = pm.xform(self.centerGuide, q=True, ws=True, t=True)
        tip = pm.xform(self.tipGuide, q=True, ws=True, t=True)
        ankle = pm.xform(self.ankleGuide, q=True, ws=True, t=True)
        ball = pm.xform(self.ballGuide, q=True, ws=True, t=True)

        A = om.MVector(ankle)
        B = om.MVector(center)
        C = om.MVector(tip)
        D = om.MVector(ball)

        # calcula a normal do sistema no triangulo entre center, ankle e tip.
        # pode ser q isso de problemas se mal colocados.
        # IMPLEMENTAR limites dos guides para evitar ma colocacao

        if self.flipAxis:
            AB = A - B
            BC = B - C
            AD = A - D
            CD = D - C
        else:
            AB = B - A
            BC = C - B
            AD = D - A
            CD = C - D

        n = AB ^ BC

        pm.select(cl=True)
        m = matrixTools.orientMatrix(mvector=AD,
                                     normal=n,
                                     pos=A,
                                     axis=self.axis)
        jntName = self.ankleJntSetup['nameTempl'] + self.jntSulfix
        j1 = pm.joint(n=jntName)
        self.skinJoints.append(j1)
        pm.xform(j1, m=m, ws=True)
        pm.makeIdentity(j1, apply=True, r=1, t=0, s=1, n=0, pn=0)

        # cria os joints
        m = matrixTools.orientMatrix(mvector=CD,
                                     normal=n,
                                     pos=D,
                                     axis=self.axis)
        jntName = self.toeJntSetup['nameTempl'] + self.jntSulfix
        j2 = pm.joint(n=jntName)
        self.skinJoints.append(j2)
        pm.xform(j2, m=m, ws=True)
        pm.makeIdentity(j2, apply=True, r=1, t=0, s=1, n=0, pn=0)

        jntName = self.toeJntSetup['nameTempl'] + self.tipJxtSulfix
        j3 = pm.joint(n=jntName)
        self.skinJoints.append(j3)
        pm.xform(j3, m=m, ws=True)
        pm.xform(j3, t=C, ws=True)
        pm.makeIdentity(j3, apply=True, r=1, t=0, s=1, n=0, pn=0)
        # e faz os ikhandles
        ballIkh = pm.ikHandle(n=self.name + 'ballIKHandle',
                              sj=j1,
                              ee=j2,
                              sol="ikRPsolver")
        tipIkh = pm.ikHandle(n=self.name + 'toeIKHandle',
                             sj=j2,
                             ee=j3,
                             sol="ikRPsolver")

        self.moveall = pm.group(em=True, n=cntrlName)
        self.moveall.translate.set(center)
        if not pm.objExists('MOVEALL'):
            pm.group(self.moveall, n='MOVEALL')
        else:
            pm.parent(self.moveall, 'MOVEALL')

        # esse controle deve levar o controle ik da ponta do limb para funcionar o pe
        displaySetup = self.toLimbCntrlSetup.copy()
        cntrlName = displaySetup['nameTempl']
        self.limbConnectionCntrl = controlTools.cntrlCrv(
            name=cntrlName,
            obj=j1,
            connType='parentConstraint',
            cntrlSulfix="_null",
            **displaySetup)

        # base cntrl
        displaySetup = self.baseCntrlSetup.copy()
        cntrlName = displaySetup['nameTempl']
        self.baseCntrl = controlTools.cntrlCrv(name=cntrlName,
                                               obj=self.centerGuide,
                                               **displaySetup)
        pm.move(.8, 0.225, 0, self.baseCntrl, r=True, os=True)
        pm.xform(self.baseCntrl, rp=ankle, ws=True)
        pm.scale(self.baseCntrl, [1, .15, .5], r=True)
        pm.makeIdentity(self.baseCntrl, apply=True, r=0, t=1, s=1, n=0, pn=0)
        self.baseCntrl.addAttr('extraRollCntrls', min=0, max=1, dv=0, k=1)

        # slidePivot
        displaySetup = self.slideCntrlSetup.copy()
        cntrlName = displaySetup['nameTempl']
        slideCntrl = controlTools.cntrlCrv(name=cntrlName,
                                           obj=self.centerGuide,
                                           **displaySetup)
        slideCompensateGrp = pm.group(em=True, n=self.name + 'Slide_grp')
        pm.parent(slideCompensateGrp, slideCntrl, r=True)
        slideMulti = pm.createNode('multiplyDivide',
                                   n=self.name + 'slideMulti')
        slideCntrl.translate >> slideMulti.input1
        slideMulti.input2.set(-1, -1, -1)
        slideMulti.output >> slideCompensateGrp.translate

        # bank cntrls
        displaySetupOut = self.outCntrlSetup.copy()
        outNameCntrl = displaySetupOut['nameTempl']
        outCntrl = controlTools.cntrlCrv(name=outNameCntrl,
                                         obj=self.inGuide,
                                         **displaySetup)
        displaySetup = self.inCntrlSetup.copy()
        cntrlName = displaySetup['nameTempl']
        inCntrl = controlTools.cntrlCrv(name=cntrlName,
                                        obj=self.outGuide,
                                        **displaySetup)
        self.baseCntrl.extraRollCntrls >> inCntrl.getParent().visibility

        # tip/heel
        displaySetup = self.tipCntrlSetup.copy()
        cntrlName = displaySetup['nameTempl']
        tipCntrl = controlTools.cntrlCrv(name=cntrlName,
                                         obj=self.tipGuide,
                                         **displaySetup)

        displaySetup = self.heelCntrlSetup.copy()
        cntrlName = displaySetup['nameTempl']
        heelCntrl = controlTools.cntrlCrv(name=cntrlName,
                                          obj=self.heelGuide,
                                          **displaySetup)

        # toe
        displaySetup = self.toeCntrlSetup.copy()
        cntrlName = displaySetup['nameTempl']
        toeCntrl = controlTools.cntrlCrv(name=cntrlName,
                                         obj=self.ballGuide,
                                         **displaySetup)
        toeCntrl.translate.set(0.5, 0, 0)
        pm.makeIdentity(toeCntrl, apply=True, r=0, t=1, s=0, n=0, pn=0)
        pm.xform(toeCntrl, rp=(-0.5, 0, 0), r=True)

        # ball
        displaySetup = self.ballCntrlSetup.copy()
        cntrlName = displaySetup['nameTempl']
        self.ballCntrl = controlTools.cntrlCrv(name=cntrlName,
                                               obj=self.ballGuide,
                                               **displaySetup)

        # rollCntrl
        displaySetup = self.rollCntrlSetup.copy()
        cntrlName = displaySetup['nameTempl']
        rollCntrl = controlTools.cntrlCrv(name=cntrlName,
                                          obj=self.ballGuide,
                                          **displaySetup)
        rollCntrl.getParent().translateBy((0, 1.5, 1))

        globalCtrl = pm.curve(n=self.name + 'GlobalFinger_cntrl',
                              d=1,
                              p=[(0, 0.25, 0), (0, 0, 0.25), (0.25, 0, 0),
                                 (0, 0.25, 0), (0, 0, -0.25), (0.25, 0, 0),
                                 (0, -0.25, 0), (0, 0, -0.25), (-0.25, 0, 0),
                                 (0, -0.25, 0), (0, 0, 0.25), (-0.25, 0, 0),
                                 (0, 0.25, 0)],
                              k=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

        globalCtrl.getShape().overrideEnabled.set(True)
        globalCtrlGrp = pm.group(n=self.name + 'GlobalFinger_grp')
        pm.parent(globalCtrlGrp, self.moveall, r=True)
        globalCtrlGrp.translate.set(.5, .75, 0)

        globalCtrl.addAttr('curl', k=1, at=float, dv=0)
        globalCtrl.addAttr('lean', k=1, at=float, dv=0)
        globalCtrl.addAttr('scrunch', k=1, at=float, dv=0)
        globalCtrl.addAttr('spread', k=1, at=float, dv=0)
        globalCtrl.addAttr('twist', k=1, at=float, dv=0)
        globalCtrl.addAttr('relax', k=1, at=float, dv=0)

        for finger in self.fingers:
            i = 0
            f = self.fingerInstances[finger]
            f.flipAxis = self.flipAxis
            f.doRig()
            self.skinJoints += f.skinJoints
            if self.fingers[finger]['isHeelFinger']:
                pm.parent(f.moveall, j1)
            else:
                pm.parent(f.moveall, j2)
            i = f.fingerId

            #if f.fingerId != 0:
            if True:
                ctrlBase = f.cntrl1
                twist_PMA = pm.listConnections(ctrlBase.twist, d=True)[0]
                globalCtrl.twist >> twist_PMA.input2D[1].input2Dx

                curl_PMA = pm.listConnections(ctrlBase.curl,
                                              d=True,
                                              t='plusMinusAverage')
                relaxMDL1 = pm.createNode('multDoubleLinear',
                                          n=self.name + 'relaxMulti1')
                relaxMDL1.input2.set(relax1[i])
                globalCtrl.relax >> relaxMDL1.input1

                relaxMDL2 = pm.createNode('multDoubleLinear',
                                          n=self.name + 'relaxMulti2')
                relaxMDL2.input2.set(relax2[i])
                globalCtrl.relax >> relaxMDL2.input1

                cond = pm.createNode('condition', n=self.name + 'relaxCond')
                globalCtrl.relax >> cond.firstTerm
                cond.secondTerm.set(0)
                cond.operation.set(2)
                relaxMDL1.output >> cond.colorIfTrue.colorIfTrueR
                relaxMDL2.output >> cond.colorIfFalse.colorIfFalseR

                for node in curl_PMA:
                    globalCtrl.curl >> node.input1D[3]
                    cond.outColor.outColorR >> node.input1D[4]

                lean_PMA = pm.listConnections(ctrlBase.lean,
                                              d=True,
                                              t='plusMinusAverage')
                for node in lean_PMA:
                    globalCtrl.lean >> node.input2D[2].input2Dy

                scrunch_MDL = pm.listConnections(
                    ctrlBase.scrunch,
                    d=True,
                )
                scrunch_PMA = []
                multi = []
                for node in scrunch_MDL:
                    multi.append(node.input2.get())
                    scrunch_PMA = scrunch_PMA + pm.listConnections(
                        node, d=True, t='plusMinusAverage')
                for j, node in enumerate(scrunch_PMA):
                    MDL = pm.createNode('multDoubleLinear',
                                        n=self.name + 'scrunchMult')
                    globalCtrl.scrunch >> MDL.input1
                    MDL.input2.set(multi[j])
                    MDL.output >> node.input1D[5]

                spread_PMA = pm.listConnections(ctrlBase.spread,
                                                d=True,
                                                t='plusMinusAverage')[0]
                spread_MDL = pm.createNode('multDoubleLinear',
                                           n=self.name + 'spreadMult')
                globalCtrl.spread >> spread_MDL.input1
                spread_MDL.input2.set(spread[i])
                spread_MDL.output >> spread_PMA.input2D[3].input2Dy

        # hierarquia
        pm.parent(self.ballCntrl.getParent(), toeCntrl.getParent(), heelCntrl)
        heelCntrl.getParent().setParent(tipCntrl)
        tipCntrl.getParent().setParent(outCntrl)
        outCntrl.getParent().setParent(inCntrl)
        inCntrl.getParent().setParent(slideCompensateGrp)
        rollCntrl.getParent().setParent(slideCompensateGrp)
        slideCntrl.getParent().setParent(self.baseCntrl)
        ballIkh[0].setParent(self.ballCntrl)
        ballIkh[0].visibility.set(0)
        tipIkh[0].setParent(toeCntrl)
        tipIkh[0].visibility.set(0)
        self.limbConnectionCntrl.getParent().setParent(self.ballCntrl)
        pm.parent(j1, self.baseCntrl.getParent(), self.moveall)

        # rollCntrl
        rollCntrl.addAttr('heelLimit', dv=50, k=1, at='float')
        rollBlend = pm.createNode('blendColors', n=self.name + 'rollBlend')
        rollCntrl.heelLimit >> rollBlend.color1.color1R

        # setDrivens do controle do Roll
        animUU = pm.createNode('animCurveUU',
                               n=self.name + 'RollAnimCrv1')  # cria curva
        multi = pm.createNode('multDoubleLinear', n=self.name + 'RollMulti')
        multi.input2.set(-1)
        pm.setKeyframe(animUU,
                       float=float(0),
                       value=float(0),
                       itt='Linear',
                       ott='Linear')
        pm.setKeyframe(animUU,
                       float=float(1.5),
                       value=float(1),
                       itt='Linear',
                       ott='Linear')
        pm.setKeyframe(animUU,
                       float=float(3),
                       value=float(0),
                       itt='Linear',
                       ott='Linear')
        rollCntrl.translateX >> animUU.input
        animUU.output >> rollBlend.blender
        rollBlend.outputR >> multi.input1
        multi.output >> self.ballCntrl.getParent().rotateZ

        animUA = pm.createNode('animCurveUA', n=self.name + 'RollAnimCrv2')
        pm.setKeyframe(animUA,
                       float=float(-3),
                       value=float(75),
                       itt='Linear',
                       ott='Linear')
        pm.setKeyframe(animUA,
                       float=float(0),
                       value=float(0),
                       itt='Linear',
                       ott='Linear')
        rollCntrl.translateX >> animUA.input
        animUA.output >> heelCntrl.getParent().rotateZ

        animUA = pm.createNode('animCurveUA', n=self.name + 'RollAnimCrv3')
        pm.setKeyframe(animUA,
                       float=float(1.5),
                       value=float(0),
                       itt='Linear',
                       ott='Linear')
        pm.setKeyframe(animUA,
                       float=float(7),
                       value=float(-180),
                       itt='Linear',
                       ott='Linear')
        rollCntrl.translateX >> animUA.input
        animUA.output >> tipCntrl.getParent().rotateZ

        animUA = pm.createNode('animCurveUA', n=self.name + 'RollAnimCrv4')
        pm.setKeyframe(animUA,
                       float=float(0),
                       value=float(0),
                       itt='Linear',
                       ott='Linear')
        pm.setKeyframe(animUA,
                       float=float(-2.5),
                       value=float(-120),
                       itt='Linear',
                       ott='Linear')
        rollCntrl.translateZ >> animUA.input
        # inverte se for mirror pq o controle tem

        if self.flipAxis:
            animUA.output >> inCntrl.getParent().rotateX
        else:
            animUA.output >> outCntrl.getParent().rotateX

        animUA = pm.createNode('animCurveUA', n=self.name + 'RollAnimCrv5')
        pm.setKeyframe(animUA,
                       float=float(0),
                       value=float(0),
                       itt='Linear',
                       ott='Linear')
        pm.setKeyframe(animUA,
                       float=float(2.5),
                       value=float(120),
                       itt='Linear',
                       ott='Linear')
        rollCntrl.translateZ >> animUA.input

        if self.flipAxis:
            animUA.output >> outCntrl.getParent().rotateX
        else:
            animUA.output >> inCntrl.getParent().rotateX

        # controles fk
        displaySetup = self.ankleFkCntrlSetup.copy()
        cntrlName = displaySetup['nameTempl']
        self.ankleFkCntrl = controlTools.cntrlCrv(name=cntrlName,
                                                  obj=j1,
                                                  connType='parentConstraint',
                                                  **displaySetup)

        displaySetup = self.toeFkCntrlSetup.copy()
        cntrlName = displaySetup['nameTempl']
        self.toeFkCntrl = controlTools.cntrlCrv(name=cntrlName,
                                                obj=self.ballGuide,
                                                align='parent',
                                                connType=None,
                                                **displaySetup)

        if self.flipAxis:
            pm.xform(self.toeFkCntrl.getParent(), ws=True, ro=[0, 0, 90])
        else:
            pm.xform(self.toeFkCntrl.getParent(), ws=True, ro=[180, 0, -90])

        pm.orientConstraint(self.toeFkCntrl, j2, mo=True)
        self.toeFkCntrl.getParent().setParent(self.ankleFkCntrl)
        self.ankleFkCntrl.getParent().setParent(self.moveall)

        # node tree ikfk Blend
        self.moveall.addAttr('ikfk', at='float', min=0, max=1, dv=1, k=1)
        ikfkRev = pm.createNode('reverse', n=self.name + 'IkFkReverse')
        ikfkVisCond1 = pm.createNode('condition', n=self.name + 'IkFkCond1')
        ikfkVisCond2 = pm.createNode('condition', n=self.name + 'IkFkCond2')

        # visibilidade ik fk
        self.moveall.ikfk >> ikfkRev.inputX
        self.moveall.ikfk >> ballIkh[0].ikBlend
        self.moveall.ikfk >> tipIkh[0].ikBlend
        self.moveall.ikfk >> ikfkVisCond1.firstTerm
        ikfkVisCond1.secondTerm.set(0)
        ikfkVisCond1.operation.set(2)
        ikfkVisCond1.colorIfTrueR.set(1)
        ikfkVisCond1.colorIfFalseR.set(0)
        ikfkVisCond1.outColorR >> self.baseCntrl.getParent().visibility

        # blend dos constraints
        self.moveall.ikfk >> ikfkVisCond2.firstTerm
        ikfkVisCond2.secondTerm.set(1)
        ikfkVisCond2.operation.set(4)
        ikfkVisCond2.colorIfTrueR.set(1)
        ikfkVisCond2.colorIfFalseR.set(0)
        ikfkVisCond2.outColorR >> self.ankleFkCntrl.getParent().visibility
        parCnstr = j1.connections(
            type='parentConstraint')[0]  # descobre constraint
        weightAttr = parCnstr.target.connections(
            p=True, t='parentConstraint')  # descobre parametros
        self.moveall.ikfk >> weightAttr[0]
        ikfkRev.outputX >> weightAttr[1]
Example #49
0
	pm.select(pnt, r=True)
	pntPos = pm.pointPosition(pnt, w=True)
	pm.select(cl=True)
	jnt = pm.joint(n=pnt.name() + "_jnt", position=pntPos)
	pntJntDic[pnt] = jnt

# Tracking and baking
startFrame = 0
endFrame = 144

while startFrame != (endFrame+1):
	pm.currentTime(startFrame)
	for pnt, jnt in pntJntDic.items():
		pntPos = pm.pointPosition(pnt, w=True)
		pm.xform(jnt, ws=True, t=pntPos)
		pm.setKeyframe(jnt + ".translate")

	startFrame += 1


## Book Set Up ##
import pymel.core as pm
import tak_misc
reload(tak_misc)

# Page
bulgeClsts = []
selLs = pm.ls(sl=True)
for sel in selLs:
	pm.select(sel, r=True)
	ffdNodes = pm.lattice(sel, divisions=[2,5,2], objectCentered=True, ldv=[2,2,2], n=sel+"_ffd")
Example #50
0
def addAnimation(animData, scene_actor, start, end, firstFrame, type, al):
    global_weight = 1.0  #0.66

    #
    face_animation = False
    if (animData.tracks):
        face_animation = True

    #CODE TO CREATE AND NEW LAYER FOR THIS ANIMATION
    # pm.animation.animLayer(scene_actor+"_addLayer", weight=1.0)
    # al = scene_actor+"_addLayer"

    for fi in range(int(start), int(end)):
        time_index = firstFrame + fi
        #if not animData.tracks:

        for bone in animData.bones:
            ## NEED TO CHECK DT AND SKIP PROPER FRAMES
            boneName = bone.BoneName + ""
            if scene_actor:
                boneName = scene_actor + ":" + bone.BoneName

            #CODE TO CREATE AND NEW LAYER FOR THIS ANIMATION
            # pm.select(boneName)
            # pm.animation.animLayer(scene_actor+"_addLayer", edit=True, addSelectedObjects=True)

            if cmds.objExists(boneName):
                cmds.select(boneName)
                sel_list = om.MSelectionList()
                sel_list.add(boneName)
                obj = sel_list.getDependNode(0)
                xform = om.MFnTransform(obj)
                orig_rotation = xform.rotation(om.MSpace.kObject,
                                               asQuaternion=True)
                try:
                    bone_frames = len(bone.positionFrames)
                    if bone_frames is 1 and bone.positionFrames[0].count(
                            0.0
                    ) == 3:  #for face animations that pass in 0s that are not used, might cause issues?
                        pass
                    else:
                        total_frames = animData.numFrames
                        frame_skip = round(
                            float(total_frames) / float(bone_frames))
                        frame_array = [
                            frame_skip * n for n in range(0, bone_frames)
                        ]
                        if float(fi) in frame_array:
                            cmds.xform(t=(
                                bone.positionFrames[frame_array.index(fi)][0],
                                bone.positionFrames[frame_array.index(fi)][1],
                                bone.positionFrames[frame_array.index(fi)][2]))
                            if al:
                                pm.setKeyframe(boneName,
                                               t=time_index,
                                               at='translate',
                                               al=al)
                            else:
                                pm.setKeyframe(boneName,
                                               t=time_index,
                                               at='translate')
                            #cmds.setKeyframe( at='translate', itt='spline', ott='spline', al=al )
                except IndexError:
                    print(IndexError.message)
                try:
                    bone_frames = len(bone.rotationFrames)
                    total_frames = animData.numFrames
                    frame_skip = round(
                        float(total_frames) / float(bone_frames))
                    frame_array = [
                        frame_skip * n for n in range(0, bone_frames)
                    ]
                    frame_quat_prev = False
                    if float(fi) in frame_array:
                        frame_quat = bone.rotationFramesQuat[frame_array.index(
                            fi)]
                        #MIMIC POSES DON'T GET INVERTED
                        if type is "face":
                            # cmds.xform( ro=(-bone.rotationFrames[frame_array.index(fi)][0],
                            #                 -bone.rotationFrames[frame_array.index(fi)][1],
                            #                 -bone.rotationFrames[frame_array.index(fi)][2]))
                            xform.setRotation(frame_quat.invertIt(),
                                              om.MSpace.kObject)
                        else:
                            ## temp solution to blend face animations on top of current animations
                            ## maybe create a new animLayer if this is the case
                            ## could get messy without a bind pose
                            ## an animLayer based off the bind pose could work so there is something to export.
                            ## exports of face animation will be borken in-game if exported as-is.
                            if face_animation:
                                xform.rotateBy(frame_quat, om.MSpace.kObject)
                            else:
                                xform.setRotation(frame_quat,
                                                  om.MSpace.kObject)
                        # if type is "face":
                        #     cmds.xform( ro=(bone.rotationFrames[frame_array.index(fi)][0],
                        #                     bone.rotationFrames[frame_array.index(fi)][1],
                        #                     bone.rotationFrames[frame_array.index(fi)][2]))
                        # else:
                        #     cmds.xform( ro=(-bone.rotationFrames[frame_array.index(fi)][0],
                        #                     -bone.rotationFrames[frame_array.index(fi)][1],
                        #                     -bone.rotationFrames[frame_array.index(fi)][2]))
                        #cmds.setKeyframe( at='rotate', itt='auto', ott='auto', al=al )
                        if al:
                            pm.setKeyframe(boneName,
                                           t=time_index,
                                           at='rotate',
                                           al=al,
                                           minimizeRotation=True,
                                           itt='linear',
                                           ott='linear')
                        else:
                            pm.setKeyframe(boneName,
                                           t=time_index,
                                           at='rotate',
                                           minimizeRotation=True,
                                           itt='linear',
                                           ott='linear')
                        ## temp solution to blend face animations
                        ## restore the orignal frame after every rotateBy keyframe
                        if face_animation:
                            xform.setRotation(orig_rotation, om.MSpace.kObject)
                except IndexError:
                    print(IndexError.message)

        if animData.tracks:
            for track in animData.tracks:
                trackname = scene_actor + "_" + track.trackName
                if pm.animLayer(trackname, query=True, ex=True):
                    try:
                        track_frames = len(track.trackFrames)
                        total_frames = animData.numFrames
                        frame_skip = round(
                            float(total_frames) / float(track_frames))
                        frame_array = [
                            frame_skip * n for n in range(0, track_frames)
                        ]
                        if float(fi) in frame_array:
                            weight = round(
                                track.trackFrames[frame_array.index(fi)], 5)
                            pm.select(trackname)
                            pm.animLayer(trackname,
                                         edit=True,
                                         weight=weight * global_weight)
                            pm.setKeyframe(trackname,
                                           attribute='weight',
                                           t=time_index)

                            #cmds.setKeyframe( at='translate', itt='spline', ott='spline', al=al )
                    except IndexError:
                        pass
Example #51
0
def bake_objects(obj_list,
                 translate,
                 rotate,
                 scale,
                 use_settings=True,
                 custom_attrs=None,
                 bake_range=None,
                 **kwargs):
    '''
    Wrapper around pm.bakeResults and sets up the scene to ensure the objects are bake-able and using the user's custom 
    bake settings.
    Note: At the end we set a key at -10000 and value 0 for rotation as a reference point for a eurler filter operation.

    Args:
        obj_list (list<PyNode>): List of objects to perform the bake operation on
        translate (boolean): Whether or not to bake translate channels
        rotate (boolean): Whether or not to bake rotate channels
        scale (boolean): Whether or not to bake scale channels
        use_settings (boolean): Whether or not to use user defined settings for bake settings
        custom_attrs (list<str>): A list of strings defining all custom attributes that should also be baked
        kwargs (kwargs): keyword arguments for pm.bakeResults
    '''

    # Temporary disable cycle checks during baking
    cycle_check = pm.cycleCheck(q=True, e=True)
    pm.cycleCheck(e=False)
    try:
        # Disable viewport refresh to speed up execution
        pm.refresh(su=True)

        # Anim Layers with a single keyframe don't bake reliably, add a second key 1 frame after the first on any single keyframe layers
        fix_solo_keyframe_layers()

        # Objects on hidden layers don't reliably bake correctly, toggle them all true, then reset values after baking.
        layer_dict = {}
        default_display_layer = pm.PyNode('defaultLayer') if pm.objExists(
            'defaultLayer') else None
        for layer in pm.ls(type='displayLayer'):
            if layer != default_display_layer:
                layer_dict[layer] = layer.visibility.get()
                layer.visibility.set(True)

        attr_list = []
        if translate: attr_list += ['.tx', '.ty', '.tz']
        if rotate: attr_list += ['.rx', '.ry', '.rz']
        if scale: attr_list += ['.sx', '.sy', '.sz']
        if custom_attrs: attr_list += custom_attrs

        process = System.Diagnostics.Process.GetCurrentProcess()
        # In maya standalone don't use user settings file
        if "mayapy" in process.ToString():
            use_settings = False

        bake_settings = v1_core.global_settings.GlobalSettings().get_category(
            v1_core.global_settings.BakeSettings, default=not use_settings)

        sample = bake_settings.sample_by

        # Set/get time range
        time_range = (pm.playbackOptions(q=True, ast=True),
                      pm.playbackOptions(q=True, aet=True))
        if use_settings:
            time_range = get_bake_time_range(obj_list, bake_settings)
        elif bake_range:
            time_range = bake_range

        time_range = [int(time_range[0]), int(time_range[1])]
        if type(time_range[0]) != int or type(time_range[1]) != int:
            raise BakeRangeError

        v1_core.v1_logging.get_logger().info(
            "Baking {0} \n Use Settings: {1}, over range {2}\nBake Attrs: {3}\nBakeSettings: {4}"
            .format(obj_list, use_settings, time_range, attr_list, kwargs))

        bake_start = time.clock()
        # Baking is stupidly slower if you pass in a value to smart bake(sr), even if it's False, so we split out the command
        if bake_settings.smart_bake:
            pm.bakeResults(obj_list,
                           at=attr_list,
                           t=time_range,
                           sb=sample,
                           sr=True,
                           preserveOutsideKeys=True,
                           **kwargs)
        else:
            pm.bakeResults(obj_list,
                           at=attr_list,
                           t=time_range,
                           sb=sample,
                           preserveOutsideKeys=True,
                           **kwargs)
        v1_core.v1_logging.get_logger().info(
            "Bake Command Completed in {0} Seconds".format(time.clock() -
                                                           bake_start))

        pm.setKeyframe(obj_list, t=-1010, at='rotate', v=0)
        pm.filterCurve(obj_list)
        pm.cutKey(obj_list, t=-1010)

        for layer, value in layer_dict.iteritems():
            layer.visibility.set(value)
    except Exception, e:
        exception_info = sys.exc_info()
        v1_core.exceptions.except_hook(exception_info[0], exception_info[1],
                                       exception_info[2])
 def set_keyframe(attr, value):
     if frame == current_frame:
         dst.attr(attr).set(value)
     pm.setKeyframe(dst, at=attr, time=frame, value=value)
Example #53
0
def keyAll(model):

    controlers = getControlers(model)
    pm.setKeyframe(controlers)
Example #54
0
    def importAnim(self, nameSpace=None, replaceString=None, *args):

        successState = True

        #  *.anim file
        filePath = pm.fileDialog2(caption='Read Animation',
                                  fileMode=1,
                                  startingDirectory=uad,
                                  fileFilter="Anim Files (*.anim)")

        if not filePath:
            pm.warning('Read animation cancelled.')
            return None

        # read anim info from file
        filePath = filePath[0]
        logfile = open(filePath, 'r')
        fileContent = logfile.read(
        )  # dictionary containing dictionaries of every object's animations
        logfile.close()

        # we can replace some parts of file to use animations on other objects.
        # for example, replace 'L' with 'R' copy animation from left side to right side.

        #replaceString = ('L','R')
        if replaceString:
            fileContent = fileContent.replace(replaceString[0],
                                              replaceString[1])

        # convert file content to a animInfos dictionary
        animInfos = eval(fileContent)

        objs = animInfos.keys()

        try:
            nameSpaceRaw = pm.ls(sl=True)[0].name().split(':')
            if len(nameSpaceRaw) > 1:
                nameSpace = nameSpaceRaw[0]
        except:
            nameSpace = None

        for obj in objs:

            if nameSpace:
                try:
                    objNode = pm.PyNode(nameSpace + ':' + obj)
                except:
                    successState = False
                    pm.warning(
                        'Could not find object to import anim to, skipped.')
                    continue

            else:
                try:
                    objNode = pm.PyNode(obj)
                except:
                    successState = False
                    pm.warning(
                        'Could not find object to import anim to, skipped.')
                    continue

            # print objNode
            # print '__________________________________________________________'

            attrs = animInfos[obj].keys()
            # print attrs

            for attr in attrs:
                #print attr
                #print '============================='
                animCurveInfos = animInfos[obj][attr]
                #print animCurveInfos
                for animCurveAttribute in animCurveInfos:

                    animCurveValues = animInfos[obj][attr][animCurveAttribute]
                    #print animCurveAttribute  # anim curve attrs such as times, values, outWeights, inWeights, inAngles, outAngles
                    #print animCurveValues # anim curve values for times, values, outWeights, inWeights, inAngles, outAngles
                    #print '--------------'
                    times = animCurveInfos['times']
                    values = animCurveInfos['values']
                    outWeights = animCurveInfos['outWeights']
                    outAngles = animCurveInfos['outAngles']
                    inWeights = animCurveInfos['inWeights']
                    inAngles = animCurveInfos['inAngles']

                    for i in range(len(animCurveInfos['times'])):
                        if nameSpace:
                            if pm.objExists(nameSpace + ':' + attr):
                                attrNode = pm.PyNode(nameSpace + ':' + attr)
                            elif pm.objExists(attr):
                                attrNode = pm.PyNode(attr)
                            else:
                                successState = False
                                pm.warning(
                                    'attrtibute was not found on target to apply animation, skipped.'
                                )
                                continue
                        else:
                            if pm.objExists(attr):
                                attrNode = pm.PyNode(attr)
                            else:
                                successState = False
                                pm.warning(
                                    'attrtibute was not found on target to apply animation, skipped.'
                                )
                                continue

                        pm.setKeyframe(attrNode,
                                       time=times[i],
                                       value=values[i])
                        pm.keyTangent(attrNode,
                                      e=True,
                                      index=(i, i),
                                      outWeight=outWeights[i],
                                      outAngle=outAngles[i],
                                      inWeight=inWeights[i],
                                      inAngle=inAngles[i])

        if successState:
            sys.stdout.write('Animation was successfully imported.')
        else:
            pm.warning(
                'Animation was imported. Not all objects or their attributes were the same. So, animation was not applied to them.'
            )
Example #55
0
    def custom_bake(self, time_range):
        stepped_limit = 0.0001

        # get objects to bake
        # baked_objects = list(self.original_selection)  # copy the list
        # joints = pm.listRelatives(self.original_selection, allDescendents=True, type='joint')
        # baked_objects.extend(pm.listRelatives(self.original_selection, allDescendents=True, type='transform'))

        # pm.select(baked_objects, r=True)

        # obj_list = om.MGlobal.getActiveSelectionList()
        # iterator = om.MItSelectionList(obj_list, om.MFn.kDagNode)
        try:
            to_bake = pm.ls(self.original_selection, type='transform')
            to_bake += pm.listRelatives(self.original_selection,
                                        allDescendents=True,
                                        type='transform')

            # create a set, and add all joints to the set
            filtered = set(pm.ls(self.original_selection, type='joint'))
            filtered |= set(
                pm.listRelatives(self.original_selection,
                                 allDescendents=True,
                                 type='joint'))  # union op.
        except:
            print "error 1"

        # add blendshapes and animated transforms to the set
        for node in to_bake:
            # blendshape?
            try:
                in_mesh = node.getShape()
                if in_mesh is not None:
                    blendshape = in_mesh.attr('inMesh').inputs()
                    if pm.nodeType(blendshape) == 'blendShape':
                        filtered.add(in_mesh[0])
            except Exception as e:
                pm.warning("Could not determine blendshape: %s" % e)

            # any inputs to transform attributes? i.e. any animation?
            for at in self.transform_attributes:
                if pm.hasAttr(node, at) and len(node.attr(at).inputs()) > 0:
                    filtered.add(node)
                    break

        to_bake = list(filtered)

        samples = 1
        has_stepped = self.has_stepped_checkbox.isChecked()
        if has_stepped:
            samples = 0.5

        # merge animation layers if necessary
        if len(pm.ls(type='animLayer')) > 1:
            pm.mel.eval('animLayerMerge( `ls -type animLayer` )')

        if len(to_bake) == 0:
            pm.select(self.original_selection, r=True)
            return

        # bake selected transforms and children with half step
        pm.bakeResults(to_bake,
                       time=time_range,
                       sampleBy=samples,
                       hierarchy='none',
                       disableImplicitControl=True,
                       preserveOutsideKeys=False,
                       sparseAnimCurveBake=False,
                       simulation=True,
                       minimizeRotation=False)

        # remove static channels to speed up analysis
        # to_bake.extend(joints)
        pm.select(to_bake, r=True)
        pm.delete(staticChannels=True)

        muted_curves = []
        for obj in to_bake:
            for curve in pm.keyframe(obj, q=True, name=True):
                # find muted curves
                connection = pm.listConnections(curve, d=True, s=False)[0]
                if pm.nodeType(connection) == 'mute':
                    if pm.getAttr('%s.mute' % connection):
                        muted_curves.append(curve)
                        continue

                # analyse half frames to determine which are stepped
                if has_stepped:
                    for key in range(int(time_range[0]), int(time_range[1])):
                        try:
                            epsilon_half = abs(
                                pm.keyframe(curve,
                                            q=True,
                                            valueChange=True,
                                            time=(key, ))[0] -
                                pm.keyframe(curve,
                                            q=True,
                                            valueChange=True,
                                            time=(key + 0.5, ))[0])
                            epsilon_full = abs(
                                pm.keyframe(curve,
                                            q=True,
                                            valueChange=True,
                                            time=(key, ))[0] -
                                pm.keyframe(curve,
                                            q=True,
                                            valueChange=True,
                                            time=(key + 1))[0])
                            if epsilon_half < stepped_limit < epsilon_full:
                                pm.keyTangent(curve, time=(key, ), ott='step')
                        except IndexError:
                            continue

        pm.delete(muted_curves)

        # remove unsnapped keys
        if has_stepped:
            pm.selectKey(to_bake, unsnappedKeys=True)
            pm.cutKey(animation='keys', clear=True)

        # apply euler filter
        if self.euler_filter_checkbox.isChecked():
            self.apply_euler_filter(to_bake)

        pm.currentTime(time_range[0])
        pm.setKeyframe(to_bake,
                       attribute=self.transform_attributes,
                       t=time_range[0],
                       insertBlend=False)

        # re-select original selection, so that we export the right thing
        pm.select(self.original_selection, r=True)
Example #56
0
def deformface():
    global dataarray
    if len(dataarray) < 3:
        return 0

    all_rows = cmds.scriptTable('scrtable', query=True, rows=True)
    global recstart
    global gnumcurrenttime
    if all_rows > 1 and recstart == 1:
        ornum = 1

        numcurrenttime = gnumcurrenttime
        bonename = cmds.textField('HeadbonenameF', q=True, tx=True)

        if len(bonename) > 0:
            cX = cmds.textField('HeadbonenameXF', q=True, tx=True)
            cY = cmds.textField('HeadbonenameYF', q=True, tx=True)
            cZ = cmds.textField('HeadbonenameZF', q=True, tx=True)
            CrX = 0
            CrY = 0
            CrZ = 0
            if cX.replace(".", "").isdigit():
                CrX = float(cX)
            if cY.replace(".", "").isdigit():
                CrY = float(cY)
            if cZ.replace(".", "").isdigit():
                CrZ = float(cZ)

            bjoint = pm.PyNode(bonename)
            pm.rotate(bjoint, [
                float(dataarray[0]) * -1 + CrX,
                float(dataarray[1]) * -1 + CrY,
                float(dataarray[2]) * -1 + CrZ
            ],
                      euler=True,
                      a=True,
                      ws=False)
            #if recnow ==1
            pm.setKeyframe(bjoint,
                           v=float(dataarray[0]) * -1 + CrX,
                           attribute='rotateX',
                           t=[numcurrenttime])
            pm.setKeyframe(bjoint,
                           v=float(dataarray[1]) * -1 + CrY,
                           attribute='rotateY',
                           t=[numcurrenttime])
            pm.setKeyframe(bjoint,
                           v=float(dataarray[2]) * -1 + CrZ,
                           attribute='rotateZ',
                           t=[numcurrenttime])

        for i in range(all_rows):
            all_colums = cmds.scriptTable('scrtable', query=True, columns=True)
            data_list = []
            for j in range(all_colums):
                cell_list = cmds.scriptTable('scrtable',
                                             cellIndex=(i, j),
                                             query=True,
                                             cellValue=True)
                if type(cell_list) == 'list':
                    cell_text = "".join(cell_list)
                elif cell_list == None:
                    cell_text = cell_list
                else:
                    cell_text = cell_list[0]

                data_list.append(cell_text)

            if i > 0 and len(dataarray) > 3:
                streng = 1.0
                if data_list[4].replace(".", "").isdigit():
                    streng = float(data_list[4])
                #recdataDeformStreng = (((float(dataarray[int(data_list[6])-2+3]))+0.0)/100.0)*(streng+0.0)
                recdataDeformStreng = ((
                    (float(dataarray[int(data_list[6]) - 2 + 3])) + 0.0) /
                                       33.0) * (streng + 0.0)
                targetdefnum = int(data_list[5]) - 2
                cmds.blendShape(selectedBlend,
                                edit=True,
                                w=[(targetdefnum, recdataDeformStreng)])
                #if recnow ==1
                cmds.setKeyframe("%s.w[%i]" % (selectedBlend, targetdefnum),
                                 t=numcurrenttime)

                if random.random() < 0.2:
                    datastring = '%.4f' % recdataDeformStreng
                    cmds.scriptTable('scrtable',
                                     e=True,
                                     ci=[i, 3],
                                     cv=datastring)
Example #57
0
def read_amb_file(scale_rate, amb_path, start_frame=-1, end_frame=-1):
    file = open(amb_path, "r")

    line = file.readline()
    num_bones = parse_amb_value(file.readline(), 1)
    num_dummey = parse_amb_value(file.readline(), 1)
    num_frame = parse_amb_value(file.readline(), 1)
    unknow = parse_amb_value(file.readline(), 1)

    if (start_frame == -1) and (end_frame == -1):
        start_frame = 0
        end_frame = num_frame

    while True:
        line = file.readline()
        if not line:
            break

        if line.find("frame start flag") != -1:
            line = file.readline()
            if line.find("frame index") != -1:
                frame_index = int(line.split("=")[-1])

                # base offset
                vec_offset = parse_amb_value(file.readline(), 3)
                vec_offset[0] *= scale_rate
                vec_offset[1] *= scale_rate
                vec_offset[2] *= scale_rate

                bone_quat = []
                dummey_vec_offset = []
                dummey_quat = []

                # bone quat
                for bi in range(0, 30):
                    quat = parse_amb_value(file.readline(), 4)
                    bone_quat.append(quat)

                # dummey info
                for di in range(0, 6):
                    line = file.readline()
                    d_vec_offset = parse_amb_value(file.readline(), 3)
                    d_vec_offset[0] *= scale_rate
                    d_vec_offset[1] *= scale_rate
                    d_vec_offset[2] *= scale_rate

                    d_quat = parse_amb_value(file.readline(), 4)

                    dummey_vec_offset.append(d_vec_offset)
                    dummey_quat.append(d_quat)

                if (frame_index >= start_frame) and (frame_index < end_frame):
                    #print bone_list
                    for i in range(0, 36):
                        bone = bone_list[i]
                        if bone.bone_type == "bone":
                            b_quat = bone_quat[i]

                            mQuat = OpenMaya.MQuaternion(
                                b_quat[1], b_quat[2], b_quat[3], b_quat[0])
                            maya_mat = to_PMatrix(mQuat)
                            if bone.bone_name == "b":
                                maya_mat.a30 = vec_offset[0]
                                maya_mat.a31 = vec_offset[1]
                                maya_mat.a32 = vec_offset[2]
                            else:
                                maya_mat.a30 = bone.bone_pivotX
                                maya_mat.a31 = bone.bone_pivotY
                                maya_mat.a32 = bone.bone_pivotZ

                            pmc.currentTime(int(frame_index))
                            pmc.select(bone.bone_name)
                            pmc.xform(matrix=maya_mat)
                            pmc.setKeyframe()
                        elif bone.bone_type == "Dummey":
                            d_vec_offset = dummey_vec_offset[int(i - 30)]
                            d_quat = dummey_quat[int(i - 30)]

                            mQuat = OpenMaya.MQuaternion(
                                d_quat[1], d_quat[2], d_quat[3], d_quat[0])
                            maya_mat = to_PMatrix(mQuat)
                            maya_mat.a30 = d_vec_offset[0]
                            maya_mat.a31 = d_vec_offset[1]
                            maya_mat.a32 = d_vec_offset[2]

                            pmc.currentTime(int(frame_index))
                            pmc.select(bone.bone_name)
                            pmc.xform(matrix=maya_mat)
                            pmc.setKeyframe()
                    print "Frame Index {0} succed".format(frame_index)
Example #58
0
def keyAllControls():
    for control in getAllControls():
        if control:
            pymel.setKeyframe(control, shape=False)
Example #59
0
    '''
    sel = pm.ls(sl=1)
    fluid = sel[0]
    emitters = sel[1:]
    for each in emitters:
        pm.connectDynamic(fluid, em=each, d=True)
        pm.connectDynamic(fluid, em=each)


# Set keys on emitters
on = 250
off = 251
rate = 100
for each in pm.ls(sl=1):
    pm.currentTime(on, edit=True)
    each.rate.set(rate)
    pm.setKeyframe(each, attribute='rate', t=[on])

    pm.currentTime(off, edit=True)
    each.rate.set(0)
    pm.setKeyframe(each, attribute='rate', t=[off])

# Zero emitters
for each in pm.ls(sl=1):
    each.rate.set(0)

# Zero emitters
for each in pm.ls(sl=1):
    each.speedMethod.set(1)
    each.directionalSpeed.set(50)
Example #60
0
def leftHandBake(mayaFalse):  #deprecated

    #hikCreateAuxEffector Character1_Ctrl_LeftWristEffector;
    #bake the left hand controller
    pm.setKeyframe('Controller_LeftHand_Locator', t=0)
    pm.setAttr('Controller_LeftHand_Locator.blendParent1', 1)

    #pm.setAttr('Character1_Ctrl_LeftWristEffector.rt', 1)
    #pm.setAttr('Character1_Ctrl_LeftWristEffector.rr', 0)

    for i in range(
            pm.intField('fromFrame', q=True, value=True),
        (1 + pm.intField('toFrame', q=True,
                         value=True))):  #copying keys from controller
        pm.currentTime(i, update=True)
        pm.setKeyframe('Character1_Ctrl_LeftWristEffectorAux1',
                       at='translateX',
                       v=pm.getAttr('Controller_LeftHand_Locator.tx', time=i))
        pm.setKeyframe('Character1_Ctrl_LeftWristEffectorAux1',
                       at='translateY',
                       v=pm.getAttr('Controller_LeftHand_Locator.ty', time=i))
        pm.setKeyframe('Character1_Ctrl_LeftWristEffectorAux1',
                       at='translateZ',
                       v=pm.getAttr('Controller_LeftHand_Locator.tz', time=i))
        pm.setKeyframe('Character1_Ctrl_LeftWristEffectorAux1',
                       at='rotateX',
                       v=pm.getAttr('Controller_LeftHand_Locator.rx', time=i))
        pm.setKeyframe('Character1_Ctrl_LeftWristEffectorAux1',
                       at='rotateY',
                       v=pm.getAttr('Controller_LeftHand_Locator.ry', time=i))
        pm.setKeyframe('Character1_Ctrl_LeftWristEffectorAux1',
                       at='rotateZ',
                       v=pm.getAttr('Controller_LeftHand_Locator.rz', time=i))