def createAnimClips(fileRef): fileN = mc.file(q=True, sn=True) exec("print fileN") for i, f in enumerate(fileRef): if i < len(fileRef) - 1: mc.file(new=True, force=True) mc.file(fileN, o=1) importFile(f) root = "Root_M" mc.select(root, hi=True) mc.BakeSimulation() mc.select("boy", r=True) tempN = f.split("/") fNameTemp = tempN[len(tempN) - 1] fNameAlmost = fNameTemp.split(".") fName = fNameAlmost[0] fname = fName.replace(" ", "") exec("print fName") mc.clip(n=fname + "clip", sc=1, animCurveRange=True) #mc.select(fname+"clip", r=True) # exec("doExportClipArgList 1 {'clipEditorPanel1ClipEditor'}") mc.file( "C:/Users/red_w/Documents/maya/projects/default/clips/boy/" + fName + ".ma", es=True, type="mayaAscii")
def make_Clip_from_MotionCaptureData(): _clipName = mel.eval( 'basenameEx(`file -q -sn`)') _Char = 'Clip' # make Character _bodyJoints = [ 'HipsTranslation','Hips','Spine','Spine1','Spine2','Spine3','Neck','Head', 'LeftShoulder','LeftArm','LeftArmRoll','LeftForeArm','LeftForeArmRoll','LeftHand', 'LeftUpLeg','LeftUpLegRoll','LeftLeg','LeftLegRoll','LeftFoot','LeftToeBase', 'RightShoulder','RightArm','RightArmRoll','RightForeArm','RightForeArmRoll','RightHand', 'RightUpLeg','RightUpLegRoll','RightLeg','RightLegRoll','RightFoot','RightToeBase' ] _attrList = ['tx','ty','tz','rx','ry','rz'] cmds.character(name=_Char) # tr, rt 속성 추가 for _jnt in _bodyJoints: for _attr in _attrList: cmds.character(_jnt+'.'+_attr ,forceElement=_Char) _attrList = ['tx','ty','tz'] # tr속성 제거 for _jnt in _bodyJoints: if _jnt == 'HipsTranslation' or _jnt == 'Hips': continue for _attr in _attrList: cmds.character( _jnt+'.'+_attr , remove=_Char ) # 애니메이션 클립 생성 cmds.clip(_Char, name=_clipName, scheduleClip=True, allAbsolute=True, animCurveRange=True)
def build( self ): for channel in self._action.curves.keys(): curve = self._action.curves[channel] tokens = channel.split() if len(tokens) == 1: object = self._mayaAgent.skelGroup attr = tokens[0] else: object = self._mayaAgent.mayaJoint(tokens[0]).name attr = tokens[1] if not attr in kAnimatableAttrs: # TODO: figure out how to handle non rot/trans attrs continue if object == self._mayaAgent.skelGroup: # TODO: handle _agent animation... are these "agent curves"? continue channelAttr = "%s.%s" % (object, attr) offset = mc.getAttr(channelAttr) for key in curve.points: mc.setKeyframe( object, attribute=attr, inTangentType="linear", outTangentType="linear", time=key[0] * self._action.maxPoints, value=key[1] + offset) clip = mc.clip(self._mayaAgent.characterSet, startTime=0, endTime=self._action.maxPoints, allRelative=True, scheduleClip=False) mc.clip(self._mayaAgent.characterSet, name=clip, newName=self._action.name)
def createClip(charSet, startTime=None, endTime=None, name=''): ''' Create a clip from the specified character set @param charSet: Object to check as anim clip @type charSet: str @param startTime: Start time for clip. If None, use timeline start frame. @type startTime: int @param endTime: End time for clip. If None, use timeline end frame. @type endTime: int @param name: Clip name @type name: str ''' # ========== # - Checks - # ========== # Check Character Set if not glTools.utils.characterSet.isCharSet(charSet): raise Exception('Object "' + charSet + '" is not a valid character set!') # Check Name if not name: name = 'clip' # Check Start/End Time if (startTime == None) or (endTime == None): charList = mc.sets(charSet, q=True) charKeys = mc.keyframe(charList, q=True, tc=True) charKeys.sort() if startTime == None: startTime = charKeys[0] if endTime == None: endTime = charKeys[-1] # =============== # - Create Clip - # =============== clip = [''] try: clip = mc.clip(charSet, startTime=startTime, endTime=endTime, name=name) except: print('Error creating clip "' + name + '"!') else: print('Clip "' + name + '" successfully created!') # ================= # - Return Result - # ================= return str(clip[0])
def createClip(charSet, startTime=None, endTime=None, name=''): """ Create a clip from the specified character set @param charSet: Object to check as anim clip @type charSet: str @param startTime: Start time for clip. If None, use timeline start frame. @type startTime: int @param endTime: End time for clip. If None, use timeline end frame. @type endTime: int @param name: Clip name @type name: str """ # ========== # - Checks - # ========== # Check Character Set if not glTools.utils.characterSet.isCharSet(charSet): raise Exception('Object "' + charSet + '" is not a valid character set!') # Check Name if not name: name = 'clip' # Check Start/End Time if (startTime == None) or (endTime == None): charList = cmds.sets(charSet, q=True) charKeys = cmds.keyframe(charList, q=True, tc=True) charKeys.sort() if startTime == None: startTime = charKeys[0] if endTime == None: endTime = charKeys[-1] # =============== # - Create Clip - # =============== clip = [''] try: clip = cmds.clip(charSet, startTime=startTime, endTime=endTime, name=name) except: print('Error creating clip "' + name + '"!') else: print('Clip "' + name + '" successfully created!') # ================= # - Return Result - # ================= return str(clip[0])
def placeCrowd( clipSources = [] ) : sels = mc.ls( sl=True ) clipSources = [ 'urukRunSwordLeft1Source' , 'urukRunSwordRight1Source' ] clipNum = len( clipSources ) - 1 for clip in clipSources : mc.setAttr( '%s.preCycle'%clip , 100 ) mc.setAttr( '%s.postCycle'%clip , 100 ) mc.setAttr( '%s.scale'%clip , 1.3 ) for ix in range( len( sels ) ) : currClip = clipSources[ random.randint( 0 , clipNum ) ] mc.clip( currClip , c=True ) currNs = 'urukA%sCrowd'%ix mc.file( '/dsPipe/Lego_LOTR/Asset/Char/Animal/urukhaiA/Dev/Maya/wip/urukhaiLow.ma' , r=True , ns=currNs , options='v=0' ) currRoot = '%s:rig_grp'%currNs mc.delete( mc.parentConstraint( sels[ ix ] , currRoot ) ) mc.parent( currRoot , sels[ ix ] ) mc.clip( '%s:uruk_character'%currNs , pasteInstance=True , sc=1 , s=random.randint(0,11) , mapMethod='byAttrName' )
def build(self): for channel in self._action.curves.keys(): curve = self._action.curves[channel] tokens = channel.split() if len(tokens) == 1: object = self._mayaAgent.skelGroup attr = tokens[0] else: object = self._mayaAgent.mayaJoint(tokens[0]).name attr = tokens[1] if not attr in kAnimatableAttrs: # TODO: figure out how to handle non rot/trans attrs continue if object == self._mayaAgent.skelGroup: # TODO: handle _agent animation... are these "agent curves"? continue channelAttr = "%s.%s" % (object, attr) offset = mc.getAttr(channelAttr) for key in curve.points: mc.setKeyframe(object, attribute=attr, inTangentType="linear", outTangentType="linear", time=key[0] * self._action.maxPoints, value=key[1] + offset) clip = mc.clip(self._mayaAgent.characterSet, startTime=0, endTime=self._action.maxPoints, allRelative=True, scheduleClip=False) mc.clip(self._mayaAgent.characterSet, name=clip, newName=self._action.name)
print char animlist=os.listdir(projpath+char+"\Animation\\") print animlist for eachanim in animlist: if "meta" not in eachanim: AllAnimList.append(eachanim) for each in AllAnimList: # char=each.split('@')[0] anim=(each.split('@')[1]).strip(".fbx") mc.file(new=1,f=1) mc.file(projpath+char+'\Animation\\'+ each,i=1,ifr=1,itr='override') mc.select("Root",hi=1) mc.character(n=char) animclip=mc.clip( char, acr=1, n=anim )[0] mc.select(animclip) melcmd='clipEditorExportClip("C:/Users/Ji/Desktop/RogueRacers/AnimationClips/'+char+'@'+anim+ '","ma")' mel.eval(melcmd) # mc.file("C:\Users\Ji\Desktop\RogueRacers\\"+ char + ".ma" ,i=1,ifr=1,itr='override') # for eachfile in animlist: # mc.file(new=1,f=1)
def AnimExport(): if cmds.objExists('imagePlane1'): cmds.hide('imagePlane1') cmds.hide('*_LOC') # делаю несколько проверок # создан ли character set if cmds.objExists('default_character'): if cmds.objExists('*Source'): activeClipCheck = cmds.clip('default_character', active = True, q = True) if activeClipCheck != 'default': cmds.select(animName + 'Source') cmds.select(GetInfo.charSet + 'Clips1', add = True) cmds.select(GetInfo.animCurvesList, add = True) # делаю экспорт clip в .ma cmds.file(GetInfo.clipPath + GetInfo.animName + '.ma', type='mayaAscii', exportSelected=True) # делаю экспорт анимации в .atom maxTime = cmds.playbackOptions( q = True, maxTime = True) cmds.select(ctrlsList) mel.eval('string $animName = `python "animName"`;') mel.eval('string $maxTime = `python "maxTime"`;') mel.eval('loadPlugin atomImportExport') mel.eval('file -force -options "precision=8;statics=1;baked=0;sdk=0;constraint=0;animLayers=1;selected=selectedOnly;whichRange=1;range=1:$maxTime;hierarchy=none;controlPoints=1;useChannelBox=1;options=keys;copyKeyCmd=-animation objects -option keys -hierarchy none -controlPoints 1 " -typ "atomExport" -es ("z:/.src/shared/chr/_face/.anims_atom/" + $animName + ".atom");') # сжимаю анимацию в два раза, чтобы она соответствовала реальному времени cmds.select(ctrlsList) cmds.scaleKey(iub = False, ts = 0.5, tp = 1, fs = 0.5, fp = 1, vs = 1, vp = 0) # задаю новые границы timeline maxTime = (cmds.playbackOptions( q = True, maxTime = True)/2) maxTime = round(maxTime) cmds.playbackOptions(maxTime = int(maxTime)) # делаю экспорт видео для просмотра cmds.playblast(fo = True, v= False, fmt = 'movie', f = 'z:/.src/shared/chr/_face/.anims_preview_database/' + animName + '.avi' ) # делаю проверку на объекты, которые не подходят к названию # нужна только для старых анимаций, созданых раньше июля 2015 if cmds.objExists('eyes_CTRL'): cmds.rename('eyes_CTRL', 'eyes_ctrl') # Удаляю группу и локаторы костей языка # Временно, пока не настроил их if cmds.objExists('tongue_1_GRP'): cmds.delete('tongue_1_GRP', 'tongue_2_GRP') # создаю переменные, где храню значение начала и конца timeline currEndTime = cmds.playbackOptions( q=True, maxTime=True ) currStartTime = cmds.playbackOptions( q=True, minTime=True ) # выделяю все лицевые контроллеры cmds.select(ctrlsList) cmds.currentTime(currStartTime, edit=True) cmds.setKeyframe(ctrlsList) cmds.currentTime(currEndTime, edit=True) cmds.setKeyframe(ctrlsList) # смещаю ключи на 10 кадров вперед относительно их позиции cmds.keyframe(edit=True, relative = True, timeChange = (0 + 10)) # задаю новые границы timeline currEndTime += 20 cmds.playbackOptions( minTime=0, maxTime=currEndTime ) # создаю функцию, которая обнуляю все каналы объектов из списка def SetKeysToZero(): global ctrlsList for ctrl in ctrlsList: attrs = cmds.listAttr(ctrl, k=True) #создает список атрибутов для каждого из выделенных объектов for attr in attrs: #для каждого атрибута из списка атрибутов if attr != "visibility": #если он не называется cmds.setAttr(ctrl + "." + attr, 0) #имя объекта+точка+название атрибута равняется нулю # ставлю нулевые ключи лицевых контроллеров вначале и конце timeline cmds.currentTime(currStartTime, edit=True) SetKeysToZero() cmds.currentTime(currEndTime, edit=True) SetKeysToZero() # запекаю анимации на timeline для всех костей fullSkeletonList = cmds.ls(type = 'joint') cmds.select(fullSkeletonList) cmds.bakeResults(fullSkeletonList, t=(currStartTime,currEndTime), simulation=True, sb=1) # перевожу переменные pytjon в mel mel.eval('string $animName = `python "animName"`;') mel.eval('string $animFBXPath = `python "animFBXPath"`;') # делаю экспорт выделенных костей в .fbx с именем файла fullSkeletonList = cmds.ls(type = 'joint') cmds.select(fullSkeletonList) mel.eval('FBXExportConstraints -v 0') mel.eval('FBXLoadExportPresetFile -f "c:/Users/user/Documents/maya/FBX/Presets/2014.1/export/AnimationOnly.fbxexportpreset"') mel.eval('FBXExport -f ($animFBXPath + $animName + ".fbx") -s') # создаю лог работы print '\n---------- export log:----------\n' if os.path.exists(atomPath + animName + '.atom'): print '.atom exported' else: print '.atom NOT exported' if os.path.exists(clipPath + animName + '.ma'): print '.ma exported' else: print '.ma NOT exported' if os.path.exists(animPreviewPath + animName + '.avi'): print '.avi exported' else: print '.avi NOT exported' if os.path.exists(animFBXPath + animName + '.fbx'): print '.fbx exported' else: print '.fbx NOT exported'