def getRoofSineCurve( startInput, endInput, minValue, maxValue ): animCurve = cmds.createNode( 'animCurveUU' ) cmds.setKeyframe( f= startInput, v=minValue ) cmds.setKeyframe( f= (startInput+endInput)/2.0, v=maxValue ) cmds.setKeyframe( f= endInput, v=minValue ) cmds.selectKey( animCurve ) cmds.setInfinity( poi='cycle', pri='cycle' ) return animCurve
def create_fk_setup(self): """Creates the FK setup.""" cmds.orientConstraint(self.controls['fan'], self.result_jnts[0], mo=True) mdl = cmds.shadingNode('multDoubleLinear', asUtility=True) mdl = cmds.rename(mdl, '%s_%s_MDL' % (self.side, self.modulename)) if self.side == 'R': cmds.expression(s='%s.input1 = time * (-1);' % mdl, o=mdl, ae=1, uc='all') else: cmds.expression(s='%s.input1 = time;' % mdl, o=mdl, ae=1, uc='all') # END if cmds.connectAttr('%s.speed' % self.controls['fan'], '%s.input2' % mdl, f=True) cmds.setDrivenKeyframe('%s.rotate%s' % (self.controls['offset'], self._up_axis), cd='%s.output' % mdl, dv=0, v=0) cmds.setDrivenKeyframe('%s.rotate%s' % (self.controls['offset'], self._up_axis), cd='%s.output' % mdl, dv=1, v=1) cmds.keyTangent('%s_rotate%s' % (self.controls['offset'], self._up_axis), itt='linear', ott='linear', f=(0, 1)) cmds.selectKey('%s_rotate%s' % (self.controls['offset'], self._up_axis), add=True, k=True, f=(0, 1)) cmds.setInfinity(pri='cycleRelative', poi='cycleRelative')
def pre_post_Linear(): #Create a alarm message!# global global_info Objects = maya.ls(type=["transform", "camera"], selection=True) if Objects == []: maya.text( global_info, edit=True, label="Please select at least one camera before pre_post_linear!") else: for i in Objects: print i maya.setAttr(i + ".tx", lock=False) maya.setAttr(i + ".ty", lock=False) maya.setAttr(i + ".tz", lock=False) maya.setAttr(i + ".rx", lock=False) maya.setAttr(i + ".ry", lock=False) maya.setAttr(i + ".rz", lock=False) maya.setAttr(i + ".sx", lock=False) maya.setAttr(i + ".sy", lock=False) maya.setAttr(i + ".sz", lock=False) maya.keyTangent(inTangentType='spline', outTangentType='spline') maya.setInfinity(poi='linear', pri='linear') maya.setAttr(i + ".tx", lock=True) maya.setAttr(i + ".ty", lock=True) maya.setAttr(i + ".tz", lock=True) maya.setAttr(i + ".rx", lock=True) maya.setAttr(i + ".ry", lock=True) maya.setAttr(i + ".rz", lock=True) maya.setAttr(i + ".sx", lock=True) maya.setAttr(i + ".sy", lock=True) maya.setAttr(i + ".sz", lock=True)
def loopKeyFrameC(obj,startFrame,endFrame,offsetFrame): print "loopKeyFrameC"#,obj,startFrame,endFrame,offsetFrame keyAbleAttList=["translateX","translateY","translateZ","rotateX","rotateY","rotateZ","scaleX","scaleY","scaleZ","slot_alpha","slot_red","slot_green","slot_blue"] #["translateX","translateY","translateZ","rotateX","rotateY","rotateZ","scaleX","scaleY","scaleZ"] SOframe = float(startFrame +offsetFrame) EOframe = float(endFrame + offsetFrame) #cmds.keyframe(obj,at="translateX",q=True) for attr in keyAbleAttList: try: keyframeList = cmds.keyframe(obj,at=attr,q=True) keyframeListCount = len(keyframeList) except: keyframeListCount = 0 print attr,obj,SOframe,EOframe,keyframeList if keyframeListCount > 0: if startFrame < keyframeList[0]: # print "startFrame" firstFrame = float(keyframeList[0]) startFrameValue = cmds.getAttr('%s.%s'%(obj,attr),t= firstFrame) cmds.setKeyframe(t=(startFrame,startFrame),e=True,at=attr,v=startFrameValue) if endFrame > keyframeList[-1]: # print "endFrame" lastFrame = float(keyframeList[-1]) endFrameValue = cmds.getAttr('%s.%s'%(obj,attr),t = lastFrame) cmds.setKeyframe(t=(endFrame,endFrame),e=True,at=attr,v=endFrameValue) cmds.cutKey(obj,at=attr,t= (startFrame,endFrame)) cmds.pasteKey(obj,at=attr , t= (SOframe,)) newKeyframeList = cmds.keyframe(obj,at=attr,q=True) newLastFrame = newKeyframeList[-1] # print "newKeyframeList,newLastFrame",newKeyframeList,newLastFrame cmds.setInfinity( obj,pri='cycle', poi='cycle' ,at=attr) cmds.keyTangent(obj,t=(newLastFrame,newLastFrame),ott ="step",e=True)
def create_moon(): """ create the moon """ n = 'moon' moon_time_period = 0.0748 cmds.sphere(name=n, axis=[0, 1.0, 0], radius=moon_radius * 0.025) cmds.setAttr(n + 'Shape.castsShadows', 0) cmds.setAttr(n + 'Shape.receiveShadows', 0) cmds.select(n) create_texture(n) cmds.circle(radius=0.25, normalY=1, normalZ=0, name=n + '_orbit') cmds.parent('moon_orbit', 'earth') cmds.select(n, n + '_orbit') cmds.pathAnimation(name=n + '_path', fractionMode=True, follow=True, followAxis='x', upAxis='y', worldUpType='vector', worldUpVector=[0, 1, 0], inverseUp=False, bank=False, startTimeU=1, endTimeU=int(moon_time_period * 10000 / time_period[3] / 2)) cmds.selectKey(clear=True) cmds.selectKey(n + '_path', keyframe=True, time=(1, int(moon_time_period * 10000 / time_period[3] / 2))) cmds.keyTangent(inTangentType='linear', outTangentType='linear') cmds.setInfinity(postInfinite='cycle') animate_rotation('moon', int(moon_time_period * 10000 / time_period[3] / 2))
def pre_post_Linear(): #Create a alarm message!# alarmWindow = maya.window(title="Message") maya.columnLayout(adjustableColumn=False) maya.text(label="Please select at least one camera!") Objects = maya.ls(type=["transform", "camera"], selection=True) if Objects == []: maya.showWindow(alarmWindow) else: for i in Objects: print i maya.setAttr(i + ".tx", lock=False) maya.setAttr(i + ".ty", lock=False) maya.setAttr(i + ".tz", lock=False) maya.setAttr(i + ".rx", lock=False) maya.setAttr(i + ".ry", lock=False) maya.setAttr(i + ".rz", lock=False) maya.setAttr(i + ".sx", lock=False) maya.setAttr(i + ".sy", lock=False) maya.setAttr(i + ".sz", lock=False) maya.keyTangent(inTangentType='spline', outTangentType='spline') maya.setInfinity(poi='linear', pri='linear') maya.setAttr(i + ".tx", lock=True) maya.setAttr(i + ".ty", lock=True) maya.setAttr(i + ".tz", lock=True) maya.setAttr(i + ".rx", lock=True) maya.setAttr(i + ".ry", lock=True) maya.setAttr(i + ".rz", lock=True) maya.setAttr(i + ".sx", lock=True) maya.setAttr(i + ".sy", lock=True) maya.setAttr(i + ".sz", lock=True)
def Bake(): #########################################################################-------------> setting loop but not for legs <------------------######################################################################### global spineCount, fromFrameNum, toFrameNum, loopADD, fpsDesired, stepCheck, stepNum global pelvis, spine, neck1, neck2, head, shoulder, upArm, lowArm, wrist mc.currentUnit(t = str(fpsDesired) + 'fps') mc.select(pelvis, neck1, head, 'CTRL_L'+shoulder, 'CTRL_FK_L'+upArm, 'CTRL_FK_L'+lowArm, 'CTRL_FK_L'+wrist, 'CTRL_R'+shoulder, 'CTRL_FK_R'+upArm, 'CTRL_FK_R'+lowArm, 'CTRL_FK_R'+wrist, 'CTRL_L'+ikFoot, 'CTRL_R'+ikFoot, 'CTRL_L'+ikKnee, 'CTRL_R'+ikKnee, 'CTRL_L'+fRoll, 'CTRL_R'+fRoll, 'CTRL_L'+tRoll, 'CTRL_R'+tRoll) for i in range(spineCount): mc.select(spine + str(i+1), add = True) if(loopADD): mc.setInfinity(poi = 'cycle') if(stepCheck): toFrameNum = fpsDesired / 2 * stepNum + fromFrameNum print toFrameNum mc.playbackOptions(e = True, min = fromFrameNum) mc.playbackOptions(e = True, max = toFrameNum) mc.bakeResults(simulation = True, t = (fromFrameNum,toFrameNum), attribute = 'rotate', disableImplicitControl = True, preserveOutsideKeys = True, removeBakedAttributeFromLayer = False, removeBakedAnimFromLayer = False, bakeOnOverrideLayer = False, minimizeRotation = True) mc.select(deselect = True) mc.select(pelvis) mc.bakeResults(simulation = True, t = (fromFrameNum,toFrameNum), attribute = 'translate', disableImplicitControl = True, preserveOutsideKeys = True, removeBakedAttributeFromLayer = False, removeBakedAnimFromLayer = False, bakeOnOverrideLayer = False, minimizeRotation = True) mc.confirmDialog(title = 'Done!', message = 'Animation successfully generated!')
def apply(self, attr): obj = attr.node() obj_mel = obj.__melobject__() attr_longName = attr.longName() attrMel = attr.__melobject__() if len(self.times) > 0: for time, value in zip(self.times, self.values): cmds.setKeyframe(obj_mel, time=time, attribute=attr_longName, value=value, breakdown=False, # TODO: Approve hierarchy='none', # TODO: Approve controlPoints=False, # TODO: Approve shape=False) # TODO: Approve # set tangents cmds.keyTangent(attrMel, edit=True, wt=int(self.weightedTangent)) # todo: approve int cast for time, inAngle, outAngle, inWeight, outWeight, inTangentType, outTangentType, lock in zip( self.times, self.inAngles, self.outAngles, self.inWeights, self.outWeights, self.inTangentTypes, self.outTangentTypes, self.locks): fn_keyTangent = functools.partial(cmds.keyTangent, attrMel, edit=True, time=(time, time)) fn_keyTangent(inAngle=inAngle, outAngle=outAngle, inWeight=inWeight, outWeight=outWeight) fn_keyTangent(inTangentType=inTangentType,outTangentType=outTangentType) fn_keyTangent(lock=lock) # TODO: Optimise # set infinity if self.preInfinity != "constant": cmds.setInfinity(obj, attribute=attr_longName, preInfinity=self.preInfinity) if self.postInfinity != "constant": cmds.setInfinity(obj, attribute=attr_longName, postInfinity=self.postInfinity) else: attr.set(self.value)
def motionPath(itemList, curvePath, upObject, frontAxis, invertFront, upAxis, invertUp, cycleAttributeName): attributeList = [cycleAttributeName, 'frontTwist', 'upTwist', 'sideTwist'] for attr in attributeList: if not ma.objExists(upObject + '.' + attr): ma.addAttr(upObject, ln=attr, at='double') ma.setAttr(upObject + '.' + attr, e=1, k=1, cb=0) #calculate current sceneUnitMultiplier sceneUnitDict = { 'cm': 1.0, 'mm': 10.0, 'm': 0.01, 'km': 9.999969839999708e-6, 'in': 0.393701, 'ft': 0.0328083, 'yd': 0.0109361, 'mi': 6.213693181818e-6 } sceneUnitMultiplier = sceneUnitDict.get(ma.currentUnit(l=1, q=1)) offset = 1.0 / float(len(itemList)) if len(itemList) > 1 else 0.5 for i in range(0, len(itemList)): #create motionpath path = ma.pathAnimation(itemList[i], c=curvePath, n=itemList[i] + '_' + pathSuffix, fm=1, f=1, fa=frontAxis, ua=upAxis, wut='object', wuo=upObject, iu=invertUp, inverseFront=invertFront, b=0) ma.cutKey(path) driven = path + '.' + 'uValue' #setDrivenKeys ma.setDrivenKeyframe(driven, cd=upObject + '.' + attributeList[0], dv=i * offset, v=0, itt='linear', ott='linear') ma.setDrivenKeyframe(driven, cd=upObject + '.' + attributeList[0], dv=(i * offset) + 1, v=sceneUnitMultiplier, itt='linear', ott='linear') ma.setInfinity(driven, pri='cycle', poi='cycle') for attr in attributeList: if attr != attributeList[0]: ma.connectAttr(upObject + '.' + attr, path + '.' + attr) #cleanup convertDoubleLinear(path)
def returnSetDrivenKeyData(sdkAnimCurve): ''' Returns setDrivenKey command from input sdkAnimCurve returnSetDrivenKeyData('Rt_elbow_jnt_transRot_helper_offsetX') ''' LOG.debug('Working on sdkCurve: %s' % sdkAnimCurve) if mc.objExists(sdkAnimCurve): LOG.debug('sdkCurve exists: %s' % sdkAnimCurve) # Find driver and driven objects driver = mc.listConnections('%s.input' % sdkAnimCurve, scn=True, source=True, destination=False, plugs=True) driven = mc.listConnections('%s.output' % sdkAnimCurve, source=False, destination=True, plugs=True) # Find keyframes and values driverKeys = mc.keyframe(sdkAnimCurve, q=True, floatChange=True) drivenKeys = mc.keyframe(sdkAnimCurve, q=True, valueChange=True) # Get animCurve tangent types itt = mm.eval("keyTangent -query -itt %s ;" % sdkAnimCurve) ott = mm.eval("keyTangent -query -ott %s ;" % sdkAnimCurve) # Get animCurve pre/post infinity mc.selectKey(sdkAnimCurve, add=True, k=True, f=(driverKeys[0], driverKeys[0])) pri = mc.setInfinity(q=True, pri=True)[0] mc.selectKey(clear=True) mc.selectKey(sdkAnimCurve, add=True, k=True, f=(driverKeys[-1], driverKeys[-1])) poi = mc.setInfinity(q=True, poi=True)[0] # Return sdk data sdkDict = {} sdkDict['driver'] = driver[0] sdkDict['driven'] = driven[0] sdkDict['driverKeys'] = driverKeys sdkDict['drivenKeys'] = drivenKeys sdkDict['itt'] = itt sdkDict['ott'] = ott sdkDict['pri'] = pri sdkDict['poi'] = poi return sdkDict
def getRoofLinearCurve( startInput, endInput, minValue, maxValue ): animCurve = cmds.createNode( 'animCurveUU' ) cmds.setKeyframe( f= startInput, v=minValue ) cmds.setKeyframe( f= endInput, v=maxValue ) cmds.keyTangent( itt='linear', ott='linear' ) cmds.selectKey( animCurve ) cmds.setInfinity( poi='cycle', pri='cycle' ) return animCurve
def create_fk_setup(self): """Creates the FK setup.""" cmds.setDrivenKeyframe('%s.translateX' % self.fk_jnts[1], cd='%s.length' % self.fk_jnts[0], dv=1, itt='linear', ott='linear') cmds.setDrivenKeyframe('%s.translateX' % self.fk_jnts[1], cd='%s.length' % self.fk_jnts[0], dv=0, v=0, itt='linear', ott='linear') cmds.setDrivenKeyframe('%s.translateX' % self.fk_jnts[2], cd='%s.length' % self.fk_jnts[1], dv=1, itt='linear', ott='linear') cmds.setDrivenKeyframe('%s.translateX' % self.fk_jnts[2], cd='%s.length' % self.fk_jnts[1], dv=0, v=0, itt='linear', ott='linear') cmds.selectKey('%s_translateX' % self.fk_jnts[1], k=True, f=(1,)) cmds.setInfinity(poi='cycleRelative') cmds.selectKey('%s_translateX' % self.fk_jnts[2], k=True, f=(1,)) cmds.setInfinity(poi='cycleRelative')
def rotationBakingToLayer(i): cmds.bakeResults( listObjects[i], t = (asT, aeT), sm=True, bol=True, at = "rotate" ) #+ cmds.select( listObjects[i], r=True ) if (cycleInfinity): cmds.setInfinity( pri="cycle", poi="cycle" ) else: cmds.setInfinity( pri="constant", poi="constant" ) cmds.delete( aimLoc, zeroLoc ) #+ cmds.container( "BakeResultsContainer", e=True, rc=True ) cmds.animLayer( "BakeResults", e=True, p = layerName ) cmds.rename( "BakeResults", layerComp ) resetRangeTime()
def loop(self, plug=None, offset=False): """Loop this animation. Args: plug (HPlug): plug being driven (for efficiency) offset (bool): cycle with offset """ _plug = plug or self.get_plug() _mode = 'cycle' if not offset else 'cycleRelative' cmds.setInfinity(_plug, preInfinite=_mode, postInfinite=_mode)
def testInfinities(curves): print '\nTESTING INFINITY MODES\n' errors = 0 for inf in [ 'constant', 'linear', 'cycle', 'cycleRelative', 'oscillate' ]: print "### Checking {} infinity mode".format(string.upper(inf)) for curve in curves: cmds.setInfinity(curve, pri=inf, poi=inf) errors += verifyCurve(curve) return errors
def main(): """ Available types: constant, linear, cycle, cycleRelative, oscillate """ if "cycle" in set(cmds.setInfinity(q=True, preInfinite=True)): print("Setting pre- and post-infinite to CONSTANT") cmds.setInfinity(preInfinite="constant", postInfinite="constant") else: print("Setting pre- and post-infinite to CYCLE WITHOUT OFFSET") cmds.setInfinity(preInfinite="cycle", postInfinite="cycle")
def animate_rotation(n, period): """ animates rotation of an object """ cmds.select(n) cmds.currentTime(1) cmds.setKeyframe(n, breakdown=False, attribute="rotateY") cmds.currentTime(period) cmds.setAttr(n + '.rotateY', 360) cmds.setKeyframe(n, breakdown=False, attribute="rotateY") cmds.selectKey(n + '.rotateY') cmds.keyTangent(inTangentType='linear', outTangentType='linear') cmds.setInfinity(postInfinite='cycle')
def readSetDrivenKeyDataFromFile(filePath, lock=False): ''' Reads and reconstructs setDrivenKeyfraomes from json file exported from writeSetDrivenKeyDataToFile() sdkFile = 'Z:/users/tcoleman/code/temp_sdk_data.json' readSetDrivenKeyDataFromFile(sdkFile) ''' fh = open(filePath, 'r') sdkDataDict = json.load(fh) fh.close() # iterate through dict keys for sdkCurve, sdkDict in sdkDataDict.iteritems(): driver = sdkDict['driver'] driven = sdkDict['driven'] driverKeys = sdkDict['driverKeys'] drivenKeys = sdkDict['drivenKeys'] itt = sdkDict['itt'] ott = sdkDict['ott'] pri = sdkDict['pri'] poi = sdkDict['poi'] if mc.objExists(driver) and mc.objExists(driven): i = 0 for driverKey, drivenKey in zip(driverKeys, drivenKeys): # Create setDrivenKeyframes mc.setDrivenKeyframe(driven, cd=driver, dv=driverKey, value=drivenKey) LOG.debug('SetDrivenKeyframe: Driver=%s.%s, Driven=%s.%s' % (driver, driven, driverKey, drivenKey)) # Set keyframe tangents mc.selectKey(sdkCurve, add=True, k=True, f=(driverKey, driverKey)) mc.keyTangent(itt=itt[i], ott=ott[i]) i = i + 1 # Set pre/post infinity mc.selectKey(sdkCurve, add=True, k=True, f=(driverKeys[0], driverKeys[0])) mc.setInfinity(pri=pri) mc.selectKey(clear=True) mc.selectKey(sdkCurve, add=True, k=True, f=(driverKeys[-1], driverKeys[-1])) mc.setInfinity(poi=poi) # Lock setDrivenKeyframes if specified if lock: mc.setAttr('%s.keyTimeValue' % sdkCurve, lock=True) mc.refresh() LOG.info('SetDrivenKeyframe Data read from %s' % filePath)
def copyPaste_main_animation(i): cmds.animLayer(obj.final_layer_name, e = True, at = obj.nonLockedList) cmds.select(obj.temp_obj_node, r = True) if (obj.check_cycle): #print myLog, 'Infinity changed to "Cycle"' cmds.cutKey(time = (obj.min_loop_time, obj.start_time - 1)) cmds.cutKey(time = (obj.end_time + 1, obj.max_loop_time)) cmds.setInfinity(pri = "cycle", poi = "cycle") else: #print myLog, 'Infinity changed to "Constant"' cmds.setInfinity(pri = "constant", poi = "constant") temp_copyKey = cmds.copyKey(obj.temp_obj_node, at = obj.nonLocked_attributes) #cmds.copyKey(obj.temp_obj_node, at = nonLocked_attributes) cmds.pasteKey(obj.list_objects[i], o = "replace", al = obj.final_layer_name, at = obj.nonLocked_attributes)
def createParticleSystem_goal(): # Create a constant sized particle object following a deformed torus shape (using goal) cmds.file(new=True, force=True) # Create a torus, we will use it as goal xrez = 14 yrez = 8 goalTorus = cmds.polyTorus( r=1, sr=0.5, tw=0, sx=xrez, sy=yrez, ax=(0, 1, 0), cuv=1, ch=0)[0] # nParticle creation depends on an optoinVar value, make sure we use the default one cmds.optionVar( sv=("NParticleStyle","Points") ) # Emit a lot of particle, the actual number will be limited to the max particle attribute in the particleShape emitter = cmds.emitter(dx=1, dy=0, dz=0, sp=0.1, pos=(0, 5, 0),rate=2500)[0] particleSystem, particleSystemShape = cmds.nParticle(n="nParticle_test_goal") cmds.setAttr('%s.lfm' % particleSystemShape, 0) # live forever cmds.setAttr('%s.particleRenderType' % particleSystemShape, 7) # Blobby, to see radius cmds.setAttr('%s.maxCount' % particleSystemShape, xrez*yrez) # max count is the number of vertices on the torus cmds.connectDynamic( particleSystemShape, em=emitter) # Create Goal cmds.goal(particleSystem, w=1, utr=0, g=goalTorus); # Create Initial state to we start with the correct amount of particle # NOTE: When using this script in command line, the first frame is not correctly evaluated and the particleShape is empty # This doesn't happens in interactive maya for i in range(1, 10): cmds.currentTime(i) cmds.saveInitialState(particleSystemShape) cmds.currentTime(1) bend, bendHandle = cmds.nonLinear( goalTorus, type="bend", lowBound=-1, highBound=1, curvature=0) cmds.setAttr( "%s.rotateZ" % bendHandle, 90) cmds.setKeyframe( "%s.curvature" % bend, v=0, t=1, inTangentType="flat", outTangentType="flat") cmds.setKeyframe( "%s.curvature" % bend, v=-130, t=12, inTangentType="flat", outTangentType="flat") cmds.setKeyframe( "%s.curvature" % bend, v=130, t=24, inTangentType="flat", outTangentType="flat") # Make the bend animation loop cmds.setInfinity( bend, poi="oscillate", attribute="curvature") return particleSystem, particleSystemShape
def createParticleSystem_goal(): # Create a constant sized particle object following a deformed torus shape (using goal) cmds.file(new=True, force=True) # Create a torus, we will use it as goal xrez = 14 yrez = 8 goalTorus = cmds.polyTorus(r=1, sr=0.5, tw=0, sx=xrez, sy=yrez, ax=(0, 1, 0), cuv=1, ch=0)[0] # nParticle creation depends on an optoinVar value, make sure we use the default one cmds.optionVar(sv=("NParticleStyle", "Points")) # Emit a lot of particle, the actual number will be limited to the max particle attribute in the particleShape emitter = cmds.emitter(dx=1, dy=0, dz=0, sp=0.1, pos=(0, 5, 0), rate=2500)[0] particleSystem, particleSystemShape = cmds.nParticle(n="nParticle_test_goal") cmds.setAttr('%s.lfm' % particleSystemShape, 0) # live forever cmds.setAttr('%s.particleRenderType' % particleSystemShape, 7) # Blobby, to see radius cmds.setAttr('%s.maxCount' % particleSystemShape, xrez * yrez) # max count is the number of vertices on the torus cmds.connectDynamic(particleSystemShape, em=emitter) # Create Goal cmds.goal(particleSystem, w=1, utr=0, g=goalTorus); # Create Initial state to we start with the correct amount of particle # NOTE: When using this script in command line, the first frame is not correctly evaluated and the particleShape is empty # This doesn't happens in interactive maya for i in range(1, 10): cmds.currentTime(i) cmds.saveInitialState(particleSystemShape) cmds.currentTime(1) bend, bendHandle = cmds.nonLinear(goalTorus, type="bend", lowBound=-1, highBound=1, curvature=0) cmds.setAttr("%s.rotateZ" % bendHandle, 90) cmds.setKeyframe("%s.curvature" % bend, v=0, t=1, inTangentType="flat", outTangentType="flat") cmds.setKeyframe("%s.curvature" % bend, v=-130, t=12, inTangentType="flat", outTangentType="flat") cmds.setKeyframe("%s.curvature" % bend, v=130, t=24, inTangentType="flat", outTangentType="flat") # Make the bend animation loop cmds.setInfinity(bend, poi="oscillate", attribute="curvature") return particleSystem, particleSystemShape
def infinity_cycle(): infinities = ["constant", "linear", "cycle"] selected_infinity = cmds.setInfinity(q=1, preInfinite=1, postInfinite=1)[0] cmds.setInfinity(preInfinite=infinities[infinities.index(selected_infinity)-1]) cmds.setInfinity(postInfinite=infinities[infinities.index(selected_infinity)-1]) message = infinities[infinities.index(selected_infinity)-1] status_message = '<div style="color:{2}; font-family:{1}">{0} </div>'\ .format( message , FONT , FONT_COLOR ) cmds.inViewMessage( statusMessage=status_message , fade=True , backColor=BACKGROUND_COLOR , fadeStayTime=600 , fadeInTime=0 , fadeOutTime=200 , position="topCenter" )
def LinearToArc(radius): diameter = radius * 2 origframe = cmds.currentTime(q=True) selection = cmds.ls(selection=True) if (len(selection) == 0): cmds.warning("Select the object with the travel distance") return tZ = "%s.translateZ" % selection[0] tX = "%s.translateX" % selection[0] startZ = cmds.getAttr(tZ, t=0) endZ = cmds.getAttr(tZ, t=30) cmds.cutKey(selection[0], clear=True) newX = cmds.getAttr(tX) newX += (diameter / 2.0) if (startZ != endZ): pivot = cmds.spaceLocator(name="TurnPivot") cmds.animLayer(lt.GetSelectedLayers()[0], edit=True, addSelectedObjects=True) pivotName = pivot[0] distance = endZ - startZ pi = 3.142857142857143 circumf = diameter * pi degrees = (distance / circumf) * 360 cmds.setAttr(tZ, 0) cmds.setAttr(tX, newX) cmds.parentConstraint(pivot, selection[0], mo=True) cmds.setKeyframe(pivot, t=0) cmds.currentTime(30) #animate the arc rY = "%s.rotateZ" % pivotName cmds.setAttr(rY, -degrees) cmds.setKeyframe(pivot, t=30) cmds.currentTime(origframe) #set the curve to linear rotCurve = "%s_rotateZ" % pivotName cmds.selectKey(rotCurve, r=True) cmds.keyTangent(itt="linear", ott="linear") cmds.setInfinity(poi="cycleRelative") cmds.bakeResults(selection[0], t=(0, 30)) if (startZ == endZ): cmds.warning("The object is not traveling")
def offsetCycleSpeedControlNodeSetup(waveDeformer, speedAttr, cycleLength, offset): """ Providing the proper variables, creates a nodal setup to control the speed of an offset animation """ """ Create the nodes """ speedMDNode = createNamedNode("speedMult", "multiplyDivide") offsetNode = createNamedNode("offset", "multiplyDivide") # mc.setAttr ((frameCountDivNode+'.operation'),2) """ create the cycle """ mc.setKeyframe((waveDeformer + ".offset"), time=0, value=0, inTangentType="spline", outTangentType="spline") mc.setKeyframe( (waveDeformer + ".offset"), time=cycleLength, value=(offset * 0.99), inTangentType="linear", outTangentType="linear", ) mc.setInfinity((waveDeformer + ".offset"), pri="linear", poi="linear") """ Connect the nodes """ mc.connectAttr(("time1.outTime"), (speedMDNode + ".input1X")) mc.connectAttr(speedAttr, (speedMDNode + ".input2.input2X")) mc.connectAttr((speedMDNode + ".outputX"), (waveDeformer + "_offset.input"))
def ballCycle(self, part, cycleMethod): at = "rotateZ" cycle = "{}.{}".format(self.robot, part) ball = "{}|{}|ballParent1|ballParent2".format( self.robot, part.replace("cycleF", "f").replace("cycleB", "b")) if cmds.getAttr(cycle): for i, t in enumerate(self.keyTime): cmds.setKeyframe(ball, value=self.keyRotate[i], attribute=at, time=t) cmds.keyTangent(ball, inTangentType="linear", attribute=at, time=(0, 81)) cmds.setInfinity(ball, attribute=at, postInfinite="cycle") else: cmds.cutKey(ball, time=(1, 80), attribute=at) self.setJob(cycle, cycleMethod)
def makeInfinity(): """Set the infinity type""" if checkSelected() is None: cmds.warning("Nothing Selected!") return if checkKeys(checkSelected()) is None: cmds.warning("Object has no keys!") return preInfi, proInfi = queryInfinity() newPre = switchSetting(preInfi) newPro = switchSetting(proInfi) cmds.setInfinity(graphEditor, pri=newPre) cmds.setInfinity(graphEditor, poi=newPro) print "Pre Infinity is now {0}. Post Infinity is now {1}.".format( newPre, newPro), #Display infinity graphEditorAC = "graphEditor1GraphEd" cmds.animCurveEditor(graphEditorAC, e=True, displayInfinities="on")
def connectToMesher(name = 'object'): gp = cmd.ls(sl=True) if len(gp) is not 1: cmd.error('You must select only a "GEO_GP" group node') else: subObjects = cmd.listRelatives(gp , allDescendents = True, noIntermediate= True, type = 'mesh') count = len(subObjects) choice = cmd.shadingNode('choice', asUtility = True, name = '%s_mesher' %name) for i in range(count): cmd.connectAttr('%s.worldMesh[0]' % subObjects[i], '%s.input[%d]' %(choice, i), force = True) cmd.setKeyframe('%s.selector' % choice, time = i+1, value = i) outMesh = cmd.createNode('transform', name = '%s_mesh' % name) outShape = cmd.createNode('mesh', name = '%sShape' % outMesh, parent = outMesh) cmd.connectAttr('%s.output' % choice, '%s.inMesh' % outShape) cmd.selectKey('%s_selector' % choice, k = True) cmd.setInfinity(pri = 'cycle', poi = 'cycle') obs = cmd.listRelatives(gp, type = 'transform') for one in range(1, count): cmd.parent(subObjects[one], obs[0], r = True, s = True) cmd.delete(obs[one]) for one in [outMesh, obs[0]] : cmd.parent(one, world = True) cmd.rename(obs[0], '%s_shapes' % name)
def create_orbit_animation(i): # i'm offsetting the frames by 1500 (i may increase this) so that I can do the first part of the script # this creates orbits and animates them from frame 1500 to 11500 cmds.circle(radius=i * 2 + 5, normalY=1, normalZ=0, name=names[i] + '_orbit') cmds.select(names[i] + '_orbit') cmds.setAttr(names[i] + '_orbit.rotateY', int(i * 90 / 8)) cmds.select(names[i], names[i] + '_orbit') # cmds.pathAnimation(name=names[i]+'_path', fractionMode=True, follow=True, followAxis='x', upAxis='y', worldUpType='vector', worldUpVector=[0, 1, 0], inverseUp=False, bank=False, startTimeU=1500, endTimeU=1500+int(time_period[i]*10000/time_period[3]/2)) cmds.pathAnimation(name=names[i] + '_path', fractionMode=True, follow=False, startTimeU=1500, endTimeU=1500 + int(time_period[i] * 10000 / time_period[3] / 2)) cmds.selectKey(clear=True) cmds.selectKey(names[i] + '_path', keyframe=True, time=(1500, 1500 + int(time_period[i] * 10000 / time_period[3] / 2))) cmds.keyTangent(inTangentType='linear', outTangentType='linear') cmds.setInfinity(postInfinite='cycle')
def offsetCycleSpeedControlNodeSetup(waveDeformer, speedAttr, cycleLength, offset): """ Providing the proper variables, creates a nodal setup to control the speed of an offset animation """ """ Create the nodes """ speedMDNode = createNamedNode('speedMult', 'multiplyDivide') offsetNode = createNamedNode('offset', 'multiplyDivide') #mc.setAttr ((frameCountDivNode+'.operation'),2) """ create the cycle """ mc.setKeyframe((waveDeformer + '.offset'), time=0, value=0, inTangentType='spline', outTangentType='spline') mc.setKeyframe((waveDeformer + '.offset'), time=cycleLength, value=(offset * .99), inTangentType='linear', outTangentType='linear') mc.setInfinity((waveDeformer + '.offset'), pri='linear', poi='linear') """ Connect the nodes """ mc.connectAttr(('time1.outTime'), (speedMDNode + '.input1X')) mc.connectAttr(speedAttr, (speedMDNode + '.input2.input2X')) mc.connectAttr((speedMDNode + '.outputX'), (waveDeformer + '_offset.input'))
def loadAnimData(animFile,lineID,targetNS,frameOffset=0,infinityOverride=None): ''' Apply anim data from anim file @param animFile: Anim file path @type animFile: str @param lineID: Line ID (number) which marks the start of the node.attr anim data @type lineID: int @param targetNS: Target namespace to apply the static data to @type targetNS: str @param frameOffset: Frame offset to apply to the loaded animation data @type frameOffset: int or float @param infinityOverride: Force infinity mode override for loaded animation data. @type infinityOverride: str or None ''' # Initialize Target Attribute attrPath = '' animData = [] # ============= # - Read File - # ============= f = open(animFile,'r') for i, line in enumerate(f): # Skip to relevant line items if i < lineID: continue # Get Anim Data Header if i == lineID: lineItem = line.split() attr = lineItem[2] obj = lineItem[3].split(':')[-1] attrPath = targetNS+':'+obj+'.'+attr # Check Target Attribute if not mc.objExists(attrPath): print('Attribute "'+attrPath+'" does not exist!! Skipping...') return False if not mc.getAttr(attrPath,se=True): print('Attribute "'+attrPath+'" is not settable!! Skipping...') return False # Proceed to Next Line continue # Check Anim Data End if '}' in line: break # Build Anim Data animData.append(line) # =================== # - Apply Anim Data - # =================== # Get Curve Data weighted = bool(animData[1].split()[-1][:-1]) preInf = animData[2].split()[-1][:-1] postInf = animData[3].split()[-1][:-1] # Check Infinity Mode Override if infinityOverride: # Check Valid Infinity Mode if not infinityOverride in ['constant','linear','cycle','cycleRelative','oscillate']: print('Invalid infinity mode "'+infinityOverride+'"! Using stored values...') else: preInf = infinityOverride postInf = infinityOverride # Load Animation Data for data in animData[5:]: # Clean Data Line data = data.replace(';','') # Split Data Items dataItem = data.split() # Apply Time Offset time = float(dataItem[0])+frameOffset value = float(dataItem[1]) ittype = dataItem[2] ottype = dataItem[3] lock = bool(dataItem[4]) bd = bool(int(dataItem[6][0])) mc.setKeyframe(attrPath,t=time,v=value) mc.keyTangent(attrPath,e=True,weightedTangents=weighted) mc.keyTangent(attrPath,e=True,t=(time,time),lock=lock,itt=ittype,ott=ottype) mc.keyframe(attrPath,e=True,t=(time,time),breakdown=bd) if weighted: mc.keyTangent(attrPath,weightLock=1) if len(dataItem) == 11: inAn = float(dataItem[7]) inWt = float(dataItem[8]) otAn = float(dataItem[9]) otWt = float(dataItem[10]) mc.keyTangent( attrPath, e=True, t=(time,time), inAngle=inAn, inWeight=inWt, outAngle=otAn, outWeight=otWt ) # Set Curve Infinity mc.setInfinity(attrPath,pri=preInf,poi=postInf) # Return Result return True
def getAnimData(animCurves=None, showProgress=None): if animCurves is None: getCurves = getAnimCurves(True) animCurves = getCurves[0] getFrom = getCurves[1] else: getFrom = None if not animCurves: return if getFrom is None: keysSel = getTarget("keysSel", animCurves, getFrom, rangeAll=True) else: keysSel = getTarget("keysSel", animCurves, getFrom) if utilMod.isEmpty(keysSel): return if showProgress: utilMod.startProgressBar("aTools - Saving animation data...") objsAttrs = getTarget("", animCurves=animCurves) objects = objsAttrs[0] attributes = objsAttrs[1] animData = {"objects": objects, "animData": []} if showProgress: firstStep = 0 totalSteps = len(animCurves) estimatedTime = None status = "aTools - Saving animation data..." startChrono = None for thisStep, loopCurve in enumerate(animCurves): if showProgress: startChrono = utilMod.chronoStart(startChrono, firstStep, thisStep, totalSteps, estimatedTime, status) if objects[thisStep] is None: continue if len(keysSel[thisStep]) == 0: continue weighted = cmds.keyTangent(loopCurve, query=True, weightedTangents=True) if weighted is not None: weighted = weighted[0] objAttr = "%s.%s" % (objects[thisStep], attributes[thisStep]) infinity = cmds.setInfinity(objAttr, query=True, preInfinite=True, postInfinite=True) animData["animData"].append( {"objAttr": objAttr, "curveData": [weighted, infinity], "keyframeData": [], "tangentData": []} ) time = (keysSel[thisStep][0], keysSel[thisStep][-1]) timeChange = cmds.keyframe(loopCurve, query=True, time=time, timeChange=True) valueChange = cmds.keyframe(loopCurve, query=True, time=time, valueChange=True) breakdowns = cmds.keyframe(loopCurve, query=True, time=time, breakdown=True) inTangentType = cmds.keyTangent(loopCurve, query=True, time=time, inTangentType=True) outTangentType = cmds.keyTangent(loopCurve, query=True, time=time, outTangentType=True) ix = cmds.keyTangent(loopCurve, query=True, time=time, ix=True) iy = cmds.keyTangent(loopCurve, query=True, time=time, iy=True) ox = cmds.keyTangent(loopCurve, query=True, time=time, ox=True) oy = cmds.keyTangent(loopCurve, query=True, time=time, oy=True) lock = cmds.keyTangent(loopCurve, query=True, time=time, lock=True) weightLock = cmds.keyTangent(loopCurve, query=True, time=time, weightLock=True) for n, loopKey in enumerate(keysSel[thisStep]): breakdown = (timeChange[n] in breakdowns) if breakdowns else [] keyframe = [timeChange[n], valueChange[n], breakdown] tangent = [inTangentType[n], outTangentType[n], ix[n], iy[n], ox[n], oy[n], lock[n], weightLock[n]] animData["animData"][-1]["keyframeData"].append(keyframe) animData["animData"][-1]["tangentData"].append(tangent) if showProgress: estimatedTime = utilMod.chronoEnd(startChrono, firstStep, thisStep, totalSteps) if showProgress: utilMod.setProgressBar(endProgress=True) return animData
def applyAnimData(animData, pasteInPlace=True, onlySelectedNodes=False, showProgress=None, status=None): if animData: status = "aTools - Applying animation data..." if not status else status objects = animData["objects"] if not onlySelectedNodes: # print "objects1", objects if len(objects) > 0: objects = [loopObj for loopObj in objects if loopObj is not None and cmds.objExists(loopObj)] # print "objects2", objects if len(objects) > 0: cmds.select(objects) else: objects = getObjsSel() if not objects: cmds.warning("No objects to apply.") return cmds.refresh(suspend=True) if showProgress: utilMod.startProgressBar(status) if pasteInPlace: currKey = cmds.currentTime(query=True) for aData in animData["animData"]: allKeys = [] keys = aData["keyframeData"] for n, key in enumerate(keys): timeChange = aData["keyframeData"][n][0] allKeys.append(timeChange) firstKey = 0 if allKeys: firstKey = min(allKeys) lastKey = max(allKeys) cutIn = currKey + firstKey cuOut = lastKey + firstKey else: cutIn = -49999 cuOut = 50000 objsAttrs = [loopItem["objAttr"] for loopItem in animData["animData"]] existObjsAttrs = [loopObjAttr for loopObjAttr in objsAttrs if cmds.objExists(loopObjAttr)] createDummyKey(existObjsAttrs) cmds.cutKey(existObjsAttrs, time=(cutIn, cuOut), clear=True) if showProgress: totalSteps = 0 firstStep = 0 thisStep = 0 estimatedTime = None startChrono = None for loopObjAttr in existObjsAttrs: index = objsAttrs.index(loopObjAttr) aData = animData["animData"][index] keys = aData["keyframeData"] totalSteps = totalSteps + len(keys) for loopObjAttr in existObjsAttrs: index = objsAttrs.index(loopObjAttr) aData = animData["animData"][index] weighted = aData["curveData"][0] infinity = aData["curveData"][1] keys = aData["keyframeData"] for n, key in enumerate(keys): if showProgress: if cmds.progressBar(G.progBar, query=True, isCancelled=True): refresh() utilMod.setProgressBar(endProgress=True) return startChrono = utilMod.chronoStart( startChrono, firstStep, thisStep, totalSteps, estimatedTime, status ) # read values timeChange = aData["keyframeData"][n][0] valueChange = aData["keyframeData"][n][1] breakdown = aData["keyframeData"][n][2] inTangentType = aData["tangentData"][n][0] outTangentType = aData["tangentData"][n][1] ix = aData["tangentData"][n][2] iy = aData["tangentData"][n][3] ox = aData["tangentData"][n][4] oy = aData["tangentData"][n][5] lock = aData["tangentData"][n][6] weightLock = aData["tangentData"][n][7] if pasteInPlace: timeChange = timeChange - firstKey + currKey time = (timeChange, timeChange) # create key cmds.setKeyframe(loopObjAttr, time=time, value=valueChange, noResolve=True) if n == 0: cmds.keyTangent(loopObjAttr, weightedTangents=weighted) cmds.setInfinity(loopObjAttr, edit=True, preInfinite=infinity[0], postInfinite=infinity[1]) if breakdown: cmds.keyframe(loopObjAttr, edit=True, time=time, breakdown=True) cmds.keyTangent(loopObjAttr, time=time, ix=ix, iy=iy, ox=ox, oy=oy, lock=lock) if weighted: cmds.keyTangent(loopObjAttr, time=time, weightLock=weightLock) cmds.keyTangent(loopObjAttr, time=time, inTangentType=inTangentType, outTangentType=outTangentType) if showProgress: estimatedTime = utilMod.chronoEnd(startChrono, firstStep, thisStep, totalSteps) thisStep += 1 deleteDummyKey(existObjsAttrs) if showProgress: refresh() utilMod.setProgressBar(endProgress=True)
def translationStart(): global asT asT = cmds.playbackOptions(query=True, min=True) # Левая граница анимации global aeT aeT = cmds.playbackOptions(query=True, max=True) # Правая граница анимации resetLoopTime() global listObjects listObjects = cmds.ls(sl=True) # Список трансформов #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| global listFixed listFixed = listObjects[:] for i in range(len(listFixed)): listFixed[i] = listFixed[i].replace("|", "_") #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| global mainLayerName mainLayerName = "OVERLAPPER" # Имя главного слоя if (cmds.objExists(mainLayerName)): print "\n||| OVERLAPPER start |||\n" else: cmds.animLayer(mainLayerName) print "\n||| OVERLAPPER start ||| Layer created |||\n" #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| for i in range(len(listFixed)): # Основной цикл global aimLoc aimLoc = listFixed[i] + "_aim_loc" # Имя аим локатора global tempLoc tempLoc = listFixed[i] + "_temp_loc" # Имя физ локатора global tempPart tempPart = listFixed[i] + "_temp_part" # Имя физ частицы global tempNucl tempNucl = "nucleus1" # Имя физ ноды global partAimLoc partAimLoc = aimLoc + ".translate" # Обращение к позиции аим локатора global partRtype partRtype = tempPart + "Shape.particleRenderType" # Обращение к типу отображения частицы global partRrad partRrad = tempPart + "Shape.radius" # Обращение к размеру частицы global partRsm partRsm = tempPart + "Shape.goalSmoothness" # Обращение к мягкости физики global partRwe partRwe = tempPart + "Shape.goalWeight[0]" # Обращение к весу ноды global partPos partPos = tempPart + ".center" # Обращение к центру частицы global partNucl partNucl = tempNucl + ".timeScale" # Обращение к скейлу времени физ ноды global nuclStart nuclStart = tempNucl + ".startFrame" # Обращение к старту симуляции физ ноды cmds.spaceLocator(n=tempLoc) # Создаём физ локатор cmds.matchTransform(tempLoc, listObjects[i], pos=True) # Перемещаем локатор в пивот объекта objCenter = tempLoc + ".translate" # Обращение к центру объекта objC = cmds.getAttr(objCenter) # Записываем центр объекта locCenter = tempLoc + ".center" # Обращение к центру физ локатора locTr = tempLoc + ".translate" # Обращение к позиции физ локатора cmds.nParticle(p=objC, n=tempPart, c=1) # Создаём частицу в целевой позиции cmds.goal(tempPart, w=goalW, utr=1, g=tempLoc) # Создаём физическую связь cmds.select(tempLoc, r=True) # Выделяем физ локатор cmds.select(listObjects[i], add=True) # Выделяем целевого родителя cmds.parent(r=True) # Создаём иерархию cmds.matchTransform(tempLoc, listObjects[i], pos=True) # Перемещаем локатор в пивот объекта #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| cmds.setAttr(partRtype, pShape) cmds.setAttr(partRrad, pRad) cmds.setAttr(partRsm, goalSmooth) cmds.setAttr(partRwe, goalW) cmds.setAttr(partNucl, timeScale) cmds.setAttr(nuclStart, asT) #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| cmds.duplicate(tempLoc, rr=True, n=aimLoc) # Дублируем локатор cmds.select(aimLoc, r=True) # Выделяем аим локатор cmds.parent(w=True) # Разбираем иерархию cmds.connectAttr(partPos, partAimLoc, f=True) # Привязываем аим локатор к частице global minLoopTime minLoopTime = aeT * -2 global maxLoopTime maxLoopTime = aeT * 2 if (cycle): cmds.setAttr(nuclStart, minLoopTime) cmds.bakeResults( aimLoc, t=(minLoopTime, maxLoopTime), sm=True, at="translate") # Запекание аим локатора для цикла cmds.delete(tempLoc, tempPart, tempNucl) # Удаляем объекты физики setTimeToMin() cmds.select(aimLoc, r=True) # Выделяем аим локатор как родителя cmds.select(listObjects[i], add=True) # Выделяем объект как подчиненного cmds.parentConstraint(mo=True, sr=["x", "y", "z"], w=1) # Создаём позиционный констрейн resetLoopTime() else: cmds.bakeResults( aimLoc, t=(asT, aeT), sm=True, at="translate") # Запекание аим локатора для линейной анимации cmds.delete(tempLoc, tempPart, tempNucl) # Удаляем объекты физики resetLoopTime() cmds.select(aimLoc, r=True) # Выделяем аим локатор как родителя cmds.select(listObjects[i], add=True) # Выделяем объект как подчиненного cmds.parentConstraint(mo=True, sr=["x", "y", "z"], w=1) # Создаём позиционный констрейн #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| layerBase = "translate_" # Имя базы слоя layerName = layerBase + listFixed[i] # Имя слоя layerComp = listFixed[i] + '_layer_{0}'.format( "0") # Имя компонента слоя if (cmds.objExists(layerName)): cmds.bakeResults(listObjects[i], t=(asT, aeT), sm=True, bol=True, at="translate") # Запекаем объект в слой cmds.select(listObjects[i], r=True) cmds.setInfinity(pri="cycle", poi="cycle") cmds.delete(aimLoc) # Удаляем объекты скрипта cmds.container("BakeResultsContainer", e=True, rc=True) # Удаляем контейнер cmds.animLayer( "BakeResults", e=True, p=layerName ) # Переносим слой с анимацией в основной слой объекта cmds.rename("BakeResults", layerComp) # Переименовываем слой resetLoopTime() else: cmds.animLayer( layerName) # Создаём пустой слой для всех оверлапов объекта cmds.animLayer( layerName, e=True, p=mainLayerName) # Переносим базу слоя в главный слой cmds.bakeResults(listObjects[i], t=(asT, aeT), sm=True, bol=True, at="translate") # Запекаем объект в слой cmds.select(listObjects[i], r=True) cmds.setInfinity(pri="cycle", poi="cycle") cmds.delete(aimLoc) # Удаляем объекты скрипта cmds.container("BakeResultsContainer", e=True, rc=True) # Удаляем контейнер cmds.animLayer( "BakeResults", e=True, p=layerName ) # Переносим слой с анимацией в основной слой объекта cmds.rename("BakeResults", layerComp) # Переименовываем слой resetLoopTime() cmds.select(d=True) # Деселект for l in listObjects: cmds.select(l, add=True) print "\n||| OVERLAPPER end |||\n"
def testCurves(): """ Testing suite function that will generate a random animation for a cube and run checks whether the values evaluated by the animation library match Maya's. The test will iterate over all infinity and tangent types as well as interpolation methods for rotation curves""" cmds.file(f=True, new=True) name = 'cube' # generate random animation for the cube cmds.polyCube(name=name) cmds.currentTime(-10) cmds.move(rand.uniform(-100.0, 100.0), rand.uniform(-100.0, 100.0), rand.uniform(-100.0, 100.0), name, a=True) cmds.rotate(rand.uniform(-360.0, 360.0), rand.uniform(-360.0, 360.0), rand.uniform(-360.0, 360.0), name, a=True) cmds.setKeyframe(name) cmds.currentTime(0) cmds.move(rand.uniform(-100.0, 100.0), rand.uniform(-100.0, 100.0), rand.uniform(-100.0, 100.0), name, a=True) cmds.rotate(rand.uniform(-360.0, 360.0), rand.uniform(-360.0, 360.0), rand.uniform(-360.0, 360.0), name, a=True) cmds.setKeyframe(name) cmds.currentTime(10) cmds.move(rand.uniform(-100.0, 100.0), rand.uniform(-100.0, 100.0), rand.uniform(-100.0, 100.0), name, a=True) cmds.rotate(rand.uniform(-360.0, 360.0), rand.uniform(-360.0, 360.0), rand.uniform(-360.0, 360.0), name, a=True) cmds.setKeyframe(name) cmds.currentTime(20) cmds.move(rand.uniform(-100.0, 100.0), rand.uniform(-100.0, 100.0), rand.uniform(-100.0, 100.0), name, a=True) cmds.rotate(rand.uniform(-360.0, 360.0), rand.uniform(-360.0, 360.0), rand.uniform(-360.0, 360.0), name, a=True) cmds.setKeyframe(name) cmds.currentTime(30) cmds.move(rand.uniform(-100.0, 100.0), rand.uniform(-100.0, 100.0), rand.uniform(-100.0, 100.0), name, a=True) cmds.rotate(rand.uniform(-360.0, 360.0), rand.uniform(-360.0, 360.0), rand.uniform(-360.0, 360.0), name, a=True) cmds.setKeyframe(name) curves = [ name + '_translateX', name + '_rotateX', name + '_rotateY', name + '_rotateZ', name + '_visibility' ] rotCurves = [ name + '_rotateX', name + '_rotateY', name + '_rotateZ', ] infinities = ['constant', 'linear', 'cycle', 'cycleRelative', 'oscillate'] tangents = [ 'linear', 'fast', 'slow', 'flat', 'step', 'stepnext', 'fixed', 'clamped', 'plateau', 'spline' ] interpolation = [ 'none', 'euler', 'quaternion', 'quaternionSlerp', 'quaternionSquad' ] errors = 0 print '\nTESTING INFINITY MODES\n' for inf in infinities: print "### Checking infinity mode: {}".format(inf) for curve in curves: cmds.setInfinity(curve, pri=inf, poi=inf) errors += verifyCurve(curve) print '\nTESTING TANGENT TYPES\n' for tan in tangents: print "### Checking tangent: {}".format(tan) cmds.keyTangent(curves, edit=True, time=(':', ), itt=tan, ott=tan) for curve in curves: errors += verifyCurve(curve) print '\nTESTING INTERPOLATION MODES\n' for int in interpolation: print "### Checking interpolation mode: {}".format(int) for curve in rotCurves: cmds.rotationInterpolation(curve, convert=int) if int == "none" or int == "euler": for curve in rotCurves: errors += verifyCurve(curve) else: errors += verifyCurveQuaternion(rotCurves[0], rotCurves[1], rotCurves[2]) print "\nTotal errors: {}".format(errors)
def Importanim(posefile,*args): lst=mc.ls(sl=1) if lst==[]: mc.confirmDialog (title='About' ,message= 'Nothing is selected',ma='center', button=['OK'] ,defaultButton='Yes') else: Currnt_time = mc.currentTime(q = True) imp_name1=lst[0].split(':')[0] imp_name =imp_name1 filename = open(posefile,'r+') lines = filename.readlines() astName='' for line in lines: if 'Asst_name' in line: astName=line.split(' ')[1].strip() elif 'frameRange' in line: range =line.split(' ')[1].strip() filename.close() print 'range '+range offset = Currnt_time - float(range) print offset filename = open(posefile,'r+') print "\nReading Animation Curves\n" endit = 0 line1 = filename.readline() postI='constant';preI='constant' while(line1 != 'End of Anim'): line1 = filename.readline() wrd=line1.split() if line1 [0:5] == "anim " or line1 [0:6]== "static": repl_wrd=wrd[3].replace(astName,imp_name) curAttr=repl_wrd+'.'+wrd[1] node=repl_wrd;attr=wrd[1];endit=0 curAttrLong = (node + "." + attr) if mc.objExists(node): test2 = mc.ls (curAttrLong) if len(test2)>0: if line1 [0:6]== "static": connected = mc.listConnections (curAttrLong,d=0) if (mc.getAttr(curAttrLong,l=1)== 0 and connected == None): setMe = ("mc.setAttr('" + curAttrLong + "'," + wrd[5] + ")") eval(setMe) else: print ("Warning: Attribute is locked - " + curAttr + "\n") elif line1 [0:5] == "anim ": while (endit == 0): line1 = filename.readline() if line1 [2:11]=='weighted ': if line1 [11:12]=='T': weighted = mc.keyTangent(curAttr,e=1,weightedTangents=1) weightState = 1 else: weightState = 0 if line1 [2:7]=='preIn': wrd=line1.split() preI=wrd[1] if line1 [2:8]=='postIn': wrd=line1.split() postI=wrd[1] if line1 [2:6]=='keys': line1 = filename.readline() while (line1 != "}"): try: wrd=line1.split() if not wrd[0] == "}": frameTime = float(wrd[0]) timediff = offset + frameTime time = timediff value = wrd[1] inType = wrd[2] outType = wrd[3] tanLock = wrd[4] weightLock = wrd[5] breakDown = 0 tan1=0 tan2=0 weight1=0 weight2=0 wrd_len=len(wrd) if wrd_len==7: breakDown = wrd[6] else: breakDown = wrd[6] if wrd_len>7: tan1 = wrd[7] weight1=wrd[8] if wrd_len>9: tan2 = wrd[9] weight2=wrd[10] mc.setKeyframe(curAttr,time=time,value=float(value),bd=int(breakDown)) mc.keyTangent(curAttr,lock=bool(tanLock),t=(time,time)) if weightState == 1 : mc.keyTangent(curAttr,t=(time,time),weightLock=int(weightLock)) if inType != "fixed" and outType != "fixed": mc.keyTangent(curAttr,e=1,a=1,t=(time,time),itt=inType,ott=outType) if inType == "fixed" and outType != "fixed": mc.keyTangent(curAttr,e=1,a=1,t=(time,time),inAngle=tan1,inWeight=float(weight1),itt=inType,ott=outType) if inType != "fixed" and outType == "fixed": mc.keyTangent(curAttr,e=1,a=1,t=(time,time),outAngle=tan1,inWeight=float(weight1),itt=inType,ott=outType) if inType == "fixed" and outType == "fixed": mc.keyTangent(curAttr,e=1,a=1,t=(time,time),inAngle=tan1,inWeight=float(weight1),outAngle=tan2,outWeight=float(weight2),itt=inType,ott=outType) line1 = filename.readline() except IndexError: break mc.setInfinity(curAttr,poi=postI,pri=preI) endit=1 else: print 'Warning:'+curAttrLong+ ' Does not exist..Skipping' else: print 'Warning:'+wrd[3]+ ' Does not exist..Skipping' filename.close() mc.select(clear = True) print "\nDone Reading Animation Curves\n"
def linear_cycle(planet): cmds.selectKey( planet, keyframe=True) cmds.keyTangent( inTangentType ='linear', outTangentType='linear' ) cmds.setInfinity ( poi='cycle' )
def loadAnimXML(xmlTree, ctrl, targRes = "texture", obj = None): errorLog = [] ctrlObjColon = ctrl.tag.replace(".", ":") ctrlObj = convertName(ctrlObjColon, targRes) objName = obj if obj else ctrlObj if not mc.objExists(objName): errorLog.append("Object does not exist : %s"%objName) else: for attr in ctrl.getchildren(): ctrlAttrib = attr.tag curAttr = '%s.%s'%(objName, ctrlAttrib) try: mc.getAttr(curAttr, l = 1) except: errorLog.append("Attribute missing : %s"%curAttr) continue animType = attr.attrib['Type'] if animType == 'static': attrValue = attr.attrib['valueStatic'] if attrValue == "True": attrValue = True elif attrValue == "False": attrValue = False else: attrValue = float(attrValue) mc.setAttr(curAttr, attrValue) elif animType == 'anim': attrBd = attr.attrib['breakDown'] attrPreIn = attr.attrib['preInfinity'] attrPosIn = attr.attrib['postInfinity'] attrWeight = attr.attrib['weightedTangents'] breakDn = False for key in attr.getchildren(): keytim = key.tag time = keytim.split('key')[1] inAng = key.attrib['inAngle'] outAng = key.attrib['outAngle'] inTan = key.attrib['inTangent'] outTan = key.attrib['outTangent'] inWei = float(key.attrib['inWeight']) outWei = float(key.attrib['outWeight']) tanLok = key.attrib['tanLock'] weiLok = key.attrib['weightLock'] keyVal = key.attrib['valueChange'] breakDn = False bd_itm = str(attrBd) if bd_itm != 'None': breakDn = True mc.setKeyframe(curAttr, time = time, value = float(keyVal), bd = breakDn) mc.keyTangent(curAttr, lock = bool(tanLok), t = (time,time)) if attrWeight == 'True': try: mc.keyTangent(curAttr, t = (time,time), weightLock = weiLok) except: pass if inTan != "fixed" and outTan != "fixed": mc.keyTangent(curAttr, e = 1, a = 1, t = (time,time), itt = inTan, ott = outTan) if inTan == "fixed" and outTan != "fixed": mc.keyTangent(curAttr, e = 1, a = 1, t = (time,time), inAngle = inAng, inWeight = inWei, itt = inTan, ott = outTan) if inTan != "fixed" and outTan == "fixed": mc.keyTangent(curAttr, e = 1, a = 1, t = (time,time), outAngle = outAng, inWeight = inWei, itt = inTan, ott = outTan) if inTan == "fixed" and outTan == "fixed": mc.keyTangent(curAttr, e = 1, a = 1, t = (time,time), inAngle = inAng, inWeight = inWei, outAngle = outAng, outWeight = outWei, itt = inTan, ott = outTan) mc.setInfinity(curAttr, poi = attrPosIn, pri = attrPreIn) return errorLog
def toObjs(self, **args): replace = args.get('replace', False) inverse = args.get('inverse', False) startFrame = args.get('startFrame', self.getRange()[0]) objsToFilter = args.get('objsToFilter', None) matchObjName = args.get('matchObjName', None) mirror = args.get('mirror', None) overrideNamespace = args.get('overrideNamespace', None) tanType = [ 'clamped', 'fast', 'flat', 'linear', 'plateau', 'slow', 'spline', 'step next', 'fixed', 'stepped' ] # default: keyTangent listCmdsTanType = [] listCmdsTanType.append('fixed') listCmdsTanType.append('linear') listCmdsTanType.append('flat') listCmdsTanType.append('step') listCmdsTanType.append('slow') listCmdsTanType.append('fast') listCmdsTanType.append('spline') listCmdsTanType.append('clamped') listCmdsTanType.append('plateau') listCmdsTanType.append('stepnext') listCmdsTanType.append('auto') dictNodeTanType = {} dictNodeTanType['1'] = listCmdsTanType[0] #'Fixed' dictNodeTanType['2'] = listCmdsTanType[1] #'Linear' dictNodeTanType['3'] = listCmdsTanType[2] #'Flat' dictNodeTanType['5'] = listCmdsTanType[3] #'Step' dictNodeTanType['6'] = listCmdsTanType[4] #'Slow' dictNodeTanType['7'] = listCmdsTanType[5] #'Fast' dictNodeTanType['9'] = listCmdsTanType[6] #'Spline' dictNodeTanType['10'] = listCmdsTanType[7] #'Clamped' dictNodeTanType['16'] = listCmdsTanType[8] #'Plateau' dictNodeTanType['17'] = listCmdsTanType[9] #'StepNext' dictNodeTanType['18'] = listCmdsTanType[10] #'Auto' #RANGE curentRange = self.getRange() middleRange = (curentRange[0] + curentRange[1]) / 2 offsetFrame = startFrame - curentRange[0] #MATCH OBJ objs = self.getObjs() matchObjs = objs if not (matchObjName == None): matchObjs = self.getMatchObjs(matchObjName) for i in range(len(self.objsAttrs)): outObj, outAttr = self.objsAttrs[i].split('.') objsAttr = outObj + '.' + outAttr if (matchObjName): iTmp = objs.index(outObj) outObj = matchObjs[iTmp] objsAttr = outObj + '.' + outAttr if not (overrideNamespace == None): if (':' in objsAttr): if (overrideNamespace == ''): objsAttr = objsAttr.split(':')[1] else: objsAttr = overrideNamespace + ':' + objsAttr.split( ':')[1] else: if not (overrideNamespace == ''): objsAttr = overrideNamespace + ':' + objsAttr if not (mc.objExists(objsAttr)): print('animCurve - toObjs - ATTR DOESNT EXISTS - {}'.format( objsAttr)) continue if (objsToFilter) and not (outObj in objsToFilter): continue if (replace): inConnections = mc.listConnections(objsAttr, s=True, d=False) if ('animCurve' in mc.nodeType(inConnections[0])): mc.delete(inConnections[0]) inverseMult = 1 if (inverse): inverseMult = -1 for j in range(len(self.values[i])): time = (self.times[i][j] - middleRange) * inverseMult + middleRange + offsetFrame value = self.values[i][j] #if( '.rotate' in objsAttr ):value = math.degrees(self.values[i][j]) if (mirror) and ('.translateX' in objsAttr): value = self.values[i][j] * -1 if (mirror) and ('.translateY' in objsAttr): value = self.values[i][j] * -1 if (mirror) and ('.translateZ' in objsAttr): value = self.values[i][j] * -1 if (mirror) and ('TranslateX' in objsAttr): value = self.values[i][j] * -1 if (mirror) and ('TranslateY' in objsAttr): value = self.values[i][j] * -1 if (mirror) and ('TranslateZ' in objsAttr): value = self.values[i][j] * -1 mc.setKeyframe(objsAttr, t=time, v=value) if not (self.breakdown == []): mc.setKeyframe(objsAttr, e=True, t=time, v=value, bd=self.breakdown[i][j]) if not (self.tInType == []): mc.keyTangent( objsAttr, t=(time, time), itt=dictNodeTanType['{}'.format(self.tInType[i][j])], ott=dictNodeTanType['{}'.format(self.tOutType[i][j])], ix=self.tInX[i][j], iy=self.tInY[i][j], ox=self.tOutX[i][j], oy=self.tOutY[i][j], l=self.tLock[i][j]) #, wl = self.tWeightLock[i][j] ) if not (self.others == []): try: mc.setInfinity(objsAttr, pri=self.others[i][2], poi=self.others[i][3]) except: print('animCurve - toObjs - setInfinity issue - {}'.format( objsAttr))
def rigRf(): # rig foot rolling cmds.setDrivenKeyframe("footRoll_" + RFCHAIN[2] + ".rotateX", currentDriver=RFCTRL + "." + ATTRLS[1][0]) cmds.setDrivenKeyframe("footRoll_" + RFCHAIN[3] + ".rotateX", currentDriver=RFCTRL + "." + ATTRLS[1][0]) cmds.setDrivenKeyframe("footRoll_" + RFCHAIN[4] + ".rotateX", currentDriver=RFCTRL + "." + ATTRLS[1][0]) # rig heel pivot cmds.setDrivenKeyframe(RFCHAIN[2] + ".rotateX", currentDriver=RFCTRL + "." + ATTRLS[2][0], ott="spline", itt="spline") cmds.setDrivenKeyframe(RFCHAIN[2] + ".rotateX", currentDriver=RFCTRL + "." + ATTRLS[2][0], ott="spline", itt="spline", driverValue=1, value=1) cmds.selectKey(clear=True) cmds.selectKey(RFCHAIN[2] + "_rotateX", keyframe=True, float=(0, 0)) cmds.setInfinity(poi="linear", pri="linear") # rig heel slide cmds.setDrivenKeyframe(RFCHAIN[2] + ".rotateY", currentDriver=RFCTRL + "." + ATTRLS[3][0], ott="spline", itt="spline") cmds.setDrivenKeyframe(RFCHAIN[2] + ".rotateY", currentDriver=RFCTRL + "." + ATTRLS[3][0], ott="spline", itt="spline", driverValue=1, value=1) cmds.selectKey(clear=True) cmds.selectKey(RFCHAIN[2] + "_rotateY", keyframe=True, float=(0, 0)) cmds.setInfinity(poi="linear", pri="linear") # rig toe pivot cmds.setDrivenKeyframe(RFCHAIN[3] + ".rotateX", currentDriver=RFCTRL + "." + ATTRLS[4][0], ott="spline", itt="spline") cmds.setDrivenKeyframe(RFCHAIN[3] + ".rotateX", currentDriver=RFCTRL + "." + ATTRLS[4][0], ott="spline", itt="spline", driverValue=1, value=1) cmds.selectKey(clear=True) cmds.selectKey(RFCHAIN[3] + "_rotateX", keyframe=True, float=(0, 0)) cmds.setInfinity(poi="linear", pri="linear") # rig toe slide cmds.setDrivenKeyframe(RFCHAIN[3] + ".rotateY", currentDriver=RFCTRL + "." + ATTRLS[5][0], ott="spline", itt="spline") cmds.setDrivenKeyframe(RFCHAIN[3] + ".rotateY", currentDriver=RFCTRL + "." + ATTRLS[5][0], ott="spline", itt="spline", driverValue=1, value=1) cmds.selectKey(clear=True) cmds.selectKey(RFCHAIN[3] + "_rotateY", keyframe=True, float=(0, 0)) cmds.setInfinity(poi="linear", pri="linear") # rig ball pivot cmds.setDrivenKeyframe(RFCHAIN[4] + ".rotateX", currentDriver=RFCTRL + "." + ATTRLS[6][0], ott="spline", itt="spline") cmds.setDrivenKeyframe(RFCHAIN[4] + ".rotateX", currentDriver=RFCTRL + "." + ATTRLS[6][0], ott="spline", itt="spline", driverValue=1, value=1) cmds.selectKey(clear=True) cmds.selectKey(RFCHAIN[4] + "_rotateX", keyframe=True, float=(0, 0)) cmds.setInfinity(poi="linear", pri="linear") # rig ball slide cmds.setDrivenKeyframe(RFCHAIN[4] + ".rotateY", currentDriver=RFCTRL + "." + ATTRLS[7][0], ott="spline", itt="spline") cmds.setDrivenKeyframe(RFCHAIN[4] + ".rotateY", currentDriver=RFCTRL + "." + ATTRLS[7][0], ott="spline", itt="spline", driverValue=1, value=1) cmds.selectKey(clear=True) cmds.selectKey(RFCHAIN[4] + "_rotateY", keyframe=True, float=(0, 0)) cmds.setInfinity(poi="linear", pri="linear") # rig banking cmds.setDrivenKeyframe(RFCHAIN[0] + ".rotateZ", currentDriver=RFCTRL + "." + ATTRLS[8][0]) cmds.setDrivenKeyframe(RFCHAIN[1] + ".rotateZ", currentDriver=RFCTRL + "." + ATTRLS[8][0])
def rotationStart(): global asT asT = cmds.playbackOptions(query=True, min=True) # Левая граница анимации global aeT aeT = cmds.playbackOptions(query=True, max=True) # Правая граница анимации resetLoopTime() global listObjects listObjects = cmds.ls(sl=True) # Список трансформов #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| global listFixed listFixed = listObjects[:] for i in range(len(listFixed)): listFixed[i] = listFixed[i].replace("|", "_") #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| global mainLayerName mainLayerName = "OVERLAPPER" # Имя главного слоя if (cmds.objExists(mainLayerName)): print "\n||| OVERLAPPER start |||\n" else: cmds.animLayer(mainLayerName) print "\n||| OVERLAPPER start ||| Layer created |||\n" #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| for i in range(len(listFixed)): # Основной цикл if (i + 1 != len(listFixed)): global zeroLoc zeroLoc = listFixed[i] + "_base_loc" # Имя нулевого локатора global aimLoc aimLoc = listFixed[i] + "_aim_loc" # Имя следящего локатора global tempLoc tempLoc = listFixed[i] + "_temp_loc" # Имя физического локатора global tempAimLoc tempAimLoc = listFixed[i] + "_tempAim_loc" # Имя целевого локатора global tempPart tempPart = listFixed[i] + "_temp_part" # Имя частицы global tempNucl tempNucl = "nucleus1" # Имя физической ноды global partRtype partRtype = tempPart + "Shape.particleRenderType" # Обращение к типу отображения частицы global partRrad partRrad = tempPart + "Shape.radius" # Обращение к размеру частицы global partRsm partRsm = tempPart + "Shape.goalSmoothness" # Обращение к мягкости физики global partRwe partRwe = tempPart + "Shape.goalWeight[0]" # Обращение к весу ноды global partNucl partNucl = tempNucl + ".timeScale" # Обращение к скейлу времени физ ноды global nuclStart nuclStart = tempNucl + ".startFrame" # Обращение к старту симуляции физ ноды #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| cmds.spaceLocator(n=zeroLoc) # Создаём нулевой локатор cmds.spaceLocator(n=aimLoc) # Создаём следящий локатор cmds.spaceLocator(n=tempLoc) # Создаём физический локатор cmds.matchTransform( zeroLoc, listObjects[i], pos=True ) # Перемещаем нулевой локатор в пивот главного объекта cmds.matchTransform( tempLoc, listObjects[i + 1], pos=True ) # Перемещаем физический локатор в пивот целевого объекта cmds.select(tempLoc, r=True) # Выделяем физический локатор cmds.duplicate( n=tempAimLoc) # Дублируем его и создаём целевой локатор cmds.select(listObjects[0], r=True) # Выделяем главный объект cmds.select(zeroLoc, add=True) # Выделяем нулевой локатор cmds.parentConstraint(mo=True, w=1) # Создаём пэрент констрейн cmds.select(aimLoc, r=True) # Выделяем следящий локатор cmds.select(zeroLoc, add=True) # Выделяем нулевой локатор cmds.parent(r=True) # Создаём иерархию cmds.select(listObjects[1], r=True) # Выделяем целевой объект cmds.select(tempLoc, add=True) # Выделяем физический локатор cmds.parentConstraint(mo=True, sr=["x", "y", "z"], w=1) # Создаём позиционный констрейн aimPosName = tempLoc + ".translate" # Обращение к позиции физического локатора partCenter = tempPart + ".center" # Обращение к центру частицы aimLocPos = tempAimLoc + ".translate" # Обращение к позиции целевого локатора aimPos = cmds.getAttr( aimPosName) # Берём позицию физического локатора cmds.nParticle(p=aimPos, n=tempPart, c=1) # Создаём частицу в целевой позиции cmds.goal( tempPart, w=0.5, utr=1, g=tempLoc) # Создаём физическую связь с физическим локатором cmds.connectAttr(partCenter, aimLocPos, f=True) # Привязываем целевой локатор к частице cmds.select(tempAimLoc, r=True) # Выделяем целевой локатор cmds.select(aimLoc, add=True) # Выделяем следящий локатор cmds.aimConstraint(w=1, aim=(0, 1, 0), u=(0, 1, 0), wut="vector", wu=(0, 1, 0), sk="y") # Создаём аим констреён по двум осям #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| cmds.setAttr(partRtype, pShape) cmds.setAttr(partRrad, pRad) cmds.setAttr(partRsm, goalSmoothRot) cmds.setAttr(partRwe, goalWRot) cmds.setAttr(partNucl, timeScaleRot) cmds.setAttr(nuclStart, asT) #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| global minLoopTime minLoopTime = aeT * -2 global maxLoopTime maxLoopTime = aeT * 2 if (cycleRot): cmds.setAttr(nuclStart, minLoopTime) cmds.bakeResults( zeroLoc, t=(asT, aeT), sm=True, at=("translate", "rotate")) # Запекание нулевого локатора для цикла cmds.bakeResults( aimLoc, t=(minLoopTime, maxLoopTime), sm=True, at="rotate") # Запекание аим локатора для цикла cmds.delete(tempAimLoc, tempLoc, tempPart, tempNucl) # Удаляем объекты физики zeroParent = zeroLoc + "_parentConstraint1" cmds.delete(zeroParent) setTimeToMin() cmds.select(aimLoc, r=True) # Выделяем аим локатор как родителя cmds.select(listObjects[i], add=True) # Выделяем объект как подчиненного cmds.parentConstraint(mo=True, st=["x", "y", "z"], w=1) # Создаём ротэйт констрейн resetLoopTime() else: cmds.bakeResults( zeroLoc, t=(asT, aeT), sm=True, at=("translate", "rotate" )) # Запекание нулевого локатора для линейной анимации cmds.bakeResults( aimLoc, t=(asT, aeT), sm=True, at="rotate" ) # Запекание аим локатора для линейной анимации cmds.delete(tempAimLoc, tempLoc, tempPart, tempNucl) # Удаляем объекты физики zeroParent = zeroLoc + "_parentConstraint1" cmds.delete(zeroParent) resetLoopTime() cmds.select(aimLoc, r=True) # Выделяем аим локатор как родителя cmds.select(listObjects[i], add=True) # Выделяем объект как подчиненного cmds.parentConstraint(mo=True, st=["x", "y", "z"], w=1) # Создаём ротэйт констрейн #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| layerBase = "rotate_" # Имя базы слоя layerName = layerBase + listFixed[i] # Имя слоя layerComp = listFixed[i] + '_layer_{0}'.format( "0") # Имя компонента слоя if (cmds.objExists(layerName)): cmds.bakeResults(listObjects[i], t=(asT, aeT), sm=True, bol=True, at="rotate") # Запекаем объект в слой cmds.select(listObjects[i], r=True) cmds.setInfinity(pri="cycle", poi="cycle") cmds.delete(aimLoc, zeroLoc) # Удаляем объекты скрипта cmds.container("BakeResultsContainer", e=True, rc=True) # Удаляем контейнер cmds.animLayer( "BakeResults", e=True, p=layerName ) # Переносим слой с анимацией в основной слой объекта cmds.rename("BakeResults", layerComp) # Переименовываем слой resetLoopTime() else: cmds.animLayer( layerName ) # Создаём пустой слой для всех оверлапов объекта cmds.animLayer( layerName, e=True, p=mainLayerName) # Переносим базу слоя в главный слой cmds.bakeResults(listObjects[i], t=(asT, aeT), sm=True, bol=True, at="rotate") # Запекаем объект в слой cmds.select(listObjects[i], r=True) cmds.setInfinity(pri="cycle", poi="cycle") cmds.delete(aimLoc, zeroLoc) # Удаляем объекты скрипта cmds.container("BakeResultsContainer", e=True, rc=True) # Удаляем контейнер cmds.animLayer( "BakeResults", e=True, p=layerName ) # Переносим слой с анимацией в основной слой объекта cmds.rename("BakeResults", layerComp) # Переименовываем слой resetLoopTime() cmds.select(d=True) # Деселект for l in listObjects: cmds.select(l, add=True) print "\n||| OVERLAPPER end |||\n"
def build( startJoint=None, middleJoint=None, endJoint=None, extraJoint=None, side=None, name=None, twistJointCount=None, isLeg=False, cleanUp=True ): if not startJoint or not middleJoint or not endJoint or not extraJoint or not side or not name or not twistJointCount: print 'limb: Error! Must supply all arguments.' return # first reconstruct the joints for our system joint1 = cmds.createNode( 'joint', n=side+"_"+name+'_start_drvJnt' ) joint2 = cmds.createNode( 'joint', n=side+"_"+name+'_middle_drvJnt' ) joint3 = cmds.createNode( 'joint', n=side+"_"+name+'_end_jnt' ) joint4 = cmds.createNode( 'joint', n=side+"_"+name+'_extra_drvJnt' ) common.align( node=joint1, target=startJoint ) cmds.setAttr('%s.jointOrient' % joint1, 0,0,0) common.align( node=joint2, target=middleJoint ) cmds.setAttr('%s.jointOrient' % joint2, 0,0,0) common.align( node=joint3, target=endJoint ) cmds.setAttr('%s.jointOrient' % joint3, 0,0,0) common.align( node=joint4, target=extraJoint ) cmds.setAttr('%s.jointOrient' % joint4, 0,0,0) cmds.parent( joint4, joint3 ) cmds.parent( joint3, joint2 ) cmds.parent( joint2, joint1 ) if isLeg: cmds.setAttr( joint2+'.preferredAngle', 0, 0, -90 ) else: cmds.setAttr( joint2+'.preferredAngle', 0, -90, 0 ) cmds.makeIdentity( joint1, apply=True ) # auto color controls using the 'side' argument myColor = 'green' if side == 'lf': myColor = 'blue' elif side == 'rt': myColor = 'red' # creation of the start control (shoulder or hips offset) limbStartCtrl = controls.Control( side=side, rigPart='limb', function=name+'_start', nodeType='ctrl', size=0.4, color=myColor, aimAxis='y' ) limbStartCtrl.pinCtrl() common.align( node=limbStartCtrl.control, target=joint1, orient=False ) limbStartCtrlGrp = common.insertGroup( node=limbStartCtrl.control ) # creation of the end control (hand or foot) limbEndCtrl = controls.Control( side=side, rigPart='limb', function=name+'_end', nodeType='ctrl', size=0.4 + 0.2*isLeg, color=myColor, aimAxis='x' ) limbEndCtrl.cubeCtrl() common.align( node=limbEndCtrl.control, target=joint3, orient=False ) limbEndCtrlGrp = common.insertGroup( node=limbEndCtrl.control ) # entire system group systemGrp = cmds.group( empty=True, n=side+'_'+name+'_xform_grp') cmds.parent( joint1, systemGrp ) # # NON ROLLs CREATION # startNonRoll = nonRoll.build(joint=joint1, name = name+'Start') cmds.parent(startNonRoll['main_grp'], systemGrp) upNonRoll = nonRoll.build(joint=joint2, name = name+'Mid') cmds.parent(upNonRoll['main_grp'], joint1) lowNonRoll = nonRoll.build(joint=joint3, name = name+'End') cmds.parent(lowNonRoll['main_grp'], joint2) ''' if isLeg: if side == 'lf': aimUp = (0, 1, 0) elif side == 'rt': aimUp = (0, -1, 0) cmds.aimConstraint( lowNonRollEnd, lowNonRollLoc, aimVector=aimVec, upVector=aimUp, worldUpType='objectrotation', worldUpVector=aimWorldUp, worldUpObject=joint3 ) if isLeg: common.align( node=lowNonRollLocGrp, target=joint3 ) else: common.align( node=lowNonRollLocGrp, target=joint2 ) common.align( node=lowNonRollLocGrp, target=joint3, orient=False ) cmds.setAttr( lowNonRollGrp+'.v', 0 ) cmds.setAttr( lowTwistIkHandle+'.poleVector', 0, 0, 0 ) if not isLeg: if side == 'rt': cmds.setAttr( lowNonRollLocGrp+'.r', 0, 0, 0 ) else: if side == 'lf': cmds.setAttr( lowNonRollLocGrp+'.r', 90, 0, 0 ) ''' # create stretch setup ssStartPos = cmds.group( empty=True, n=side+'_'+name+'_stretchStart_loc') ssEndPos = cmds.group( empty=True, n=side+'_'+name+'_stretchEnd_loc') common.align( node=ssStartPos, target=joint1, orient=False ) cmds.pointConstraint( limbEndCtrl.control, ssEndPos ) ssGrp = cmds.group( ssStartPos, ssEndPos, n=side+'_'+name+'_stretchLocs_grp') cmds.parent( ssGrp, systemGrp ) # sums the two separate distances to create the stretch originalUpLimbTx = cmds.getAttr( joint2+'.translateX' ) originalLowLimbTx = cmds.getAttr( joint3+'.translateX' ) limbSize = common.getDistance( joint1, joint2 ) + common.getDistance( joint2, joint3 ) dbNode = cmds.createNode( 'distanceBetween', n=side+'_'+name+'_stretch_distance') cmds.connectAttr( ssStartPos+'.t', dbNode+'.point1' ) cmds.connectAttr( ssEndPos+'.t', dbNode+'.point2' ) # creates a keyframe-based stretch factor ssKeyUp = cmds.createNode( 'animCurveUL', n=side+'_'+name+'_upStretch_key' ) cmds.connectAttr( dbNode+'.distance', ssKeyUp+'.input' ) cmds.connectAttr( ssKeyUp+'.output', joint2+'.translateX' ) ssKeyLow = cmds.createNode( 'animCurveUL', n=side+'_'+name+'_LowStretch_key' ) cmds.connectAttr( dbNode+'.distance', ssKeyLow+'.input' ) cmds.connectAttr( ssKeyLow+'.output', joint3+'.translateX' ) # set driven key values cmds.setDrivenKeyframe( joint2+'.translateX', currentDriver=dbNode+'.distance', driverValue=limbSize, value=originalUpLimbTx, itt='linear', ott='linear' ) cmds.setDrivenKeyframe( joint2+'.translateX', currentDriver=dbNode+'.distance', driverValue=limbSize*2, value=originalUpLimbTx*2, itt='linear', ott='spline' ) cmds.setInfinity( joint2+'.translateX', poi='linear' ) cmds.setDrivenKeyframe( joint3+'.translateX', currentDriver=dbNode+'.distance', driverValue=limbSize, value=originalLowLimbTx, itt='linear', ott='linear' ) cmds.setDrivenKeyframe( joint3+'.translateX', currentDriver=dbNode+'.distance', driverValue=limbSize*2, value=originalLowLimbTx*2, itt='linear', ott='spline' ) cmds.setInfinity( joint3+'.translateX', poi='linear' ) # create the twistSections twistUp = 'z' if isLeg: twistUp = 'y' doNotInvertUp = False if isLeg and side == 'rt': doNotInvertUp = True upTwistDict = twistSection.build( side=side, name='up_'+name, startPos=joint1, endPos=joint2, jointCount=twistJointCount, worldUpVector=twistUp, worldUpObject=startNonRoll['nonRoll'], twistReader=startNonRoll['info'], doNotInvertUp=doNotInvertUp ) lowTwistDict = twistSection.build( side=side, name='low_'+name, startPos=joint2, endPos=joint3, jointCount=twistJointCount, worldUpVector=twistUp, worldUpObject=upNonRoll['nonRoll'], twistReader=lowNonRoll['info'], doNotInvertUp=doNotInvertUp ) # create the joints that will skin the twistSection curves # to get that nice bendy effect for free # start with the shoulder/hips joint mdNode = None crvJntA1 = cmds.createNode( 'joint', n=side+'_'+name+'_up_curve_1_jnt') crvJntA2 = cmds.createNode( 'joint', n=side+'_'+name+'_up_curve_2_jnt') cmds.parent( crvJntA2, crvJntA1 ) cmds.parent( crvJntA1, systemGrp ) cmds.addAttr( limbEndCtrl.control, ln='start_tangent', min=0, dv=0.1, k=True ) if side == 'lf': cmds.connectAttr( limbEndCtrl.control+'.start_tangent', crvJntA2+'.translateX' ) else: mdNode = cmds.createNode( 'multiplyDivide', n=side+'_'+name+'_pma' ) cmds.setAttr( mdNode+'.input2', -1, -1, -1 ) cmds.connectAttr( limbEndCtrl.control+'.start_tangent', mdNode+'.input1X' ) cmds.connectAttr( mdNode+'.outputX', crvJntA2+'.translateX' ) common.align( node=crvJntA1, target=joint1 ) # elbow/knee joints avgGrp = cmds.group( empty=True, n=side+'_'+name+'_avg_grp' ) crvJntB1 = cmds.createNode( 'joint', n=side+'_'+name+'_cn_curve_1_avgJnt') crvJntB2 = cmds.createNode( 'joint', n=side+'_'+name+'_cn_curve_2_avgJnt') cmds.parent( crvJntB2, crvJntB1 ) cmds.parent( crvJntB1, avgGrp ) cmds.setAttr( crvJntB1+'.rotateY', 180 ) # flip crvJntC1 = cmds.createNode( 'joint', n=side+'_'+name+'_cn_curve_3_avgJnt') crvJntC2 = cmds.createNode( 'joint', n=side+'_'+name+'_cn_curve_4_avgJnt') cmds.parent( crvJntC2, crvJntC1 ) cmds.parent( crvJntC1, avgGrp ) cmds.addAttr( limbEndCtrl.control, ln='bend_tangent', min=0, dv=0.85, k=True ) if mdNode: cmds.connectAttr( limbEndCtrl.control+'.bend_tangent', mdNode+'.input1Y' ) cmds.connectAttr( mdNode+'.outputY', crvJntB2+'.translateX' ) cmds.connectAttr( mdNode+'.outputY', crvJntC2+'.translateX' ) else: cmds.connectAttr( limbEndCtrl.control+'.bend_tangent', crvJntB2+'.translateX' ) cmds.connectAttr( limbEndCtrl.control+'.bend_tangent', crvJntC2+'.translateX' ) cmds.pointConstraint( joint2, avgGrp ) cons = cmds.orientConstraint( joint1, joint2, avgGrp )[0] cmds.setAttr( cons+'.interpType', 0 ) # noFlip # wrist/foot joints crvJntD1 = cmds.createNode( 'joint', n=side+'_'+name+'_low_curve_1_jnt') crvJntD2 = cmds.createNode( 'joint', n=side+'_'+name+'_low_curve_2_jnt') crvJntD1Grp = cmds.group( crvJntD1, n=crvJntD1+'_grp' ) cmds.parent( crvJntD2, crvJntD1 ) cmds.parent( crvJntD1Grp, systemGrp ) cmds.setAttr( crvJntD1+'.rotateY', 180 ) # flip common.align( node=crvJntD1Grp, target=joint3 ) cmds.parentConstraint( limbEndCtrl.control, crvJntD1Grp, mo=True ) cmds.addAttr( limbEndCtrl.control, ln='end_tangent', min=0, dv=0.2, k=True ) if mdNode: cmds.connectAttr( limbEndCtrl.control+'.end_tangent', mdNode+'.input1Z' ) cmds.connectAttr( mdNode+'.outputZ', crvJntD2+'.translateX' ) else: cmds.connectAttr( limbEndCtrl.control+'.end_tangent', crvJntD2+'.translateX' ) # extra jnt follow orientation of endCtrl cmds.orientConstraint( limbEndCtrl.control, joint3, mo=True ) # constrains entire limb to startCtrl cmds.orientConstraint( limbStartCtrl.control, startNonRoll['main_grp'], mo=True ) # skin the twistSection curves to these joints skinClsUp = cmds.skinCluster( crvJntA1, crvJntA2, crvJntB1, crvJntB2, upTwistDict['twist_curve'] )[0] cmds.skinPercent( skinClsUp, upTwistDict['twist_curve']+'.cv[0]', transformValue=[(crvJntA1, 1)]) cmds.skinPercent( skinClsUp, upTwistDict['twist_curve']+'.cv[1]', transformValue=[(crvJntA2, 1)]) cmds.skinPercent( skinClsUp, upTwistDict['twist_curve']+'.cv[2]', transformValue=[(crvJntB2, 1)]) cmds.skinPercent( skinClsUp, upTwistDict['twist_curve']+'.cv[3]', transformValue=[(crvJntB1, 1)]) skinClsLow = cmds.skinCluster( crvJntC1, crvJntC2, crvJntD1, crvJntD2, lowTwistDict['twist_curve'] )[0] cmds.skinPercent( skinClsLow, lowTwistDict['twist_curve']+'.cv[0]', transformValue=[(crvJntC1, 1)]) cmds.skinPercent( skinClsLow, lowTwistDict['twist_curve']+'.cv[1]', transformValue=[(crvJntC2, 1)]) cmds.skinPercent( skinClsLow, lowTwistDict['twist_curve']+'.cv[2]', transformValue=[(crvJntD2, 1)]) cmds.skinPercent( skinClsLow, lowTwistDict['twist_curve']+'.cv[3]', transformValue=[(crvJntD1, 1)]) # # IKHANDLE CREATION # ikHandle, effector = cmds.ikHandle( startJoint=joint1, endEffector=joint3, solver='ikRPsolver', n=side+'_'+name+'_ikHandle' ) pvCtrl = controls.Control( side=side, rigPart=name, function='poleVec', nodeType="ctrl", size=0.3, color=myColor, aimAxis="twistAxis" ) pvCtrl.cubeCtrl() # snaps the poleVector control to the middle joint common.align( node=pvCtrl.control, target=joint2, orient=False ) pvCtrlGrp = common.insertGroup( node=pvCtrl.control ) cmds.poleVectorConstraint( pvCtrl.control, ikHandle ) cmds.setAttr( pvCtrl.control+'.tz', -5 ) # invert poleVector position if it's a leg if isLeg: cmds.setAttr( pvCtrl.control+'.tz', 5 ) # auto follow foot control cmds.pointConstraint( limbEndCtrl.control, pvCtrlGrp, mo=True ) cmds.orientConstraint( limbEndCtrl.control, pvCtrlGrp, skip=['x'], mo=True ) # ikHandle follow endCtrl cmds.pointConstraint( limbEndCtrl.control, ikHandle ) # extra attributes to endCtrl cmds.addAttr( limbEndCtrl.control, ln='twist', k=True ) cmds.connectAttr( limbEndCtrl.control+'.twist', ikHandle+'.twist' ) ## ik lock # add attribute to control if ( cmds.attributeQuery( 'lock', node=limbEndCtrl.control, exists=True ) ) == True: print( 'Attribute %s already exists on %s.' % ( 'lock', limbEndCtrl ) ) else: cmds.addAttr( limbEndCtrl.control, longName='lock', attributeType='float', keyable=True, min=0.0, max=1.0, dv=0.0 ) # create distance locs startLoc = cmds.spaceLocator( name=side + '_' + name + '_start_loc' )[0] middleLoc = cmds.spaceLocator( name=side + '_' + name + '_middle_loc' )[0] endLoc = cmds.spaceLocator( name=side + '_' + name + '_end_loc' )[0] upDist = cmds.createNode( 'distanceDimShape' ) lowDist = cmds.createNode( 'distanceDimShape' ) cmds.connectAttr( cmds.listRelatives(startLoc)[0] + '.worldPosition[0]', upDist + '.startPoint' ) cmds.connectAttr( cmds.listRelatives(middleLoc)[0] + '.worldPosition[0]', upDist + '.endPoint' ) cmds.connectAttr( cmds.listRelatives(middleLoc)[0] + '.worldPosition[0]', lowDist + '.startPoint' ) cmds.connectAttr( cmds.listRelatives(endLoc)[0] + '.worldPosition[0]', lowDist + '.endPoint' ) cmds.pointConstraint( limbStartCtrl.control, startLoc ) cmds.pointConstraint( pvCtrl.control, middleLoc ) cmds.pointConstraint( limbEndCtrl.control, endLoc ) # create and connect blend utilities bl2aLockUp = cmds.shadingNode( 'blendTwoAttr', asUtility=True ) bl2aLockUp = cmds.rename(bl2aLockUp, common.getName(node=bl2aLockUp, side=side, rigPart=name, function='lock_up', nodeType='bl2a')) bl2aLockLow = cmds.shadingNode( 'blendTwoAttr', asUtility=True ) bl2aLockLow = cmds.rename(bl2aLockLow, common.getName(node=bl2aLockLow, side=side, rigPart=name, function='lock_low', nodeType='bl2a')) cmds.connectAttr( ssKeyUp+'.output', bl2aLockUp + '.input[0]' ) cmds.connectAttr( upDist + '.distance', bl2aLockUp + '.input[1]' ) cmds.connectAttr( limbEndCtrl.control + '.lock', bl2aLockUp + '.attributesBlender' ) cmds.connectAttr( bl2aLockUp + '.output', joint2 + '.translateX', force = True ) cmds.connectAttr( ssKeyLow+'.output', bl2aLockLow + '.input[0]' ) cmds.connectAttr( lowDist + '.distance', bl2aLockLow + '.input[1]' ) cmds.connectAttr( limbEndCtrl.control + '.lock', bl2aLockLow + '.attributesBlender' ) cmds.connectAttr( bl2aLockLow + '.output', joint3 + '.translateX', force = True ) # get distance nodes transforms and rename upDist = cmds.listRelatives( upDist, parent=True )[0] upDist = cmds.rename( upDist, common.getName(node=upDist, side=side, rigPart=name, function='up', nodeType='distance') ) lowDist = cmds.listRelatives( lowDist, parent=True )[0] lowDist = cmds.rename( lowDist, common.getName(node=lowDist, side=side, rigPart=name, function='low', nodeType='distance') ) # negate distance output if side = rt if side == 'rt': mdivLockRev = cmds.shadingNode( 'multiplyDivide', asUtility=True) mdivLockRev = cmds.rename( mdivLockRev, common.getName(node=mdivLockRev, side=side, rigPart=name, function='lock_dist_rev', nodeType='mdiv') ) cmds.setAttr( mdivLockRev + '.input2', -1, -1, -1 ) cmds.connectAttr( upDist + '.distance', mdivLockRev + '.input1X', force=True ) cmds.connectAttr( mdivLockRev + '.outputX', bl2aLockUp + '.input[1]', force=True ) cmds.connectAttr( lowDist + '.distance', mdivLockRev + '.input1Y', force=True ) cmds.connectAttr( mdivLockRev + '.outputY', bl2aLockLow + '.input[1]', force=True ) # group lock utilities lockGrp = cmds.group( startLoc, middleLoc, endLoc, upDist, lowDist, name=side + '_' + name + '_lock_grp' ) # # CLEAN UP # # hide objects if cleanUp: cmds.setAttr( ikHandle+'.v', 0 ) cmds.parent( ikHandle, limbEndCtrl.control ) cmds.setAttr( lowTwistDict['twist_curve']+'.inheritsTransform', 0 ) cmds.setAttr( upTwistDict['twist_curve']+'.inheritsTransform', 0 ) for mp in cmds.listRelatives( lowTwistDict['motionPaths_group'] ) + cmds.listRelatives( upTwistDict['motionPaths_group'] ): cmds.setAttr( mp+'.inheritsTransform', 0 ) if isLeg: cmds.setAttr( limbStartCtrl.control+'.v', 0 ) # hides first control of the leg # parenting everything under one group cmds.parent( limbStartCtrlGrp, limbEndCtrlGrp, pvCtrlGrp, systemGrp ) # ctrls hideGrp = cmds.group( joint1, startNonRoll['main_grp'], ssGrp, lockGrp, crvJntA1, crvJntD1Grp, lowTwistDict['twist_curve'], upTwistDict['twist_curve'], avgGrp, lowTwistDict['motionPaths_group'], upTwistDict['motionPaths_group'], upTwistDict['joints_group'], lowTwistDict['joints_group'], name=systemGrp.replace('_grp', '_hide_grp'), parent=systemGrp ) cmds.setAttr( hideGrp+'.v', 0 ) cmds.parentConstraint( limbStartCtrl.control, hideGrp, mo=True ) # lock and hide attributes cmds.setAttr( limbStartCtrl.control + '.sx', lock=True, keyable=False, channelBox=False ) cmds.setAttr( limbStartCtrl.control + '.sy', lock=True, keyable=False, channelBox=False ) cmds.setAttr( limbStartCtrl.control + '.sz', lock=True, keyable=False, channelBox=False ) cmds.setAttr( limbStartCtrl.control + '.visibility', lock=True, keyable=False, channelBox=False ) cmds.setAttr( pvCtrl.control + '.rx', lock=True, keyable=False, channelBox=False ) cmds.setAttr( pvCtrl.control + '.ry', lock=True, keyable=False, channelBox=False ) cmds.setAttr( pvCtrl.control + '.rz', lock=True, keyable=False, channelBox=False ) cmds.setAttr( pvCtrl.control + '.sx', lock=True, keyable=False, channelBox=False ) cmds.setAttr( pvCtrl.control + '.sy', lock=True, keyable=False, channelBox=False ) cmds.setAttr( pvCtrl.control + '.sz', lock=True, keyable=False, channelBox=False ) cmds.setAttr( pvCtrl.control + '.visibility', lock=True, keyable=False, channelBox=False ) cmds.setAttr( limbEndCtrl.control + '.visibility', lock=True, keyable=False, channelBox=False ) cmds.setAttr( limbEndCtrl.control + '.sx', lock=True, keyable=False, channelBox=False ) cmds.setAttr( limbEndCtrl.control + '.sy', lock=True, keyable=False, channelBox=False ) cmds.setAttr( limbEndCtrl.control + '.sz', lock=True, keyable=False, channelBox=False ) returnDic = { 'ikHandle' : ikHandle, 'jointList' : [ joint1, joint2, joint3, joint4 ], 'poleVector' : pvCtrl, 'poleVector_grp' : pvCtrlGrp, 'start_ctrl' : limbStartCtrl.control, 'end_ctrl' : limbEndCtrl.control, 'end_ctrl_grp' : limbEndCtrlGrp, 'skinJoints_group' : [ upTwistDict['joints_group'], lowTwistDict['joints_group'] ], 'limbSystem_grp' : systemGrp, 'stretch_positions': [ ssStartPos, ssEndPos ] } return returnDic