def convertConnectionAsAnimCurve( node, attr ): separateParentConnection( node, attr ) cons = cmds.listConnections( node+'.'+attr, s=1, d=0, p=1, c=1 ) if not cons: return None attrType = cmds.attributeQuery( attr, node= node, attributeType=1 ) if attrType == 'doubleLinear': animCurveType= 'animCurveUL' elif attrType == 'doubleAngle': animCurveType = 'animCurveUA' else: animCurveType = 'animCurveUU' animCurve = cmds.createNode( animCurveType ) cmds.connectAttr( cons[1], animCurve+'.input' ) cmds.connectAttr( animCurve+'.output', cons[0], f=1 ) cmds.setKeyframe( animCurve, f= -1, v= -1 ) cmds.setKeyframe( animCurve, f=-.5, v=-.5 ) cmds.setKeyframe( animCurve, f= 0, v= 0 ) cmds.setKeyframe( animCurve, f= .5, v= .5 ) cmds.setKeyframe( animCurve, f= 1, v= 1 ) cmds.setAttr( animCurve + ".postInfinity", 1 ) cmds.setAttr( animCurve + ".preInfinity", 1 ) cmds.selectKey( animCurve ) cmds.keyTangent( itt='spline', ott='spline' ) return animCurve
def setSmartKey(time=None, animCurves=None, select=True, insert=True, replace=True, addTo=False): if not time: time = animMod.getTimelineTime() getFrom = "timeline" if not animCurves: getCurves = animMod.getAnimCurves() animCurves = getCurves[0] getFrom = getCurves[1] if animCurves and getFrom != "timeline": cmds.setKeyframe(animCurves, time=time, insert=insert) if select: cmds.selectKey(animCurves, replace=replace, addTo=addTo, time=time) else: objects = animMod.getObjsSel() if objects: channelboxSelObjs = animMod.channelBoxSel() if channelboxSelObjs: #objsAttrs = ["%s.%s"%(loopObj, loopChannelboxSel) for loopObj in objects for loopChannelboxSel in channelboxSel] #key selected attributes in the channelbox for n, loopObjAttr in enumerate(channelboxSelObjs): prevKey = cmds.findKeyframe(loopObjAttr, time=(time,time), which="previous") tangentType = cmds.keyTangent(loopObjAttr, query=True, outTangentType=True, time=(prevKey,prevKey)) if not tangentType: #if there is no key tangentType = cmds.keyTangent(query=True, g=True, outTangentType=True) inTangentType = tangentType[0].replace("fixed", "auto").replace("step", "auto") outTangentType = tangentType[0].replace("fixed", "auto") cmds.setKeyframe(loopObjAttr, time=time, insert=False, shape=False, inTangentType=inTangentType, outTangentType=outTangentType) continue inTangentType = tangentType[0].replace("fixed", "auto").replace("step", "auto") outTangentType = tangentType[0].replace("fixed", "auto") cmds.setKeyframe(loopObjAttr, time=time, insert=insert, shape=False, inTangentType=inTangentType, outTangentType=outTangentType) else: #allChannels = animMod.getAllChannels(objects) #objAttrs = ["%s.%s"%(objects[n], loopAttr) for n, loopObj in enumerate(allChannels) for loopAttr in loopObj] prevKeys = [cmds.findKeyframe(obj, time=(time,time), which="previous") for obj in objects] tangentTypes = [cmds.keyTangent(obj, query=True, outTangentType=True, time=(prevKeys[n],prevKeys[n])) for n, obj in enumerate(objects)] #prevKeys = [cmds.findKeyframe(obj, time=(time,time), which="previous") for obj in objAttrs] #tangentTypes = [cmds.keyTangent(obj, query=True, outTangentType=True, time=(prevKeys[n],prevKeys[n])) for n, obj in enumerate(objAttrs)] #key all atributes cmds.setKeyframe(objects, time=time, insert=insert, shape=False) #cmds.setKeyframe(objAttrs, time=time, insert=insert, shape=False) if insert: #will force create key if there is no key for n, loopTangent in enumerate(tangentTypes): if not loopTangent: cmds.setKeyframe(objects[n], time=time, insert=False, shape=False)
def keyFullRotation (pObjectName, pStartTime, pEndTime, pTargetAttribute): cmds.cutKey (pObjectName, time = (pStartTime, pEndTime), attribute=pTargetAttribute) cmds.setKeyframe (pObjectName, time = pStartTime, attribute=pTargetAttribute, value=0) cmds.setKeyframe (pObjectName, time = pEndTime, attribute=pTargetAttribute, value=360) cmds.selectKey (pObjectName, time = (pStartTime, pEndTime), attribute=pTargetAttribute, keyframe=True) cmds.keyTangent (inTangentType='linear', outTangentType='linear')
def smoothAnimCurves(objects, isLoop): """Set all keys on provided objects to auto tangent, optionally matching in and out tangents.""" if isinstance(objects, types.StringTypes): objects = [objects] if not isinstance(objects, types.ListType) and not isinstance(objects, types.TupleType): sys.stderr.write("ERROR: Unable to smooth animation curves on object %s. Argument must be a string, list, or tuple of objects or attribute names.\n") return False for object in objects: cmds.selectKey(object) cmds.keyTangent(itt="spline", ott="spline") if isLoop: matchInOutTangents(object) return True
def keyFullRotation(pObjectName, pStartTime, pEndTime, pTangentAttribute): # Enable key on selected objects cmds.cutKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTangentAttribute) # Set keyframes cmds.setKeyframe(pObjectName, time=pStartTime, attribute=pTangentAttribute, value=0) cmds.setKeyframe(pObjectName, time=pEndTime, attribute=pTangentAttribute, value=360) # Set linear tangent cmds.selectKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTangentAttribute) cmds.keyTangent(inTangentType='linear', outTangentType='linear')
def keyFullRotation(pObjectName, pStartTime, pEndTime, pTargetAttribute): #The keys are deleted cmds.cutKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute) #Define new keys for the animations (rotation in the axis Y). cmds.setKeyframe(pObjectName, time= pStartTime, attribute=pTargetAttribute, value = 0) cmds.setKeyframe(pObjectName,time=pEndTime, attribute=pTargetAttribute, value = 360) #In order to mantain a constant rate of rotation with linear tangents cmds.selectKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute) cmds.keyTangent( inTangentType='linear', outTangentType='linear')
def smoothKeys(weight=0.5): crvs = cmds.keyframe(q=True, name=True, sl=True) if crvs: for crv in crvs: frames = cmds.keyframe(crv, q=True, sl=True) size = len(frames) if size > 2: # first key val # x = cmds.keyframe(crvs, q=True, vc=True, time=(frames[0], frames[0]))[0] i = 0 for frame in frames: if frame == frames[0] or frame == frames[size - 1]: pass else: # previous itter x = cmds.keyframe(crv, q=True, vc=True, time=(frames[i - 1], frames[i - 1]))[0] # this itter y = cmds.keyframe(crv, q=True, vc=True, time=(frame, frame))[0] # next itter z = cmds.keyframe(crv, q=True, vc=True, time=(frames[i + 1], frames[i + 1]))[0] # frame range between keys frameRange = int((frames[i - 1] - frames[i + 1]) * -1) # value range between keys, account for negative valueRange = x - z # force positive if valueRange < 0: valueRange = valueRange * -1 # find increments inc = valueRange / frameRange # how many increments to add mlt = int((frames[i - 1] - frame) * -1) # add up increments keyPos = inc * mlt # final value to add/subtract from previous key # operation depends on x relative to z value if x < z: # print 'above' val = x + keyPos # print y, ' current' # print val, ' actual' val = y - val # print val, ' dif' val = val * weight # print val, ' multip' val = y - val # print val, ' final' else: # print 'below' val = x - keyPos # print y, ' current' # print val, ' actual' val = y - val # print val, ' dif' val = val * weight # print val, ' multip' val = y - val # print val, ' final' cmds.keyframe(crv, vc=val, time=(frame, frame)) cmds.keyTangent(crv, edit=True, itt='auto', ott='auto', time=(frame, frame)) i = i + 1
def set_tangents(self, type_): """Set all tangents on this curve. Args: type_ (str): tangent type """ cmds.keyTangent(self, inTangentType=type_, outTangentType=type_)
def apply_1f(scu, lv=1, ihi=1): # Apply geo = cmds.getAttr('{}.origGeo'.format(scu)) attr = apply(scu, 'standard', lv=lv, ihi=ihi) # Key cf = cmds.currentTime(q=1) cmds.setKeyframe(geo, at=attr, time=cf, itt='linear', ott='linear', v=1) cmds.setKeyframe(geo, at=attr, time=cf - 1, itt='linear', ott='linear', v=0) cmds.setKeyframe(geo, at=attr, time=cf + 1, itt='linear', ott='linear', v=0) cmds.keyTangent(geo, at=attr, itt='linear', ott='linear') sys.stdout.write( "Applied '{}' as a keyable attribute and keyed 0-1-0 around current frame" .format(scu)) return attr
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 initTurn(obj, *arg): hdriTurnGrp = '|LookdevSetup:GRP_LookdevSetup|LookdevSetup:GRP_LIGHTING|LookdevSetup:GRP_HDRI' if obj == 'turn_locator': delete_turn_loc() cmds.spaceLocator(name=obj) cmds.setAttr(obj + '.localScaleX', 50) cmds.setAttr(obj + '.localScaleY', 50) cmds.setAttr(obj + '.localScaleZ', 50) elif obj == hdriTurnGrp: if cmds.objExists(hdriTurnGrp) == False: # Check if GRP exists cmds.warning( 'LookdevSetup:GRP_HDRI was not found, please take a nerf gun and shoot Clement because he f****d up' ) import commonTools commonTools.areeeeett() return cmds.setKeyframe(obj, at='rotateY', t=1, v=0) cmds.setKeyframe(obj, at='rotateY', t=101, v=360) cmds.selectKey(clear=True) cmds.selectKey(obj, time=(1, 101), at='rotateY') cmds.keyTangent(itt='linear', ott='linear') cmds.currentTime(1) cmds.playbackOptions(min=1, max=100) cmds.selectKey(clear=True) cmds.select(clear=True) #set render settings end frame cmds.setAttr('defaultRenderGlobals.endFrame', 100)
def main(): names = cmds.keyframe(q=True, n=True) for n in names: frames = cmds.keyframe(n, q=True, sl=True) values = cmds.keyframe(n, q=True, vc=True, sl=True) countup = 0 for i in range(len(values)): isLast = False if len(values) - 1 == countup: x1, y1, x2, y2 = frames[i], values[i], frames[i - 1], values[i - 1] isLast = True else: x1, y1, x2, y2 = frames[i], values[i], frames[i + 1], values[i + 1] c_tan = rad_deg(math.atan((y2 - y1) / (x2 - x1)), True) if not isLast: cmds.keyTangent(n, e=True, a=True, t=(frames[i], frames[i]), oa=c_tan) else: cmds.keyTangent(n, e=True, a=True, t=(frames[i], frames[i]), ia=c_tan, oa=c_tan) countup += 1
def getControlPoints(crv='', p0=[1.0, 0.0], p3=[10.0, 10.0]): # could use multiplier to adjust length of existing weights after key is inserted mltp = 0.3333333333333333 # multiplier to solve adjacent side, p[1] x coor, 33.333333333333% # gap between keys gap = p3[0] - p0[0] # print gap, ' gap' # p1 outA = cmds.keyTangent(crv, q=True, time=(p0[0], p0[0]), outAngle=True)[0] # print outA, ' p1 hyp angle' adj = gap * mltp # tangent coor in x # print adj, ' p1 adj length' opo = math.tan(math.radians(outA)) * (adj) # print opo, ' p1 opo height' p1 = [p0[0] + adj, p0[1] + opo] # print p1 # p2 outA = cmds.keyTangent(crv, q=True, time=(p3[0], p3[0]), inAngle=True)[0] # print outA, ' p2 hyp angle' adj = gap * mltp # tangent coor in x # print adj, ' p2 adj length' opo = math.tan(math.radians(outA)) * adj # print opo, ' p2 opo height' p2 = [p3[0] - adj, p3[1] - opo] # adjusting, may need fixing for +/- angles # print p2 # resort lists [x,x,x,x] [y,y,y,y] return [p0[0], p1[0], p2[0], p3[0]], [p0[1], p1[1], p2[1], p3[1]]
def hold(): curves = mc.keyframe(q=1, sl=1, name=1) for curve in curves: index = mc.keyframe(curve, q=1, sl=1, iv=1) firstValue = mc.keyframe(curve, q=1, sl=1, vc=1)[0] mc.keyframe(curve, vc=firstValue, index=(index[0], index[-1])) mc.keyTangent(itt='flat', ott='flat')
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 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 setAngle(angle): cards = cmds.ls('card*', transforms=True) for card in cards: # out angle of the first tangent cmds.keyTangent(card + '.pathValue', index=[(1, 1)], oa=angle) # in angle of the second tangent cmds.keyTangent(card + '.pathValue', index=[(2, 2)], ia=angle)
def copy_anim_curve(anim_curve, prev_idx, frames, values, tangent_infos): """ Duplicate keyframes and tangent weights for a single animation curve """ new_frames, new_values = get_new_curve_data(frames, values) for i in range(len(new_frames)): mc.setKeyframe(anim_curve, time=new_frames[i], value=new_values[i]) # for tangent values first copy the out value first_tangent_info = tangent_infos[0] last_tangent_info = tangent_infos[-1] mc.keyTangent(anim_curve, index=(prev_idx, prev_idx), inAngle=last_tangent_info[0], outAngle=first_tangent_info[1], inWeight=last_tangent_info[2], outWeight=first_tangent_info[3], inTangentType=last_tangent_info[4], outTangentType=first_tangent_info[5]) for i in range(1, len(tangent_infos)): tangent_info = tangent_infos[i] mc.keyTangent(anim_curve, index=(prev_idx + i, prev_idx + i), inAngle=tangent_info[0], outAngle=tangent_info[1], inWeight=tangent_info[2], outWeight=tangent_info[3], inTangentType=tangent_info[4], outTangentType=tangent_info[5]) return new_frames, new_values
def onNewScene(userdata): # set units cmds.optionVar(sv=("workingUnitTimeDefault", "pal")) # 25 fps cmds.optionVar(sv=("workingUnitAngularDefault", "deg")) # degree cmds.optionVar(sv=("workingUnitLinearDefault", "cm")) # cm cmds.keyTangent(e=True, g=True, weightedTangents=True) # weighted tangents cmds.optionVar(iv=("playbackMinDefault", 1001)) # playback start cmds.optionVar(iv=("playbackMaxDefault", 1125)) # playback end cmds.optionVar(iv=("playbackMinRangeDefault", 1001)) # playback range start cmds.optionVar(iv=("playbackMaxRangeDefault", 1250)) # playback range end maya.cmds.currentUnit(linear='cm', angle='deg', time='pal') cmds.playbackOptions(ast=1001, min=1001, max=1125, aet=1250) # set color management mayaVersion = cmds.about(version=True) if mayaVersion == "2022": cmds.colorManagementPrefs(e=True, configFilePath=ts_config) cmds.colorManagementPrefs(e=True, renderingSpaceName=ts_renderingSpace) cmds.colorManagementPrefs(e=True, displayName=ts_display) cmds.colorManagementPrefs(e=True, viewName=ts_view) else: cmds.colorManagementPrefs(e=True, renderingSpaceName=ts_renderingSpace) cmds.colorManagementPrefs(e=True, viewTransformName=ts_viewTransform) print( '\n---------------------------------\nTom Sporer defaults set\n---------------------------------' )
def gpsTurntable(): # Set up framerange startTime = cmds.playbackOptions ( query = True, minTime = True ) endTime = cmds.playbackOptions ( query = True, maxTime = True ) # Get current selection selectionList = cmds.ls (selection = True) if selectionList: # Get centre of selection bbox = cmds.exactWorldBoundingBox() centre_x = (bbox[0] + bbox[3]) / 2.0 centre_y = (bbox[1] + bbox[4]) / 2.0 centre_z = (bbox[2] + bbox[5]) / 2.0 # Create new group new_grp = cmds.group(empty=True, name="Turntable_%s_grp#" %selectionList[0]) cmds.move(centre_x, centre_y, centre_z, new_grp) # Create Turntable camera new_cam = cmds.camera() cmds.select (selectionList, r = True) cmds.viewFit (new_cam[0], allObjects = False) cmds.parent (new_cam[0], new_grp) cmds.setKeyframe (new_grp, time = startTime-1, attribute = "rotateY", value=0) cmds.setKeyframe (new_grp, time = endTime, attribute = "rotateY", value=360) cmds.selectKey (new_grp, time = (startTime-1, endTime), attribute = "rotateY", keyframe = True) cmds.keyTangent (inTangentType = "linear", outTangentType = "linear") cmds.rename ("Turntable_%s_cam#" %selectionList[0]) else: cmds.warning("Please select one or more objects!")
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 setAngle(self, angle): cubes = cmds.ls('card*', transforms=True) for card in cubes: # out angle of the first tangent cmds.keyTangent(card, index=[(1, 1)], oa=angle) # in angle of the second tangent cmds.keyTangent(card, index=[(2, 2)], ia=angle)
def process_curve(self): # self.get_data() power = cmds.floatSlider(power_sl, value=True, query=True) # Reverses the input range, as soon it is not possible to do in gui for curve in self.curves: if cmds.checkBox(b_spline, v=True, q=True): filtered_values = bspline(self.value_data[curve], n=len(self.value_data[curve]), degree=int(power)) else: filtered_values = self.gaussian(self.value_data[curve], power) filtered_values = [float(v) for v in filtered_values] filtered_values = self.set_blend(self.value_data[curve], filtered_values) if cmds.checkBox(cbx, v=True, q=True): filtered_values = self.normalize_data(filtered_values) filtered_values = self.restore_normalized_data( self.value_data[curve], filtered_values) attr = cmds.listConnections(curve, p=True)[0] self.add_keys(attr, self.frame_data[curve], filtered_values, None) cmds.keyTangent(itt='auto', ott='auto')
def menu(): ui = cmds.menuBarLayout() cmds.menu(l='UI', hm=True) cmds.menuItem(l='Close', c=removeUI) cmds.menu(l='Evaluation') prefsRadioMenu(pref='evaluation') # cmds.menu(l='Playblast') # cmds.menuItem(l='Temp Settings', c=playblastTemp) cmds.menu(l='Tangents') prefsRadioMenu(pref='default tangent', ) cmds.menuItem(l='', divider=True) cmds.menuItem(l='Weighted tangents', checkBox=(cmds.keyTangent(q=True, g=True, wt=True)), c=lambda x: cmds.keyTangent(e=True, g=True, wt=x)) cmds.menu(l='Time') prefsRadioMenu(pref='playback speed', ) prefsRadioMenu(pref='frames per second', ) # cmds.menuItem(l='', divider=True) # keepFrames = cmds.menuItem(l='Keep keys at current frames', checkBox=False) # cmds.menu(l='World') # prefsRadioMenu(pref='up axis', ) cmds.setParent('..') return ui
def keyFullRotation(pObjectName, pStartTime, pEndTime, pTargetAttribute): """Create a keyframe rotation animation for the specified object. Rotates the pObjectName around an axis pTargetAttribute, between pStartTime and pEndTime. """ # Remove any animations within the timerange cmds.cutKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute) # Sets the target values for start and end points cmds.setKeyframe(pObjectName, time=pStartTime, attribute=pTargetAttribute, value=0) cmds.setKeyframe(pObjectName, time=pEndTime, attribute=pTargetAttribute, value=360) # Ensure the rotation has linear velocity cmds.selectKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute, keyframe=True) cmds.keyTangent(inTangentType='linear', outTangentType='linear')
def test_getattrtime(): """getAttr(time=)""" transform = cmdx.createNode("transform") for time, value in ((1, 1.0), (10, 10.0)): cmds.setKeyframe(str(transform), time=[time], attribute="translateY", value=value) cmds.keyTangent(str(transform), edit=True, time=(1, 10), attribute="translateY", outTangentType="linear") # These floating point values can differ ever so slightly assert_almost_equals(transform["ty"].read(time=1), 1.0, places=5) assert_almost_equals(transform["ty"].read(time=5), 5.0, places=5) assert_almost_equals(transform["ty"].read(time=10), 10.0, places=5) # From the current context (Maya 2018 and above) if hasattr(om.MDGContext, "makeCurrent"): with cmdx.DGContext(1.0): assert_almost_equals(transform["ty"].read(), 1.0, places=5) with cmdx.DGContext(5.0): assert_almost_equals(transform["ty"].read(), 5.0, places=5) with cmdx.DGContext(10.0): assert_almost_equals(transform["ty"].read(), 10.0, places=5)
def process_curve(self): # self.get_data() threshold = cmds.floatSliderGrp(thres_slider, value=True, query=True) compr_value = cmds.floatSliderGrp( compr_slider, value=True, query=True) blend_value = cmds.floatSliderGrp(blend_slider, value=True, query=True) # Reverses the input range, as soon it is not possible to do in gui for curve in self.curves: data = self.value_data[curve] peaks = self.find_peaks(data) thres_peaks = [i for i in peaks if data[i] > threshold] peak_chains = self.get_peak_chains(thres_peaks, data) # Compressing soruce data filtered_values = self.compress( self.value_data[curve], 0, compr_value) # Extracting data by threshold filtered_values = self.filter_by_threshold( peak_chains, data, filtered_values) # Normalizing data filtered_values = self.blend_normalized( filtered_values, blend_value) attr = cmds.listConnections(curve, p=True)[0] self.add_keys(attr, self.frame_data[curve], filtered_values, None) cmds.keyTangent(itt='auto', ott='auto')
def __init__( self, attrpath, keyTime=None, keyIdx=None ): #if the attrpath doesn't exist, then just create an empty key instance if not cmd.objExists(attrpath): self.obj = None self.attr = None self.time = None self.value = None self.iw = None self.ow = None self.itt = None self.ott = None return self.obj,self.attr = attrpath.split('.') #make sure the attr name is the long version of the name, its too annoying to have to deal with shortnames AND long names... self.attr = cmd.attributeQuery(self.attr,longName=True,node=self.obj) #and just for uber convenience, store the attrpath as well... self.attrpath = attrpath if keyIdx != None: times = cmd.keyframe(attrpath,index=keyIdx,query=True) self.time = times[0] elif keyTime != None: self.time = keyTime #is there a key at the time? if cmd.keyframe(attrpath,time=(keyTime,),query=True,keyframeCount=True): self.value = cmd.keyframe(attrpath,time=(keyTime,),query=True,valueChange=True)[0] self.iw,self.ow,self.ia,self.oa = cmd.keyTangent(attrpath,time=(keyTime,),query=True,inWeight=True,outWeight=True,inAngle=True,outAngle=True) self.itt,self.ott = cmd.keyTangent(attrpath,time=(keyTime,),query=True,inTangentType=True,outTangentType=True) #this is purely 'clean up after maya' code. for whatever reason maya will return a tangent type of "fixed" even though its a completely invalid tangent type... not sure what its supposed to map to, so I'm just assuming spline if self.itt == 'fixed': self.itt = 'spline' if self.ott == 'fixed': self.ott = 'spline' else: self.value = cmd.keyframe(attrpath,time=(keyTime,),query=True,eval=True,valueChange=True) index = self.index previousOutTT = None previousOutTW = None nextInTT = None nextInTW = None if index > 1: previousOutTT = cmd.keyTangent(attrpath,index=(index-1,),query=True,outTangentType=True) previousOutTW = cmd.keyTangent(attrpath,index=(index-1,),query=True,outWeight=True) else: previousOutTT = cmd.keyTangent(attrpath,index=(index,),query=True,outTangentType=True) previousOutTW = cmd.keyTangent(attrpath,index=(index,),query=True,outWeight=True) if index < cmd.keyframe(self.attr,query=True,keyframeCount=True): nextInTT = cmd.keyTangent(attrpath,index=(index+1,),query=True,inTangentType=True) nextInTW = cmd.keyTangent(attrpath,index=(index+1,),query=True,inWeight=True) else: nextInTT = cmd.keyTangent(attrpath,index=(index,),query=True,inTangentType=True) nextInTW = cmd.keyTangent(attrpath,index=(index,),query=True,inWeight=True) #now average the tangents self.iw = self.ow = (previousOutTW + nextInTW )/2
def _cleanCurves(animCurves): '''Pulisce le curve rimuovendo le chiavi superflue.''' tol = 0.0001 for c in animCurves: keyCount = cmds.keyframe(c, query=True, keyframeCount=True) if keyCount == 0: continue # cancella le chiavi superflue intermedie if keyCount > 2: times = cmds.keyframe(c, query=True, index=(0, keyCount-1), timeChange=True) values = cmds.keyframe(c, query=True, index=(0, keyCount-1), valueChange=True) inTan = cmds.keyTangent(c, query=True, index=(0, keyCount-1), inAngle=True) outTan = cmds.keyTangent(c, query=True, index=(0, keyCount-1), outAngle=True) for i in range(1, keyCount-1): if math.fabs(values[i]-values[i-1]) < tol and math.fabs(values[i+1]-values[i]) < tol and math.fabs(inTan[i]-outTan[i-1]) < tol and math.fabs(inTan[i+1]-outTan[i]) < tol: cmds.cutKey(c, time=(times[i], times[i])) # ricalcola il numero di chiavi e pulisce le chiavi agli estremi keyCount = cmds.keyframe(c, query=True, keyframeCount=True) times = cmds.keyframe(c, query=True, index=(0, keyCount-1), timeChange=True) values = cmds.keyframe(c, query=True, index=(0, keyCount-1), valueChange=True) inTan = cmds.keyTangent(c, query=True, index=(0, keyCount-1), inAngle=True) outTan = cmds.keyTangent(c, query=True, index=(0, keyCount-1), outAngle=True) # piu' di due key rimanenti if keyCount > 2: if math.fabs(values[1]-values[0]) < tol and math.fabs(inTan[1]-outTan[0]) < tol: cmds.cutKey(c, time=(times[0], times[0])) if math.fabs(values[-1]-values[-2]) < tol and math.fabs(inTan[-1]-outTan[-2]) < tol: cmds.cutKey(c, time=(times[-1], times[-1])) # uno o due key rimanenti elif keyCount == 1 or (math.fabs(values[1]-values[0]) < tol and math.fabs(inTan[1]-outTan[0]) < tol): val = cmds.getAttr(c) # debuggato cmds.cutKey(c) cmds.setAttr(c, val)
def set_handle_in(name, dof, time, tangent, weight): node = "%s.%s" % (name, dof) cmds.selectKey(node, replace=True, k=True, t=(time,time)) cmds.keyTangent( edit=True , absolute=True , inAngle=tangent * 180.0 / m.pi , inWeight=weight )
def connectCommand( uiInstance ): sels = cmds.ls( sl=1 ) selChannels = cmds.channelBox( 'mainChannelBox', q=1, sma=1 ) numItems = uiInstance.layout.count() animNode = cmds.createNode( 'animCurveUU' ) for i in range( 1, numItems-1 ): targetWidget = uiInstance.layout.itemAt( i ).widget() key = targetWidget.lineEdit_key.text() value = targetWidget.lineEdit_value.text() cmds.setKeyframe( animNode, f=float(key), v=float(value) ) cmds.keyTangent( animNode, f=(float(key),float(key)), itt='linear', ott = 'linear' ) if sels and selChannels: cmds.connectAttr( sels[0] + '.' + selChannels[0], animNode + '.input' ) addString = '' if float(key) > 0: addString = 'positive' else: addString = 'negative' animNode = cmds.rename( animNode, selChannels[0] + '_' + addString + '_from_' + sels[0] ) cmds.select( animNode )
def sweepPipe(circle, pipeCurve): numberOfCVs = cmds.getAttr('%s.cp' % pipeCurve[0], size=1) motionPath = cmds.pathAnimation("%s" % circle[0], curve=pipeCurve[0], follow=True, startTimeU=1, endTimeU=numberOfCVs) cmds.selectKey("%s.uValue" % motionPath) cmds.keyTangent( itt="linear", ott="linear") pipeSweep = cmds.snapshot(circle, startTime=1, endTime=numberOfCVs) return pipeSweep
def getKeyByObject(obj): data = dict() #- object exists ? if not mc.objExists(obj): return data data['object'] = re.search('\w+$', obj).group() #- object has attributes ? attributes = mc.listAttr(obj, k=True) if not attributes: return data #- get keys for attr in attributes: times = mc.keyframe(obj, at=attr, q=True, tc=True) values = mc.keyframe(obj, at=attr, q=True, vc=True) inAngles = mc.keyTangent(obj, at=attr, q=True, ia=True) outAngles = mc.keyTangent(obj, at=attr, q=True, oa=True) inWeights = mc.keyTangent(obj, at=attr, q=True, iw=True) outWeights = mc.keyTangent(obj, at=attr, q=True, ow=True) #- keys not found.. if not times: continue #- save data.. data.setdefault('keyData', {})[attr] = zip(times, values, inAngles, inWeights, outAngles, outWeights) return data
def createJointRotationRemapping(joint, suffix, channel, input0=0, output0=0, input1=1, output1=1): remappingNode = None if cmds.objExists(joint): nodeName = joint + '_' + channel + suffix if cmds.objExists(nodeName): cmds.warning('Joint rotation remapping node already created.') return nodeName remappingNode = cmds.createNode('animCurveUU', n=nodeName) cmds.setKeyframe(remappingNode, float=input0, value=output0, itt='linear', ott='linear') cmds.setKeyframe(remappingNode, float=input1, value=output1, itt='linear', ott='linear') cmds.keyTangent(remappingNode, weightedTangents=False) cmds.connectAttr(joint + '.' + channel, remappingNode + '.input', f=1) else: cmds.warning('Joint not found.') return remappingNode
def defaultTangents_set(arg, inTangent=True, outTangent=True): _str_func = 'defaultTangents_set' log.debug(cgmGEN.logString_start(_str_func)) d_validArgs = { 'linear': ['ln', 'linear'], 'spline': ['sp', 'spline'], 'clamped': ['cl', 'clamped'], 'flat': ['fl', 'flat'], 'plateau': ['pl', 'plateau'], 'auto': ['au', 'auto'] } _arg = VALID.kw_fromDict(arg, d_validArgs, calledFrom=_str_func) log.debug( cgmGEN.logString_msg(_str_func, "| arg: {0} | validated: {1}".format(arg, _arg))) #Couldn't use True for setting the Tangent type had to use _arg _d = {'g': 1} if inTangent: _d['itt'] = _arg if outTangent: _d['ott'] = _arg mc.keyTangent(**_d)
def SetCannon(angle=10, distance=0.2): angle = -angle cannon = cmd.ls(sl=True, l=True, type="transform")[0] barrel1 = cmd.listRelatives(cannon, c=True, f=True, typ="transform")[0] barrel2 = cmd.listRelatives(barrel1, c=True, f=True, typ="transform")[0] size = GetSize(barrel2) print(size) cmd.setAttr(barrel1 + ".rotateX", angle) parent = cmd.listRelatives(cannon, parent=True, fullPath=True)[0] barrel2 = cmd.parent(barrel2, parent)[0] cannonShape = cmd.listRelatives(cannon, s=True, f=True)[0] barrel1Shape = cmd.listRelatives(barrel1, s=True, f=True)[0] barrel2Shape = cmd.listRelatives(barrel2, s=True, f=True)[0] newCanon = cmd.polyUnite([cannonShape, barrel1Shape], name="Cannon")[0] cmd.delete(newCanon, ch=True) newCanon = cmd.parent(newCanon, parent)[0] barrel2 = cmd.parent(barrel2, newCanon)[0] start = cmd.getAttr(barrel2 + ".t")[0] print("Start: " + str(start)) d = size[2] * distance offset = (0.0, math.sin(math.radians(angle)) * d, math.cos(math.radians(angle)) * d) print("Offset: " + str(offset)) end = (start[0] - offset[0], start[1] + offset[1], start[2] - offset[2]) print("End: " + str(end)) cmd.setKeyframe(barrel2, at="translateY", v=start[1], t=31) cmd.setKeyframe(barrel2, at="translateZ", v=start[2], t=31) cmd.setKeyframe(barrel2, at="translateY", v=end[1], t=33) cmd.setKeyframe(barrel2, at="translateZ", v=end[2], t=33) cmd.setKeyframe(barrel2, at="translateY", v=start[1], t=42) cmd.setKeyframe(barrel2, at="translateZ", v=start[2], t=42) cmd.keyTangent(barrel2, at="translateY", itt="spline", ott="spline") cmd.keyTangent(barrel2, at="translateZ", itt="spline", ott="spline") barrel2 = cmd.rename(barrel2, "barrel1")
def TankBind(): for obj in cmd.ls(sl=True): t = cmd.getAttr(obj + ".translate")[0] cmd.setAttr(obj + ".translate", 0, 0, 0) body = None for c in cmd.listRelatives(obj, c=True, f=True, typ="transform"): print(c) if c.lower().find("body") >= 0: body = c break if body != None: cmd.select(body) bindInfo = xxt.autoBind("Body") root = bindInfo[2].getJoint() for j in cmd.listRelatives(root, c=True, f=True, typ="transform"): if j.lower().find("wheel") >= 0: attr = j + ".rx" cmd.setKeyframe(attr, v=0, t=0) cmd.setKeyframe(attr, v=360, t=60) cmd.keyTangent(attr, itt="spline", ott="spline") cmd.setAttr(bindInfo[0] + ".inheritsTransform", False) cmd.parent(bindInfo[0], root, obj) else: print("can't find body") print(t) cmd.setAttr(obj + ".translate", t[0], t[1], t[2])
def convertConnectionAsAnimCurve(node, attr): separateParentConnection(node, attr) cons = cmds.listConnections(node + '.' + attr, s=1, d=0, p=1, c=1) if not cons: return None attrType = cmds.attributeQuery(attr, node=node, attributeType=1) if attrType == 'doubleLinear': animCurveType = 'animCurveUL' elif attrType == 'doubleAngle': animCurveType = 'animCurveUA' else: animCurveType = 'animCurveUU' animCurve = cmds.createNode(animCurveType) cmds.connectAttr(cons[1], animCurve + '.input') cmds.connectAttr(animCurve + '.output', cons[0], f=1) cmds.setKeyframe(animCurve, f=-1, v=-1) cmds.setKeyframe(animCurve, f=-.5, v=-.5) cmds.setKeyframe(animCurve, f=0, v=0) cmds.setKeyframe(animCurve, f=.5, v=.5) cmds.setKeyframe(animCurve, f=1, v=1) cmds.setAttr(animCurve + ".postInfinity", 1) cmds.setAttr(animCurve + ".preInfinity", 1) cmds.selectKey(animCurve) cmds.keyTangent(itt='spline', ott='spline') return animCurve
def connectCommand(uiInstance): sels = cmds.ls(sl=1) selChannels = cmds.channelBox('mainChannelBox', q=1, sma=1) numItems = uiInstance.layout.count() animNode = cmds.createNode('animCurveUU') for i in range(1, numItems - 1): targetWidget = uiInstance.layout.itemAt(i).widget() key = targetWidget.lineEdit_key.text() value = targetWidget.lineEdit_value.text() cmds.setKeyframe(animNode, f=float(key), v=float(value)) cmds.keyTangent(animNode, f=(float(key), float(key)), itt='linear', ott='linear') if sels and selChannels: cmds.connectAttr(sels[0] + '.' + selChannels[0], animNode + '.input') addString = '' if float(key) > 0: addString = 'positive' else: addString = 'negative' animNode = cmds.rename( animNode, selChannels[0] + '_' + addString + '_from_' + sels[0]) cmds.select(animNode)
def keyFullRotation(self, pObjectName, pStartTime, pEndTime, pTargetAttribute, reverse=False, isTangent=False): if reverse == False: startValue = 0 endValue = 360 else: startValue = 360 endValue = 0 cmds.cutKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute) cmds.setKeyframe(pObjectName, time=pStartTime, attribute=pTargetAttribute, value=startValue) cmds.setKeyframe(pObjectName, time=pEndTime, attribute=pTargetAttribute, value=endValue) cmds.selectKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute, keyframe=True) cmds.keyTangent(inTangentType='linear', outTangentType='linear')
def __init__(self, curve_sel, vertex_list, chain_geo): self.curve_sel = curve_sel self.verts = vertex_list self.chain_geo = chain_geo self.find_length = Find_Out() self.link_length = self.find_length.edge_length(self.verts) self.chain_length = self.find_length.curve_length(self.curve_sel) self.link_total = int(self.chain_length/self.link_length) self.motion_path_name = str(self.chain_geo) + '_Path' cmds.pathAnimation(self.chain_geo, name = self.motion_path_name, fractionMode = True, follow= True, followAxis = 'x', upAxis = 'y', worldUpType = 'object', startTimeU = 1, endTimeU = self.link_total, c = self.curve_sel) cmds.setKeyframe(self.motion_path_name + '.frontTwist', v = 0.0, t = 1 ) cmds.setKeyframe(self.motion_path_name + '.frontTwist', v = 60.0*self.link_total, t = self.link_total ) cmds.keyTangent(self.motion_path_name + '.uValue', itt = 'linear', ott = 'linear' ) cmds.keyTangent(self.motion_path_name + '.frontTwist', itt = 'linear', ott = 'linear') cmds.snapshot( self.chain_geo, constructionHistory=True, startTime=1, endTime = self.link_total, increment=1, update = 'animCurve', name = str(self.chain_geo) + '_snapShot' ) self.chain_group = cmds.group( em=True, name=str(self.chain_geo) + '_geo_grp' ) self.chain_list = cmds.listRelatives(str(self.chain_geo + '_snapShotGroup')) for dummy_geo in self.chain_list: cmds.delete(icn = True, ch = True) cmds.parent(dummy_geo, self.chain_group)
def doReplicate(): the_name = cmd.textFieldGrp("name", query=True, text=True) the_incr = cmd.floatSliderGrp("incr", query=True, value=True) selection = cmd.ls(selection=True, long=True) element = selection[0] curve = selection[1] # Build motion path the_motion_path = cmd.pathAnimation(element, curve=curve, fractionMode=True, follow=True, followAxis="z", upAxis="y", startTimeU=1, endTimeU=100) # Flat animation curves cmd.keyTangent(the_motion_path, inTangentType="linear", outTangentType="linear") # Create animation snapshot the_snapshot = cmd.snapshot(element, name=the_name, endTime=100, increment=the_incr)
def BindWheel(): bindInfo = xxt.MultiBind(name="Wheel") joints = bindInfo[2] for j in joints: attr = j + ".rx" cmd.setKeyframe(attr, v=0, t=0) cmd.setKeyframe(attr, v=360, t=30) cmd.keyTangent(attr, itt="spline", ott="spline")
def toggleTangentLock(): state = cmds.keyTangent(q=True, lock=True)[0] if state: cmds.keyTangent(lock=False) message('Tangent Broken') else: cmds.keyTangent(lock=True) message('Tangent Unified')
def addMarksToScene(marks): ''' This is temp and will possibly be rolled into future releases. ''' start, end = utl.frameRange() camera = utl.getCurrentCamera() camShape = mc.listRelatives(camera, shapes=True)[0] aov = mc.getAttr(camShape + '.horizontalFilmAperture') name = 'ml_stopwatch_' numStopwatches = len(mc.ls(name + '*', type='locator')) top = mc.spaceLocator(name=name + '#') ename = ':'.join([str(x) for x in marks]) mc.addAttr(top, longName='keyTimes', at='enum', enumName=ename, keyable=True) markRange = float(marks[-1] - marks[0]) viewWidth = aov * 2 viewHeight = -0.4 * aov + (numStopwatches * aov * 0.08) depth = 5 for mark in marks[1:-1]: ann = mc.annotate(top, text=str(mark)) mc.setAttr(ann + '.displayArrow', 0) #parent annT = mc.parent(mc.listRelatives(ann, parent=True, path=True), top)[0] annT = mc.rename(annT, 'mark_' + str(round(mark))) ann = mc.listRelatives(annT, shapes=True, path=True)[0] #set the position normalX = float(mark - marks[0]) / markRange - 0.5 mc.setAttr(annT + '.translateX', viewWidth * normalX * 2) mc.setAttr(annT + '.translateY', viewHeight) mc.setAttr(annT + '.translateZ', -depth) #keyframe for color mc.setAttr(ann + '.overrideEnabled', 1) mc.setKeyframe(ann, attribute='overrideColor', value=17, time=(int(marks[0] - 1), int(mark + 1))) mc.setKeyframe(ann, attribute='overrideColor', value=13, time=(int(mark), )) mc.keyTangent(ann + '.overrideColor', ott='step') mc.select(clear=True) mc.parentConstraint(camera, top)
def setKeyFrameControl(self, curve, attri): try: selValue = mc.keyframe(curve, at=attri, t=(startFrame,startFrame), q=True, eval=True) mc.setKeyframe(curve, at=attri, t=(actionFrame,actionFrame), v=selValue[0]) mc.setKeyframe(curve, at=attri, t=(tposeFrame,tposeFrame), v=0) mc.keyTangent(curve, at=attri, inTangentType='flat', ott='flat', time=(actionFrame, actionFrame)) mc.keyTangent(curve, at=attri, inTangentType='linear', ott='linear', time=(startFrame, startFrame)) except: return 'Fail sekkey'
def save(self): self.animation = {} for object in self.objects: data = {} connections = cmds.listConnections(object) if connections is None: return curves = [ x for x in connections if "animCurve" in cmds.nodeType(x) ] for curve in curves: times = cmds.keyframe(curve, query=True, time=(self.start, self.end)) if times is None: data[curve] = None else: values = [ cmds.keyframe(curve, time=(t, t), eval=True, query=True)[0] for t in times ] inWeights = [ cmds.keyTangent(curve, query=True, time=(t, t), inWeight=True)[0] for t in times ] inAngles = [ cmds.keyTangent(curve, query=True, time=(t, t), inAngle=True)[0] for t in times ] outWeights = [ cmds.keyTangent(curve, query=True, time=(t, t), outWeight=True)[0] for t in times ] outAngles = [ cmds.keyTangent(curve, query=True, time=(t, t), outAngle=True)[0] for t in times ] data[curve] = { "keys": list(zip(times, values)), "ins": list(zip(inWeights, inAngles)), "outs": list(zip(outWeights, outAngles)) } self.animation[object] = data
def setKeyFrameControl(self, curve, attri): try: selValue = mc.keyframe(curve, at=attri, t=(1001,1001), q=True, eval=True) mc.setKeyframe(curve, at=attri, t=(980,980), v=selValue[0]) mc.setKeyframe(curve, at=attri, t=(960,960), v=0) mc.keyTangent(curve, at=attri, inTangentType='flat', ott='flat', time=(980, 980)) mc.keyTangent(curve, at=attri, inTangentType='linear', ott='linear', time=(1001, 1001)) except: return 'Fail sekkey'
def animateFlower(): cmds.playbackOptions(min=1, max=260) cmds.setKeyframe("petal", time=10, attribute="rotateX", value=0) cmds.setKeyframe("petal", time=1, attribute="translateY", value=0) cmds.setKeyframe("petal", time=24, attribute="rotateX", value=-55) cmds.setKeyframe("petal", time=48, attribute="translateY", value=-8) cmds.setKeyframe("petal5", time=10, attribute="rotateX", value=0) cmds.setKeyframe("petal5", time=1, attribute="translateY", value=0) cmds.setKeyframe("petal5", time=24, attribute="rotateX", value=-55) cmds.setKeyframe("petal5", time=48, attribute="translateY", value=-12) cmds.setKeyframe("petal4", time=34, attribute="rotateX", value=0) cmds.setKeyframe("petal4", time=25, attribute="translateY", value=0) cmds.setKeyframe("petal4", time=48, attribute="rotateX", value=-55) cmds.setKeyframe("petal4", time=96, attribute="translateY", value=-18) cmds.setKeyframe("petal9", time=34, attribute="rotateX", value=0) cmds.setKeyframe("petal9", time=25, attribute="translateY", value=0) cmds.setKeyframe("petal9", time=48, attribute="rotateX", value=-55) cmds.setKeyframe("petal9", time=96, attribute="translateY", value=-22) cmds.setKeyframe("petal8", time=58, attribute="rotateX", value=0) cmds.setKeyframe("petal8", time=49, attribute="translateY", value=0) cmds.setKeyframe("petal8", time=96, attribute="rotateX", value=-55) cmds.setKeyframe("petal8", time=120, attribute="translateY", value=-15) cmds.setKeyframe("petal7", time=106, attribute="rotateX", value=0) cmds.setKeyframe("petal7", time=97, attribute="translateY", value=0) cmds.setKeyframe("petal7", time=120, attribute="rotateX", value=-55) cmds.setKeyframe("petal7", time=168, attribute="translateY", value=-6) cmds.setKeyframe("petal3", time=130, attribute="rotateX", value=0) cmds.setKeyframe("petal3", time=121, attribute="translateY", value=0) cmds.setKeyframe("petal3", time=144, attribute="rotateX", value=-55) cmds.setKeyframe("petal3", time=216, attribute="translateY", value=-10) cmds.setKeyframe("petal1", time=130, attribute="rotateX", value=0) cmds.setKeyframe("petal1", time=121, attribute="translateY", value=0) cmds.setKeyframe("petal1", time=144, attribute="rotateX", value=-55) cmds.setKeyframe("petal1", time=216, attribute="translateY", value=-8) cmds.setKeyframe("petal6", time=154, attribute="rotateX", value=0) cmds.setKeyframe("petal6", time=145, attribute="translateY", value=0) cmds.setKeyframe("petal6", time=168, attribute="rotateX", value=-55) cmds.setKeyframe("petal6", time=264, attribute="translateY", value=-9) cmds.setKeyframe("petal2", time=178, attribute="rotateX", value=0) cmds.setKeyframe("petal2", time=169, attribute="translateY", value=0) cmds.setKeyframe("petal2", time=192, attribute="rotateX", value=-55) cmds.setKeyframe("petal2", time=312, attribute="translateY", value=-14) cmds.keyTangent(inTangentType='linear', outTangentType='linear') cmds.play(forward=True)
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 setKeyFrameControl(self, curve, attri): try: mc.setKeyframe(curve, at=attri, t=(int(mc.textField('startText', q=1, text=1)),int(mc.textField('startText', q=1, text=1)))) selValue = mc.keyframe(curve, at=attri, t=(int(mc.textField('startText', q=1, text=1)),int(mc.textField('startText', q=1, text=1))), q=True, eval=True) mc.setKeyframe(curve, at=attri, t=(int(mc.textField('actionPoseText', q=1, text=1)),int(mc.textField('actionPoseText', q=1, text=1))), v=selValue[0]) mc.setKeyframe(curve, at=attri, t=(int(mc.textField('tposeText', q=1, text=1)),int(mc.textField('tposeText', q=1, text=1))), v=0) mc.keyTangent(curve, at=attri, inTangentType='flat', ott='flat', time=(int(mc.textField('actionPoseText', q=1, text=1)), int(mc.textField('actionPoseText', q=1, text=1)))) mc.keyTangent(curve, at=attri, inTangentType='linear', ott='linear', time=(int(mc.textField('startText', q=1, text=1)), int(mc.textField('startText', q=1, text=1)))) except: return 'Fail sekkey'
def get_tangent_points(self, frame): """ this function finds the piece-wise keyframwe of the curve and returns the 4 points needed to evaluate the curve @returns: list of 4 2D points. """ ##this work on the assumption there is a keyframe at current time frames = self.get_frame_pair(frame) if frames == sys.maxint or frames is None or frames == -1: raise ValueError("MayaAnimCurve: frame {f} falls outside the anim curve") frame1, frame2= frames f1Idx = self.get_frame_idx(frame1) f2Idx = self.get_frame_idx(frame2) #querying the tangents outx = cmds.keyTangent(self.node,attribute=self.attribute, q=1, ox=1)[f1Idx] outy = cmds.keyTangent(self.node,attribute=self.attribute, q=1, oy=1)[f1Idx] inx = cmds.keyTangent(self.node,attribute=self.attribute, q=1, ix=1)[f2Idx] iny = cmds.keyTangent(self.node,attribute=self.attribute, q=1, iy=1)[f2Idx] t2 = [outx,outy] t3 = [inx, iny] conversion_factor = self.conversion_factor t2[0]*=(conversion_factor) t3[0]*=(conversion_factor) values1 =cmds.keyframe(self.node,attribute=self.attribute, time=(frame1,frame1), query=True, valueChange=True, timeChange=True); values2 =cmds.keyframe( self.node,attribute=self.attribute, time=(frame2,frame2), query=True, valueChange=True, timeChange=True); p1 =[values1[0],values1[1]] p4 =[values2[0],values2[1]] #we need to computethe tangent mulitplier. #the multiplier is reltive to the tangent of the angle #the final multiplier has the form 1/3 * y/x , where y and x are the #componetns of the tangent vector #TODO check for divison by zero? delta = frame2-frame1 out_mult = abs((1.0/3.0)*delta * t2[1]/t2[0]) in_mult = abs((1.0/3.0)*delta * t3[1]/t3[0]) p2 = [(t2[0]*out_mult) + p1[0], (t2[1]*out_mult) + p1[1]] p3 = [(-t3[0]*in_mult) + p4[0], (-t3[1]*in_mult) + p4[1]] return [p1,p2,p3,p4]
def j_fixAdv3_99_forMaya2016(): 'fix advanceSkeleton v3.99 stretch not work in maya2016' j_drivenKey = {"antiPop":4.990848, "normal":4.878867} for drv in j_drivenKey: #数值 for pat in ("Arm","Leg"): #arm or leg for side in ("_R","_L"): for i in ("antiPop","normal"): mc.selectKey(("IKdistance" + pat + side +"Shape_"+ i), ot =True, f = (j_drivenKey[drv],)) mc.keyTangent(("IKdistance" + pat + side +"Shape_"+ i), lock = False,) mc.keyTangent( itt = "clamped",ott = "clamped",)
def emitCurve(sourceCurve,curveStart,duration,particleList,maxDistance,minDistance,emitTime,lifeTime,lifeTimeVar,fadeOut,turbulenceAmp,turbulencePer,drift): ''' Emits particles from a curve sourceCurve : Name of the curve particles will emit from curveStart : Frame to start emission duration : Number of frames to emit for particleList : List containing names of all the particles to be animatied maxDistance : Maximum distance particles will be emitted from at the middle of the curve minDistance : Maximum distance particles will be emitted from at the start and end of the curve emitTime : Number of frames particles will be affected by the emission force lifeTime : Average lifetime of a particle lifeTimeVar : Variation from average lifetime as a percentage fadeOut : Number of frames to scale down particles at the end of their lifetime turbulenceAmp : Amplitude of the turbulence animation graph turbulencePer : Period of the turbulence animation graph drift : Distance a particle will drift 10 frames. Contains (x,y,z) Updates the progress window and assigns all the elements in particleList to the class particles. Creates a locator and keys it to follow the curve linearly over the emission time. At the emit time, copies the coordinates of the locator and moves particle to that location and add a random rotation. The distance is calculated depending on the time the particle is emitted. Runs the relevant class specific procedures to animate the particle. ''' cmds.progressWindow(e=1,progress=0,status='Animating Particles...') for i in range(0,len(particleList)): particleList[i]=particles(particleList[i]) count=0 [emitter] = [cmds.spaceLocator(n='emitter')[0]] motionPath = cmds.pathAnimation(fm=1, stu=curveStart,etu=curveStart+duration,c=sourceCurve) cmds.keyTangent(motionPath,at='uValue',itt='Linear',ott='Linear') for x in particleList: launchTime=random.uniform(0,duration) [(emitX,emitY,emitZ)]=cmds.getAttr(emitter+'.translate',t=curveStart+launchTime) cmds.move(emitX,emitY,emitZ,x.name) cmds.rotate(random.uniform(0,360),random.uniform(0,360),random.uniform(0,360),x.name) if launchTime/duration <=0.5: distance=(launchTime/duration)*2*(maxDistance-minDistance)+minDistance else: distance=(1-(launchTime/duration))*2*(maxDistance-minDistance)+minDistance x.born = int(curveStart+launchTime+random.randint(-1,1)) x.explode(x.born,emitTime,distance) x.drift(x.born,drift,turbulenceAmp*random.random(),turbulencePer+random.randint(-2,2)) x.lifeTime=int(lifeTime+random.uniform(-lifeTime*lifeTimeVar*0.01,lifeTime*lifeTimeVar*0.01)) x.fadeOut=random.randint(fadeOut-2,fadeOut+2) x.bake() cmds.keyframe(x.name,at='visibility',a=1,vc=0) count+=1 cmds.progressWindow(e=1,progress=int((100.0/len(particleList))*count)) for x in particleList: x.birth() x.death() return
def clampValues(value=0, selectionOption=1, clampOption=0): keySel = _getKeySelection(selectionOption) for curve, values in zip(keySel.curves, keySel.values): indicies = None if clampOption==0: indicies = [i for i, x in enumerate(values) if x > value] elif clampOption==1: indicies = [i for i, x in enumerate(values) if x < value] if indicies: mc.keyframe(curve, index=utl.castToTime(indicies), edit=True, valueChange=value) mc.keyTangent(curve, index=utl.castToTime(indicies), itt='auto', ott='auto')
def createAnimCurve( self ): newAnim = cmds.createNode( self.nodeType, n=self.name ) if not self.tc: return None for i in range( len( self.tc ) ): cmds.setKeyframe( newAnim, t=self.tc[i], v=self.vc[i] ) cmds.keyTangent( newAnim, t=(self.tc[i],self.tc[i]), lock=self.lock[i], itt=self.itt[i], ott=self.ott[i], ia=self.ia[i], oa=self.oa[i] ) cmds.setAttr( newAnim+'.preInfinity', self.preInfinity ) cmds.setAttr( newAnim+'.postInfinity', self.postInfinity ) return newAnim
def generate( self, objects, **kwargs ): ''' generates an anim dictionary - its basically just dict with node names for keys. key values are lists of tuples with the form: (keyTime, attrDict) where attrDict is a dictionary with attribute name keys and attribute value keys ''' defaultWeightedTangentOpt = bool(cmd.keyTangent(q=True, g=True, wt=True)) self.clear() #list all keys on the objects - so we can determine the start frame, and range. all times are stored relative to this time allKeys = cmd.keyframe( objects, q=True ) allKeys.sort() self.offset = offset = allKeys[ 0 ] self.__range = allKeys[ -1 ] - offset for obj in objects: attrs = cmd.listAttr( obj, keyable=True, visible=True, scalar=True ) if attrs is None: continue objDict = {} self[ obj ] = objDict for attr in attrs: #so the attr value dict contains a big fat list containing tuples of the form: #(time, value, itt, ott, ita, ota, iw, ow, isLockedTangents, isWeightLock) attrpath = '%s.%s' % (obj, attr) times = cmd.keyframe( attrpath, q=True ) weightedTangents = defaultWeightedTangentOpt #if there is an animCurve this will return its "weighted tangent" state - otherwise it will return None and a TypeError will be raised try: weightedTangents = bool(cmd.keyTangent(attrpath, q=True, weightedTangents=True)[0]) except TypeError: pass if times is None: #in this case the attr has no animation, so simply record the pose for this attr objDict[attr] = (False, [(None, cmd.getAttr(attrpath), None, None, None, None, None, None, None, None)]) continue else: times = [t-offset for t in times] values = cmd.keyframe(attrpath, q=True, vc=True) itts = cmd.keyTangent(attrpath, q=True, itt=True) otts = cmd.keyTangent(attrpath, q=True, ott=True) ixs = cmd.keyTangent(attrpath, q=True, ix=True) iys = cmd.keyTangent(attrpath, q=True, iy=True) oxs = cmd.keyTangent(attrpath, q=True, ox=True) oys = cmd.keyTangent(attrpath, q=True, oy=True) isLocked = cmd.keyTangent(attrpath, q=True, weightLock=True) isWeighted = cmd.keyTangent(attrpath, q=True, weightLock=True) objDict[ attr ] = weightedTangents, zip(times, values, itts, otts, ixs, iys, oxs, oys, isLocked, isWeighted)
def breakTan(arg=None): """ //Break and unlock tangents undoInfo -stateWithoutFlush off; MoveTool; keyTangent -lock off; keyTangent -weightLock off; undoInfo -stateWithoutFlush on; //Unify and lock tangents undoInfo -stateWithoutFlush off; keyTangent -lock on; keyTangent -weightLock on; global string $gSelect; // Sacred Select Tool setToolTo $gSelect; undoInfo -stateWithoutFlush on; """ if arg == "Press": cmds.undoInfo(swf=False) mel.eval('MoveTool;') cmds.keyTangent(e=True, l=False) cmds.keyTangent(e=True, wl=False) cmds.undoInfo(swf=True) elif arg == "Release": cmds.undoInfo(swf=False) cmds.keyTangent(e=True, l=True) cmds.keyTangent(e=True, wl=True) mel.eval('global string $gSelect; setToolTo $gSelect') cmds.undoInfo(swf=True)