def __init__(self, uioptions, transformoptions, sourcelist, targetlist): ''' initial setup ''' #create the tool context if (mc.draggerContext(spPaint3dContextID, exists=True)): mc.deleteUI(spPaint3dContextID); mc.draggerContext(spPaint3dContextID, pressCommand=self.onPress, dragCommand=self.onDrag, releaseCommand=self.onRelease, name=spPaint3dContextID, cursor='crossHair', undoMode='step') #create context local options self.runtimeUpdate(uioptions, transformoptions, sourcelist, targetlist) #debug purpose self.reentrance = 0 #initialise world up vector if ( (mc.upAxis(q=True, axis=True)) == "y" ): self.worldUp = om.MVector (0,1,0); elif ( (mc.upAxis(q=True, axis=True)) == "z" ): self.worldUp = om.MVector (0,0,1); else: #can't figure out up vector mc.confirmDialog(title='Weird stuff happening', message='Not getting any proper info on what the current up vector is. Quitting...') sys.exit() #fetch current scene unit self.unit = mc.currentUnit(query=True, linear=True)
def restoreSettings(self): ''' restore all UI settings ''' cmds.autoKeyframe(state=self.dataStore['autoKey']) # timeline management cmds.currentTime(self.dataStore['currentTime']) cmds.playbackOptions(min=self.dataStore['minTime']) cmds.playbackOptions(max=self.dataStore['maxTime']) cmds.playbackOptions(ast=self.dataStore['startTime']) cmds.playbackOptions(aet=self.dataStore['endTime']) cmds.playbackOptions(ps=self.dataStore['playSpeed']) cmds.playbackOptions(loop=self.dataStore['playLoop']) # unit management cmds.currentUnit(time=self.dataStore['timeUnit']) cmds.currentUnit(linear=self.dataStore['sceneUnits']) if not cmds.upAxis(axis=True, q=True) == self.dataStore['upAxis']: cmds.upAxis(axis=self.dataStore['upAxis']) log.debug('Restored PlayBack / Timeline setup') # viewport colors cmds.displayPref(displayGradient=self.dataStore['displayGradient']) cmds.displayRGBColor(resetToSaved=True) # objects colors cmds.displayColor("curve", self.dataStore['curvecolor'], dormant=True) # panel management for panel, data in self.dataStore['panelStore'].items(): try: cmdString = data['settings'].replace('$editorName', panel) mel.eval(cmdString) log.debug("Restored Panel Settings Data >> %s" % panel) mel.eval('lookThroughModelPanel("%s","%s")' % (data['activeCam'], panel)) log.debug("Restored Panel Active Camera Data >> %s >> cam : %s" % (panel, data['activeCam'])) except: log.debug("Failed to fully Restore ActiveCamera Data >> %s >> cam : %s" % (panel, data['activeCam'])) # camera management for cam, settings in self.dataStore['cameraTransforms'].items(): try: cmds.setAttr('%s.translate' % cam, settings[0][0][0], settings[0][0][1], settings[0][0][2]) cmds.setAttr('%s.rotate' % cam, settings[1][0][0], settings[1][0][1], settings[1][0][2]) cmds.setAttr('%s.scale' % cam, settings[2][0][0], settings[2][0][1], settings[2][0][2]) log.debug('Restored Default Camera Transform Data : % s' % cam) except: log.debug("Failed to fully Restore Default Camera Transform Data : % s" % cam) # sound management if self.dataStore['displaySound']: cmds.timeControl(self.gPlayBackSlider, e=True, ds=1, sound=self.dataStore['activeSound']) log.debug('Restored Audio setup') else: cmds.timeControl(self.gPlayBackSlider, e=True, ds=0) log.debug('Scene Restored fully') return True
def setUpClass(cls): # The test USD data is authored Z-up, so make sure Maya is configured # that way too. cmds.upAxis(axis='z') cls._testDir = os.path.abspath('.') cls._cameraName = 'MainCamera'
def YupZup(): if cmds.upAxis(q=True, axis=True) == "y": cmds.upAxis(ax="z", rv=True) else: cmds.upAxis(ax="y", rv=True) for cam in cmds.listCameras(): cmds.viewSet(cam, animate=False, home=True) cmds.viewFit(all=True)
def exportSelected(self, sock): selection = om.MSelectionList() om.MGlobal.getActiveSelectionList(selection) selection_iter = om.MItSelectionList(selection) while not selection_iter.isDone(): obj = om.MObject() dagPath = om.MDagPath() selection_iter.getDependNode(obj) selection_iter.getDagPath(dagPath) node = om.MFnDependencyNode(obj) mt = om.MTransformationMatrix(dagPath.inclusiveMatrix()) loc = mt.translation(om.MSpace.kWorld) rot = mt.rotation().asEulerRotation() scaleUtil = om.MScriptUtil() scaleUtil.createFromList([0,0,0],3) scaleVec = scaleUtil.asDoublePtr() mt.getScale(scaleVec, om.MSpace.kWorld) scale = [om.MScriptUtil.getDoubleArrayItem(scaleVec, i) for i in range(0,3)] if (cmds.upAxis(q=True,axis=True) == "y"): self.SendUnrealBatchPlaceData(sock, unicodedata.normalize('NFKD', node.name()).encode('ascii','ignore'), str(loc.x), str(loc.z), str(loc.y), str(math.degrees(rot.x)), str(math.degrees(rot.z)), str(math.degrees(rot.y)*-1), str(scale[0]), str(scale[2]), str(scale[1])) else: self.SendUnrealBatchPlaceData(sock, unicodedata.normalize('NFKD', node.name()).encode('ascii','ignore'), str(loc.x), str(loc.y), str(loc.z), str(math.degrees(rot.x)), str(math.degrees(rot.y)), str(math.degrees(rot.z)), str(scale[0]), str(scale[1]), str(scale[2])) print "Sent mesh " + node.name() selection_iter.next() print "done sending"
def build(s): jointNum = len(s.joints) def constrain(joint): cmds.joint(joint.joint, e=True, zso=True) cmds.makeIdentity(joint.joint, apply=True) cmds.orientConstraint(joint.targets["rotation"], joint.joint, mo=True) cmds.scaleConstraint(joint.targets["scale"], joint.joint, mo=True) def LookAt(aim, up, joint): # Build our matrix aim = aim.normalize() # Looking at target up = up.normalize() # Primary Rotation right = (aim ^ up).normalize() # Nobody likes you third Axis! pos = joint.position # Position roo = joint.roo # Rotation Order if roo in ["xzy", "yxz", "zyx"]: # Axis angles to the left right = -right matrix = [[],[],[],[pos[0],pos[1],pos[2],1]] matrix[AXISPOS[roo[0]]] = [aim[0],aim[1],aim[2],0] # First rotation order matrix[AXISPOS[roo[1]]] = [up[0],up[1],up[2],0] # Second rotation order matrix[AXISPOS[roo[2]]] = [right[0],right[1],right[2],0] # Third rotation order cmds.xform(joint.joint, ws=True, m=[c for r in matrix for c in r]) # Apply Matrix if 1 < jointNum: # Nothing to rotate if only a single joint if jointNum == 2: # We don't have enough joints to aim fancy j2, j3 = s.joints aim = j3.position - j2.position up = om.MVector(0,1,0) if cmds.upAxis(q=True, ax=True) == "y" else om.MVector(0,0,1) LookAt(aim, up, j2) cmds.parent(j3.joint, j2.joint) constrain(j2) else: prev = None for i in range(jointNum - 2): j1, j2, j3 = s.joints[i], s.joints[i + 1], s.joints[i + 2] tail = j1.position - j2.position aim = j3.position - j2.position up = tail ^ aim # Flip axis if pointed the wrong way if i and s.flipping and up * prev <= 0.0: up = -up prev = up if not i: # Don't forget to aim the root! LookAt(-tail, up, j1) cmds.parent(j2.joint, j1.joint) constrain(j1) LookAt(aim, up, j2) # Aim Joint cmds.parent(j3.joint, j2.joint) # Join Limb constrain(j2) # rotate last joint LookAt(aim, up, j3) constrain(j3) else: constrain(s.joints[0])
def restoreSettings(self): ''' restore all UI settings ''' cmds.autoKeyframe(state=self.dataStore['autoKey']) #timeline management cmds.currentTime(self.dataStore['currentTime']) cmds.playbackOptions(min=self.dataStore['minTime']) cmds.playbackOptions(max=self.dataStore['maxTime']) cmds.playbackOptions(ast=self.dataStore['startTime']) cmds.playbackOptions(aet=self.dataStore['endTime']) cmds.playbackOptions(ps=self.dataStore['playSpeed']) #unit management cmds.currentUnit(time=self.dataStore['timeUnit']) cmds.currentUnit(linear=self.dataStore['sceneUnits']) cmds.upAxis(axis=self.dataStore['upAxis']) log.info('Restored PlayBack / Timeline setup') #panel management for panel, data in self.dataStore['panelStore'].items(): cmdString = data['settings'].replace('$editorName', panel) mel.eval(cmdString) log.info("Restored Panel Settings Data >> %s" % panel) mel.eval('lookThroughModelPanel("%s","%s")' % (data['activeCam'], panel)) log.info("Restored Panel Active Camera Data >> %s >> cam : %s" % (panel, data['activeCam'])) # camera management for cam, settings in self.dataStore['cameraTransforms'].items(): cmds.setAttr('%s.translate' % cam, settings[0][0][0], settings[0][0][1], settings[0][0][2]) cmds.setAttr('%s.rotate' % cam, settings[1][0][0], settings[1][0][1], settings[1][0][2]) cmds.setAttr('%s.scale' % cam, settings[2][0][0], settings[2][0][1], settings[2][0][2]) log.info('Restored Default Camera Transform Data : % s' % cam) #sound management if self.dataStore['displaySound']: cmds.timeControl(self.gPlayBackSlider, e=True, ds=1, sound=self.dataStore['activeSound']) log.info('Restored Audio setup') else: cmds.timeControl(self.gPlayBackSlider, e=True, ds=0) return True
def new_scene(force=True): """ Open new scene. Set all scene variables and options correctly. """ axis = os.getenv("UPAXIS") units = os.getenv("UNITS") # Force new open if force: cmds.file(f=force, new=1) else: mel.eval('saveChanges("file -f -new")') cmds.file(f=force, new=1) # Up Axis if cmds.upAxis(q=1, axis=1).capitalize() != axis.capitalize(): cmds.upAxis(axis=axis, rv=1) # FPS intFps=int(os.getenv("FPS")) fps=fps_val(intFps) cmds.currentUnit(time=fps, ua=0) # Units cmds.currentUnit(l=units) # Set Clipping Planes cmds.setAttr("perspShape.nearClipPlane", 0.001) cmds.setAttr("perspShape.farClipPlane", 1000) cmds.setAttr("sideShape.nearClipPlane", 0.001) cmds.setAttr("sideShape.farClipPlane", 1000) cmds.setAttr("topShape.nearClipPlane", 0.001) cmds.setAttr("topShape.farClipPlane", 1000) cmds.setAttr("frontShape.nearClipPlane", 0.001) cmds.setAttr("frontShape.farClipPlane", 1000) # Grid if units == "meter": cmds.grid(size=10, divisions=5, sp=5) elif units == "centimeter": cmds.grid(size=100, divisions=50, sp=5) elif units == "millimeter": cmds.grid(size=1000, divisions=500, sp=5) # Set timeline to first frame cmds.currentTime(1) cmds.playbackOptions(aet=100, min=1, max=100) # Fit view cmds.viewFit(an=1, all=1)
def storeSettings(self): ''' main work function, store all UI settings ''' self.dataStore['autoKey'] = cmds.autoKeyframe(query=True, state=True) # timeline management self.dataStore['currentTime'] = cmds.currentTime(q=True) self.dataStore['minTime'] = cmds.playbackOptions(q=True, min=True) self.dataStore['maxTime'] = cmds.playbackOptions(q=True, max=True) self.dataStore['startTime'] = cmds.playbackOptions(q=True, ast=True) self.dataStore['endTime'] = cmds.playbackOptions(q=True, aet=True) self.dataStore['playSpeed'] = cmds.playbackOptions(query=True, playbackSpeed=True) self.dataStore['playLoop'] = cmds.playbackOptions(query=True, loop=True) # unit management self.dataStore['timeUnit'] = cmds.currentUnit(q=True, fullName=True, time=True) self.dataStore['sceneUnits'] = cmds.currentUnit(q=True, fullName=True, linear=True) self.dataStore['upAxis'] = cmds.upAxis(q=True, axis=True) # viewport colors self.dataStore['displayGradient'] = cmds.displayPref(q=True, displayGradient=True) # objects colors self.dataStore['curvecolor'] = cmds.displayColor("curve", q=True, dormant=True) # panel management self.dataStore['panelStore'] = {} for panel in ['modelPanel1', 'modelPanel2', 'modelPanel3', 'modelPanel4']: if not cmds.modelPanel(panel, q=True, exists=True): continue self.dataStore['panelStore'][panel] = {} self.dataStore['panelStore'][panel]['settings'] = cmds.modelEditor(panel, q=True, sts=True) activeCam = cmds.modelPanel(panel, q=True, camera=True) if not cmds.nodeType(activeCam) == 'camera': activeCam = cmds.listRelatives(activeCam, f=True)[0] self.dataStore['panelStore'][panel]['activeCam'] = activeCam # camera management # TODO : store the camera field of view etc also self.dataStore['cameraTransforms'] = {} for cam in ['persp', 'top', 'side', 'front']: try: self.dataStore['cameraTransforms'][cam] = [cmds.getAttr('%s.translate' % cam), cmds.getAttr('%s.rotate' % cam), cmds.getAttr('%s.scale' % cam)] except: log.debug("Camera doesn't exists : %s" % cam) # sound management self.dataStore['activeSound'] = cmds.timeControl(self.gPlayBackSlider, q=True, s=1) self.dataStore['displaySound'] = cmds.timeControl(self.gPlayBackSlider, q=True, ds=1)
def __init__(self, uioptions, transformoptions, sourcelist, targetlist): ''' initial setup ''' #create the tool context if (mc.draggerContext(spPaint3dContextID, exists=True)): mc.deleteUI(spPaint3dContextID); mc.draggerContext(spPaint3dContextID, pressCommand=self.onPress, prePressCommand=self.onBeforePress, dragCommand=self.onDrag, holdCommand=self.onHold, releaseCommand=self.onRelease, name=spPaint3dContextID, cursor='crossHair', undoMode='step') #create context local options self.runtimeUpdate(uioptions, transformoptions, sourcelist, targetlist) #initialise world up vector if ( (mc.upAxis(q=True, axis=True)) == "y" ): self.worldUp = om.MVector (0,1,0); elif ( (mc.upAxis(q=True, axis=True)) == "z" ): self.worldUp = om.MVector (0,0,1); #fetch current scene unit self.unit = mc.currentUnit(query=True, linear=True) self.reentrance=0 self.mState = modifierManager()
def prefsRadioMenu(pref, *args): if pref: # Get pref type if pref == 'evaluation': list = ['off', 'serial', 'parallel'] current = cmds.evaluationManager(q=True, mode=True)[0] elif pref == 'default tangent': list = ['auto', 'step', 'linear', 'spline'] current = cmds.keyTangent(q=True, g=True, itt=True)[0] elif pref == 'frames per second': list = ['film', 'ntsc', 'ntscf'] current = cmds.currentUnit(q=True, t=True) elif pref == 'playback speed': list = [0.0, 1.0] current = cmds.playbackOptions(q=True, ps=True) elif pref == 'up axis': list = ['y', 'z'] current = cmds.upAxis(q=True, ax=True) elif pref == 'working units': list = ['mm', 'cm', 'm'] current = cmds.currentUnit(q=True, l=True) # Build Menu # Divider cmds.menuItem(l=pref.capitalize(), divider=True) cmds.radioMenuItemCollection() # Radio Buttons for obj in list: if obj == current: currentVar = True else: currentVar = False item = cmds.menuItem(label=str(obj).capitalize(), radioButton=currentVar, c=partial(prefFunction, pref, obj)) return
def exportSelected(self, sock): selection = om.MSelectionList() om.MGlobal.getActiveSelectionList(selection) selection_iter = om.MItSelectionList(selection) while not selection_iter.isDone(): obj = om.MObject() dagPath = om.MDagPath() selection_iter.getDependNode(obj) selection_iter.getDagPath(dagPath) node = om.MFnDependencyNode(obj) mt = om.MTransformationMatrix(dagPath.inclusiveMatrix()) loc = mt.translation(om.MSpace.kWorld) rot = mt.rotation().asEulerRotation() scaleUtil = om.MScriptUtil() scaleUtil.createFromList([0, 0, 0], 3) scaleVec = scaleUtil.asDoublePtr() mt.getScale(scaleVec, om.MSpace.kWorld) scale = [ om.MScriptUtil.getDoubleArrayItem(scaleVec, i) for i in range(0, 3) ] if (cmds.upAxis(q=True, axis=True) == "y"): self.SendUnrealBatchPlaceData( sock, unicodedata.normalize('NFKD', node.name()).encode( 'ascii', 'ignore'), str(loc.x), str(loc.z), str(loc.y), str(math.degrees(rot.x)), str(math.degrees(rot.z)), str(math.degrees(rot.y) * -1), str(scale[0]), str(scale[2]), str(scale[1])) else: self.SendUnrealBatchPlaceData( sock, unicodedata.normalize('NFKD', node.name()).encode( 'ascii', 'ignore'), str(loc.x), str(loc.y), str(loc.z), str(math.degrees(rot.x)), str(math.degrees(rot.y)), str(math.degrees(rot.z)), str(scale[0]), str(scale[1]), str(scale[2])) print "Sent mesh " + node.name() selection_iter.next() print "done sending"
def exportSelected(self): exportable = False export_body = "" selection = om.MSelectionList() om.MGlobal.getActiveSelectionList(selection) selection_iter = om.MItSelectionList(selection) while not selection_iter.isDone(): obj = om.MObject() dagPath = om.MDagPath() selection_iter.getDependNode(obj) selection_iter.getDagPath(dagPath) node = om.MFnDependencyNode(obj) unrealName = self.getUnrealMesh(node.name()) if (unrealName is not None): exportable = True mt = om.MTransformationMatrix(dagPath.inclusiveMatrix()) loc = mt.translation(om.MSpace.kWorld) rot = mt.rotation().asEulerRotation() scaleUtil = om.MScriptUtil() scaleUtil.createFromList([0, 0, 0], 3) scaleVec = scaleUtil.asDoublePtr() mt.getScale(scaleVec, om.MSpace.kWorld) scale = [ om.MScriptUtil.getDoubleArrayItem(scaleVec, i) for i in range(0, 3) ] if (cmds.upAxis(q=True, axis=True) == "y"): export_body += GetTemplatedExportBody( node.name(), unrealName, loc.x, loc.z, loc.y, math.degrees(rot.x), math.degrees(rot.z), math.degrees(rot.y), scale[0], scale[2], scale[1]) else: export_body += GetTemplatedExportBody( node.name(), unrealName, loc.x, loc.y, loc.z, math.degrees(rot.x), math.degrees(rot.y), math.degrees(rot.z), scale[0], scale[1], scale[2]) selection_iter.next() if (exportable is True): export = ue4_static_header + export_body + ue4_static_footer clipboard = QtWidgets.QApplication.clipboard() clipboard.setText(export)
def CreateAnimation(self): import maya.mel as mel # get the up axis: axis = cmds.upAxis(query=True, axis=True) cmds.currentTime( 0 ) if axis == 'y': cmds.setKeyframe( cmds.getAttr("CMSettings.ModelName"), attribute='rotateY', itt = 'linear', ott = 'linear' ) cmds.currentTime( 36 ) cmds.rotate( 0, 360, 0, cmds.getAttr("CMSettings.ModelName")) cmds.setKeyframe( cmds.getAttr("CMSettings.ModelName"), attribute='rotateY', itt = 'linear', ott = 'linear' ) if axis == 'z': cmds.setKeyframe( cmds.getAttr("CMSettings.ModelName"), attribute='rotateZ', itt = 'linear', ott = 'linear' ) cmds.currentTime( 36 ) cmds.rotate(0, 0, 360, cmds.getAttr("CMSettings.ModelName")) cmds.setKeyframe( cmds.getAttr("CMSettings.ModelName"), attribute='rotateZ', itt = 'linear', ott = 'linear' ) cmds.currentTime( 0 ) mel.eval("setPlaybackRangeToMinMax;")
def __enter__(s): if cmds.objExists(s.baseName): cmds.delete(s.baseName) sel = cmds.ls(sl=True) win = cmds.playblast(activeEditor=True) cam = cmds.modelEditor(win, q=True, camera=True) p1 = om.MVector(cmds.xform(cam, q=True, ws=True, t=True)) p2 = om.MVector(0,0,0) # Center of world scale = (p1 - p2).length() s.baseName = cmds.circle( r=scale * 0.4, n=s.baseName, nr= (0,1,0) if cmds.upAxis(q=True, ax=True) == "y" else (0,0,1) )[0] for at in [".tx", ".ty", ".tz", ".rx", ".ry", ".rz", ".sx", ".sy", ".sz"]: cmds.setAttr(s.baseName + at, l=True, k=False, cb=False) cmds.addAttr(s.baseName, ln="markerSize", dv=1, k=True) cmds.setAttr("%s.markerSize" % s.baseName, scale * 0.005) cmds.select(sel, r=True) return s.createMarker
import os g_vec_axis = [0.0,1.0,0.0] def MVectorFromList(l): da = om.MScriptUtil() da.createFromList(l,3) return da.asDoublePtr() def getRotate(v): chips=om.MQuaternion() chips=om.MVector(g_vec_axis[0],g_vec_axis[1],g_vec_axis[2]).rotateTo(om.MVector(v[0],v[1],v[2])) rot = chips.asEulerRotation() return [rot.x, rot.y ,rot.z] ax = cmds.upAxis( q=True, axis=True ) if ax == 'z': g_vec_axis = [0.0,0.0,1.0] w_path = cmds.workspace( q=True, dir=True ) print "---------------------------------------------------" print "Current directory: " + os.getcwd() print "Current workspace directory: " + w_path print "Current axis_up: " + ax print "---------------------------------------------------" nodes = cmds.ls( tr=True ) th_node = [ x for x in nodes if 'leaf_TRA0_3_LP' in x or 'leaft2_TRA0_3_LP' in x or 'leaft3_TRA0_3_LP' in x] th_children = cmds.listRelatives(th_node)
#Mike Marra #Intial Maya Setup for UDK Script #Sets up the preferences commonly used in maya for working with UDK '''Run this script on a new scene''' import maya.cmds as cmds # Enables polygon borders and sets the edge width to 4 # cmds.polyOptions(np=True, db=True, sb=4) # Sets Undo amount to infinite # cmds.undoInfo(infinity=True) # Makes the viewcube visible # cmds.viewManip(visible=True) cmds.optionVar(iv=('viewCubeShowCube', 1)) # Sets the Z axis to be up # cmds.upAxis(ax='z', rv=True) # Sets the near and far clip for the persp view camera # cmds.setAttr('perspShape.nearClipPlane', 1) cmds.setAttr('perspShape.farClipPlane', 100000) # Sets the near and far clip for the top view camera # cmds.setAttr('topShape.nearClipPlane', 1) cmds.setAttr('topShape.farClipPlane', 100000) # Sets the near and far clip for the front view camera # cmds.setAttr('frontShape.nearClipPlane', 1) cmds.setAttr('frontShape.farClipPlane', 100000) # Sets the near and far clip for the side view camera # cmds.setAttr('sideShape.nearClipPlane', 1) cmds.setAttr('sideShape.farClipPlane', 100000) # To change the grid spacing and subdivisions # cmds.grid(spacing=16, d=1) # To change the grid length and width # cmds.grid(size=512)
def sceneUp_get(): _str_func = 'sceneUp_get' log.debug(cgmGEN.logString_start(_str_func)) return mc.upAxis(q=1, ax=True)
def initMels(userPrefs=True, startup=True, plugins=False, namedCommand=True): u""" 各種初期化MELを呼び出す(source する)。 Maya の設定に依存する処理をしないなら、呼び出さなくても問題はない。 一度呼び出したMELは繰り返し呼び出さないので、 この関数を繰り返し呼び出しても問題はない。 :param `bool` userPrefs: ユーザープリファレンスに関連するMELを呼び出すかどうか。 plugins=True のときは True になる。 :param `bool` startup: initStartup.mel を呼び出すかどうか。 plugins=True のときは True になる。 :param `bool` plugins: プラグインをオートロードするかどうか。 プラグインは、シーンの requires で動的に解決されるし、 バッチ処理で必要な場合は明示的にロードするようにすべきであり、 処理負荷も大きいので、デフォルトでは False としている。 :param `bool` namedCommand: ネームドコマンドを生成するかどうか。 ホットキーに mel コードを結びつけるための概念であるため、 UI が無ければ通常は不要なはずだが、処理負荷は大きくはないため、 pymelに倣いデフォルトは True としてる。 """ #plugins = plugins and ('plugins' not in _initializedMels) if plugins: userPrefs = True startup = True userPrefs = userPrefs and ('userPrefs' not in _initializedMels) startup = startup and ('startup' not in _initializedMels) namedCommand = namedCommand and ('namedCommand' not in _initializedMels) try: # 呼び出す MEL リスト。 upAxis = None prefs = getUserPrefsDir() mels = [ #### 'defaultRunTimeCommands.mel', # sourced automatically #### prefs + '/userRunTimeCommands.mel', # sourced automatically userPrefs and 'createPreferencesOptVars.mel', userPrefs and 'createGlobalOptVars.mel', userPrefs and (prefs + '/userPrefs.mel'), startup and 'initialStartup.mel', #### $HOME/Documents/maya/projects/default/workspace.mel plugins and 'initialPlugins.mel', plugins and (prefs + '/pluginPrefs.mel'), #### 'initialGUI.mel', # GUI #### 'initialLayout.mel', # GUI #### prefs + '/windowPrefs.mel', # GUI #### prefs + '/menuSetPrefs.mel', # GUI #### 'hotkeySetup.mel', # GUI namedCommand and 'namedCommandSetup.mel', namedCommand and (prefs + '/userNamedCommands.mel'), ####'initAfter.mel', # GUI ] # 各 MEL の呼び出し。 import maya.cmds as cmds from maya.mel import eval as mel_eval for f in mels: if f and (not _os_path_isabs(f) or _os_path_isfile(f)): # initialStartup.mel の実行で upAxis の変更が無いセットの warning が出るのを防ぐ。 if f == 'initialStartup.mel': upAxis = cmds.optionVar(q='upAxisDirection') if upAxis == 'y': cmds.upAxis(axis='z', rv=True) try: #print('# ' + f) mel_eval('source "' + f + '"') except: pass finally: # upAxis のセットがうまくいかなかった場合の修復。 if upAxis and upAxis != cmds.upAxis(q=True, axis=True): cmds.upAxis(axis=upAxis, rv=True) # 呼び出し済みのやつを記録。 if plugins: _initializedMels.add('plugins') if userPrefs: _initializedMels.add('userPrefs') if startup: _initializedMels.add('startup') if namedCommand: _initializedMels.add('namedCommand')
#Mike Marra #Intial Maya Setup for UDK Script #Sets up the preferences commonly used in Maya for working with UDK import maya.cmds as cmds # Enables polygon borders and sets the edge width to 4 # cmds.polyOptions(np=True, db=True, sb=4) # Sets Undo amount to infinite # cmds.undoInfo(infinity=True) # Makes the viewcube visible # cmds.viewManip(visible=True) cmds.optionVar(iv=('viewCubeShowCube', 1)) # Sets the Z axis to be up # cmds.upAxis(ax='z', rv=True) # Sets the near and far clip for the persp view camera # cmds.setAttr('perspShape.nearClipPlane', 1) cmds.setAttr('perspShape.farClipPlane', 100000) # Sets the near and far clip for the top view camera # cmds.setAttr('topShape.nearClipPlane', 1) cmds.setAttr('topShape.farClipPlane', 100000) # Sets the near and far clip for the front view camera # cmds.setAttr('frontShape.nearClipPlane', 1) cmds.setAttr('frontShape.farClipPlane', 100000) # Sets the near and far clip for the side view camera # cmds.setAttr('sideShape.nearClipPlane', 1) cmds.setAttr('sideShape.farClipPlane', 100000) # To change the grid spacing and subdivisions # cmds.grid(spacing=16, d=1) # To change the grid length and width # cmds.grid(size=512)
def GetWorldUp(): if cmds.upAxis(query=True, axis=True) == 'z': return om.MVector(0, 0, 1) else: return om.MVector(0, 1, 0)
def setUpAxis(self, axis, rotateView=False): """This flag specifies the axis as the world up direction. The valid axis are either 'y' or 'z'.""" cmds.upAxis(axis=axis, rotateView=rotateView)
def getUpAxis(self): """This flag gets the axis set as the world up direction. The valid axis are either 'y' or 'z'.""" return cmds.upAxis(q=True, axis=True)
def run(*args, **kwargs): """This test determines if objects at the top of the hierarchy are centered at the world origin. Precision is 0.001. This test will only work as expected for objects that are perfectly symmetrical. Visual inspection is recommended for organic models. --- For each root level node, find the bounding box and determine if the bounding box center in x and z == 0 (for a scene where upAxis == y) the bounding box center in x and y == 0 (for a scene where upAxis == z) Returns True/False, the number of off-center objects and a list Set Floor to True to test for objects proper positioned on the floor Which is (y = 0) if y-up or (z = 0) if z-up Arguments -verbose boolean # print messages -floor boolean # include testing for minY == 0 is_centeredatorigin(verbose=boolean, floor=boolean) -> boolean, int, list """ t0=time.time() valid_kwargs = ['verbose', 'floor'] for k, v in kwargs.iteritems(): if k not in valid_kwargs: raise TypeError("Invalid keyword argument %s" % k) result = False err = list() verbose = False # verbose defaults to False if verbose option not set in menu # or specified in cmdline try: verbose = kwargs['verbose'] except KeyError: verbose = False if cmds.optionVar(exists='checkmateVerbosity'): verbose = cmds.optionVar(query='checkmateVerbosity') else: pass try: floor = kwargs['floor'] except KeyError: floor = False pass # get the up axis: axis = cmds.upAxis(query=True, axis=True) # find all the root transforms in the scene # ignore cameras Lignore = cmds.listRelatives(cmds.ls(cameras=True),parent=True) # ignore lights try: Lignore.extend(cmds.listRelatives(cmds.ls(lights=True),parent=True)) except TypeError: pass transforms = [x for x in cm.utils.roots.get() if not x in Lignore] # temporarily make everything in the ignorelist Lignore invisble for x in Lignore : cmds.setAttr('%s.visibility' % x, 0) for transform in transforms: if verbose: print transform (bbMinX, bbMinY, bbMinZ, bbMaxX, bbMaxY, bbMaxZ) = cmds.exactWorldBoundingBox(transform, ignoreInvisible=True) if verbose: print 'bbMinX: %f\nbbMinY: %f\nbbMinZ: %f\nbbMaxX: %f\nbbMaxY: %f\nbbMaxZ: %f\n ' % (bbMinX, bbMinY, bbMinZ, bbMaxX, bbMaxY, bbMaxZ) if axis == 'y': centerX = round(( bbMaxX + bbMinX ) / 2.0, 3) centerZ = round(( bbMaxZ + bbMinZ ) / 2.0, 3) if (floor and bbMinY !=0) or centerX != 0 or centerZ !=0: result = True err.append(transform) if verbose: print 'floor:%s\nbbMinY:%f\ncenterX:%f\ncenterZ:%f' % (floor, bbMinY, centerX, centerZ) if axis == 'z': centerX = ( bbMaxX + bbMinX ) / 2.0 centerY = ( bbMaxY + bbMinZ ) / 2.0 if (floor and bbMinZ !=0) or centerX != 0 or bbMinX != 0: err.append(transform) result = True if verbose: print (floor, bbMinZ, centerX, bbMinX) if len(err): cmds.select(err) # make everything in the ignorelist Lignore visible again for x in Lignore : cmds.setAttr('%s.visibility' % x, 1 ) # hide default cameras cmds.hide([u'front', u'persp', u'side', u'top']) print '%-24s : %.6f seconds' % ('xforms.centered.run()', (float(time.time())-t0)) return result, len(err), err
def setUpClass(cls): # The test USD data is authored Z-up, so make sure Maya is configured # that way too. cmds.upAxis(axis='z') cmds.loadPlugin('pxrUsd')
OPT_VAR_PREFIX = 'fx_flyCamera_' MOUSE_ORIGIN_X = 500 MOUSE_ORIGIN_Y = 500 MOUSE_HOR = 1 MOUSE_VER = 2 SPD_MOVE_X = 1 # x -> right, -x -> left SPD_MOVE_Y = 2 # y -> up, -y -> down SPD_MOVE_Z = 3 # z -> backward, -z -> forward SPD_ROTATE_X = 4 # x -> up, -x -> down SPD_ROTATE_Y = 5 # y -> left, -y -> right Y_UP = True if m.upAxis(q=True, ax=True) == 'y' else False # noinspection PyCallByClass,PyTypeChecker def moveCursorToOrigin(): QtGui.QCursor.setPos(MOUSE_ORIGIN_X, MOUSE_ORIGIN_Y) def sign(x): return (x > 0) - (x < 0) class Timer(object): def __init__(self): self.prevTime = 0 self.start()
def process(self, context): assert cmds.upAxis(q=True, axis=True) == "z", ("Invalid axis set as up axis")
def storeSettings(self): ''' main work function, store all UI settings ''' self.dataStore['autoKey'] = cmds.autoKeyframe(query=True, state=True) # timeline management self.dataStore['currentTime'] = cmds.currentTime(q=True) self.dataStore['minTime'] = cmds.playbackOptions(q=True, min=True) self.dataStore['maxTime'] = cmds.playbackOptions(q=True, max=True) self.dataStore['startTime'] = cmds.playbackOptions(q=True, ast=True) self.dataStore['endTime'] = cmds.playbackOptions(q=True, aet=True) self.dataStore['playSpeed'] = cmds.playbackOptions(query=True, playbackSpeed=True) # unit management self.dataStore['timeUnit'] = cmds.currentUnit(q=True, fullName=True, time=True) self.dataStore['sceneUnits'] = cmds.currentUnit(q=True, fullName=True, linear=True) self.dataStore['upAxis'] = cmds.upAxis(q=True, axis=True) #viewport colors self.dataStore['displayGradient'] = cmds.displayPref( q=True, displayGradient=True) #objects colors self.dataStore['curvecolor'] = cmds.displayColor("curve", q=True, dormant=True) #panel management self.dataStore['panelStore'] = {} for panel in [ 'modelPanel1', 'modelPanel2', 'modelPanel3', 'modelPanel4' ]: if not cmds.modelPanel(panel, q=True, exists=True): continue self.dataStore['panelStore'][panel] = {} self.dataStore['panelStore'][panel]['settings'] = cmds.modelEditor( panel, q=True, sts=True) activeCam = cmds.modelPanel(panel, q=True, camera=True) if not cmds.nodeType(activeCam) == 'camera': activeCam = cmds.listRelatives(activeCam, f=True)[0] self.dataStore['panelStore'][panel]['activeCam'] = activeCam #camera management #TODO : store the camera field of view etc also self.dataStore['cameraTransforms'] = {} for cam in ['persp', 'top', 'side', 'front']: try: self.dataStore['cameraTransforms'][cam] = [ cmds.getAttr('%s.translate' % cam), cmds.getAttr('%s.rotate' % cam), cmds.getAttr('%s.scale' % cam) ] except: log.debug("Camera doesn't exists : %s" % cam) #sound management self.dataStore['activeSound'] = cmds.timeControl(self.gPlayBackSlider, q=True, s=1) self.dataStore['displaySound'] = cmds.timeControl(self.gPlayBackSlider, q=True, ds=1)
def performExport(s, anim, prebake=False): # Validate scene data before export if not s.data["pref"]: return cmds.confirmDialog(t="Oh no..", m="Please add a prefix.") pref = s.data["pref"] if not s.data["objs"]: return cmds.confirmDialog(t="Oh no..", m="Please add some objects to export.") objs = [o for o in s.data["objs"] if cmds.objExists(o)] if not objs: return cmds.confirmDialog(t="Oh no..", m="None of the selected objects could be found.") if not s.data["dirs"]: return cmds.confirmDialog(t="Oh no..", m="Please add at least one folder to export into.") dirs = [absolutePath(d) for d in s.data["dirs"]] dirs = [d for d in dirs if os.path.isdir(d)] if not dirs: return cmds.confirmDialog(t="Oh no..", m="None of the chosen folders could be found.") # Get our animation data data = anim.data if not data["name"] or not data["range"] or not data["layers"]: return cmds.configDialog(t="Oh no..", m="There was an issue with you anim data.") with cleanModify(): print "Exporting %s." % data["name"] # Prep our animation s.setAnimation(anim) if prebake: # Bake out animation manually before export cmds.bakeResults( objs, simulation=True, hierarchy="below", t=tuple(anim.data["range"]), sampleBy=1, # Mass keyframes, each frame! disableImplicitControl=True, # sparseAnimCurveBake=True, removeBakedAttributeFromLayer=True, # smart=(True, 5) minimizeRotation=True ) # Wall off edges of time cmds.setKeyframe(objs, i=True, t=anim.data["range"][0]) cmds.setKeyframe(objs, i=True, t=anim.data["range"][1]) # Remove Excess frames times = cmds.keyframe(objs, q=True, tc=True) frame_range = min(times), max(times) if frame_range[0] < anim.data["range"][0]: cmds.cutKey(objs, t=(frame_range[0], anim.data["range"][0] - 0.1), cl=True) if frame_range[1] > anim.data["range"][1]: cmds.cutKey(objs, t=(anim.data["range"][1] + 0.1, frame_range[1]), cl=True) # Create filename validate = r"[^\w_-]" filename = "%s@%s" % ( re.sub(validate, "_", pref), # unicodedata.normalize("NFKD", pref)), re.sub(validate, "_", data["name"]) # unicodedata.normalize("NFKD", data["name"])) ) files = [os.path.realpath(os.path.join(d, filename)) for d in dirs] # Prepare export command (yikes) command = """ FBXResetExport; FBXExportInAscii -v true; FBXExportCameras -v false; FBXExportLights -v false; FBXExportUpAxis %(axis)s; FBXExportUseSceneName -v false; FBXExportGenerateLog -v false; FBXExportConstraints -v false; FBXExportAxisConversionMethod addFbxRoot; FBXProperty "Export|IncludeGrp|Animation" -v true; FBXExportBakeComplexAnimation -v true; FBXExportBakeComplexStart -v %(start)s; FBXExportBakeComplexEnd -v %(end)s; FBXExportBakeComplexStep -v 1; FBXExportBakeResampleAnimation -v true; FBXExportApplyConstantKeyReducer -v true; /* FBXExportSkeleton -v true; */ FBXExportSkins -v true; FBXExportShapes -v true; FBXExportInputConnections -v false; FBXExportEmbeddedTextures -v false; """ % { "axis" : cmds.upAxis(q=True, ax=True), "start" : data["range"][0], "end" : data["range"][1] } for f in files: command += "FBXExport -f \"%s.fbx\" -s;\n" % f.replace("\\", "/") # Make our selection cmds.select(objs, r=True) # Run our mel command behemoth print "Running Mel:" for i, line in enumerate(command.split("\n")): if line: print i, "\t", line mel.eval(command)
def restoreSettings(self): ''' restore all UI settings ''' cmds.autoKeyframe(state=self.dataStore['autoKey']) #timeline management cmds.currentTime(self.dataStore['currentTime']) cmds.playbackOptions(min=self.dataStore['minTime']) cmds.playbackOptions(max=self.dataStore['maxTime']) cmds.playbackOptions(ast=self.dataStore['startTime']) cmds.playbackOptions(aet=self.dataStore['endTime']) cmds.playbackOptions(ps=self.dataStore['playSpeed']) #unit management cmds.currentUnit(time=self.dataStore['timeUnit']) cmds.currentUnit(linear=self.dataStore['sceneUnits']) cmds.upAxis(axis=self.dataStore['upAxis']) log.info('Restored PlayBack / Timeline setup') #viewport colors cmds.displayPref(displayGradient=self.dataStore['displayGradient']) cmds.displayRGBColor(resetToSaved=True) #objects colors cmds.displayColor("curve", self.dataStore['curvecolor'], dormant=True) #panel management for panel, data in self.dataStore['panelStore'].items(): try: cmdString = data['settings'].replace('$editorName', panel) mel.eval(cmdString) log.info("Restored Panel Settings Data >> %s" % panel) mel.eval('lookThroughModelPanel("%s","%s")' % (data['activeCam'], panel)) log.info( "Restored Panel Active Camera Data >> %s >> cam : %s" % (panel, data['activeCam'])) except: log.debug( "Failed to fully Restore ActiveCamera Data >> %s >> cam : %s" % (panel, data['activeCam'])) # camera management for cam, settings in self.dataStore['cameraTransforms'].items(): try: cmds.setAttr('%s.translate' % cam, settings[0][0][0], settings[0][0][1], settings[0][0][2]) cmds.setAttr('%s.rotate' % cam, settings[1][0][0], settings[1][0][1], settings[1][0][2]) cmds.setAttr('%s.scale' % cam, settings[2][0][0], settings[2][0][1], settings[2][0][2]) log.info('Restored Default Camera Transform Data : % s' % cam) except: log.debug( "Failed to fully Restore Default Camera Transform Data : % s" % cam) #sound management if self.dataStore['displaySound']: cmds.timeControl(self.gPlayBackSlider, e=True, ds=1, sound=self.dataStore['activeSound']) log.info('Restored Audio setup') else: cmds.timeControl(self.gPlayBackSlider, e=True, ds=0) log.debug('Scene Restored fully') return True
def main(): cmds.currentUnit(l='cm') cmds.currentUnit(t='ntsc') cmds.upAxis(ax='z') cmds.grid(reset=True) cmds.grid(s=500, d=4, sp=100, dab=True, ddl=True, dpl=True)
def repair(cls, instance): cmds.upAxis(axis="z", rotateView=True)
def cryMakeSceneRoot(naturalOrientation): root_name = 'SceneRoot' if cmds.objExists(root_name): parents = cmds.listRelatives(root_name, p=True) if parents: cmds.confirmDialog( title='CryTools', message= '{0} node has a parent - it is not recommended.\nPlease delete the node {0} or move it to the top of the scene graph.' .format(root_name), button=[ 'Ok', ], defaultButton='Ok') cmds.select(root_name, r=True) return children = cmds.listRelatives(root_name, c=True) if children and sorted(children) != sorted(['forward', 'up']): cmds.confirmDialog( title='CryTools', message= 'A *non-standard* node {0} is found - it is not supported.\nPlease delete the node {0}.' .format(root_name), button=[ 'Ok', ], defaultButton='Ok') cmds.select(root_name, r=True) return cmds.delete(root_name, hi='all') # Creating SceneRoot node cmds.createNode('transform', n=root_name) # Creating geometry of SceneRoot, # including in-scene text labels for the axes. # Note that 'size' is actually a scaler, not a real size size = 1.4 shaft_length = 60.0 * size shaft_radius = 2.0 * size arrowhead_length = 13.0 * size arrowhead_radius = 6.0 * size sphere_radius = 7.0 * size font_size = 40.0 * size font = "Arial|h-" + str(font_size) + "|w400|c0" obj = cmds.createNode('transform') crySetParent(root_name, obj, 'forward') obj = cmds.createNode('transform') crySetParent(root_name, obj, 'up') obj = cmds.polyCylinder(ch=True, o=True, ax=(0, 1, 0), r=shaft_radius, h=shaft_length, sc=1, cuv=3, sx=4) crySetTransform(obj[0], [0.0, shaft_length * 0.5, 0.0], [0.0, 0.0, 0.0]) crySetParent(root_name + '|forward', obj[0], "shaft") obj = cmds.polyCylinder(ch=True, o=True, ax=(0, 0, 1), r=shaft_radius, h=shaft_length, sc=1, cuv=3, sx=4) crySetTransform(obj[0], [0.0, 0.0, shaft_length * 0.5], [0.0, 0.0, 0.0]) crySetParent(root_name + '|up', obj[0], "shaft") obj = cmds.polyCone(ch=True, o=True, ax=(0, 1, 0), r=arrowhead_radius, h=arrowhead_length, cuv=3, sx=6) crySetTransform(obj[0], [0.0, shaft_length + arrowhead_length * 0.5, 0.0], [0.0, 0.0, 0.0]) crySetParent(root_name + '|forward', obj[0], "arrowhead") obj = cmds.polySphere(ch=True, o=True, r=sphere_radius, sx=8, sy=8) crySetTransform(obj[0], [0.0, 0.0, shaft_length + sphere_radius * 0.5], [90.0, 0.0, 0.0]) crySetParent(root_name + '|up', obj[0], "sphere") obj = cmds.textCurves(f=font, t="Forward") crySetTransform(obj[0], [-2.0 * shaft_radius, 0.1 * shaft_length, 0.0], [0.0, 0.0, 90.0]) crySetParent(root_name + '|forward', obj[0], "text") obj = cmds.textCurves(f=font, t="Up") crySetTransform(obj[0], [-2.0 * shaft_radius, 0.0, 0.7 * shaft_length], [0.0, 90.0, 90.0]) crySetParent(root_name + '|up', obj[0], "text") cmds.select(root_name + '|forward', hi=True) cmds.polyColorPerVertex(rgb=(0.0, 0.6, 0.0), a=1, cdo=True) cmds.select(root_name + '|up', hi=True) cmds.polyColorPerVertex(rgb=(0.0, 0.0, 1.0), a=1, cdo=True) # Setting orientation of SceneRoot node if cmds.upAxis(q=True, axis=True) == "z": if naturalOrientation: crySetTransform(root_name, [0, 0, 0], [0, 0, 180.0]) else: crySetTransform(root_name, [0, 0, 0], [0, 0, 0]) else: if naturalOrientation: crySetTransform(root_name, [0, 0, 0], [90.0, 0, 180.0]) else: crySetTransform(root_name, [0, 0, 0], [-90.0, 0, 0]) # Selecting SceneRoot node to let the user see that something happened and/or # to help the user delete/hide/etc. the node. cmds.select(root_name, r=True)