def enableBordersHighlight(self, *args): ''' ''' if cmds.objExists(self._IScontextTool._mVoroObject): bEnabled = cmds.checkBox(self._ISborderEdgesCbx, query = True, value = True) if bEnabled: if int(cmds.about(version = True).split()[0]) < 2016: mDisplay = cmds.listRelatives(self._IScontextTool._mVoroDisplay[0], fullPath = True)[1] cmds.setAttr(mDisplay + '.overrideEnabled', False) aShapes = cmds.listRelatives(self._IScontextTool._mVoroObject, children = True, shapes = True, type = 'mesh', f = True) if aShapes: self._IScontextTool._mDisplayType = cmds.attributeQuery('displayEdges', node = aShapes[0], max = True)[0] # Depending on Maya Version Max Number can be 2 or 3 else: self._IScontextTool._mDisplayType = 2 else: if int(cmds.about(version = True).split()[0]) < 2016: mDisplay = cmds.listRelatives(self._IScontextTool._mVoroDisplay[0], fullPath = True)[1] cmds.setAttr(mDisplay + '.overrideEnabled', True) self._IScontextTool._mDisplayType = 1 try: if cmds.objExists(self._IScontextTool._mVoroDisplay[0]): mVoroDisplayShape = cmds.listRelatives(self._IScontextTool._mVoroDisplay[0], fullPath = True)[1] cmds.setAttr(mVoroDisplayShape + '.displayEdges', self._IScontextTool._mDisplayType) except: pass
def enableaPlugin(filename): extDict = {'win64':'mll','mac':'bundle','linux':'so','linux64':'so'} os = cmds.about(os=True) ext = extDict[os] version = cmds.about(v=True)[:4] pluginName = 'deltaMushToSkinCluster_%s' % version fileFullName = '%s.%s' % (pluginName,ext) rootPath = getParentPath(currentFileDirectory()) pluginsPath = rootPath+'/plug-ins/' pluginFilePath = pluginsPath+fileFullName pluginStr = mel.eval('getenv "MAYA_PLUG_IN_PATH";')+';'+pluginsPath mel.eval('putenv "MAYA_PLUG_IN_PATH" "%s";' % pluginStr) with open(filename,'a+') as f: state = True for line in f.readlines(): if re.findall(fileFullName,line): state = False if state: f.write(r'evalDeferred("autoLoadPlugin(\"\", \"%s\", \"%s\")");' % (fileFullName,pluginName)) if not cmds.pluginInfo( pluginFilePath, query=True, autoload=True): cmds.pluginInfo( pluginFilePath, edit=True, autoload=True) if not cmds.pluginInfo(pluginFilePath,query=True,loaded=True): cmds.loadPlugin(pluginFilePath)
def printTopExceptionForDebug(error_stack_frames): ''' Prints top-down unhandled exception info generated by MRT. To be used for debugging. ''' # Collect maya/os info. debugInfoTxt = '\n\n{0} MRT ERROR/EXCEPTION OCCURRED {0}'.format('*'*40) debugInfoTxt += '\n%s(Please use the text below for sending error messages)\n' % ('\t'*7) debugInfoTxt += '\nMRT VERSION: %s' % _mrt_version debugInfoTxt += '\nMAYA VERSION: %sx%s' % (cmds.about(version=True), 64 if cmds.about(is64=True) else 32) debugInfoTxt += '\nOS: %s' % cmds.about(os=True) debugInfoTxt += '\nPY VERSION: %s' % platform.python_version() debugInfoTxt += '\n\nEXCEPTION DATA (SOURCE TOP DOWN):-\n' # Collect info for each error stack trace, from top down. for e_frame in error_stack_frames[-1::-1]: e_frame_info = traceback.extract_stack(e_frame, 1)[0] debugInfoTxt += '\nSOURCE: %s\nLINE: %s\nFRAME: "%s"\nAT: "%s"\nLOCALS:' % (e_frame_info[0], e_frame_info[1], e_frame_info[2], e_frame_info[3]) local_items = e_frame.f_locals.items() if local_items: for key, value in local_items: debugInfoTxt += '\n%30s = %s' % (key, value) else: debugInfoTxt += 'None' debugInfoTxt += '\n' return debugInfoTxt
def fileDialog2_openDirInExplorer(self, *args): ctrlName = long(self.MQtUtil.findControl('QFileDialog')) qObj = self.wrapInstance(ctrlName, self.QtGui.QFileDialog) dirPath = qObj.directory().path() if cmds.about(macOS= 1): subprocess.Popen(['open', '--', dirPath]) if cmds.about(linux= 1): subprocess.Popen(['xdg-open', '--', dirPath]) if cmds.about(windows= 1): os.startfile(dirPath)
def loadStringResourcesForModule( moduleName ): """ Load the string resources associated with the given module Note that the argument must be a string containing the full name of the module (eg "maya.app.utils"). The module of that name must have been previously imported. The base resource file is assumed to be in the same location as the file defining the module and will have the same name as the module except with _res.py appended to it. So, for the module foo, the resource file should be foo_res.py. If Maya is running in localized mode, then the standard location for localized scripts will also be searched (the location given by the command cmds.about( localizedResourceLocation=True )) Failure to find the base resources for the given module will trigger an exception. Failure to find localized resources is not an error. """ try: module = sys.modules[moduleName] except: raise RuntimeError( 'Failed to load base string resources for module %s because it has not been imported' % moduleName ) modulePath, moduleFileName = os.path.split( module.__file__ ) moduleName, extension = os.path.splitext( moduleFileName ) resourceFileName = moduleName + '_res.py' # Try to find the base version of the file next to the module try: baseVersionPath = os.path.join( modulePath, resourceFileName ) execfile( baseVersionPath, {} ) except: raise RuntimeError( 'Failed to load base string resources for module %s' % moduleName ) if cmds.about( uiLanguageIsLocalized=True ): scriptPath = cmds.about( localizedResourceLocation=True ) if scriptPath != '': localizedPath = os.path.join( scriptPath, 'scripts', resourceFileName ) try: execfile( localizedPath, {} ) # We don't generate any warnings or errors if localized # file is not there # TODO: we could consider issuing a warning in debug mode except IOError: pass except Exception, err: raise RuntimeError( 'Unexpected error encountered when attempting to load localized string resources for module %s: %s' % (moduleName,err) )
def env_from_sql(table_location,initial_vars): print "\n============================================================\n" print " GLOBAL VARIABLE SETTING INITIALIZED \n\nRunning SQL ENV Var Settings from '%s'\n"%(table_location) # Retrieve Version String version = mc.about(v=1) # Retrieve Mode batch = mc.about(b=1) print "\n Maya Version Detected as %s"%(version) if batch ==1: mode = 'BATCH' print " Maya Running in Batch Mode" else: mode = 'GUI' print " Maya is Running in GUI Mode" # Pass Vars to SQL and retrieve Vals print "\n Retrieving variables for Version = '",version,"'","\n Mode = '",mode,"'" # Get Strings from SQL Table for version of Maya returned_new_envs = sql_handle(version,mode,table_location) print "\n ....Variables Retrieved" # Conglomerate Strings from existing Envs vars_to_set = conglomerate_vars(returned_new_envs) print " ....Variables Conglomerated Setting " # Print Vars print_vars(vars_to_set) # Set Vars set_env_vars(vars_to_set) print "\n Completed ENV Setting" print "\n==============================================================" print " LOADING APPROPRIATE PLUG-INS \n\nRunning SQL Plugin Var Settings from '%s'\n"%(table_location) # Pass Vars to SQL and retrieve Vals print "\n Retrieving Loadable Plug-ins for Version = '",version,"'","\n Mode = '",mode,"'" plugins_loadable = sql_plugin_handle(version,mode,table_location) print "\n ...Retrieved Loadable Plug-ins " load_plugins_status = load_plugins(plugins_loadable) print "\n=============================================================="
def returnMayaInfo(): mayaInfoDict = {} mayaInfoDict['year'] = mc.about(file=True) mayaInfoDict['qtVersion'] = mc.about(qtVersion=True) mayaInfoDict['version'] = mc.about(version=True) mayaInfoDict['apiVersion'] = mc.about(apiVersion=True) mayaInfoDict['product'] = mc.about(product=True) mayaInfoDict['qtVersion'] = mc.about(qtVersion=True) mayaInfoDict['environmentFile'] = mc.about(environmentFile=True) mayaInfoDict['operatingSystem'] = mc.about(operatingSystem=True) mayaInfoDict['operatingSystemVersion'] = mc.about(operatingSystemVersion=True) mayaInfoDict['currentTime'] = mc.about(currentTime=True) mayaInfoDict['currentUnit'] = mc.currentUnit(q=True,linear=True) return mayaInfoDict
def renderLogCallback(line): if "Writing image" in line: imageName = line.split("\"")[-2] # Display the render if not cmds.about(batch=True): MitsubaRendererUI.showRender(imageName)
def isAnimation(self): animation = cmds.getAttr("defaultRenderGlobals.animation") if not cmds.about(batch=True) and animation: print( "Animation isn't currently supported outside of Batch mode. Rendering current frame." ) animation = False mayaReleasePythonGIL = os.environ.get('MAYA_RELEASE_PYTHON_GIL') mayaVersion = float(cmds.about(version=True)) if mayaVersion >= 2016 and not mayaReleasePythonGIL: print( "\n\n\n\n") print( "For versions of Maya 2016 and greater, you must set the environment variable MAYA_RELEASE_PYTHON_GIL" " to 1 to render animations. Rendering current frame only." ) print( "\n\n\n\n") animation = False return animation
def __init__(self): self.dGlobals = {} self.dMasterRenderGlobals = {} self.lstLayers = [] self.sCurrentLayer = "" self.oCurrentLayer = None self.sMasterLayer = "masterLayer" self.bIsFirstRun = False self.lstSelection = [] # Get the Maya version as a integer self.iMayaVersion = int(re.search("\d+", mc.about(v=True)).group()) self.reloadEngines() self.out = libOutput.Output(self) self.utils = libUtils.Utils() self.node = libNode.Node() self.reIsLight = re.compile("Light$") self.reload() # Post actions that have to take place after the initialization of above classes self.selectLayer(self.node.selected())
def getMayaVersion(): ''' returns maya version (use Utils.MAYA* constants for comparision of a returned result) currently uses "about -v" string parsing ''' if Utils.CURRENT_MAYA_VERSION is None: version = cmds.about(v=True) Utils.CURRENT_MAYA_VERSION = Utils.MAYA_UNKNOWN_VERSION def testVersion(search,result): if search in version: Utils.CURRENT_MAYA_VERSION = result return True return False testVersion('2011', Utils.MAYA2011) or \ testVersion('2012', Utils.MAYA2012) or \ testVersion('2013', Utils.MAYA2013) or \ testVersion('2014', Utils.MAYA2014) or \ testVersion('2015', Utils.MAYA2015) or \ testVersion('2016', Utils.MAYA2016) return Utils.CURRENT_MAYA_VERSION
def clearCallbacks(): if cmds.about(batch=True): return try: cmds.callbacks(clearAllCallbacks=True, owner="arnold") except: pass
def __init__(self, title, *args, **kwargs ): QWidget.__init__( self, *args ) self.infoPath = cmds.about(pd=True) + "/sg/fingerWeightCopy/Widget_loadJoints_%s.txt" % title sgCmds.makeFile( self.infoPath ) layout = QVBoxLayout( self ); layout.setContentsMargins(0,0,0,0) groupBox = QGroupBox( title ) layout.addWidget( groupBox ) baseLayout = QVBoxLayout() groupBox.setLayout( baseLayout ) listWidget = QListWidget() hl_buttons = QHBoxLayout(); hl_buttons.setSpacing( 5 ) b_addSelected = QPushButton( "Add Selected" ) b_clear = QPushButton( "Clear" ) hl_buttons.addWidget( b_addSelected ) hl_buttons.addWidget( b_clear ) baseLayout.addWidget( listWidget ) baseLayout.addLayout( hl_buttons ) self.listWidget = listWidget QtCore.QObject.connect( listWidget, QtCore.SIGNAL( "itemClicked(QListWidgetItem*)" ), self.selectJointFromItem ) QtCore.QObject.connect( b_addSelected, QtCore.SIGNAL("clicked()"), self.addSelected ) QtCore.QObject.connect( b_clear, QtCore.SIGNAL( "clicked()" ), self.clearSelected ) self.otherWidget = None self.loadInfo()
def _install_maya(use_threaded_wrapper): """Helper function to Autodesk Maya support""" from maya import utils, cmds def threaded_wrapper(func, *args, **kwargs): return utils.executeInMainThreadWithResult( func, *args, **kwargs) sys.stdout.write("Setting up Pyblish QML in Maya\n") if use_threaded_wrapper: register_dispatch_wrapper(threaded_wrapper) if cmds.about(version=True) == "2018": _remove_googleapiclient() app = QtWidgets.QApplication.instance() if not _is_headless(): # mayapy would have a QtGui.QGuiApplication app.aboutToQuit.connect(_on_application_quit) # acquire Maya's main window _state["hostMainWindow"] = { widget.objectName(): widget for widget in QtWidgets.QApplication.topLevelWidgets() }["MayaWindow"] _set_host_label("Maya")
def arnoldBatchRenderOptionsString(): origFileName = cmds.file(q=True, sn=True) if not cmds.about(batch=True): silentMode = 0 try: silentMode = int(os.environ["MTOA_SILENT_MODE"]) except: pass if silentMode != 1: dialogMessage = "Are you sure you want to start a potentially long task?" if platform.system().lower() == "linux": dialogMessage += " (batch render on linux cannot be stopped)" ret = cmds.confirmDialog( title="Confirm", message=dialogMessage, button=["Yes", "No"], defaultButton="Yes", cancelButton="No", dismissString="No", ) if ret != "Yes": raise Exception("Stopping batch render.") try: port = core.MTOA_GLOBALS["COMMAND_PORT"] return ' -r arnold -ai:ofn \\"' + origFileName + '\\" -ai:port %i ' % port except: return ' -r arnold -ai:ofn \\"' + origFileName + '\\" '
def __init__(self, *args, **kwargs ): QWidget.__init__( self, *args ) title = "" if kwargs.has_key( 'title' ): title = kwargs['title'] self.infoPath = cmds.about(pd=True) + "/sg/fingerWeightCopy/Widget_LoadVertex_%s.txt" % title sgCmds.makeFile( self.infoPath ) vLayout = QVBoxLayout( self ); vLayout.setContentsMargins(0,0,0,0) groupBox = QGroupBox( title ) groupBox.setAlignment( QtCore.Qt.AlignCenter ) vLayout.addWidget( groupBox ) hLayout = QHBoxLayout() lineEdit = QLineEdit() button = QPushButton("Load"); button.setFixedWidth( 50 ) hLayout.addWidget( lineEdit ) hLayout.addWidget( button ) groupBox.setLayout( hLayout ) self.lineEdit = lineEdit QtCore.QObject.connect( button, QtCore.SIGNAL( "clicked()" ), self.loadVertex ) self.loadInfo()
def SGMPlugMod01Command_markingMenu_defaultMenu( parentName ): modeFilePath = uiInfoPath = cmds.about(pd=True) + "/sg/sg_toolInfo/SGMPlugMod01.txt" SGMPlugMod01_file.makeFile( modeFilePath ) f = open( modeFilePath, 'r' ) data = f.read() f.close() if not data: mel.eval( "SGMPlugMod01Command -sym 0" ) f = open( modeFilePath, 'w' ) f.write( 'False' ) f.close() SGMPlugMod01_markingMenuCmd.mirrorValue = 0 else: if data == 'True': mel.eval( "SGMPlugMod01Command -sym 1" ) SGMPlugMod01_markingMenuCmd.mirrorValue = 1 else: mel.eval( "SGMPlugMod01Command -sym 0" ) SGMPlugMod01_markingMenuCmd.mirrorValue = 0 cmds.menuItem( "Symmetry X", cb=SGMPlugMod01_markingMenuCmd.mirrorValue, rp="N", c=SGMPlugMod01_markingMenuCmd.symmetryXOn, p=parentName ) cmds.menuItem( l="Average", p=parentName, sm=1, rp='NW' ) cmds.menuItem( l="Average Normal", rp="NW", c = SGMPlugMod01_markingMenuCmd.averageNormal ) cmds.menuItem( l="Average Vertex", rp="W", c = SGMPlugMod01_markingMenuCmd.averageVertex ) cmds.menuItem( l="Delete History", p = parentName, c = SGMPlugMod01_markingMenuCmd.deleteHistory )
def createPreviewMayaFile(self): """docstring for createPreviewMayaFile""" createPrevScript = os.path.dirname(os.path.abspath(__file__)) + '/createPreview.py' cmd = 'C:/"Program Files"/Autodesk/Maya' + mc.about(v = True) + '/bin/' + 'mayapy.exe ' + createPrevScript + ' ' + self.path + self.name + '.ma' print cmd #create preview scene os.popen( cmd )
def getRefFiles(self,file,*args): """ Scan .ma file for reference file names. Prompt the user to browse to them if their path is invalid. """ version = cmds.about(v=True) rootFile = open(file,'r') refLines = [] refFiles = [] for line in rootFile: if line.strip().startswith('file -rdi'): refLines.append(line) count = 0 refPath = "" for each in refLines: temp1 = refLines[count].split() #No spaces in path name if len(temp1) == 7: refPath = temp1[7][1:-2] #Spaces in path name if len(temp1) > 7: refPath = self.buildRefPath(temp1) refFiles.append(refPath) count = count + 1 for each in refFiles: print each self.editRef(each)
def zipManyFiles(files): fileName = maya.cmds.file(q=True, sceneName=True) # If the scene has not been saved if (fileName==""): pyError( maya.stringTable['y_zipScene.kSceneNotSavedError'] ) return # If the scene has been created, saved and then erased from the disk elif (maya.cmds.file(q=True, exists=True)==0): msg = maya.stringTable['y_zipScene.kNonexistentFileError'] % fileName pyError(msg) return # get the default character encoding of the system theLocale = cmds.about(codeset=True) # get a list of all the files associated with the scene # files = maya.cmds.file(query=1, list=1, withoutCopyNumber=1) # create a zip file named the same as the scene by appending .zip # to the name zipFileName = (files[0])+'.zip' zip=zipfile.ZipFile(zipFileName, 'w', zipfile.ZIP_DEFLATED) # add each file associated with the scene, including the scene # to the .zip file for file in files: name = file.encode(theLocale) zip.write(name) zip.close() # output a message whose result is the name of the zip file newly created pyResult(zipFileName)
def appendPluginPath(): putenvStr = mel.eval( 'getenv "MAYA_PLUG_IN_PATH"' ) if os.name == 'posix': sepChar = ':' else: sepChar = ';' pythonPathName = sepChar + os.path.dirname( __file__.replace( '\\', '/' ) ) + '/pluginRoot' version = cmds.about(version=True)[:4] cppPathName = sepChar + os.path.dirname( __file__.replace( '\\', '/' ) ) + '/pluginRoot/' + version putenvStr = putenvStr.replace( pythonPathName, '' ) putenvStr += pythonPathName putenvStr = putenvStr.replace( cppPathName, '' ) putenvStr += cppPathName mel.eval( 'putenv "MAYA_PLUG_IN_PATH" "%s"' % putenvStr ) putenvStr = mel.eval( 'getenv "MAYA_PLUG_IN_PATH"' ) print "MAYA_PLUG_IN_PATH : " for path in putenvStr.split( sepChar ): print " ", path
def convert(*args): ''' Convert chosen files into xpm. ''' # Grab the path from the ScrollField targetPath = cmds.scrollField( "mecCVTDir", q=True, text=True) # Grabbing the selected elements from the textScrollList tslSel = cmds.textScrollList("mecCVTTSL", q=True, si=True) # - Checking to see if anything is selcted in the textScrollList # if nothing is selected grab everything. if( not(tslSel) ): print("Nothing selected in textScrollList Selected.\n Converting everything.") tslSel = cmds.textScrollList("mecCVTTSL", q=True, ai=True) for tsl in tslSel: # Creating the proper path to the files. # split file up to get the file name with out the extension. baseFile = tsl.split(".")[0] destFile = '"' + targetPath + "/""" + baseFile + '.xpm"' sourceFile = '"' + targetPath + "/" + tsl + '"' # Switching from front slashes to backslashes if on a windows machine. if(cmds.about(os=True) == "nt"): destFile = convertSlashes( destFile ) sourceFile = convertSlashes( sourceFile ) # Compiling the command line to convert the images. runLine = 'imconvert ' + sourceFile + " " + destFile print(runLine) # Executing the imconvert program from the command prompt (DOS) os.popen2(runLine)
def initPlugin(invert=False): pluginFolder = cmds.about(preferences=True) + "/modules/<pluginName>" if not invert: if not pluginFolder in sys.path: sys.path.append(pluginFolder) else: if pluginFolder in sys.path: sys.path.remove(pluginFolder)
def prompt( self ): """Aquire the information using a prompt dialog :return: prompted value if input was confirmed using confirmToken, or the cancelValue if cancelToken was pressed :note: tokens correspond to buttons :note: handles batch mode correctly""" if cmds.about( batch = 1 ): return super( Prompt, self ).prompt( ) default_text = ( self.confirmDefault is not None and self.confirmDefault ) or "" tokens = [ self.confirmToken ] token_kwargs = { "db" : self.confirmToken } if self.cancelToken is not None: tokens.append( self.cancelToken ) token_kwargs[ "cb" ] = self.cancelToken # END token preparation token_kwargs.update( self._kwargs ) ret = cmds.promptDialog( t="Prompt", m = self.msg, b = tokens, text = default_text, **token_kwargs ) if ret == self.cancelToken: return self.cancelDefault if ret == self.confirmToken: return cmds.promptDialog( q=1, text = 1 ) return self.confirmDefault
def loadPlugin(): """ load softSelectionQuery plugin """ mayaVers = int(mayaVersion()) os = cmds.about(os=1) if os == 'win64': pluginName = 'softSelectionQuery_%s-x64.mll' % mayaVers elif os == 'mac': pluginName = 'softSelectionQuery_%s.bundle' % mayaVers elif os == 'linux64': pluginName = 'softSelectionQuery_%s.so' % mayaVers else: cmds.error('Soft Cluster EX is available for 64bit version of Autodesk Maya 2011 ' 'or above under Windows 64bit, Mac OS X and Linux 64bit!') if not cmds.pluginInfo(pluginName, q=True, l=True ): cmds.loadPlugin(pluginName) version = cmds.pluginInfo(pluginName, q=1, v=1) log.info('Plug-in: %s v%s loaded success!' % (pluginName, version)) else: version = cmds.pluginInfo(pluginName, q=1, v=1) log.info('Plug-in: %s v%s has been loaded!' % (pluginName, version))
def run(*args, **kwargs): """ prepare the scene for the tests converts scene to use centimeters set the grid to the default """ valid_kwargs = ['verbose'] for k, v in kwargs.iteritems(): if k not in valid_kwargs: raise TypeError("Invalid keyword argument %s" % k) # verbose defaults to False if verbose option not set in menu or set # as cmdline argument try: verbose = kwargs['verbose'] except KeyError: verbose = False if cmds.optionVar(exists='checkmateVerbosity'): verbose = cmds.optionVar(query='checkmateVerbosity') else: verbose = False batch = cmds.about(batch=True) # get the name of the script Editor's output control from maya import mel as mel # Turn off Echo All Commands in the Script Editor # Disable Stack Tracevin the Script Editor # Turn off Line Numbers in errors in the Script Editor # Reset the grid # Set the background color # Turn off the heads-up displays # Switch to wrireframe mode # Close all windows (except main) # Close ChannelBox, Attribute Editor and Outliner () if not batch: try: gCommandReporter = mel.eval("proc string f(string $g){return $g;}f($gCommandReporter);") except RuntimeError: gCommandReporter = '' pass try: cmds.cmdScrollFieldReporter(gCommandReporter, edit=True, echoAllCommands=False, lineNumbers=True, stackTrace=True, suppressResults=False, suppressInfo=False, suppressWarnings=False, suppressErrors=False, suppressStackTrace=False, ) except RuntimeError: if verbose: print 'No Script Editor' pass # convert scene to cm to fix crashes in nearestnormal cmds.currentUnit(linear='cm')
def get_maya_version(): version = 2015 try: import maya.cmds as mc version = int(mc.about(v=1)) except: pass return version
def _getTimelineWinSize(): '''Dimensione finestra timeline a seconda se sono su qt o no.''' mayaVersion = cmds.about(version=True).split()[0] if _isQt: return (cmds.layout('MainTimeSliderLayout|formLayout9|frameLayout2', q=True, w=True)-17, 38) else: return ((cmds.control('MayaWindow|mayaMainWindowForm', q=True, w=True)-311), 70)
def __init__(self): """ Base init function for maya convert.write Class. """ self.supported_tan_types = ["spline", "linear", "clamped", "step", "fixed"] rodin_logger.info("kip maya writing class initialized") self.maya_version = "maya,%s" % cmds.about(v=True) self.kip_maya_version = "kipMaya%s" % os.getenv("DRD_KIPMAYA_VERSION")
def zipScene(archiveUnloadedReferences): fileName = cmds.file(q=True, sceneName=True) # If the scene has not been saved if (fileName == ""): pyError(maya.stringTable['y_zipScene.kSceneNotSavedError']) return # If the scene has been created, saved and then erased from the disk elif (cmds.file(q=True, exists=True) == 0): msg = maya.stringTable['y_zipScene.kNonexistentFileError'] % fileName pyError(msg) return # If the scene has been modified elif (cmds.file(q=True, anyModified=True) == 1): if (cmds.about(batch=True)): # batch mode, save the scene automatically. cmds.warning( maya.stringTable['y_zipScene.kSavingSceneBeforeArchiving']) cmds.file(force=True, save=True) else: noStr = maya.stringTable['y_zipScene.kArchiveSceneNo'] yesStr = maya.stringTable['y_zipScene.kArchiveSceneYes'] dismissStr = 'dismiss' result = cmds.confirmDialog( title=maya.stringTable['y_zipScene.kArchiveSceneTitle' ], message=maya.stringTable['y_zipScene.kArchiveSceneMsg' ], \ button=[yesStr,noStr], defaultButton=yesStr, cancelButton=noStr, dismissString=dismissStr ) if (result == yesStr): cmds.file(force=True, save=True) elif (result == dismissStr): return # get the default character encoding of the system theLocale = cmds.about(codeset=True) # get a list of all the files associated with the scene files = cmds.file(query=1, list=1, withoutCopyNumber=1) # create a zip file named the same as the scene by appending .zip to the name. # this need to be done before set(files) because set won't keep the order of filenames but we rely on that order to get the first one to construct zipFileName. zipFileName = (files[0]) + '.zip' zip = zipfile.ZipFile(zipFileName, 'w', zipfile.ZIP_DEFLATED) # If user choose to archive unloaded reference files, then find all referenced files of the current scene. # For any unloaded reference, load them first, get file list that should be archived and then restore its unloaded status. if (archiveUnloadedReferences == True): refNodes = cmds.ls(type='reference') isLoadOldList = [] for refNode in refNodes: if (refNode.find('sharedReferenceNode') == -1): isLoadOld = cmds.referenceQuery(refNode, isLoaded=True) isLoadOldList.append(isLoadOld) # Load the unloaded reference if (isLoadOld == False): cmds.file(loadReference=refNode, loadReferenceDepth='all') # Get all external files related to this reference filesOfThisRef = cmds.file(query=1, list=1, withoutCopyNumber=1) for fileOfThisRef in filesOfThisRef: files.append(fileOfThisRef) # Unload the reference that are unloaded at the beginning if (isLoadOld == False): cmds.file(unloadReference=refNode) # remove the possible duplicated file names files = set(files) files = list(files) # add the project workspace.mel file also workspacePath = cmds.workspace(q=True, fullName=True) + '/workspace.mel' files.append(workspacePath) # add each file associated with the scene, including the scene # to the .zip file for file in files: if (path.isfile(file)): name = file.encode(theLocale) zip.write(name) else: msg = maya.stringTable['y_zipScene.kArchiveFileSkipped'] % file cmds.warning(msg) zip.close() # output a message whose result is the name of the zip file newly created pyResult(zipFileName)
import numpy as np from os.path import splitext from os.path import basename from scipy.optimize import minimize import maya.cmds as cmds import maya.mel as mel import math from Qt import QtCore, QtWidgets from maya import OpenMayaUI as omui if int(cmds.about(v=True)) < 2017: from shiboken import wrapInstance else: from shiboken2 import wrapInstance mayaMainWindowPtr = omui.MQtUtil.mainWindow() mayaMainWindow = wrapInstance(long(mayaMainWindowPtr), QtWidgets.QWidget) class dm2skin_UI(QtWidgets.QDialog): """Builds the GUI""" def __init__(self, parent=mayaMainWindow): super(dm2skin_UI, self).__init__(parent) self.setWindowTitle('dm2skin') self.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed) self.setFixedHeight(175)
This code supports Pylint. Rc file in project. """ # pylint: disable=missing-function-docstring import os import platform # Check if this script is using mayapy. try: import maya.cmds as cmds except ImportError: raise RuntimeError( "Could not find Maya. You should use this script inside Maya, just drag it into the viewport." ) mayaVersion = cmds.about(version=True) # Import gfCore module to get information needed to install gfTools Maya plugins. gfCore is platform independant. try: from gfTools import gfCore except ImportError: raise RuntimeError("Could not find gfCore module.") dialogTitle = "gfTools for Maya Uninstallation" uninstallMsg = "This will uninstall gfTools plugins for Autodesk Maya. Are you sure you want to uninstall it?" modPathErrorMsg = "Could not find Maya module path. Uninstallation interrupted." appNotFounded = "gfTools installation not founded. Uninstallation interrupted." sucessMsg = "Uninstallation completed! You need to restart Maya to take effects." def windows():
def enabled(): return not cmds.about( batch=True) and not ExportListener.instance().isExporting()
def mayaVersionRelease(): return cmds.about(api=True)
def uninitialize_maya(): # Starting Maya 2016, we have to call uninitialize to properly shutdown if float(cmds.about(v=True)) >= 2016.0: maya.standalone.uninitialize()
_logger.error( "maya.standalone was successfully initialized, but pymel failed to import maya.cmds (or it was not populated)" ) raise finally: if oldSkipSetup is None: del os.environ['MAYA_SKIP_USERSETUP_PY'] else: os.environ['MAYA_SKIP_USERSETUP_PY'] = oldSkipSetup if not mayaStartupHasRun(): _logger.debug("running maya.app.startup") # If we're in 'maya -prompt' mode, and a plugin loads pymel, then we # can have a state where maya.standalone has been initialized, but # the python startup code hasn't yet been run... if about(batch=True): import maya.app.startup.batch else: import maya.app.startup.gui # return True, meaning we had to initialize maya standalone isInitializing = True return True def initMEL(): if 'PYMEL_SKIP_MEL_INIT' in os.environ or pymel_options.get( 'skip_mel_init', False): _logger.info("Skipping MEL initialization") return
# -*- coding: utf-8 -*- import maya.cmds as cmds import platform import random from functools import partial from tracker import before_tracking, after_tracking, send _VERSION = "0.0.1" _WINDOW_NAME = "GATrackingWindow" GA_BASE_PARAMS = {'ul': str(cmds.about(uil=True)), 'an': 'ga_plugin_example', 'aid': 'ga_plugin_example_id', 'av': _VERSION, 'aiid': str(cmds.about(iv=True)), 'cd': _WINDOW_NAME, 'cd1': str(platform.platform())} class GATrackingWindow(object): def __init__(self): self.windowName = _WINDOW_NAME self.windowTitle = self.windowName + "(v{0})".format(_VERSION) @classmethod def main(cls, *args): cls().create_gui() @before_tracking("screenview", GA_BASE_PARAMS) def create_gui(self): if cmds.window(self.windowName, exists=True):
# Built-in import os import urllib2 import xml.etree.cElementTree as etree # Third-party import maya.cmds as mc import maya.mel as mel # Custom # ------------------------------------------------------------------------- # ----------------------------------------------------------- Globals ----- __version__ = "3.0.0 b1c" MAYA_VERSION = mc.about(version=True) # ------------------------------------------------------------------------- # --------------------------------------------------------- Functions ----- def clear_menu(menu): """ Clear the specified menu of its current contents """ try: [mc.deleteUI(i) for i in mc.menu(menu, q=True, ia=True)] except: pass
def doIt(self, argList): global renderSettings print "Rendering with Cycles..." # Create a render settings node createRenderSettingsNode() #Save the user's selection userSelection = cmds.ls(sl=True) print("Render Settings - Node : %s" % renderSettings) #Get the directories and other variables projectDir = cmds.workspace(q=True, fn=True) renderDir = os.path.join(projectDir, "renderData") pluginDir = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe()))) version = cmds.about(v=True).replace(" ", "-") # Get render settings cyclesPath = cmds.getAttr("%s.%s" % (renderSettings, "cyclesPath")) oiiotoolPath = cmds.getAttr("%s.%s" % (renderSettings, "oiiotoolPath")) mtsDir = os.path.split(cyclesPath)[0] integrator = cmds.getAttr("%s.%s" % (renderSettings, "integrator")) sampler = cmds.getAttr("%s.%s" % (renderSettings, "sampler")) sampleCount = cmds.getAttr("%s.%s" % (renderSettings, "sampleCount")) reconstructionFilter = cmds.getAttr( "%s.%s" % (renderSettings, "reconstructionFilter")) keepTempFiles = cmds.getAttr("%s.%s" % (renderSettings, "keepTempFiles")) verbose = cmds.getAttr("%s.%s" % (renderSettings, "verbose")) print("Render Settings - Cycles Path : %s" % cyclesPath) print("Render Settings - Integrator : %s" % integrator) print("Render Settings - Sampler : %s" % sampler) print("Render Settings - Sample Count : %s" % sampleCount) print("Render Settings - Reconstruction : %s" % reconstructionFilter) print("Render Settings - Keep Temp Files : %s" % keepTempFiles) print("Render Settings - Verbose : %s" % verbose) print("Render Settings - Render Dir : %s" % renderDir) print("Render Settings - oiiotool Path : %s" % cyclesPath) animation = self.isAnimation() print("Render Settings - Animation : %s" % animation) # Animation if animation: startFrame = int(cmds.getAttr("defaultRenderGlobals.startFrame")) endFrame = int(cmds.getAttr("defaultRenderGlobals.endFrame")) byFrame = int(cmds.getAttr("defaultRenderGlobals.byFrameStep")) print("Animation frame range : %d to %d, step %d" % (startFrame, endFrame, byFrame)) for frame in range(startFrame, endFrame + 1, byFrame): print("Rendering frame " + str(frame) + " - begin") self.exportAndRender(renderDir, renderSettings, cyclesPath, oiiotoolPath, mtsDir, keepTempFiles, animation, frame, verbose) print("Rendering frame " + str(frame) + " - end") print("Animation finished") # Single frame else: imageName = self.exportAndRender(renderDir, renderSettings, cyclesPath, oiiotoolPath, mtsDir, keepTempFiles, animation, None, verbose) # Display the render if not cmds.about(batch=True): pass #CyclesRendererUI.showRender(imageName) # Select the objects that the user had selected before they rendered, or clear the selection if len(userSelection) > 0: cmds.select(userSelection) else: cmds.select(cl=True)
# Install SOuP on farm import maya.cmds as cmds version = cmds.about(v=True) soup_path = '//SEQ-LIVE/live_projects/_Plugins/Maya/SOuP/plug-ins/maya' + version + '_win' os.environ['MAYA_PLUG_IN_PATH'] += os.pathsep + soup_path
def init_engine(self): """ Initializes the Maya engine. """ self.logger.debug("%s: Initializing...", self) # check that we are running an ok version of maya current_os = cmds.about(operatingSystem=True) if current_os not in ["mac", "win64", "linux64"]: raise tank.TankError( "The current platform is not supported! Supported platforms " "are Mac, Linux 64 and Windows 64.") maya_ver = cmds.about(version=True) if maya_ver.startswith("Maya "): maya_ver = maya_ver[5:] if maya_ver.startswith(("2014", "2015", "2016", "2017", "2018")): self.logger.debug("Running Maya version %s", maya_ver) # In the case of Maya 2018 on Windows, we have the possility of locking # up if we allow the PySide shim to import QtWebEngineWidgets. We can # stop that happening here by setting the environment variable. version_num = int(maya_ver[0:4]) if version_num >= 2018 and current_os.startswith("win"): self.logger.debug( "Maya 2018+ on Windows can deadlock if QtWebEngineWidgets " "is imported. Setting SHOTGUN_SKIP_QTWEBENGINEWIDGETS_IMPORT=1..." ) os.environ["SHOTGUN_SKIP_QTWEBENGINEWIDGETS_IMPORT"] = "1" elif maya_ver.startswith(("2012", "2013")): # We won't be able to rely on the warning dialog below, because Maya # older than 2014 doesn't ship with PySide. Instead, we just have to # raise an exception so that we bail out here with an error message # that will hopefully make sense for the user. msg = "Shotgun integration is not compatible with Maya versions older than 2014." raise tank.TankError(msg) else: # show a warning that this version of Maya isn't yet fully tested with Shotgun: msg = ( "The Shotgun Pipeline Toolkit has not yet been fully tested with Maya %s. " "You can continue to use Toolkit but you may experience bugs or instability." "\n\nPlease report any issues to: [email protected]" % (maya_ver)) # determine if we should show the compatibility warning dialog: show_warning_dlg = self.has_ui and "SGTK_COMPATIBILITY_DIALOG_SHOWN" not in os.environ if show_warning_dlg: # make sure we only show it once per session: os.environ["SGTK_COMPATIBILITY_DIALOG_SHOWN"] = "1" # split off the major version number - accomodate complex version strings and decimals: major_version_number_str = maya_ver.split(" ")[0].split(".")[0] if major_version_number_str and major_version_number_str.isdigit( ): # check against the compatibility_dialog_min_version setting: if int(major_version_number_str) < self.get_setting( "compatibility_dialog_min_version"): show_warning_dlg = False if show_warning_dlg: # Note, title is padded to try to ensure dialog isn't insanely narrow! title = "Warning - Shotgun Pipeline Toolkit Compatibility! " # padded! cmds.confirmDialog(title=title, message=msg, button="Ok") # always log the warning to the script editor: self.logger.warning(msg) # In the case of Maya 2018 on Windows, we have the possility of locking # up if we allow the PySide shim to import QtWebEngineWidgets. We can # stop that happening here by setting the environment variable. if current_os.startswith("win"): self.logger.debug( "Maya 2018+ on Windows can deadlock if QtWebEngineWidgets " "is imported. Setting SHOTGUN_SKIP_QTWEBENGINEWIDGETS_IMPORT=1..." ) os.environ["SHOTGUN_SKIP_QTWEBENGINEWIDGETS_IMPORT"] = "1" # Set the Maya project based on config self._set_project() # add qt paths and dlls self._init_pyside() # default menu name is Shotgun but this can be overriden # in the configuration to be Sgtk in case of conflicts self._menu_name = "Shotgun" if self.get_setting("use_sgtk_as_menu_name", False): self._menu_name = "Sgtk" if self.get_setting("automatic_context_switch", True): # need to watch some scene events in case the engine needs rebuilding: cb_fn = lambda en=self.instance_name, pc=self.context, mn=self._menu_name: on_scene_event_callback( en, pc, mn) self.__watcher = SceneEventWatcher(cb_fn) self.logger.debug("Registered open and save callbacks.") # Initialize a dictionary of Maya panels that have been created by the engine. # Each panel entry has a Maya panel name key and an app widget instance value. self._maya_panel_dict = {}
from maya import cmds def main(): from transfer_blend_shape import install install.execute() if not cmds.about(batch=True): cmds.evalDeferred(main)
首先选择被约束物体,第二个物体是驱动物体。 最后执行 `Python` 命令: sys.FXTD_Odyssey_VertexConstraintDeformer() ''' import sys import maya.OpenMaya as OpenMaya import maya.OpenMayaMPx as OpenMayaMPx from maya import mel import math nodeName = "VertexConstraint" nodeId = OpenMaya.MTypeId(0xAA2fff) import maya.cmds as cmds kApiVersion = cmds.about(apiVersion=True) if kApiVersion < 201600: kInput = OpenMayaMPx.cvar.MPxDeformerNode_input kInputGeom = OpenMayaMPx.cvar.MPxDeformerNode_inputGeom kOutputGeom = OpenMayaMPx.cvar.MPxDeformerNode_outputGeom kEnvelope = OpenMayaMPx.cvar.MPxDeformerNode_envelope kGroupId = OpenMayaMPx.cvar.MPxDeformerNode_groupId else: kInput = OpenMayaMPx.cvar.MPxGeometryFilter_input kInputGeom = OpenMayaMPx.cvar.MPxGeometryFilter_inputGeom kOutputGeom = OpenMayaMPx.cvar.MPxGeometryFilter_outputGeom kEnvelope = OpenMayaMPx.cvar.MPxGeometryFilter_envelope kGroupId = OpenMayaMPx.cvar.MPxGeometryFilter_groupId class VertexConstraint(OpenMayaMPx.MPxDeformerNode):
def get_soft_version(): """ :return: MAYA VERSION """ return mc.about(v=True)
def DisplayPoly(self, myPlane): mayaversions = mc.about(v=True) rendererName = mc.modelEditor(self.myactivePlane, q=True, rendererName=True) if mayaversions.find('2009') >= 0: mc.modelEditor(myPlane, e=True, polymeshs=True, nurbsCurves=False, nurbsSurfaces=False, subdivSurfaces=False, planes=True, light=False, cameras=False, joints=False, ikHandles=False, deformers=False, dynamics=False, fluids=True, hairSystems=False, follicles=False, nCloths=False, nParticles=False, nRigids=False, dynamicConstraints=False, locators=False, dimension=False, pivots=False, handles=False, textures=False, strokes=False, manipulators=False, grid=False, hud=False, rendererName=rendererName) else: mc.modelEditor(myPlane, e=True, polymeshes=True, nurbsCurves=False, nurbsSurfaces=False, subdivSurfaces=False, planes=False, lights=False, cameras=False, joints=False, ikHandles=False, deformers=False, dynamics=False, fluids=True, hairSystems=False, follicles=False, nCloths=False, nParticles=False, nRigids=False, dynamicConstraints=False, locators=True, dimensions=False, pivots=False, handles=False, textures=False, strokes=False, motionTrails=False, manipulators=False, clipGhosts=False, grid=False, hud=False, rendererName=rendererName)
def rigModule(self, *args): Base.StartClass.rigModule(self) # verify if the guide exists: if cmds.objExists(self.moduleGrp): try: hideJoints = cmds.checkBox('hideJointsCB', query=True, value=True) except: hideJoints = 1 # start as no having mirror: sideList = [""] # analisys the mirror module: self.mirrorAxis = cmds.getAttr(self.moduleGrp + ".mirrorAxis") if self.mirrorAxis != 'off': # get rigs names: self.mirrorNames = cmds.getAttr(self.moduleGrp + ".mirrorName") # get first and last letters to use as side initials (prefix): sideList = [ self.mirrorNames[0] + '_', self.mirrorNames[len(self.mirrorNames) - 1] + '_' ] for s, side in enumerate(sideList): duplicated = cmds.duplicate( self.moduleGrp, name=side + self.userGuideName + '_Guide_Base')[0] allGuideList = cmds.listRelatives(duplicated, allDescendents=True) for item in allGuideList: cmds.rename(item, side + self.userGuideName + "_" + item) self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True) cmds.parent(side + self.userGuideName + '_Guide_Base', self.mirrorGrp, absolute=True) # re-rename grp: cmds.rename( self.mirrorGrp, side + self.userGuideName + '_' + self.mirrorGrp) # do a group mirror with negative scaling: if s == 1: if cmds.getAttr(self.moduleGrp + ".flip") == 0: for axis in self.mirrorAxis: gotValue = cmds.getAttr( side + self.userGuideName + "_Guide_Base.translate" + axis) flipedValue = gotValue * (-2) cmds.setAttr( side + self.userGuideName + '_' + self.mirrorGrp + '.translate' + axis, flipedValue) else: for axis in self.mirrorAxis: cmds.setAttr( side + self.userGuideName + '_' + self.mirrorGrp + '.scale' + axis, -1) # joint labelling: jointLabelAdd = 1 else: # if not mirror: duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName + '_Guide_Base')[0] allGuideList = cmds.listRelatives(duplicated, allDescendents=True) for item in allGuideList: cmds.rename(item, self.userGuideName + "_" + item) self.mirrorGrp = cmds.group(self.userGuideName + '_Guide_Base', name="Guide_Base_Grp", relative=True) #for Maya2012: self.userGuideName+'_'+self.moduleGrp+"_Grp" # re-rename grp: cmds.rename(self.mirrorGrp, self.userGuideName + '_' + self.mirrorGrp) # joint labelling: jointLabelAdd = 0 # store the number of this guide by module type dpAR_count = utils.findModuleLastNumber(CLASS_NAME, "dpAR_type") + 1 # run for all sides for s, side in enumerate(sideList): self.base = side + self.userGuideName + '_Guide_Base' cmds.select(clear=True) # declare guide: self.guide = side + self.userGuideName + "_Guide_JointLoc1" # create a joint: self.jnt = cmds.joint(name=side + self.userGuideName + "_Jnt", scaleCompensate=False) cmds.addAttr(self.jnt, longName='dpAR_joint', attributeType='float', keyable=False) utils.setJointLabel(self.jnt, s + jointLabelAdd, 18, self.userGuideName) # create a control: if not self.getHasIndirectSkin(): if self.curveDegree == 0: self.curveDegree = 1 # work with curve shape and rotation cases: indirectSkinRot = (0, 0, 0) if self.langDic[ self.langName]['c058_main'] in self.userGuideName: ctrlTypeID = "id_054_SingleMain" if len(sideList) > 1: if self.langDic[self.langName][ 'c041_eyebrow'] in self.userGuideName: indirectSkinRot = (0, 0, -90) else: indirectSkinRot = (0, 0, 90) else: ctrlTypeID = "id_029_SingleIndSkin" if self.langDic[ self.langName]['c045_lower'] in self.userGuideName: indirectSkinRot = (0, 0, 180) elif self.langDic[self.langName][ 'c043_corner'] in self.userGuideName: if "00" in self.userGuideName: indirectSkinRot = (0, 0, 90) else: indirectSkinRot = (0, 0, -90) self.singleCtrl = self.ctrls.cvControl( ctrlTypeID, side + self.userGuideName + "_Ctrl", r=self.ctrlRadius, d=self.curveDegree, rot=indirectSkinRot) utils.originedFrom(objName=self.singleCtrl, attrString=self.base + ";" + self.guide) # position and orientation of joint and control: cmds.delete( cmds.parentConstraint(self.guide, self.jnt, maintainOffset=False)) cmds.delete( cmds.parentConstraint(self.guide, self.singleCtrl, maintainOffset=False)) # zeroOut controls: zeroOutCtrlGrp = utils.zeroOut([self.singleCtrl], offset=True)[0] # hide visibility attribute: cmds.setAttr(self.singleCtrl + '.visibility', keyable=False) # fixing flip mirror: if s == 1: if cmds.getAttr(self.moduleGrp + ".flip") == 1: cmds.setAttr(zeroOutCtrlGrp + ".scaleX", -1) cmds.setAttr(zeroOutCtrlGrp + ".scaleY", -1) cmds.setAttr(zeroOutCtrlGrp + ".scaleZ", -1) if not self.getHasIndirectSkin(): cmds.addAttr(self.singleCtrl, longName='scaleCompensate', attributeType="bool", keyable=False) cmds.setAttr(self.singleCtrl + ".scaleCompensate", 1, channelBox=True) cmds.connectAttr(self.singleCtrl + ".scaleCompensate", self.jnt + ".segmentScaleCompensate", force=True) if self.getHasIndirectSkin(): # create a fatherJoint in order to zeroOut the skinning joint: cmds.select(clear=True) jxtName = self.jnt.replace("_Jnt", "_Jxt") self.jxt = cmds.duplicate(self.jnt, name=jxtName)[0] cmds.deleteAttr(self.jxt, attribute="dpAR_joint") cmds.parent(self.jnt, self.jxt) cmds.makeIdentity(self.jnt, apply=True, jointOrient=False) attrList = [ 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz' ] for attr in attrList: cmds.connectAttr(self.singleCtrl + '.' + attr, self.jnt + '.' + attr) if s == 1: if cmds.getAttr(self.moduleGrp + ".flip") == 1: cmds.setAttr(self.jxt + ".scaleX", -1) cmds.setAttr(self.jxt + ".scaleY", -1) cmds.setAttr(self.jxt + ".scaleZ", -1) if self.getHasHolder(): cmds.delete(self.singleCtrl + "Shape", shape=True) self.singleCtrl = cmds.rename( self.singleCtrl, self.singleCtrl + "_" + self.langDic[self.langName]['c046_holder'] + "_Grp") self.ctrls.setLockHide([self.singleCtrl], [ 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz' ]) self.jnt = cmds.rename( self.jnt, self.jnt.replace( "_Jnt", "_" + self.langDic[self.langName]['c046_holder'] + "_Jis")) self.ctrls.setLockHide([self.jnt], [ 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz' ], True, True) else: self.jnt = cmds.rename( self.jnt, self.jnt.replace("_Jnt", "_Jis")) else: # like a fkLine # create parentConstraint from ctrl to jnt: cmds.parentConstraint(self.singleCtrl, self.jnt, maintainOffset=False, name=self.jnt + "_ParentConstraint") # create scaleConstraint from ctrl to jnt: cmds.scaleConstraint(self.singleCtrl, self.jnt, maintainOffset=True, name=self.jnt + "_ScaleConstraint") # create end joint: cmds.select(self.jnt) self.cvEndJoint = side + self.userGuideName + "_Guide_JointEnd" self.endJoint = cmds.joint(name=side + self.userGuideName + "_JEnd") cmds.delete( cmds.parentConstraint(self.cvEndJoint, self.endJoint, maintainOffset=False)) self.mainJisList.append(self.jnt) # create a masterModuleGrp to be checked if this rig exists: self.toCtrlHookGrp = cmds.group( side + self.userGuideName + "_Ctrl_Zero_Grp", name=side + self.userGuideName + "_Control_Grp") if self.getHasIndirectSkin(): locScale = cmds.spaceLocator(name=side + self.userGuideName + "_Scalable_DO_NOT_DELETE")[0] cmds.setAttr(locScale + ".visibility", 0) self.toScalableHookGrp = cmds.group( locScale, name=side + self.userGuideName + "_IndirectSkin_Grp") jxtGrp = cmds.group(side + self.userGuideName + "_Jxt", name=side + self.userGuideName + "_Joint_Grp") self.toStaticHookGrp = cmds.group( jxtGrp, self.toScalableHookGrp, self.toCtrlHookGrp, name=side + self.userGuideName + "_Grp") else: self.toScalableHookGrp = cmds.group( side + self.userGuideName + "_Jnt", name=side + self.userGuideName + "_Joint_Grp") self.toStaticHookGrp = cmds.group( self.toCtrlHookGrp, self.toScalableHookGrp, name=side + self.userGuideName + "_Grp") # create a locator in order to avoid delete static or scalable group loc = cmds.spaceLocator(name=side + self.userGuideName + "_DO_NOT_DELETE")[0] cmds.parent(loc, self.toStaticHookGrp, absolute=True) cmds.setAttr(loc + ".visibility", 0) self.ctrls.setLockHide([loc], [ 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v' ]) # add hook attributes to be read when rigging integrated modules: utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook') utils.addHook(objName=self.toScalableHookGrp, hookType='scalableHook') utils.addHook(objName=self.toStaticHookGrp, hookType='staticHook') cmds.addAttr(self.toStaticHookGrp, longName="dpAR_name", dataType="string") cmds.addAttr(self.toStaticHookGrp, longName="dpAR_type", dataType="string") cmds.setAttr(self.toStaticHookGrp + ".dpAR_name", self.userGuideName, type="string") cmds.setAttr(self.toStaticHookGrp + ".dpAR_type", CLASS_NAME, type="string") self.aStaticGrpList.append(self.toStaticHookGrp) self.aCtrlGrpList.append(self.toCtrlHookGrp) # add module type counter value cmds.addAttr(self.toStaticHookGrp, longName='dpAR_count', attributeType='long', keyable=False) cmds.setAttr(self.toStaticHookGrp + '.dpAR_count', dpAR_count) if hideJoints: cmds.setAttr(self.toScalableHookGrp + ".visibility", 0) # delete duplicated group for side (mirror): cmds.delete(side + self.userGuideName + '_' + self.mirrorGrp) # check mirror indirectSkin bug in Maya2018: if (int(cmds.about(version=True)[:4]) == 2018): if self.mirrorAxis != 'off': if self.getHasIndirectSkin(): meshList = cmds.ls(selection=False, type="mesh") if meshList: self.detectedBug = True # finalize this rig: self.integratingInfo() cmds.select(clear=True) # delete UI (moduleLayout), GUIDE and moduleInstance namespace: self.deleteModule()
def sang_poly(chue_tem_file, mmddata, khanat=8, ao_alpha_map=1, yaek_poly=0, watsadu=1, yaek_alpha=0): try: from PIL import Image except ImportError: yaek_alpha = 0 chue_file = os.path.basename(chue_tem_file) # ชื่อไฟล์ไม่รวมพาธ # ชื่อโมเดลเอาชื่อไฟล์มาตัดสกุลออกแล้วเปลี่ยนเป็นภาษาญี่ปุ่นเป็นโรมาจิให้หมด chue_model = romaji(chuedidi(mmddata.name, os.path.splitext(chue_file)[0])) vers = int(mc.about( version=1).split(' ')[0]) >= 2018 # เวอร์ชันเป็น 2018 ขึ้นไปหรือไม่ print(u'面を作成中') if (yaek_poly): # ถ้าเลือกว่าจะแยกโพลิกอนก็ยังไม่ต้องทำอะไร list_chue_nod_poly = [] else: # ถ้าไม่ได้เลือกว่าจะแยกโพลิกอนก็ให้สร้างโพลิกอนผิวเลย n_chut = len(mmddata.vertices) # จำนวนจุดยอดของโมเดล chut = om.MFloatPointArray(n_chut) u = om.MFloatArray(n_chut) v = om.MFloatArray(n_chut) # วนซ้ำไล่ดึงข้อมูลของจุดยอดแต่ละจุด for i, c in enumerate(mmddata.vertices): # ตั้งค่าตำแหน่งของจุดยอด p = c.position p = om.MFloatPoint(p.x * khanat, p.y * khanat, -p.z * khanat) chut.set(p, i) # ตั้งค่า uv u[i] = c.uv.x v[i] = 1. - c.uv.y n_index = 0 # จำนวนจุดที่ใช้ได้ list_index_chut = [] # วนซ้ำเพื่อป้อนค่าดัชนีของจุด for i in range(0, len(mmddata.indices), 3): ic0 = mmddata.indices[i] ic1 = mmddata.indices[i + 1] ic2 = mmddata.indices[i + 2] if (ic0 != ic1 != ic2 != ic0): # หน้าที่ใช้ได้คือจะต้องไม่ใช้จุดซ้ำกันในหน้าเดียว list_index_chut.extend([ic2, ic1, ic0]) # ใส่จุดลงในลิสต์ n_index += 3 index_chut = om.MIntArray(n_index) for i, ic in enumerate(list_index_chut): index_chut.set(ic, i) n_na = n_index / 3 # จำนวนหน้า array_n_chut_to_na = om.MIntArray( n_na, 3) # จำนวนจุดต่อหน้า ตั้งให้แต่ละหน้ามี 3 จุดทั้งหมด trans_fn = om.MFnTransform() trans_obj = trans_fn.create() trans_fn.setName(chue_model) chue_nod_poly = trans_fn.name() fn_mesh = om.MFnMesh() # สร้างโพลิกอนจากข้อมูลทั้งหมดที่เตรียมไว้ fn_mesh.create(n_chut, n_na, chut, array_n_chut_to_na, index_chut, u, v, trans_obj) fn_mesh.setName(chue_nod_poly + 'Shape') fn_mesh.assignUVs(array_n_chut_to_na, index_chut) # เพิ่มค่าองค์ประกอบที่บอกว่ามาจาก MMD mc.addAttr(chue_nod_poly, ln='chakMMD', nn=u'MMDから', at='bool') mc.setAttr(chue_nod_poly + '.chakMMD', 1) # ทำให้โปร่งใสได้ สำหรับอาร์โนลด์ if (watsadu == 4): mc.setAttr(chue_nod_poly + '.aiOpaque', 0) # ถ้าไม่เอาสีผิวก็ให้ใส่ผิวตั้งต้นแล้วก็ไม่ต้องสร้างวัสดุแล้ว if (not watsadu): mc.select(chue_nod_poly) mc.hyperShade(a='lambert1') return chue_nod_poly, [] # สร้างวัสดุพื้นผิว path_file = os.path.dirname(chue_tem_file) # พาธของไฟล์โมเดล set_index_tex = set([mat.texture_index for mat in mmddata.materials ]) # เซ็ตของไฟล์เท็กซ์เจอร์ที่ถูกใช้ list_chue_nod_file = [] # ลิสต์เก็บชื่อโหนดของไฟล์เท็กซ์เจอร์ list_chue_nod_file_alpha = [ ] # ลิสต์เก็บชื่อโหนดของไฟล์อัลฟาของเท็กซ์เจอร์ for i, tex in enumerate(mmddata.textures): path_tem_tex = os.path.join( *([path_file] + tex.split('\\'))) # ไฟล์เท็กซ์เจอร์ เพิ่มพาธของไฟล์โมเดลลงไป chue_tex = tex.replace('\\', '_').replace('/', '_').replace('.', '_') chue_tex = romaji(chue_tex) # เปลี่ยนชื่อเป็นโรมาจิ chue_nod_file = chue_tex + '_file_' + chue_model #+'_%d'%os.stat(chue_tem_file).st_mtime chue_nod_file_alpha = chue_nod_file if (i in set_index_tex ): #if(not mc.objExists(chue_nod_file) and i in set_index_tex): # สร้างโหนดไฟล์เท็กซ์เจอร์ chue_nod_file = mc.shadingNode('file', at=1, n=chue_nod_file) chue_nod_file_alpha = chue_nod_file mc.setAttr(chue_nod_file + '.ftn', path_tem_tex, typ='string') # สร้างโหนด placed2d chue_nod_placed2d = mc.shadingNode('place2dTexture', au=1, n=chue_tex + '_placed2d_' + chue_model) # เชื่อมค่าต่างๆของโหนด placed2d เข้ากับโหนดไฟล์ for cp in chueam_placed2d: mc.connectAttr('%s.%s' % (chue_nod_placed2d, cp[0]), '%s.%s' % (chue_nod_file, cp[1]), f=1) # กรณีที่เลือกว่าจะแยกอัลฟาไปอีกไฟล์ และไฟล์นั้นมีอัลฟาอยู่ด้วย if (yaek_alpha and ao_alpha_map and mc.getAttr(chue_nod_file + '.fileHasAlpha') == 1): file_phap = Image.open(path_tem_tex) # เปิดอ่านไฟล์ด้วย PIL file_alpha = file_phap.split()[-1] # สกัดเอาเฉพาะอัลฟา pta = os.path.split(path_tem_tex) path_tem_alpha = os.path.join( pta[0], u'00arufa_' + pta[1]) # ชื่อไฟล์ใหม่ที่จะสร้าง แค่เติมคำนำหน้า file_alpha.save(path_tem_alpha) # สร้างไฟล์ค่าอัลฟา chue_nod_file_alpha = mc.shadingNode('file', at=1, n=chue_nod_file + '_alpha') # โหนดไฟล์อัลฟา mc.setAttr(chue_nod_file_alpha + '.ftn', path_tem_alpha, typ='string') mc.setAttr(chue_nod_file_alpha + '.alphaIsLuminance', 1) for cp in chueam_placed2d: # เชื่อมกับโหนด placed2d อันเดียวกับของไฟล์ภาพ mc.connectAttr('%s.%s' % (chue_nod_placed2d, cp[0]), '%s.%s' % (chue_nod_file_alpha, cp[1]), f=1) list_chue_nod_file.append(chue_nod_file) list_chue_nod_file_alpha.append(chue_nod_file_alpha) list_mat_ao_alpha = [] # ถ้าเลือกว่าจะทำอัลฟาแม็ป if (ao_alpha_map): try: # ลองหาดูว่าไฟล์โมเดลเคยมีบันทึกการทำอัลฟาแม็ปหรือไม่ ถ้ามีก็ดึงข้อมูลที่ว่าวัสดุไหนจะทำอัลฟาแม็ป with codecs.open( os.path.join(os.path.dirname(__file__), u'modelalpha.txt'), 'r', 'utf-8') as f: for thaeo in f: if (chue_tem_file in thaeo): list_mat_ao_alpha = f.readline()[1:].strip().split( '::') break except: 0 # สร้างโหนดวัสดุ nap_na = 0 list_mat_mi_alpha = [] # ลิสต์เก็บวัสดุที่มีอัลฟา if ( watsadu == 4 ): # ดูเวอร์ชันของมายาเพื่อแยกแยะว่าใช้แอตทริบิวต์ของ aiStandard หรือ aiStandardSurface attr = [[ 'color', 'KsColor', 'opacity', 'Ks', 'specularRoughness', 'Kd' ], [ 'baseColor', 'specularColor', 'opacity', 'specular', 'specularRoughness', 'base' ]][vers] # เริ่มวนไล่สร้างวัสดุทีละอัน for i, mat in enumerate(mmddata.materials): n_index = mat.vertex_count # จำนวนดัชนีจุด (เป็น 3 เท่าของจำนวนหน้า) if (n_index == 0): continue n_na = n_index / 3 # จำนวนหน้าที่วัสดุจะไปแปะลง # ตั้งชื่อให้เป็นโรมาจิ chue_mat = romaji(chuedidi(mat.name, u'watsadu%d' % i)) chue_nod_mat = chue_mat + '_mat_' + chue_model #+'_%d'%os.stat(chue_tem_file).st_mtime if (0): #if(mc.objExists(chue_nod_mat)): chue_nod_sg = chue_nod_mat + 'SG' else: # ดึงข้อมูลค่าคุณสมบัติต่างๆของวัสดุ i_tex = mat.texture_index # ดัชนีของเท็กซ์เจอร์ที่จะใช้ใส่วัสดุนี้ dc = (mat.diffuse_color.r, mat.diffuse_color.g, mat.diffuse_color.b) ambc = (mat.ambient_color.r, mat.ambient_color.g, mat.ambient_color.b) spec = (mat.specular_color.r, mat.specular_color.g, mat.specular_color.b) opa = (mat.alpha, mat.alpha, mat.alpha) trans = (1 - mat.alpha, 1 - mat.alpha, 1 - mat.alpha) sf = mat.specular_factor # สร้างโหนดวัสดุและตั้งค่าคุณสมบัติต่างๆของวัสดุตามข้อมูลที่ดึงมาได้ if (watsadu == 1): chue_nod_mat = mc.shadingNode('blinn', asShader=1, n=chue_nod_mat) mc.setAttr(chue_nod_mat + '.specularColor', *spec, typ='double3') mc.setAttr(chue_nod_mat + '.specularRollOff', 0.75**(math.log(max(sf, 2**-10), 2) + 1)) mc.setAttr(chue_nod_mat + '.eccentricity', sf * 0.01) elif (watsadu == 2): chue_nod_mat = mc.shadingNode('phong', asShader=1, n=chue_nod_mat) mc.setAttr(chue_nod_mat + '.specularColor', *spec, typ='double3') mc.setAttr(chue_nod_mat + '.cosinePower', max((10000. / max(sf, 15)**2 - 3.357) / 0.454, 2)) elif (watsadu == 3): chue_nod_mat = mc.shadingNode('lambert', asShader=1, n=chue_nod_mat) if (watsadu in [1, 2, 3]): mc.setAttr(chue_nod_mat + '.color', *dc, typ='double3') if (i_tex == -1): # กรณีที่ไม่ได้ใช้เท็กซ์เจอร์ แอมเบียนต์มักถูกปรับตามสีหลัก ต้องทำการปรับคืน c = [] for a, d in zip(ambc, dc): if (d != 0): c.append(min(a / d, 1)) else: c.append(0) mc.setAttr(chue_nod_mat + '.ambientColor', *ambc, typ='double3') else: mc.setAttr(chue_nod_mat + '.ambientColor', *ambc, typ='double3') mc.setAttr(chue_nod_mat + '.transparency', *trans, typ='double3') elif (watsadu == 4): # ใช้วัสดุเป็น aiStandard หรือ aiStandardSurface แล้วแต่เวอร์ชัน if (vers): chue_nod_mat = mc.shadingNode('aiStandardSurface', asShader=1, n=chue_nod_mat) else: chue_nod_mat = mc.shadingNode('aiStandard', asShader=1, n=chue_nod_mat) mc.setAttr(chue_nod_mat + '.' + attr[0], *dc, typ='double3') mc.setAttr(chue_nod_mat + '.' + attr[1], *spec, typ='double3') mc.setAttr(chue_nod_mat + '.' + attr[2], *opa, typ='double3') mc.setAttr(chue_nod_mat + '.' + attr[3], 0.75**(math.log(max(sf, 0.5), 2) + 1)) mc.setAttr(chue_nod_mat + '.' + attr[4], min(sf * 0.01, 1)) mc.setAttr(chue_nod_mat + '.' + attr[5], 0.8) # เก็บชื่อเดิม (ชื่อญี่ปุ่น) ของวัสดุไว้เผื่อใช้ mc.addAttr(chue_nod_mat, ln='namae', nn=u'名前', dt='string') mc.setAttr(chue_nod_mat + '.namae', chuedidi(mat.name), typ='string') # ถ้าไม่มีเท็กซ์เจอร์จะเป็น -1 ก็ไม่ต้องไปเชื่อมต่อ if (i_tex >= 0): chue_nod_file = list_chue_nod_file[ i_tex] # โหนดไฟล์เท็กซ์เจอร์ # เชื่อมต่อสีจากไฟล์เข้ากับวัสดุ if (vers and watsadu == 4): mc.connectAttr(chue_nod_file + '.outColor', chue_nod_mat + '.baseColor') else: mc.connectAttr(chue_nod_file + '.outColor', chue_nod_mat + '.color') # ถ้าเลือกว่าจะทำอัลฟาแม็ปด้วย และไฟล์มีอัลฟาแม็ป if (ao_alpha_map and mc.getAttr(chue_nod_file + '.fileHasAlpha') == 1): # and mat.alpha==1. if (mmddata.textures[i_tex].split('.')[-1].lower() in ['png', 'tga', 'dds', 'bmp']): if (list_mat_ao_alpha != [] and chue_mat not in list_mat_ao_alpha and ao_alpha_map == 1): # ถ้าไม่มีอยู่ในลิสต์ที่เลือกไว้แล้วว่าจะทำอัลฟาแม็ป ao_alpha = 0 else: chue_nod_file_alpha = list_chue_nod_file_alpha[ i_tex] # โหนดไฟล์เท็กซ์เจอร์ # ถ้ามีอยู่ในลิสต์ที่ต้องการทำ หรือยังไม่ได้บันทึกข้อมูลการเลือกเอาไว้ if (watsadu in [1, 2, 3]): mc.connectAttr( chue_nod_file_alpha + '.outTransparency', chue_nod_mat + '.transparency') elif (watsadu == 4): mc.connectAttr( chue_nod_file_alpha + '.outAlpha', chue_nod_mat + '.opacityR') mc.connectAttr( chue_nod_file_alpha + '.outAlpha', chue_nod_mat + '.opacityG') mc.connectAttr( chue_nod_file_alpha + '.outAlpha', chue_nod_mat + '.opacityB') ao_alpha = 1 list_mat_mi_alpha.append( (chue_nod_mat, chue_mat, ao_alpha)) chue_nod_sg = mc.sets(r=1, nss=1, em=1, n=chue_nod_mat + 'SG') mc.connectAttr(chue_nod_mat + '.outColor', chue_nod_sg + '.surfaceShader', f=1) if (yaek_poly): # ถ้าเลือกว่าให้แยกโพลิกอนให้ทำการสร้างโพลิกอนแยกตามวัสดุขึ้นมาตรงนี้ nap_index = nap_na * 3 n_index_chaidai = 0 list_index_chut = [] dic_chut = {} # ดิกเก็บเลขดัชนีของจุดยอดที่ถูกใช้ k = 0 # ค่าดัชนีใหม่ for j in range(0, n_index, 3): # ค่าดัชนีจากในไฟล์ ic0 = mmddata.indices[nap_index + j] ic1 = mmddata.indices[nap_index + j + 1] ic2 = mmddata.indices[nap_index + j + 2] if (ic0 != ic1 != ic2 != ic0): if (ic0 not in dic_chut): dic_chut[ic0] = k # จับคู่ดัชนีใหม่กับดัชนีในไฟล์ k += 1 if (ic1 not in dic_chut): dic_chut[ic1] = k k += 1 if (ic2 not in dic_chut): dic_chut[ic2] = k k += 1 list_index_chut.extend( [dic_chut[ic2], dic_chut[ic1], dic_chut[ic0]]) n_index_chaidai += 3 index_chut = om.MIntArray(n_index_chaidai) for j, ic in enumerate(list_index_chut): index_chut.set(ic, j) n_na_chaidai = n_index_chaidai / 3 array_n_chut_to_na = om.MIntArray(n_na_chaidai, 3) n_chut = len(dic_chut) chut = om.MFloatPointArray(n_chut) u = om.MFloatArray(n_chut) v = om.MFloatArray(n_chut) for ic in dic_chut: k = dic_chut[ic] c = mmddata.vertices[ic] # ตั้งค่าตำแหน่งของจุดยอด p = c.position p = om.MFloatPoint(p.x * khanat, p.y * khanat, -p.z * khanat) chut.set(p, k) # ตั้งค่า uv u[k] = c.uv.x v[k] = 1. - c.uv.y trans_fn = om.MFnTransform() trans_obj = trans_fn.create() chue_nod_poly = chue_model + '_%d' % (i + 1) while (mc.objExists(chue_nod_poly)): chue_nod_poly += u'_' trans_fn.setName(chue_nod_poly) chue_nod_poly = trans_fn.name() fn_mesh = om.MFnMesh() # สร้างโพลิกอน fn_mesh.create(n_chut, n_na_chaidai, chut, array_n_chut_to_na, index_chut, u, v, trans_obj) fn_mesh.setName(chue_nod_poly + 'Shape') fn_mesh.assignUVs(array_n_chut_to_na, index_chut) # ทำให้โปร่งใสได้ สำหรับอาร์โนลด์ if (watsadu == 4): mc.setAttr(chue_nod_poly + '.aiOpaque', 0) # เพิ่มค่าองค์ประกอบที่บอกว่ามาจาก MMD mc.addAttr(chue_nod_poly, ln='chakMMD', nn=u'MMDから', at='bool') mc.setAttr(chue_nod_poly + '.chakMMD', 1) # ใส่วัสดุให้กับผิว mc.sets(chue_nod_poly + '.f[%s:%s]' % (0, n_na_chaidai - 1), fe=chue_nod_sg) nap_na += n_na # นับไล่หน้าต่อ list_chue_nod_poly.append(chue_nod_poly) else: # ถ้าไม่ได้เลือกว่าจะแยกโพลิกอนก็แค่ให้นำวัสดุมาแปะกับผิวที่สร้างไว้แล้ว mc.sets(chue_nod_poly + '.f[%s:%s]' % (nap_na, nap_na + n_na - 1), fe=chue_nod_sg) # ใส่วัสดุให้กับผิวตามหน้าที่กำหนด nap_na += n_na # นับไล่หน้าต่อ if (yaek_poly): chue_nod_poly = mc.group(list_chue_nod_poly, n=chue_model) return chue_nod_poly, list_mat_mi_alpha
def mayaPrefs(): ''' Root of Maya prefs folder ''' return os.path.dirname(cmds.about(env=True))
try: from shiboken2 import wrapInstance except: from shiboken import wrapInstance from BroTools.common.broqt.vendor.Qt import * from BroTools.common.broqt.vendor.Qt.QtWidgets import * from BroTools.common.broqt.vendor.Qt.QtGui import * from BroTools.common.broqt.vendor.Qt.QtCore import * # Custom logging function with support of print-like comma-separated args and more from BroTools.common.debug import default_logger as log # Globals maya_version = int(cmds.about(v=True)) # Classes class BroMainWindow_Dockable(MayaQWidgetDockableMixin, QMainWindow): DOCK_LABEL_NAME = 'no name window' # Window display name CONTROL_NAME = 'no_name_window' # Window unique object name instances = list() def __init__(self): super(BroMainWindow_Dockable, self).__init__() self.delete_instances() self.__class__.instances.append(weakref.proxy(self)) # Not sure, but I suppose that we better keep track of instances of our window and keep Maya environment clean. # So we'll remove all instances before creating a new one. if maya_version >= 2017:
def mayaVersionQT(): try: return cmds.about(qt=True) except: pass
PARENT_CONSTRAINT_SUFFIX = '_PC' # If this constant is True ZVPM will not include the control suffix on ZVPM object names # i.e. the snap group of leftfoot_CTRL will be named leftfoot_SN instead of leftfoot_CTRL_SN. REMOVE_CONTROL_SUFFIX = False # This constant is used only if REMOVE_CONTROL_SUFFIX = True. CONTROL_SUFFIX = '_CTRL' # The hierarchy of a referenced file is read-only so ZVPM cannot create its parent groups. # However the root of a referenced file can be grouped, so you can use ZVPM on it. # Set this constant to False in case you don't want a ref file root object to be used with ZVPM. ALLOW_REFERENCE_ROOT = True # Private constants _isQt = not cmds.about( version=True).split()[0] in ['8.5', '2008', '2009', '2010'] _defaultSize = _isQt and (38, 208) or (52, 238) _locSfx = '_TMPLOC' _timeWinSfx = '_WIN' _timeFormDiv = 10000 _timeFormSfx = '_TMFRM' _labelSfx = ['_TMLB', '_ATLB'] _timelineHsvCols = [(55.0, 1.0, 1.0), (135.0, 1.0, 1.0), (190.0, 1.0, 1.0), (218.0, 0.85, 1.0), (276.0, 0.67, 1.0), (314.0, 0.65, 1.0), (0.0, 1.0, 1.0), (32.0, 0.8, 1.0), (32.0, 0.8, 0.75), (345.0, 1.0, 0.46)] # You can place the zv folder either in icons or in the scripts folder _pmpath = os.path.dirname(__file__) + '/zv/parentmaster/' try: _pmpath = os.path.join([
if cmds.nodeType(node) in allowed: result.append(node) else: shapes = cmds.listRelatives(node, shapes=True, path=True) if shapes: result += [ node for node in shapes if cmds.nodeType(node) in allowed ] return result connectDynamicCB_ID = None # Detect Autodesk Maya 2014 Extension 1 try: strVersion = cmds.about(installedVersion=True) aVersion = strVersion.split(' ') gMayaVersion = float(aVersion[2]) if gMayaVersion == 2014 and 'extension' in strVersion.lower(): gMayaVersion = 2014.5 except: gMayaVersion = 2015 def addDynamicConnectHook(): global connectDynamicCB_ID if connectDynamicCB_ID: removeDynamicConnectHook() if gMayaVersion > 2014: connectDynamicCB_ID = cmds.connectDynamic( addScriptHandler=connectDynamicCB)
import os try: import numpy as np np_flag = True except: np_flag = False import imp try: imp.find_module('PySide2') from PySide2.QtWidgets import * from PySide2.QtGui import * from PySide2.QtCore import * except ImportError: from PySide.QtGui import * from PySide.QtCore import * maya_ver = int(cmds.about(v=True)[:4]) def reset_pivot_pos(nodes): if not nodes: nodes = cmds.ls(sl=True, tr=True, l=True) for s in nodes: cmds.xform(s+'.scalePivot', t=[0, 0, 0], os=True) cmds.xform(s+'.rotatePivot', t=[0, 0, 0], os=True) def move_center_each_object(): object_mode = cmds.selectMode( q=True, o=True ) cmds.selectMode(o=True) selection = cmds.ls(sl=True, l=True) meshes = common.search_polygon_mesh(selection, fullPath=True, nurbs=True) if not meshes: return
#coding=utf8 from maya import OpenMayaUI, cmds import os, json from functools import partial from maya import cmds if int( cmds.about( v=1 ) ) < 2017: from PySide import QtGui, QtCore import shiboken from PySide.QtGui import QListWidgetItem, QDialog, QListWidget, QMainWindow, QWidget, QColor, QLabel,\ QVBoxLayout, QHBoxLayout, QLineEdit, QPushButton, QAbstractItemView, QMenu,QCursor, QMessageBox, QBrush, QSplitter,\ QScrollArea, QSizePolicy, QTextEdit, QApplication, QFileDialog, QCheckBox, QDoubleValidator, QSlider, QIntValidator,\ QImage, QPixmap, QTransform, QPaintEvent, QTabWidget, QFrame, QTreeWidgetItem, QTreeWidget, QComboBox, QGroupBox, QAction,\ QFont, QGridLayout, QProgressBar, QIcon else: from PySide2 import QtGui, QtCore, QtWidgets import shiboken2 as shiboken from PySide2.QtWidgets import QListWidgetItem, QDialog, QListWidget, QMainWindow, QWidget, QVBoxLayout, QLabel,\ QVBoxLayout, QHBoxLayout, QLineEdit, QPushButton, QAbstractItemView, QMenu, QMessageBox, QSplitter,\ QScrollArea, QSizePolicy, QTextEdit, QApplication, QFileDialog, QCheckBox, QSlider,\ QTabWidget, QFrame, QTreeWidgetItem, QTreeWidget, QComboBox, QGroupBox, QAction, QGridLayout, QProgressBar from PySide2.QtGui import QColor, QCursor, QBrush, QDoubleValidator, QIntValidator, QImage, QPixmap, QTransform,\ QPaintEvent, QFont, QIcon
def init_engine(self): """ Initializes the Maya engine. """ self.log_debug("%s: Initializing..." % self) # check that we are running an ok version of maya current_os = cmds.about(operatingSystem=True) if current_os not in ["mac", "win64", "linux64"]: raise tank.TankError("The current platform is not supported! Supported platforms " "are Mac, Linux 64 and Windows 64.") maya_ver = cmds.about(version=True) if maya_ver.startswith("Maya "): maya_ver = maya_ver[5:] if maya_ver.startswith(("2012", "2013", "2014", "2015", "2016")): self.log_debug("Running Maya version %s" % maya_ver) else: # show a warning that this version of Maya isn't yet fully tested with Shotgun: msg = ("The Shotgun Pipeline Toolkit has not yet been fully tested with Maya %s. " "You can continue to use Toolkit but you may experience bugs or instability." "\n\nPlease report any issues to: [email protected]" % (maya_ver)) # determine if we should show the compatibility warning dialog: show_warning_dlg = self.has_ui and "SGTK_COMPATIBILITY_DIALOG_SHOWN" not in os.environ if show_warning_dlg: # make sure we only show it once per session: os.environ["SGTK_COMPATIBILITY_DIALOG_SHOWN"] = "1" # split off the major version number - accomodate complex version strings and decimals: major_version_number_str = maya_ver.split(" ")[0].split(".")[0] if major_version_number_str and major_version_number_str.isdigit(): # check against the compatibility_dialog_min_version setting: if int(major_version_number_str) < self.get_setting("compatibility_dialog_min_version"): show_warning_dlg = False if show_warning_dlg: # Note, title is padded to try to ensure dialog isn't insanely narrow! title = "Warning - Shotgun Pipeline Toolkit Compatibility! " # padded! cmds.confirmDialog(title = title, message = msg, button = "Ok") # always log the warning to the script editor: self.log_warning(msg) self._maya_version = maya_ver try: self.log_user_attribute_metric("Maya version", maya_ver) except: # ignore all errors. ex: using a core that doesn't support metrics pass # Set the Maya project based on config self._set_project() # add qt paths and dlls self._init_pyside() # add custom system paths _custom_system_paths() # default menu name is Shotgun but this can be overriden # in the configuration to be Sgtk in case of conflicts self._menu_name = "Shotgun" if self.get_setting("use_sgtk_as_menu_name", False): self._menu_name = "Sgtk" if self.get_setting("automatic_context_switch", True): # need to watch some scene events in case the engine needs rebuilding: cb_fn = lambda en=self.instance_name, pc=self.context, mn=self._menu_name:on_scene_event_callback(en, pc, mn) self.__watcher = SceneEventWatcher(cb_fn) self.log_debug("Registered open and save callbacks.")
class Window( QMainWindow ): objectName = 'ui_createRenderLayer' title = "UI - Create Render Layer" defaultWidth = 400 defaultHeight = 50 infoBaseDir = cmds.about( pd=1 ) + "/sg/ui_createRenderLayer" uiInfoPath = infoBaseDir + '/uiInfo.json' def __init__(self, *args, **kwargs ): QMainWindow.__init__( self, *args, **kwargs ) self.installEventFilter( self ) self.setObjectName( Window.objectName ) self.setWindowTitle( Window.title ) mainWidget = QWidget(); self.setCentralWidget( mainWidget ) mainLayout = QVBoxLayout( mainWidget ) addButtonsLayout = QHBoxLayout() buttonAddTab = QPushButton( 'Add Tab' ) buttonAddLine = QPushButton( 'Add Line' ) addButtonsLayout.addWidget( buttonAddTab ) addButtonsLayout.addWidget( buttonAddLine ) tabWidget = TabWidget() self.tabWidget = tabWidget buttonLayout = QHBoxLayout() buttonCreate = QPushButton( "Create" ) buttonClose = QPushButton( "Close" ) buttonLayout.addWidget( buttonCreate ) buttonLayout.addWidget( buttonClose ) mainLayout.addLayout( addButtonsLayout ) mainLayout.addWidget( tabWidget ) mainLayout.addLayout( buttonLayout ) QtCore.QObject.connect( buttonAddTab, QtCore.SIGNAL( 'clicked()' ), partial( self.addTab ) ) QtCore.QObject.connect( buttonAddLine, QtCore.SIGNAL( "clicked()" ), partial( tabWidget.addLine ) ) QtCore.QObject.connect( buttonCreate, QtCore.SIGNAL( "clicked()" ), self.cmd_create ) QtCore.QObject.connect( buttonClose, QtCore.SIGNAL( "clicked()" ), self.cmd_close ) def addTab(self): dialog = QDialog( self ) dialog.setWindowTitle( 'Add Tab' ) dialog.resize( 300, 50 ) mainLayout = QVBoxLayout( dialog ) tabNameLayout = QHBoxLayout() labelTabName = QLabel( 'Tab Name : ' ) lineEditTabName = QLineEdit() tabNameLayout.addWidget( labelTabName ) tabNameLayout.addWidget( lineEditTabName ) buttonsLayout = QHBoxLayout() buttonCreate = QPushButton( "Create" ) buttonCancel = QPushButton( "Cancel") buttonsLayout.addWidget( buttonCreate ) buttonsLayout.addWidget( buttonCancel ) mainLayout.addLayout( tabNameLayout ) mainLayout.addLayout( buttonsLayout ) dialog.show() def cmd_create(): tabName = lineEditTabName.text() if not tabName: msgbox = QMessageBox( self ) msgbox.setText( "�̸��� �������ּ���".decode( 'utf-8' ) ) msgbox.exec_() return self.tabWidget.addTab( tabName ) dialog.deleteLater() def cmd_cancel(): dialog.deleteLater() QtCore.QObject.connect( lineEditTabName, QtCore.SIGNAL( 'returnPressed()' ), cmd_create ) QtCore.QObject.connect( buttonCreate, QtCore.SIGNAL( 'clicked()' ), cmd_create ) QtCore.QObject.connect( buttonCancel, QtCore.SIGNAL( 'clicked()' ), cmd_cancel ) def cmd_create(self): self.tabWidget.removeAll() pass def cmd_close(self): cmds.deleteUI( Window.objectName ) def show( self, *args, **kwargs): self.loadUIInfo() QMainWindow.show( self, *args, **kwargs ) def eventFilter(self, *args, **kwargs ): event = args[1] if event.type() in [ QtCore.QEvent.Resize, QtCore.QEvent.Move ]: self.saveUIInfo() def saveUIInfo( self ): Commands.makeFile( Window.uiInfoPath ) f = open( Window.uiInfoPath, 'r' ) try:data = json.load( f ) except:data = {} f.close() mainWindowDict = {} mainWindowDict['position'] = [ self.x(), self.y() ] mainWindowDict['size'] = [ self.width(), self.height() ] data[ 'mainWindow' ] = mainWindowDict f = open( Window.uiInfoPath, 'w' ) json.dump( data, f ) f.close() def loadUIInfo( self ): Commands.makeFile( Window.uiInfoPath ) f = open( Window.uiInfoPath, 'r' ) try:data = json.load( f ) except:data = {} f.close() if not data.items(): self.resize( self.defaultWidth, self.defaultHeight ) return try: posX, posY = data['mainWindow']['position'] width, height = data['mainWindow']['size'] except: return desktop = QApplication.desktop() desktopWidth = desktop.width() desktopHeight = desktop.height() if posX + width > desktopWidth: posX = desktopWidth - width if posY + height > desktopWidth: posY = desktopHeight - height if posX < 0 : posX = 0 self.move( posX, posY ) self.resize( width, height )
import os from functools import partial from maya import cmds, OpenMaya, OpenMayaUI from . import utils from .classes.keyframeReduction import KeyframeReduction # ---------------------------------------------------------------------------- # import pyside, do qt version check for maya 2017 > qtVersion = cmds.about(qtVersion=True) if qtVersion.startswith("4") or type(qtVersion) not in [str, unicode]: from PySide.QtGui import * from PySide.QtCore import * import shiboken else: from PySide2.QtGui import * from PySide2.QtCore import * from PySide2.QtWidgets import * import shiboken2 as shiboken # ---------------------------------------------------------------------------- FONT = QFont() FONT.setFamily("Consolas") BOLT_FONT = QFont() BOLT_FONT.setFamily("Consolas") BOLT_FONT.setWeight(100) # ----------------------------------------------------------------------------
) if action == 'Cancel': return False # Otherwise ask where to install else: #'(Advanced) "Custom" lets you choose anywhere by editing userSetup.\n' if mayaVersionHint: assert mayaVersionHint in [ALL_VERSION, HERE], 'mayaVersionHint was {} but does not match {} or {}'.format(mayaVersionHint, ALL_VERSION, HERE) return mayaVersionHint action = cmds.confirmDialog(m=VERSION_MSG, button=[ALL_VERSION, HERE, 'Cancel']) if action == ALL_VERSION: mayaVersion = ALL_VERSION elif action == HERE: mayaVersion = HERE else: return False return mayaVersion ALL_VERSION = 'common' HERE = str(cmds.about(q=True, v=True)) VERSION_MSG = 'Where do you want to install?\n\n' \ '"' + ALL_VERSION + '" will install to the scripts folder for all Maya versions.\n\n' \ '"' + HERE + '" will install to this version of Maya.\n\n'
def maya_version(): return float(cmds.about(version=1))
def __init__(self, *args, **kwargs ): QWidget.__init__( self, *args ) self.infoPath = cmds.about(pd=True) + "/sg/fingerWeightCopy/Widget_SelectionGrow.txt" sgCmds.makeFile( self.infoPath ) validator = QIntValidator() layout = QHBoxLayout( self ); layout.setContentsMargins(0,0,0,0) groupBox = QGroupBox() layout.addWidget( groupBox ) hLayout = QHBoxLayout() labelTitle = QLabel( "Grow Selection : " ) buttonGrow = QPushButton( "Grow" ); buttonGrow.setFixedWidth( 50 ) buttonShrink = QPushButton( "Shrink" ); buttonShrink.setFixedWidth( 50 ) lineEdit = QLineEdit(); lineEdit.setValidator( validator );lineEdit.setText( '0' ) hLayout.addWidget( labelTitle ) hLayout.addWidget( buttonGrow ) hLayout.addWidget( buttonShrink ) hLayout.addWidget( lineEdit ) groupBox.setLayout( hLayout ) self.lineEdit = lineEdit QtCore.QObject.connect( buttonGrow, QtCore.SIGNAL("clicked()"), self.growNum ) QtCore.QObject.connect( buttonShrink, QtCore.SIGNAL("clicked()"), self.shrinkNum ) self.vtxLineEditList = [] self.loadInfo()