def doTest2(): minTime = om.MTime() maxTime = om.MTime() currentTime = om.MTime() minTime = omAnim.MAnimControl().minTime() maxTime = omAnim.MAnimControl().maxTime() currentTime = omAnim.MAnimControl().currentTime() print minTime.value() print maxTime.value() print currentTime.asUnits( 8 )
def convertToWorld(self): '''converts the clip's motion to a world space path''' global g_validWorldAttrs import maya.OpenMaya as api import maya.OpenMayaAnim as anim #use the api to control the time changes as it doesn't refresh viewports making it way faster timeControl = anim.MAnimControl() orgTime = timeControl.currentTime() for frame in self.frames: timeControl.setCurrentTime(api.MTime(frame[0].time)) #cmd.currentTime(frame[0].time) transformKeys = [ key for key in frame if key.attr in g_validWorldAttrs ] xform = cmd.xform(key.obj, query=True, worldSpace=True, rotatePivot=True) xform += cmd.xform(key.obj, query=True, worldSpace=True, rotation=True) for k in transformKeys: try: idx = g_validWorldAttrs.index(k.attr) k.value = xform[idx] except: print 'bad', k.attrpath, k.time continue timeControl.setCurrentTime(orgTime) #restore time self.hasWorld = True
def trimTimeRange(start, end): animCtrl = oma.MAnimControl() startTime = om.MTime(start) endTime = om.MTime(end) animCtrl.setAnimationStartEndTime(startTime, endTime) animCtrl.setMinMaxTime(startTime, endTime)
def OutputAnimationData(obj, outfilepath, sf, ef): dagNode = OpenMaya.MFnDagNode(obj) dagPath = dagNode.fullPathName() namefix = cleanMayaLongName(dagPath[1:]) outfilepath = 'C://' #DEBUG DEBUG fHandle = open((outfilepath + '/' + namefix + '.chan'), "w") MANIM = OpenMayaAnim.MAnimControl() for i in range(sf, ef): MANIM.setCurrentTime(OpenMaya.MTime(i)) fn = OpenMaya.MFnTransform(obj) TRANSLATION = fn.getTranslation(0) oiler = OpenMaya.MEulerRotation() ROTATION = fn.getRotation(oiler) ROTVEC = OpenMaya.MVector(oiler.asVector()) line = (str(TRANSLATION[0]) + ' ' + str(TRANSLATION[1]) + ' ' + str(TRANSLATION[2]) + ' ' + str(radian_to_degree(ROTVEC[0])) + ' ' + str(radian_to_degree(ROTVEC[1])) + ' ' + str(radian_to_degree(ROTVEC[2])) + '\n') fHandle.write(line) fHandle.close() MANIM.setCurrentTime(OpenMaya.MTime(0))
def __init__(self) : # get the currently selected objects and make sure we have only one object selected = OM.MSelectionList() OM.MGlobal.getActiveSelectionList(selected) self.selectedObjects = [] selected.getSelectionStrings(self.selectedObjects) if len(self.selectedObjects) == 0 : cmds.confirmDialog( title='No objects Selected', message='Select a Mesh Object', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' ) elif len(self.selectedObjects) > 1 : cmds.confirmDialog( title='Select One Object', message='Only One Mesh mat be exported at a time', button=['Ok'], defaultButton='Ok', cancelButton='Ok', dismissString='Ok' ) # now we have the correct criteria we can proceed with the export else : # get the start and end values for our UI sliders anim=OMA.MAnimControl() minTime=anim.minTime() maxTime=anim.maxTime() self.m_start=int(minTime.value()) self.m_end=int(maxTime.value()) # now we create a window ready to populate the components self.m_window = cmds.window( title='NCCA Pointbake Export' ) # create a layout cmds.columnLayout() # create two sliders for start and end we also attach methods to be called when the slider # changes self.m_startSlider=cmds.intSliderGrp( changeCommand=self.startChanged,field=True, label='Start Frame', minValue=self.m_start, maxValue=self.m_end, fieldMinValue=self.m_start, fieldMaxValue=self.m_end, value=self.m_start ) self.m_endSlider=cmds.intSliderGrp( changeCommand=self.endChanged ,field=True, label='End Frame', minValue=self.m_start, maxValue=self.m_end, fieldMinValue=self.m_end, fieldMaxValue=self.m_end, value=self.m_end ) # create a button and add the method called when pressed cmds.button( label='Export', command=self.export ) # finally show the window cmds.showWindow( self.m_window )
def set_time(mt_time, b_full=True, b_end=False): """ !@Brief Set start time @type mt_time: OpenMaya.MTime @param mt_time: Time value. @type b_full: bool @param b_full: If is True get animationStart else get minStart. @type b_end: bool @param b_end: If True set end time else set start time. """ anim_control = OpenMayaAnim.MAnimControl() if b_end is True: if b_full is True: anim_control.setAnimationEndTime(mt_time) else: anim_control.setMaxTime(mt_time) else: if b_full is True: anim_control.setAnimationStartTime(mt_time) else: anim_control.setMinTime(mt_time)
def get_frame_range(self): maim_control = OpenMayaAnim.MAnimControl() min_time = maim_control.minTime() max_time = maim_control.maxTime() values = ( min_time.value(), max_time.value(), ) return values
def __current_keyframe(self, backward = True, keyframeOffset = 1.0): '''get the current keyframe by the given flags''' #--- current time omac = oma.MAnimControl() currentFrame = omac.currentTime() #--- go back in frame if backward: currentFrame = currentFrame - keyframeOffset return currentFrame.value()
def current_time(): """ !@Brief Get current frame. @rtype: OpenMaya.MTime @return: Current frame in MTime. """ return OpenMayaAnim.MAnimControl().currentTime()
def trimTimeRange(start, end): """ Args: start (float) end (float) """ animCtrl = oma.MAnimControl() startTime = om.MTime(start) endTime = om.MTime(end) animCtrl.setAnimationStartEndTime(startTime, endTime) animCtrl.setMinMaxTime(startTime, endTime)
def set_playbacks(): print '\nset playbacks' manim_control = OpenMayaAnim.MAnimControl() manim_control.setMinMaxTime(OpenMaya.MTime(1), OpenMaya.MTime(24)) manim_control.setAnimationStartEndTime(OpenMaya.MTime(1), OpenMaya.MTime(24)) manim_control.setPlaybackMode( manim_control.kPlaybackLoop) # loop = continuous manim_control.setViewMode( manim_control.kPlaybackViewAll) # playback in all views. manim_control.setPlaybackSpeed(1) print '\tframe range: <1, 24>' print '\tplayback mode: <loop, continuous>' print '\tview mode: <playback in all views>' print '\tplayback speed: <real-time>'
def export_alembic(objs=None, fileName=None, minTime=None, maxTime=None, uvWrite=True): """ Function to export object to Clarisse :param objs: str (list), Name of the nodes that need to be exported :param fileName: str, full file path :param minTime: int, start frame for the export :param maxTime: int, end frame for the export :param uvWrite: bool, export UVs flag :return: """ anim = oma.MAnimControl() if minTime is None: minTime = anim.minTime().value() if maxTime is None: maxTime = anim.maxTime().value() if objs is None: cmds.warning("[Alembic exporter] No objects set for export") return if fileName is None: cmds.warning("[Alembic exporter] No filename set for export") return exportString = "" for node in objs: exportString += '-root %(dagPath)s ' % { "dagPath": get_mdagpath(node).fullPathName() } if uvWrite: exportString += "-uvWrite " exportString += '-renderableOnly -stripNamespaces -frameRange %(minTime)i %(maxTime)i -file %(fileName)s' \ % {"minTime": minTime, "maxTime": maxTime, "fileName": fileName} cmds.AbcExport(j=exportString)
def get_time(f_time=None, b_full=True, b_set=False, b_end=False): """ !@Brief Get StartAnimationValue @type f_time: float @param f_time: Start frame value. @type b_full: bool @param b_full: If is True get animationStart else get minStart. @type b_set: bool @param b_set: If True set timeLine if float given is less than start frame. @type b_end: bool @param b_end: If True get end time else get start time. @rtype: OpenMaya.MTime @return: Start frame in MTime. """ anim_control = OpenMayaAnim.MAnimControl() if b_end is True: mt_time = anim_control.animationEndTime( ) if b_full is True else anim_control.maxTime() else: mt_time = anim_control.animationStartTime( ) if b_full is True else anim_control.minTime() # No float given if f_time is None: return mt_time # Float given mt_gtime = OpenMaya.MTime() mt_gtime.setUnit(mt_time.unit()) if isinstance(f_time, OpenMaya.MTime) is True: mt_gtime.setValue(f_time.value()) else: mt_gtime.setValue(float(f_time)) if mt_gtime > mt_time if b_end is True else mt_gtime < mt_time: if b_set is True: set_time(mt_gtime, b_full=b_full, b_end=b_end) else: raise Exception("Time given out of time range -- {0} | {1}".format( mt_gtime.value(), mt_time.value())) return mt_gtime
def WriteAnimCurveValue(prof): if not FindAnimPlug(prof): return print(' %s is sampled' % prof.animPlug.name()) rec = open(prof.fileName, 'w') mtm = om.MTime() acon = oam.MAnimControl() for i in range(prof.minFrame, prof.maxFrame + 1): for j in range(0, prof.samplePerFrame): frame = i + j * prof.sampleTimeStep mtm.setValue(frame) acon.setCurrentTime(mtm) fval = prof.animPlug.asFloat() print(' %f: %f' % (frame, fval)) rec.write("%f\n" % fval) rec.close() print(' saved sample time file %s' % prof.fileName)
def __init__(self,_selectedText): ## @brief the object selected to load the data too. self.m_selectedObject=_selectedText ## @brief the Character Data stored as part of parsing self.m_charData="" ## @brief the m_meshName extracted from the PointBake file self.m_meshName="" ## @brief number of vertices in the mesh, we will check this against the number of points in ## the mesh / obj loaded as a basic compatibility check self.m_numVerts=0 ## @brief the Start frame for the data loaded self.m_startFrame=0 ## @brief m_endFrame of the data loaded self.m_endFrame=0 ## @brief number of frames stored in file not used in this example self.m_numFrames=0 ## @brief the Offset into the vertex list for the current data to be set too self.m_offset=None ## @brief the Current frame to be stored / keyed self.m_currentFrame=0 # the maya time control self.m_anim=OMA.MAnimControl() # a point array structure, we will load each frame's worth of data into this then # load it to the mesh point data each frame, once this is done we need to clear this data for # the next frame self.m_vertData=OM.MFloatPointArray() # grab the object ready to set the point data selected = OM.MSelectionList() obj=OM.MObject( ) selected.add(self.m_selectedObject) selected.getDependNode(0,obj) fn = OM.MFnTransform(obj) self.m_mesh="" oChild = fn.child(0) if(oChild.apiTypeStr()=="kMesh") : print "got Mesh" # get our mesh self.m_mesh=OM.MFnMesh(oChild)
def doIt(self, args): ''' Main call: arguements passed back from the MSyntax/MArgDatabase are object names as strings. ''' Source = None Destin = None result = [] #Build the Arg List from the MSyntax/MArgDatabase, we need to #do this as when called this object is in the API world not Python argData = OpenMaya.MArgDatabase(self.syntax(), args) if argData.isFlagSet(self.kSourceFlag): Source = argData.flagArgumentString(self.kSourceFlag, 0) if argData.isFlagSet(self.kDestinationFlag): Destin = argData.flagArgumentString(self.kDestinationFlag, 0) if argData.isFlagSet(self.kTimeFlag): self.TimeEnabled = argData.flagArgumentBool(self.kTimeFlag, 0) if argData.isFlagSet(self.kTransFlag): self.snapTranslation = argData.flagArgumentBool(self.kTransFlag, 0) if argData.isFlagSet(self.kRotsFlag): self.snapRotation = argData.flagArgumentBool(self.kRotsFlag, 0) #print ('timeEnabled',self.TimeEnabled) #Make the api.MFnTransorm Nodes self.MFntSource = self.__MFnTransformNode(Source) self.MFntDestin = self.__MFnTransformNode(Destin) #set the internal Time if self.TimeEnabled: #If we're not shifting timelines in the wrapper proc then #we don't want to set the AnimControl time as the scene is #already at the correct frame self.origTime = apiAnim.MAnimControl().currentTime() apiAnim.MAnimControl.setCurrentTime(self.origTime) if self.snapTranslation: #-------------------------- #DEAL WITH THE TRANSLATES : #-------------------------- rotPivA = OpenMaya.MVector( self.MFntSource.rotatePivot(OpenMaya.MSpace.kWorld)) rotPivB = OpenMaya.MVector( self.MFntDestin.rotatePivot(OpenMaya.MSpace.kWorld)) self.origTrans = self.MFntDestin.getTranslation( OpenMaya.MSpace.kWorld) #We subtract the destinations translation from it's rotPivot, before adding it #to the source rotPiv. This compensates for offsets in the 2 nodes pivots targetTrans = (rotPivA + (self.origTrans - rotPivB)) self.MFntDestin.setTranslation(targetTrans, OpenMaya.MSpace.kWorld) result.append(targetTrans) if self.snapRotation: #----------------------- #DEAL WITH THE ROTATES : #----------------------- #Fill the Undo self.origRots = OpenMaya.MQuaternion() self.MFntDestin.getRotation(self.origRots, OpenMaya.MSpace.kWorld) #Read the source Quaternions and copy to destination Quat = OpenMaya.MQuaternion() self.MFntSource.getRotation(Quat, OpenMaya.MSpace.kWorld) self.MFntDestin.setRotation(Quat, OpenMaya.MSpace.kWorld) result.append(Quat) #set the returns OpenMayaMPx.MPxCommand.clearResult() #Pass back the destination co-ordinates required #OpenMayaMPx.MPxCommand.setResult([targetTrans,Quat]) OpenMayaMPx.MPxCommand.setResult(result)
def NCCAPointBake(_fileName,_name,_startFrame,_endFrame) : # grab the selected object selected = OM.MSelectionList() obj=OM.MObject( ) selected.add(_name) selected.getDependNode(0,obj) # get the parent transform fn = OM.MFnTransform(obj) Mesh="" oChild = fn.child(0) # check to see if what we have is a mesh if(oChild.apiTypeStr()=="kMesh") : print "got Mesh" # get our mesh Mesh=OM.MFnMesh(oChild) else : print "Didn't get mesh ", oChild.apiType() return # now we try and open the file for writing try : file=open(str(_fileName[0]),'w') # if this fails catch the error and exit except IOError : print "Error opening file",str(_fileName) return # set the frame to start print "PB get anim control" currFrame=OM.MTime() anim=OMA.MAnimControl() # as these can take time to process we have an interupter to allow for the process to be # stopped interupter=OM.MComputation() # set the start of the heavy computation interupter.beginComputation() # now we set the tab level to 0 for the initial write to the file tabIndent=0 # now we get the mesh number of points numPoints = cmds.polyEvaluate( _name, v=True) # write the xml headers file.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n") file.write("<NCCAPointBake>\n") # up the tab level tabIndent=tabIndent+1 # write the initial header data WriteData(file,tabIndent,"<MeshName> %s </MeshName>" %(_name)) WriteData(file,tabIndent,"<NumVerts> %d </NumVerts>" %(numPoints)) WriteData(file,tabIndent,"<StartFrame> %s </StartFrame>" %(_startFrame)) WriteData(file,tabIndent,"<EndFrame> %s </EndFrame>" %(_endFrame)) WriteData(file,tabIndent,"<NumFrames> %s </NumFrames>" %(_endFrame-_startFrame)) WriteData(file,tabIndent,"<TranslateMode> %s </TranslateMode>" %("absolute")) # now for every frame write out the vertex data for frame in range(_startFrame,_endFrame) : print "Doing frame %04d" %(frame) # move to the correct frame currFrame.setValue (frame) anim.setCurrentTime(currFrame) # write out the frame tag WriteData(file,tabIndent,"<Frame number=\"%d\">" %(frame)) tabIndent=tabIndent+1 for vertex in range(0,numPoints) : # now the actual vertex data for the current mesh index value data = cmds.xform( (_name+ ".vtx["+str(vertex)+"]"), q=True, ws=True, t=True ) WriteData(file,tabIndent,"<Vertex number=\"%d\" attrib=\"translate\"> %f %f %f </Vertex>" %(vertex,data[0],data[1],data[2])) # now un-indent as we have ended the frame tabIndent=tabIndent-1 WriteData(file,tabIndent,"</Frame>") # if we have interupted exit and finish if interupter.isInterruptRequested() : file.write("</NCCAPointBake>\n") file.close() print "File export interrupted "; return # now finish file.write("</NCCAPointBake>\n") # and close the file file.close()
def get_current_time(): anim_control = OpenMayaAnim.MAnimControl() return anim_control.currentTime().value()
def get_active_frame_range(): anim_control = OpenMayaAnim.MAnimControl() return (anim_control.minTime().value(), anim_control.maxTime().value())
def move_to_frame(frame): anim_control = OpenMayaAnim.MAnimControl() anim_control.setCurrentTime( OpenMaya.MTime(frame, OpenMaya.MTime.uiUnit()))
def __init__(self,epmv,period=0.1): self.period = period self.callback = None self.epmv = epmv self.mv = self.epmv.mv self.timeControl = oma.MAnimControl()
def __init__(self, **kw): general_plugClass.__init__(self, **kw) OpenMayaMPx.MPxCommand.__init__(self) self.period = 0.1 self.timeControl = oma.MAnimControl() self.callback = None
def faceForwardAnim(transform, aimAxis='z', upAxis='y', upVector=(0, 1, 0), upVectorType='vector', upVectorObject='', previousFrameVelocity=False, frameStart=-1, frameEnd=-1, sampleByFrame=0): ''' Key the rotation attributes of the specified transform so that a set axis is always aimed in the direction of its movement @param transform: The transform to face forward @type transform: str @param aimAxis: The axis of the transform to aim forward @type aimAxis: str @param upAxis: The axis of the transform to aim towards the upVector @type upAxis: str @param upVector: The axis of the transform to aim towards the upVector @type upVector: tuple or list @param upVectorType: The method used to calculate the upVector @type upVectorType: str @param upVectorObject: The object to derive the upVector from @type upVectorObject: str @param previousFrameVelocity: Use the velocity of the previous frame instead of the current frame @type previousFrameVelocity: bool @param frameStart: The first frame to calculate the face forward rotation for. If left at default, will use first frame in the timeline. @type frameStart: int @param frameEnd: The last frame to calculate the face forward rotation for. If left at default, will use last frame in the timeline. @type frameEnd: int @param sampleByFrame: How often to sample the face forward rotation. If left at default, will sample at every translate keyframe. @type sampleByFrame: int ''' # Check transform if not mc.objExists(transform): raise UserInputError('Object "' + transform + '" does not exist!!') # Check upVectorObject if upVectorType == 'object' and not mc.objExists(upVectorObject): raise UserInputError('UpVector object "' + upVectorObject + '" does not exist!!') # Get transform parent parent = '' parentList = mc.listRelatives(transform, p=True, pa=True) if parentList: parent = parentList[0] # Get sample frames sFrames = [] if frameStart < 0: frameStart = OpenMayaAnim.MAnimControl().minTime().value() if frameEnd < 0: frameEnd = OpenMayaAnim.MAnimControl().maxTime().value() if sampleByFrame: sFrames = range(frameStart, frameEnd + 1, sampleByFrame) else: tAnimCurve = mc.listConnections( [transform + '.tx', transform + '.ty', transform + '.tz'], s=True, d=True, type='animCurve') if not tAnimCurve: raise UserInputError( 'Object "' + transform + '" has no translate keys! Set sampleByFrame argument greater than zero!' ) [ sFrames.append(i) for i in mc.keyframe( tAnimCurve, q=True, tc=True, t=(frameStart, frameEnd)) if not sFrames.count(i) ] # Sample frames for f in sFrames: # Get rotation values rotate = faceForwardRotation(transform, aimAxis, upAxis, upVector, upVectorType, upVectorObject, previousFrameVelocity, f) print rotate # Set rotation key mc.setAttr(transform + '.rotateX', rotate[0]) mc.setKeyframe(transform, at='rotateX', t=f, v=rotate[0]) mc.setAttr(transform + '.rotateY', rotate[1]) mc.setKeyframe(transform, at='rotateY', t=f, v=rotate[1]) mc.setAttr(transform + '.rotateZ', rotate[2]) mc.setKeyframe(transform, at='rotateZ', t=f, v=rotate[2]) # Filter Curves mc.filterCurve([ transform + '.rotateX', transform + '.rotateY', transform + '.rotateZ' ])
def importAnimationNode(node, path): # We need to be sure to disable auto keyframe, because it breaks import of animations # do this now so we don't forget... sceneAnimationController = OpenMayaAnim.MAnimControl() sceneAnimationController.setAutoKeyMode(False) switcherLoop = { None: OpenMayaAnim.MAnimControl.kPlaybackOnce, 0: OpenMayaAnim.MAnimControl.kPlaybackOnce, 1: OpenMayaAnim.MAnimControl.kPlaybackLoop, } sceneAnimationController.setPlaybackMode(switcherLoop[node.Looping()]) switcherFps = { None: OpenMaya.MTime.kFilm, 2: OpenMaya.MTime.k2FPS, 3: OpenMaya.MTime.k3FPS, 24: OpenMaya.MTime.kFilm, 30: OpenMaya.MTime.kNTSCFrame, 60: OpenMaya.MTime.kNTSCField, 100: OpenMaya.MTime.k100FPS, 120: OpenMaya.MTime.k120FPS, } if int(node.Framerate()) in switcherFps: wantedFps = switcherFps[int(node.Framerate())] else: wantedFps = switcherFps[None] # If the user toggles this setting, we need to shift incoming frames # by the current time if sceneSettings["importAtTime"]: startFrame = sceneAnimationController.currentTime() else: startFrame = OpenMaya.MTime(0, wantedFps) # We need to determine the proper time to import the curves, for example # the user may want to import at the current scene time, and that would require # fetching once here, then passing to the curve importer. wantedSmallestFrame = OpenMaya.MTime(0, wantedFps) wantedLargestFrame = OpenMaya.MTime(1, wantedFps) curves = node.ChildrenOfType(Curve) progress = utilityCreateProgress("Importing animation...", len(curves)) for x in curves: (smallestFrame, largestFrame) = importCurveNode(x, path, wantedFps, startFrame, node.TransformSpace()) if smallestFrame < wantedSmallestFrame: wantedSmallestFrame = smallestFrame if largestFrame > wantedLargestFrame: wantedLargestFrame = largestFrame utilityStepProgress(progress) utilityEndProgress(progress) # Set the animation segment sceneAnimationController.setAnimationStartEndTime(wantedSmallestFrame, wantedLargestFrame) sceneAnimationController.setMinMaxTime(wantedSmallestFrame, wantedLargestFrame) sceneAnimationController.setCurrentTime(wantedSmallestFrame)