def listStorableAttrs(self , node, shortName=True, noCompound=True): """ @brief List every attributes of a node who can go trough the pipeline and whose value will be stored. @return : List @param node - String - Node to get the attributes of. @param shortName - Bool - If True, return attributes short name. @param noCompound - Bool - If True, exclude compound attributes. """ def __getShortName(node, attr, shortName): result = attr if shortName: names = attr.split('.') snames = [] for name in names: if name.endswith(']'): snames.append(name) else: snames.append(mc.attributeQuery(name, node=node, shortName=True)) result = ".".join(snames) return result result = [] nodeType = mc.nodeType(node) if not mc.listAnimatable(node): return result for s in mc.listAnimatable(node): if noCompound: if len(s.split('.')) > 2: continue nodeName = s.split('.')[0] attr = ".".join(s.split('.')[1:]) ## Remove attributes on the shapes (listAnimatable return them) if mc.nodeType(node) == mc.nodeType(nodeName): attr = __getShortName(node, attr, shortName) result.append(str(attr)) attrs = mc.listAttr(node, cb=True) if attrs: for attr in attrs: attr = __getShortName(node, attr, shortName) result.append(str(attr)) if mc.listAttr(node, userDefined=True): extra = [str(x) for x in mc.listAttr(node, userDefined=True) if mc.getAttr("%s.%s" % (node, x), type=True) == 'string' if not x.startswith("rnkInit_") if not mc.getAttr("%s.%s" % (node, x), lock=True)] if extra: result.extend(extra) return result
def reset_animation_attributes(node): for attr in mc.listAnimatable(node): try: set_default_attribute_value(node, attr) except RuntimeError: print('Skipped %s' % attr) continue
def copyKeyframes(): objs = cmds.ls(selection=True) if (len(objs) < 2): cmds.error("Please select at least two Objects") sourceObj = objs[0] # First selected object is for copy # Find animated attributes and put on a list animAttributes = cmds.listAnimatable(sourceObj) # Go round the list for attribute in animAttributes: # Get the key frame numbers of animated attributes numKeyframes = cmds.keyframe(attribute, query=True, keyframeCount=True) if (numKeyframes > 0): # Copy keyframes where animated attribute is existed cmds.copyKey(attribute) # Hold keyframes temporarily in memory # No additional flag, grabbing all keyframes for the specified attribute # Paste keyframes to other objects for obj in objs[1:]: cmds.pasteKey(obj, attribute=getAttrName(attribute), option="replace")
def cam_con_move(self): # 按钮执行函数 cam = selected()[0] cam_grp = cam.root() cam_aim = 0 try: for i in cam_grp.listRelatives(): if 'locator' in i.getShape().type(): cam_aim = 1 self.cam_aim_aim_name = i.name() except: animAttributes = cmds.listAnimatable(cam.name()) for attribute in animAttributes: # 求出K了多少次 numKeyframes = cmds.keyframe(attribute, query=True, keyframeCount=True) if numKeyframes > 0: self.cam_copyKeyframes(cam) break else: self.cam_noaim_con(cam) if cam_aim: for i in cam_grp.listRelatives(): if 'camera' in i.getShape().type(): select(i) cam = selected()[0] self.cam_aim_con(cam)
def run(): # get objects objs = cmds.ls(sl=1, l=1) # get playback settings startTime = int(cmds.playbackOptions(q=1, min=1)) endTime = int(cmds.playbackOptions(q=1, max=1)) timeRange = range(startTime, endTime + 1) allDict = {} attrDict = {} for o in objs: print("object", o) attrs = cmds.listAnimatable(o) frames = cmds.keyframe(obj, q=True, at=attr) values = cmds.keyframe(obj, q=True, at=attr, vc=True) for t in timeRange: print("frame", t) for a in attrs: print a val = cmds.keyframe(o, at=a, t=(t, t), ev=1, q=1) if val == None: val = cmds.getAttr(a, t=t) #print val attrDict[a] = val allDict[t] = attrDict print allDict
def getAnimationData(): objs = cmds.ls(selection=True) obj = objs[0] animAttributes = cmds.listAnimatable(obj) for attribute in animAttributes: numKeyframes = cmds.keyframe(attribute, query=True, keyframeCount=True) if (numKeyframes > 0): print("---------------------------") print("Found ", numKeyframes, " keyframes on ", attribute) times = cmds.keyframe(attribute, query=True, index=(0, numKeyframes), timeChange=True) values = cmds.keyframe(attribute, query=True, index=(0, numKeyframes), valueChange=True) print('frame#, time, value') for i in range(0, numKeyframes): print(i, times[i], values[i]) print("---------------------------")
def listAnimatable(*args, **kwargs): """ Modifications: - returns an empty list when the result is None - returns wrapped classes """ return map(_general.PyNode, _util.listForNone(cmds.listAnimatable(*args, **kwargs)))
def cbAttrs(ctrl): '''Find all visible attributes in the channel box''' cb_list = cmds.listAnimatable(ctrl) new_list = [] if cb_list is not None: for atr_long in cb_list: atr_short = atr_long.rpartition('.')[2] new_list.append(atr_short) return new_list return
def copyKeyframes(self): undoInfo(closeChunk=True) objs = cmds.ls(selection=True) if (len(objs) < 2): cmds.error("Please select at least two objects") sourceObj = objs[0] animAttributes = cmds.listAnimatable(sourceObj); for attribute in animAttributes: numKeyframes = cmds.keyframe(attribute, query=True, keyframeCount=True) if (numKeyframes > 0): cmds.copyKey(attribute) for obj in objs[1:]: cmds.pasteKey(obj, attribute=self.getAttName(attribute), option="replace") undoInfo(closeChunk=True)
def getAnimatableAttributes(obj): '''Returns keyable attributes on an object. Always returns a list''' attrs = cmd.listAnimatable(obj) if attrs: # Remove shapes from attributes. List animatable includes them # by default. # attrs = [attr for attr in attrs if not cmd.ls(attr.split('.')[0], s = 1)] # Homogenize names. (listAnimatable returns FULL paths). # ListAnimatable might return a shape instead of the original # given object, so cmd.ls(attr, o = 1)[0] is needed to determine # the relative path. attrs = [homogonizeName(attr) for attr in attrs] else: attrs = [] removeUnderworldFromPath(attrs) return attrs
def copyKeyframes(self, obj1, obj2): obj1 = obj1.name() obj2 = obj2.name() objs = [obj1, obj2] if (len(objs) < 2): cmds.error("Please select at least two objects") sourceObj = objs[0] animAttributes = cmds.listAnimatable(sourceObj) for attribute in animAttributes: numKeyframes = cmds.keyframe(attribute, query=True, keyframeCount=True) if (numKeyframes > 0): cmds.copyKey(attribute) for obj in objs[1:]: cmds.pasteKey(obj, attribute=self.getAttName(attribute), option="replace")
def TranslateZ(amountToScale): """TranslateZ of the root by amountToScale. Use percentage from 0.0-2.0""" objs = mc.ls(sl=True) obj = objs[0] animAttr = mc.listAnimatable(obj) animAttrIndex = 0 for attr in animAttr: numKeyFrames = mc.keyframe(attr, query=True, keyframeCount=True) if (attr == u'|root.translateZ'): times = mc.keyframe(attr, query=True, index=(0, numKeyFrames), timeChange=True) values = mc.keyframe(attr, query=True, index=(0, numKeyFrames), valueChange=True) for i in range(0, numKeyFrames): mc.setKeyframe(obj + '.translateZ', value=values[i] * amountToScale, time=times[i])
def getAnimationData(): ''' Get Animation Data about selected object ''' # Grab first selected object objs = cmds.ls(selection=True) obj = objs[0] # Get the Animation Data on List animAttributes = cmds.listAnimatable(obj) # Go round the list for attribute in animAttributes: # Count the Keyframes numKeyframes = cmds.keyframe(attribute, query=True, time=(1, 100), keyframeCount=True) if (numKeyframes > 0): # Could Key frames be negative? print("---------------------------") print("Found ", numKeyframes, " keyframes on ", attribute) times = cmds.keyframe(attribute, query=True, index=(0, numKeyframes), timeChange=True) values = cmds.keyframe(attribute, query=True, index=(0, numKeyframes), valueChange=True) print("frame#, time, value") for i in range(0, numKeyframes): print(i, times[i], values[i]) print("---------------------------")
def mirrorTempControls(obj, plug=True): attributes = [] # allAttrs = cmds.listAttr(obj) cbAttrs = cmds.listAnimatable(obj) if allAttrs and cbAttrs: orderedAttrs = [ attr for attr in allAttrs for cb in cbAttrs if cb.endswith(attr) ] if u'visibility' in orderedAttrs: orderedAttrs.remove(u'visibility') orderedAttrs.append(u'visibility') attributes.extend(orderedAttrs) # print attributes node = obj.replace('_L_', '_R_') for attr in attributes: # if plug: if cmds.objExists(obj + '.%s' % attr) and cmds.objExists(node + '.%s' % attr): if not cmds.isConnected(obj + '.%s' % attr, node + '.%s' % attr): cmds.connectAttr(obj + '.%s' % attr, node + '.%s' % attr, f=True) else: if cmds.objExists(obj + '.%s' % attr) and cmds.objExists(node + '.%s' % attr): if cmds.isConnected(obj + '.%s' % attr, node + '.%s' % attr): cmds.disconnectAttr(obj + '.%s' % attr, node + '.%s' % attr)
def adjustment_blend_selected(): sel = cmds.ls(sl=1) if not sel: cmds.warning("Nothing happened. Nothing selected.") return None for thing in sel: cmds.select(clear=True) cmds.select(thing) attributes = cmds.listAnimatable() for attribute in attributes: attribute = attribute.split('|')[-1] layer_membership = get_layer_membership(attribute) if len(layer_membership) > 2: cmds.error( "Selected channel belongs to more than two layers -> {}". format(layer_membership)) cmds.warning( "For proper use, the channel should belong to only BaseAnimation plus one anim layer to composite the offset." ) continue if len(layer_membership) < 2: print "No adjustment curve found for {}.".format(attribute) continue # This is much simpler: layers_curves = {} for layer in layer_membership: curves = cmds.animLayer( layer, q=True, findCurveForPlug=attribute) or [] for curve in curves: layers_curves[layer] = curve adjustment_range = [] adjustment_curve = '' base_curve = '' adjustment_layer = '' base_layer = '' for layer, curve in layers_curves.items(): if layer != cmds.animLayer(query=True, root=True): times = cmds.keyframe(curve, q=True, timeChange=True) adjustment_range = [min(times), max(times)] adjustment_curve = curve adjustment_layer = layer else: base_curve = curve base_layer = layer adjustment_range_filled = get_curve_range(base_curve, adjustment_curve) if len(adjustment_range_filled) < 3: print "No meaningful adjustment found for {0}".format( attribute) continue base_curve_values = [] for time in adjustment_range_filled: base_curve_values.append( cmds.keyframe(base_curve, query=True, time=(time, ), eval=True, valueChange=True, absolute=True)[0]) base_value_graph = [0.0] for i in xrange(len(base_curve_values)): if i > 0: current_value = base_curve_values[i] previous_value = base_curve_values[i - 1] base_value_graph.append(abs(current_value - previous_value)) adjustment_curve_values = [] for time in adjustment_range_filled: adjustment_curve_values.append( cmds.keyframe(adjustment_curve, query=True, time=(time, ), eval=True, valueChange=True, absolute=True)[0]) adjustment_value_graph = [0.0] for i in xrange(len(adjustment_curve_values)): if i > 0: current_value = adjustment_curve_values[i] previous_value = adjustment_curve_values[i - 1] adjustment_value_graph.append( abs(current_value - previous_value)) if sum(adjustment_value_graph) > sum(base_value_graph): print "sum({0}) is larger than sum({1}). This *may* lead to weird results. Or it might be fine.".format( adjustment_curve, base_curve) normalized_adjustment_value_graph = normalize_values( adjustment_value_graph) if abs(sum(base_value_graph)) > 0.0: normalized_base_value_graph = normalize_values( base_value_graph) else: # Be 'smart' about rotates and translates by bundling them for stragglers # Check neighboring axis other_value_graphs = {} current_axis = [ x for x in AXIS if (x in attribute.split('.')[-1]) ] or None if current_axis: for axis in AXIS: # Sorry if axis != current_axis[0]: adjacent_attribute = attribute.split( '.')[-1].replace(current_axis[0], axis) new_adjacent_attribute_name = attribute.replace( attribute.split('.')[-1], adjacent_attribute) adjacent_curve = cmds.animLayer( base_layer, q=True, findCurveForPlug=new_adjacent_attribute_name) if adjacent_curve: adjacent_curve_values = [] for time in adjustment_range_filled: value = cmds.keyframe(adjacent_curve, query=True, time=(time, ), eval=True, valueChange=True, absolute=True) or [] adjacent_curve_values.extend(value) adjacent_curve_value_graph = [0.0] for i in xrange(len(adjacent_curve_values)): if i > 0: current_value = adjacent_curve_values[ i] previous_value = adjacent_curve_values[ i - 1] adjacent_curve_value_graph.append( abs(current_value - previous_value)) other_value_graphs[ axis] = adjacent_curve_value_graph # Add the other axis together to see if it's non-zero added_graphs = [0.0 for x in adjustment_range_filled] for _, values in other_value_graphs.items(): for i, value in enumerate(values): added_graphs[i] += value # Normalize the added graphs normalized_base_value_graph = normalize_values( added_graphs) if normalized_base_value_graph: adjustment_curve_keys = cmds.keyframe(adjustment_curve, q=True, timeChange=True) adjustment_spans = zip(adjustment_curve_keys, adjustment_curve_keys[1:]) # Ok, this area got FUGLY but it works. Sorry. # TODO: Come back and make this not look like shit. for span in adjustment_spans: if span[-1] - 1.0 == span[0]: continue # Ignore please new_value_curve = [] sum_percentage = 0.0 adjustment_range_filled_cropped = [] adjustment_curve_values_cropped = [] cropped_base_value_graph = [] for index, time in enumerate(adjustment_range_filled): if time >= min(span) and time <= max(span): adjustment_range_filled_cropped.append(time) adjustment_curve_values_cropped.append( adjustment_curve_values[index]) cropped_base_value_graph.append( normalized_base_value_graph[index]) normalized_cropped_base_value_graph = normalize_values( cropped_base_value_graph) if normalized_cropped_base_value_graph: for i in xrange(len(adjustment_range_filled_cropped)): sum_percentage += normalized_cropped_base_value_graph[ i] # This will add up to 100 along the life of the curve new_value = map_from_to( sum_percentage, 0, 100, adjustment_curve_values_cropped[0], adjustment_curve_values_cropped[-1]) new_value_curve.append(new_value) # Now set the keys for index, time in enumerate( adjustment_range_filled_cropped): cmds.setKeyframe(adjustment_curve, animLayer=adjustment_layer, time=(time, ), value=new_value_curve[index]) else: for index, time in enumerate(adjustment_range_filled): cmds.setKeyframe( adjustment_curve, animLayer=adjustment_layer, time=(time, ), value=adjustment_curve_values[index]) else: for index, time in enumerate(adjustment_range_filled): cmds.setKeyframe(adjustment_curve, animLayer=adjustment_layer, time=(time, ), value=adjustment_curve_values[index]) cmds.select(clear=True) cmds.select(sel)
def Anim_obj1(Animpose_name,currentImagePath): Val1=mc.floatField('Start_F',q=1,v=1) Val2=mc.floatField('End_F',q=1,v=1) Val1=str(Val1);Val2=str(Val2) frm_rang="("+str(Val1)+'-'+str(Val2)+")" frameNumber = mc.currentTime(q=1) frameNumber =int(frameNumber) iconTmp = currentImagePath + "iconTmp." + str(frameNumber)+ ".bmp" print ("\niconTmp = " + iconTmp) Currnt_path=savepathini+'SavePose/' Anim_newname=Animpose_name+frm_rang testpath = savepathini seltab5 = mc.shelfTabLayout('Animation',q=1,st=1) animpath = (testpath + 'SavePose/Animation/'+seltab5+'/') animpath1= animpath animpath2= animpath1 + Anim_newname + '.anim' newAnimIconFile = animpath1 + Anim_newname +".bmp" if mc.file(animpath2,q=1,ex=1): Overrite = mc.confirmDialog( title='Confirm Save Anim', message='Overwrite the existing anim: '+Anim_newname+'?', button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if Overrite =='No': return mc.sysFile(iconTmp,copy=newAnimIconFile) sel_obj = mc.ls(sl=1) chkanim=mc.listConnections(sel_obj,t='animCurve',d=0) if chkanim==None: mc.confirmDialog (title='Error' ,message= 'Selected object has no anim', button=['OK'] ,defaultButton='Yes') return print '\nWriting Animation Curves...\n' fileID = open(animpath2,'w') fileID.write('#Generated by Anim_Poselib.py\n#\n#poselib written by Sreekanth.S.R\n#[email protected]\n#\n') if ":" in sel_obj[0]: ref_name = sel_obj[0].split(':')[0] else: ref_name = sel_obj[0] fileID.write('Asst_name '+ ref_name+'\n') fileID.write('frameRange '+Val1+'\n') for item in sel_obj: shortItem= mc.ls(item,sl=1) channels = mc.listConnections(item,t='animCurve', d = 0) if channels: for chan in channels: connects= mc.listConnections(chan,p=1) curattr = connects[0].split('.') num = len(curattr) buffer=curattr num = num - 1 node='' for i in range(num): if i==0: node=buffer[i] else: node=node+'.'+buffer[i] nodeTemp=[] nodeTemp = mc.ls(node) attr = buffer[num] node = nodeTemp[0] nodeTemp = mc.listRelatives(node,p=1) if nodeTemp != None : parent1 = 1 elif nodeTemp == None : parent1 = 0 testit =mc.listAnimatable(connects) # if Val1==Val2: # testit2=mc.keyframe(chan,q=1) # else: testit2=mc.keyframe(chan,q=1,time=(Val1,Val2)) if testit and testit2: evalme = mc.getAttr(chan + '.preInfinity') if evalme == 0: preIn = 'constant' if evalme == 1: preIn = 'linear' if evalme == 2: preIn = 'constant' if evalme == 3: preIn = 'cycle' if evalme == 4: preIn = 'cycleRelative' if evalme == 5: preIn = 'oscillate' evalme = mc.getAttr (chan + '.postInfinity') if evalme == 0: postIn = 'constant' if evalme == 1: postIn = 'linear' if evalme == 2: postIn = 'constant' if evalme == 3: postIn = 'cycle' if evalme == 4: postIn = 'cycleRelative' if evalme == 5: postIn = 'oscillate' evalme = mc.getAttr (chan + '.weightedTangents') weighted = evalme fileID.write('anim ' + attr + ' ' + attr + ' ' + node + ' ' + str(parent1) + ' 0 0\n' ) fileID.write('animData \n') fileID.write(' weighted ' + str(weighted) + '\n') fileID.write(' preInfinity ' + preIn + '\n') fileID.write(' postInfinity ' + postIn + '\n') fileID.write(' keys {\n') breakDown=[] # if Val1==Val2: # keys = mc.keyframe(chan,q=1) # values = mc.keyframe (chan,q=1,vc=1) # inTan = mc.keyTangent(chan,q=1,itt=1) # outTan = mc.keyTangent(chan,q=1,ott=1) # tanLock= mc.keyTangent (chan,q=1,lock=1) # weightLock=mc.keyTangent(chan,q=1,weightLock=1) # breakDown= mc.keyframe (chan,q=1,breakdown=1) # inAngle= mc.keyTangent (chan,q=1,inAngle=1) # outAngle= mc.keyTangent (chan,q=1,outAngle=1) # inWeight= mc.keyTangent (chan,q=1,inWeight=1) # outWeight= mc.keyTangent (chan,q=1,outWeight=1) # else: keys = mc.keyframe(chan,q=1,time=(Val1,Val2)) values = mc.keyframe (chan,q=1,vc=1,time=(Val1,Val2)) inTan = mc.keyTangent(chan,q=1,itt=1,time=(Val1,Val2)) outTan = mc.keyTangent(chan,q=1,ott=1,time=(Val1,Val2)) tanLock= mc.keyTangent (chan,q=1,lock=1,time=(Val1,Val2)) weightLock=mc.keyTangent(chan,q=1,weightLock=1,time=(Val1,Val2)) breakDown= mc.keyframe (chan,q=1,breakdown=1,time=(Val1,Val2)) inAngle= mc.keyTangent (chan,q=1,inAngle=1,time=(Val1,Val2)) outAngle= mc.keyTangent (chan,q=1,outAngle=1,time=(Val1,Val2)) inWeight= mc.keyTangent (chan,q=1,inWeight=1,time=(Val1,Val2)) outWeight= mc.keyTangent (chan,q=1,outWeight=1,time=(Val1,Val2)) for i in range (len(keys)): bd=0 if breakDown!=None: for bd_item in breakDown: if bd_item == keys[i]: bd=1 fileID.write(' ' + str(keys[i]) + ' ' + str(values[i])+ ' ' + str(inTan[i]) + ' ' + str(outTan[i]) + ' ' + str(tanLock[i]) + ' ' + str(weightLock[i]) + ' ' + str(bd)) if inTan[i]=='fixed': fileID.write(' ' + str(inAngle[i]) + ' ' + str(inWeight[i])) if outTan[i]=='fixed': fileID.write(' ' + str(outAngle[i]) + ' ' + str(outWeight[i])) fileID.write('\n') fileID.write(' }\n}\n') staticChans = mc.listAnimatable(item) for staticChan in staticChans: curAttr = staticChan curattr = curAttr.split('.') num = len(curattr) buffer=curattr num = num - 1 node='' for i in range(num): if i==0: node=buffer[i] else: node=node+'.'+buffer[i] nodeTemp=[] nodeTemp = mc.ls(node) attr = buffer[num] node = nodeTemp[0] nodeTemp = mc.listRelatives(node,p=1) if nodeTemp != None : parent1 = 1 elif nodeTemp == None : parent1 = 0 staticChan = (node + "." + attr) testit = mc.keyframe (staticChan,q=1) connected = mc.listConnections(staticChan,d=0) if not testit and not connected : fileID.write('static ' + attr + ' ' + attr + ' ' + node + ' ' + str(parent1) + ' ' + str(mc.getAttr(staticChan)) + '\n') fileID.write('End of Anim') fileID.close() mc.select(clear = True) for item in sel_obj: mc.select(item, toggle = True) print "\nDone Writing Animation Curves\n" #print frm_rang mc.shelfButton(Anim_newname,i1=newAnimIconFile,w=110,h=80,l=Anim_newname,bgc=(.2,.6,.3),st='iconAndTextVertical',p=(seltab5),c=partial(Importanim,animpath2)) Refresh_UI(savepathini) mc.shelfTabLayout('tabs',e=1,st=Animation) mc.shelfTabLayout('Animation',e=1,st=seltab5) animposewinclose()
def writeAnimFile(animFile, animNodes=[]): ''' Write pose data to file. @param poseFile: Destination pose file @type poseFile: str @param poseNodes: List of nodes to save pose data for @type poseNodes: list ''' # Initialize First Frame Value firstKeyTime = 1000000 # Open File for Writing print('\nWriting Animation Curves...\n') f = open(animFile, 'w') f.write('# Generated by VFX animLib\n#\n') f.write('# dkAnim written by Daniel Kramer MOD by Mark Behm\n#\n') f.write('# Source workfile: ' + mc.file(q=True, sn=True) + '\n#\n\n') for item in animNodes: # Get Animated Channels channels = mc.listConnections(item, s=True, d=False, p=True, c=True, type='animCurve') for i in range(0, len(channels), 2): chan = mc.ls(channels[i], o=True)[0] node = mc.ls(channels[i + 1], o=True)[0] attr = channels[i + 1].split('.')[-1] attrName = channels[i + 1] parent = 0 nodeParent = mc.listRelatives(node, p=True) if nodeParent: parent = 1 # Infinity infValue = [ 'constant', 'linear', 'constant', 'cycle', 'cycleRelative', 'oscillate' ] preIn = infValue[mc.getAttr(chan + '.preInfinity')] postInf = infValue[mc.getAttr(chan + '.postInfinity')] # Weighted weighted = int(mc.getAttr(chan + '.weightedTangents')) # ==================== # - Write Curve Data - # ==================== f.write('anim ' + attr + ' ' + attr + ' ' + node + ' ' + parent + ' 0 0;\n') f.write('animData {\n') f.write(' weighted ' + str(weighted) + ';\n') f.write(' preInfinity ' + preIn + ';\n') f.write(' postInfinity ' + postIn + ';\n') f.write(' keys {\n') # ================== # - Write Key Data - # ================== # Get Key Data keys = mc.keyframe(chan, q=True) values = mc.keyframe(chan, q=True, vc=True) inTan = mc.keyTangent(chan, q=True, itt=True) outTan = mc.keyTangent(chan, q=True, ott=True) tanLock = mc.keyTangent(chan, q=True, lock=True) weightLock = mc.keyTangent(chan, q=True, weightLock=True) breakDown = mc.keyframe(chan, q=True, breakdown=True) inAngle = mc.keyTangent(chan, q=True, inAngle=True) outAngle = mc.keyTangent(chan, q=True, outAngle=True) inWeight = mc.keyTangent(chan, q=True, inWeight=True) outWeight = mc.keyTangent(chan, q=True, outWeight=True) # Write Key Data for i in range(len(keys)): # Get Breakdown Status bd = int(bool(keys[i] in breakDown)) # First Key if keys[i] < firstKeyTime: firstKeyTime = keys[i] # Write Key Data to File f.write(' ' + str(keys[i]) + ' ' + str(values[i]) + ' ' + inTan[i] + ' ' + outTan[i] + ' ' + str(tanLock[i]) + ' ' + str(weightLock[i]) + ' ' + str(bd)) if inTan[i] == 'fixed': f.write(' ' + str(inAngle[i]) + ' ' + str(inWeight[i])) if outTan[i] == 'fixed': f.write(' ' + str(outAngle[i]) + ' ' + str(outWeight[i])) f.write(';\n') f.write(' }\n}\n') # ========================= # - Write Static Channels - # ========================= staticChans = mc.listAnimatable(item) for staticChan in staticChans: node = mc.ls(staticChan, o=True)[0] attr = staticChan.split('.')[-1] parent = 0 nodeParent = mc.listRelatives(node, p=True) if nodeParent: parent = 1 #staticChan = node+'.'+attr keys = mc.keyframe(staticChan, q=True) connected = mc.listConnections(staticChan, s=True) if not keys and not connected: f.write('static ' + attr + ' ' + attr + ' ' + node + ' ' + parent + ' ' + str(mc.getAttr(staticChan)) + '\n') # Record First Key Offset f.write('firstKeyTime ' + str(firstKeyTime)) # Close File f.close() # ================= # - Return Result - # ================= print '\nDone Writing Animation Curves\n' return animFile
def recordStop(self): cmds.play(state=False) self.removeAttrsToRecord(\ [attr.split('.')[-1] for attr in cmds.listAnimatable(cmds.ls(sl=True))])
def writeAnimFile(animFile,animNodes=[]): ''' Write pose data to file. @param poseFile: Destination pose file @type poseFile: str @param poseNodes: List of nodes to save pose data for @type poseNodes: list ''' # Initialize First Frame Value firstKeyTime = 1000000 # Open File for Writing print('\nWriting Animation Curves...\n') f = open(animFile,'w') f.write('# Generated by VFX animLib\n#\n') f.write('# dkAnim written by Daniel Kramer MOD by Mark Behm\n#\n') f.write('# Source workfile: '+mc.file(q=True,sn=True)+'\n#\n\n') for item in animNodes: # Get Animated Channels channels = mc.listConnections(item,s=True,d=False,p=True,c=True,type='animCurve') for i in range(0,len(channels),2): chan = mc.ls(channels[i],o=True)[0] node = mc.ls(channels[i+1],o=True)[0] attr = channels[i+1].split('.')[-1] attrName = channels[i+1] parent = 0 nodeParent = mc.listRelatives(node,p=True) if nodeParent: parent = 1 # Infinity infValue = ['constant','linear','constant','cycle','cycleRelative','oscillate'] preIn = infValue[mc.getAttr(chan+'.preInfinity')] postInf = infValue[mc.getAttr(chan+'.postInfinity')] # Weighted weighted = int(mc.getAttr(chan+'.weightedTangents')) # ==================== # - Write Curve Data - # ==================== f.write('anim '+attr+' '+attr+' '+node+' '+parent+' 0 0;\n') f.write('animData {\n') f.write(' weighted '+str(weighted)+';\n') f.write(' preInfinity '+preIn+';\n') f.write(' postInfinity '+postIn+';\n') f.write(' keys {\n') # ================== # - Write Key Data - # ================== # Get Key Data keys = mc.keyframe(chan,q=True) values = mc.keyframe(chan,q=True,vc=True) inTan = mc.keyTangent(chan,q=True,itt=True) outTan = mc.keyTangent(chan,q=True,ott=True) tanLock = mc.keyTangent(chan,q=True,lock=True) weightLock = mc.keyTangent(chan,q=True,weightLock=True) breakDown = mc.keyframe(chan,q=True,breakdown=True) inAngle = mc.keyTangent(chan,q=True,inAngle=True) outAngle = mc.keyTangent(chan,q=True,outAngle=True) inWeight = mc.keyTangent(chan,q=True,inWeight=True) outWeight = mc.keyTangent(chan,q=True,outWeight=True) # Write Key Data for i in range(len(keys)): # Get Breakdown Status bd = int(bool(keys[i] in breakDown)) # First Key if keys[i] < firstKeyTime: firstKeyTime = keys[i] # Write Key Data to File f.write(' '+str(keys[i])+' '+str(values[i])+' '+inTan[i]+' '+outTan[i]+' '+str(tanLock[i])+' '+str(weightLock[i])+' '+str(bd)) if inTan[i] == 'fixed': f.write(' '+str(inAngle[i])+' '+str(inWeight[i])) if outTan[i] == 'fixed': f.write(' '+str(outAngle[i])+' '+str(outWeight[i])) f.write(';\n') f.write(' }\n}\n') # ========================= # - Write Static Channels - # ========================= staticChans = mc.listAnimatable(item) for staticChan in staticChans: node = mc.ls(staticChan,o=True)[0] attr = staticChan.split('.')[-1] parent = 0 nodeParent = mc.listRelatives(node,p=True) if nodeParent: parent = 1 #staticChan = node+'.'+attr keys = mc.keyframe(staticChan,q=True) connected = mc.listConnections(staticChan,s=True) if not keys and not connected: f.write('static '+attr+' '+attr+' '+node+' '+parent+' '+str(mc.getAttr(staticChan))+'\n') # Record First Key Offset f.write('firstKeyTime '+str(firstKeyTime)) # Close File f.close() # ================= # - Return Result - # ================= print '\nDone Writing Animation Curves\n' return animFile
def slice_curves(): sel = cmds.ls(sl=1) if not sel: return None objects_to_skip = [] # Does the object have a key on it to begin with? for obj in sel: shape_keyables = [] shapes = cmds.listRelatives(obj, shapes=True) for shape in shapes: # shape = 'ARCT_WelderBot_01_rig:backFoot_01FK_L_CTRLShape1' keyCountShape = cmds.keyframe(shape, q=True, kc=True, shape=True) found = cmds.listAnimatable(shape) or [] if found and not keyCountShape: shape_keyables.append(shape) keyCountCtrl = cmds.keyframe(obj, q=True, kc=True, shape=False) if shape_keyables: keyCountShape = cmds.keyframe(shape_keyables, q=True, kc=True, shape=True) if keyCountCtrl == 0 and keyCountShape > 0: # Keys on the shape node but not on the ctrl cmds.setKeyframe(obj, breakdown=False, hierarchy='none', controlPoints=False, shape=False) objects_to_skip.append(obj) if keyCountCtrl == 0 and keyCountShape == 0: cmds.setKeyframe(obj, breakdown=False, hierarchy='none', controlPoints=False, shape=True) objects_to_skip.append(obj) if keyCountCtrl > 0 and keyCountShape == 0: for shape in shape_keyables: cmds.setKeyframe(shape, breakdown=False, hierarchy='none', controlPoints=False, shape=True) else: keyCountCtrl = cmds.keyframe(obj, q=True, kc=True, shape=False) if not keyCountCtrl: cmds.setKeyframe(obj, breakdown=False, hierarchy='none', controlPoints=False, shape=False) # Get selected curves in GE selectedCurves = cmds.keyframe(selected=True, q=True, name=True) or [] # return curves of selected keys if selectedCurves: cmds.setKeyframe(selectedCurves, insert=True) return True # Get selection from GE_outliner # ge_outliner_selection = mel.eval("string $temp[] = `selectionConnection -q -object graphEditor1FromOutliner`;") # if ge_outliner_selection: # cmds.setKeyframe(ge_outliner_selection, insert=True) # return True # Get selection from channelbox channelbox_selection = [] cb_attr_main, cb_attr_shapes = _get_selected_channels() if cb_attr_main: for obj in sel: for attr in cb_attr_main: if cmds.objExists(obj + "." + attr): channelbox_selection.append(obj + "." + attr) if cb_attr_shapes: for obj in sel: shape_nodes = cmds.listRelatives(obj, shapes=True) for shape_node in shape_nodes: for attr in cb_attr_shapes: if cmds.objExists(shape_node + "." + attr): channelbox_selection.append(shape_node + "." + attr) if channelbox_selection: for attr in channelbox_selection: if cmds.keyframe(attr, q=True, kc=True): cmds.setKeyframe(channelbox_selection, insert=True) else: cmds.setKeyframe(channelbox_selection) return True # Ok, maybe no selection. Just insert all the ones we didn't initially do a setkey for obj in sel: if obj not in objects_to_skip: cmds.setKeyframe(obj, insert=True, shape=True) '''
def recordStop(self): cmds.play(state=False) self.removeAttrsToRecord([attr.split('.')[-1] for attr in cmds.listAnimatable(cmds.ls(sl=True))])
def channelBoxCommand(self, operation, *args): channelSel = cmds.channelBox(self.cb1, query=True, sma=True) objSel = cmds.ls(sl=True) # reset default channels transformChannels = ["translateX", "translateY", "translateZ", "rotateX", "rotateY", "rotateZ"] scaleChannels = ["scaleX", "scaleY", "scaleZ", "visibility"] if (operation == "-channelEditor"): mel.eval("lockingKeyableWnd;") elif (operation == "-setAllToZero"): for obj in objSel: for channel in transformChannels: cmds.setAttr(obj + "." + channel, 0) for channel in scaleChannels: cmds.setAttr(obj + "." + channel, 1) # reset created channels for obj in objSel: createdChannels = [] allChannels = cmds.listAnimatable(obj) for channel in allChannels: attrName = channel.split(".")[-1] createdChannels.append(attrName) channels = list(set(createdChannels) - set(transformChannels) - set(scaleChannels)) for channel in channels: defaultValue = cmds.addItem(obj + "." + channel, query=True, dv=True) cmds.setAttr(obj + "." + channel, defaultValue) elif (operation == "-keySelected"): print 'Channel Box', channelSel, objSel for obj in objSel: for channel in channelSel: cmds.setKeyframe(obj + "." + channel) elif (operation == "-keyAll"): for obj in objSel: allChannels = cmds.listAnimatable(obj) cmds.select(obj) for channel in allChannels: cmds.setKeyframe(channel) elif (operation == "-breakDownSelected"): for obj in objSel: for channel in channelSel: cmds.setKeyframe(obj + "." + channel, breakdown=True) elif (operation == "-breakDownAll"): for obj in objSel: allChannels = cmds.listAnimatable(obj) cmds.select(obj) for channel in allChannels: cmds.setKeyframe(channel, breakdown=True) elif (operation == "-cutSelected") or (operation == "-deleteSelected"): for obj in objSel: for channel in channelSel: cmds.cutKey(obj, at=channel) elif (operation == "-copySelected"): for obj in objSel: for channel in channelSel: cmds.copyKey(obj, at=channel) elif (operation == "-pasteSelected"): for obj in objSel: for channel in channelSel: cmds.pasteKey(obj, connect=True, at=channel) elif (operation == "-breakConnection"): for obj in objSel: for channel in channelSel: attr = obj + "." + channel mel.eval("source channelBoxCommand; CBdeleteConnection \"%s\"" % attr) elif (operation == "-lockSelected"): for obj in objSel: for channel in channelSel: cmds.setAttr(obj + "." + channel, lock=True) elif (operation == "-unlockSelected"): for obj in objSel: for channel in channelSel: cmds.setAttr(obj + "." + channel, lock=False) elif (operation == "-hideSelected"): for obj in objSel: for channel in channelSel: cmds.setAttr(obj + "." + channel, keyable=False, channelBox=False) elif (operation == "-lockAndHideSelected"): for obj in objSel: for channel in channelSel: cmds.setAttr(obj + "." + channel, lock=True) cmds.setAttr(obj + "." + channel, keyable=False, channelBox=False) elif (operation == "-unhideHided"): # channelBoxChannels = transformChannels + scaleChannels for obj in objSel: # for channel in channelBoxChannels: # cmds.setAttr( obj + "." + channel, l=False, k=True ) # get locked channel lockChannels = cmds.listAttr(obj, locked=True) if lockChannels == None: message = "nothing is locked" self.warningPopup(message) break else: for channel in lockChannels: cmds.setAttr(obj + "." + channel, keyable=True, channelBox=True) elif (operation == "-showDefault"): for obj in objSel: defaultChannel = ["tx", "ty", "tz", "rx", "ry", "rz", "sx", "sy", "sz"] for channel in defaultChannel: cmds.setAttr(obj + "." + channel, k=True, cb=True) elif (operation == "-expression"): mel.eval('expressionEditor EE "" "";') elif (operation == "-unhideHided"): mel.eval('SetDrivenKeyOptions;') elif (operation == "-deleteAttribute"): for obj in objSel: for channel in channelSel: cmds.deleteAttr(obj, at=channel) elif (operation == "-about"): cmds.confirmDialog(t="About DAMG Controller Maker", m=("Thank you for using my script :D\n" "Made by Do Trinh - JimJim\n" "Please feel free to give your feedback\n" "Email me: [email protected]\n"), b="Close")
def extract_world_space_data(): ''' Extracts the world space data from the objects that were loaded into selections ''' # Double check target availability available_ctrls = [] for obj in gt_world_space_baker_settings.get('stored_elements'): if cmds.objExists(obj): available_ctrls.append(obj) # Store Current Time original_time = cmds.currentTime(q=True) # Last Validation is_valid = True if available_ctrls == 0: is_valid = False cmds.warning( 'Loaded objects couldn\'t be found. Please review your settings and try again' ) elif gt_world_space_baker_settings.get( 'start_time_range') >= gt_world_space_baker_settings.get( 'end_time_range'): is_valid = False cmds.warning( 'Starting frame can\'t be higher than ending frame. Review your animation range settings and try again.' ) # Extract Keyframes: if is_valid: for obj in available_ctrls: attributes = cmds.listAnimatable(obj) needs_ws_transforms = True frame_translate_values = [] frame_rotate_values = [] for attr in attributes: try: # short_attr = attr.split('.')[-1] # frames = cmds.keyframe(obj, q=1, at=short_attr) # values = cmds.keyframe(obj, q=1, at=short_attr, valueChange=True) # in_angle_tangent = cmds.keyTangent(obj, at=short_attr, inAngle=True, query=True) # out_angle_tanget = cmds.keyTangent(obj, at=short_attr, outAngle=True, query=True) # is_locked = cmds.keyTangent(obj, at=short_attr, weightLock=True, query=True) # in_weight = cmds.keyTangent(obj, at=short_attr, inWeight=True, query=True) # out_weight = cmds.keyTangent(obj, at=short_attr, outWeight=True, query=True) # in_tangent_type = cmds.keyTangent(obj, at=short_attr, inTangentType=True, query=True) # out_tangent_type = cmds.keyTangent(obj, at=short_attr, outTangentType=True, query=True) # gt_world_space_baker_anim_storage['{}.{}'.format(obj, short_attr)] = zip(frames, values, in_angle_tangent, out_angle_tanget, is_locked, in_weight, out_weight, in_tangent_type, out_tangent_type) # WS Values # Translate and Rotate for the desired frame range if 'translate' in attr or 'rotate' in attr: if needs_ws_transforms: cmds.currentTime( gt_world_space_baker_settings.get( 'start_time_range')) for index in range( gt_world_space_baker_settings.get( 'end_time_range') - gt_world_space_baker_settings.get( 'start_time_range') + 1): frame_translate_values.append([ cmds.currentTime(q=True), cmds.xform(obj, ws=True, q=True, t=True) ]) frame_rotate_values.append([ cmds.currentTime(q=True), cmds.xform(obj, ws=True, q=True, ro=True) ]) cmds.currentTime(cmds.currentTime(q=True) + 1) needs_ws_transforms = False if attr.split('.')[-1].startswith('translate'): gt_world_space_baker_anim_storage['{}.{}'.format( obj, 'translate')] = frame_translate_values if attr.split('.')[-1].startswith('rotate'): gt_world_space_baker_anim_storage['{}.{}'.format( obj, 'rotate')] = frame_rotate_values # if attr.endswith('X'): # channel_index = 0 # channel_str = 'X' # elif attr.endswith('Y'): # channel_index = 1 # channel_str = 'Y' # elif attr.endswith('Z'): # channel_index = 2 # channel_str = 'Z' # if attr.split('.')[-1].startswith('translate'): # desired_data = [] # for frame_translate in frame_translate_values: # desired_data.append([frame_translate[0], frame_translate[1][channel_index]]) # gt_world_space_baker_anim_storage['{}.{}'.format(obj, 'translate' + channel_str)] = desired_data # if attr.split('.')[-1].startswith('rotate'): # desired_data = [] # for frame_translate in frame_translate_values: # desired_data.append([frame_translate[0], frame_translate[1][channel_index]]) # gt_world_space_baker_anim_storage['{}.{}'.format(obj, 'rotate' + channel_str)] = desired_data except: pass # 0 keyframes cmds.currentTime(original_time) return True
def writeAnimFile(animFile, animNodes=[]): """ Write pose data to file. @param poseFile: Destination pose file @type poseFile: str @param poseNodes: List of nodes to save pose data for @type poseNodes: list """ # Initialize First Frame Value firstKeyTime = 1000000 # Open File for Writing print ("\nWriting Animation Curves...\n") f = open(animFile, "w") f.write("# Generated by VFX animLib\n#\n") f.write("# dkAnim written by Daniel Kramer MOD by Mark Behm\n#\n") f.write("# Source workfile: " + cmds.file(q=True, sn=True) + "\n#\n\n") for item in animNodes: # Get Animated Channels channels = cmds.listConnections(item, s=True, d=False, p=True, c=True, type="anicmdsurve") for i in range(0, len(channels), 2): chan = cmds.ls(channels[i], o=True)[0] node = cmds.ls(channels[i + 1], o=True)[0] attr = channels[i + 1].split(".")[-1] attrName = channels[i + 1] parent = 0 nodeParent = cmds.listRelatives(node, p=True) if nodeParent: parent = 1 # Infinity infValue = ["constant", "linear", "constant", "cycle", "cycleRelative", "oscillate"] preIn = infValue[cmds.getAttr(chan + ".preInfinity")] postInf = infValue[cmds.getAttr(chan + ".postInfinity")] # Weighted weighted = int(cmds.getAttr(chan + ".weightedTangents")) # ==================== # - Write Curve Data - # ==================== f.write("anim " + attr + " " + attr + " " + node + " " + parent + " 0 0;\n") f.write("animData {\n") f.write(" weighted " + str(weighted) + ";\n") f.write(" preInfinity " + preIn + ";\n") f.write(" postInfinity " + postIn + ";\n") f.write(" keys {\n") # ================== # - Write Key Data - # ================== # Get Key Data keys = cmds.keyframe(chan, q=True) values = cmds.keyframe(chan, q=True, vc=True) inTan = cmds.keyTangent(chan, q=True, itt=True) outTan = cmds.keyTangent(chan, q=True, ott=True) tanLock = cmds.keyTangent(chan, q=True, lock=True) weightLock = cmds.keyTangent(chan, q=True, weightLock=True) breakDown = cmds.keyframe(chan, q=True, breakdown=True) inAngle = cmds.keyTangent(chan, q=True, inAngle=True) outAngle = cmds.keyTangent(chan, q=True, outAngle=True) inWeight = cmds.keyTangent(chan, q=True, inWeight=True) outWeight = cmds.keyTangent(chan, q=True, outWeight=True) # Write Key Data for i in range(len(keys)): # Get Breakdown Status bd = int(bool(keys[i] in breakDown)) # First Key if keys[i] < firstKeyTime: firstKeyTime = keys[i] # Write Key Data to File f.write( " " + str(keys[i]) + " " + str(values[i]) + " " + inTan[i] + " " + outTan[i] + " " + str(tanLock[i]) + " " + str(weightLock[i]) + " " + str(bd) ) if inTan[i] == "fixed": f.write(" " + str(inAngle[i]) + " " + str(inWeight[i])) if outTan[i] == "fixed": f.write(" " + str(outAngle[i]) + " " + str(outWeight[i])) f.write(";\n") f.write(" }\n}\n") # ========================= # - Write Static Channels - # ========================= staticChans = cmds.listAnimatable(item) for staticChan in staticChans: node = cmds.ls(staticChan, o=True)[0] attr = staticChan.split(".")[-1] parent = 0 nodeParent = cmds.listRelatives(node, p=True) if nodeParent: parent = 1 # staticChan = node+'.'+attr keys = cmds.keyframe(staticChan, q=True) connected = cmds.listConnections(staticChan, s=True) if not keys and not connected: f.write( "static " + attr + " " + attr + " " + node + " " + parent + " " + str(cmds.getAttr(staticChan)) + "\n" ) # Record First Key Offset f.write("firstKeyTime " + str(firstKeyTime)) # Close File f.close() # ================= # - Return Result - # ================= print "\nDone Writing Animation Curves\n" return animFile