def reloadPlugin(cls, plugin='', autoload=False, *args, **kwargs): """ reloads a plugin by name and sets it to autoload if necessary """ if not pm.pluginInfo(plugin, query=True, loaded=True) and not plugin == '': try: pm.loadPlugin(plugin) pm.pluginInfo(plugin, edit=True, autoload=autoload) except: pm.warning('Something went wrong, does this plugin - {0} - exist?'.format(plugin))
def load_plugin( auto_load = False ): add_plugin_dir( ) plugin_file = os.path.normpath( '{0}/bake_layer_init.py'.format( PLUGIN_DIR ) ) if not pmc.pluginInfo( 'bake_layer_init.py', q = True, loaded = True ): pmc.loadPlugin( plugin_file ) if auto_load: pmc.pluginInfo( 'bake_layer_init.py', e = True, autoload = True )
def load_plugin(plugin_name): """ if the plugin is not loaded, it is loaded and set to autoload pluginName: name of the plugin to be loaded """ if not pm.pluginInfo(plugin_name, q=True, loaded=True): pm.loadPlugin(plugin_name) pm.pluginInfo(plugin_name, edit=True, autoload=True)
def setUp(self): """create the test setup """ # be sure that arnold and redshift is loaded if not pm.pluginInfo('mtoa', q=1, loaded=1): pm.loadPlugin('mtoa') if not pm.pluginInfo('redshift4maya', q=1, loaded=1): pm.loadPlugin('redshift4maya')
def createAutoShaderNodes(): removeAutoShaderNodes() asDependNodes = pm.pluginInfo("mayatoappleseed_maya2014", q=True, dependNode=True) shadingGroups = pm.ls(type="shadingEngine") supportedNodeTypes = ['lambert', 'phong'] for shadingGroup in shadingGroups: if shadingGroup.name() == "initialParticleSE": continue log.debug("Check shadingGroup {0}".format(shadingGroup)) inputs = shadingGroup.surfaceShader.inputs() for input in inputs: if input.nodeType() in asDependNodes: log.debug("Inputnode {0} is an appleseed shader.".format(input)) continue if input.nodeType() in supportedNodeTypes: log.debug("Creating temp nodes for non appleseed nodeType {0}.".format(input.nodeType())) mat = createAsMaterialNode(input) psh = createAsPhysicalSurfaceNode(input) bsdf = createAsBsdfNode(input) psh.outColor >> mat.surface_shader bsdf.outColor >> mat.bsdf mat.outColor >> shadingGroup.surfaceShader print "Connections of mat", mat.inputs()
def checkAndLoadPlugin(pluginName): """ Checks and loads plugin with GUI dialogs """ if pm.pluginInfo(pluginName, query=True, loaded=True) == False: ans = pm.confirmDialog( title="Warning!!!", message="%s not loaded,,, \n Do you wish to load it now?" % pluginName, button=["YES", "NO"], defaultButton="YES", dismissString="NO", ) if ans == "YES": try: pm.loadPlugin(pluginName) return True except RuntimeError: pm.warning("%s plugin not found in path!" % pluginName) pm.confirmDialog( title="Warning!!!", message="%s plugin not found!" % pluginName, button=["OK"], defaultButton="OK", dismissString="OK", ) return False # TODO : Raise Plugin Not Found Error! if ans == "NO": return False
def __init__(self): """Global constructor""" # Dictionnary containing all the UI elements self.globalWidgets = {} # Dictionnary containing all the UI elements for the shaders list self.sListWidgets = {} # Dictionnary containing all the UI elements for the shaders attributes self.sAttrWidgets = {} # Dictionnary containing all dynamic buttons self.dynamicButtons = {} # Dictionnary containing all secondary UI # - List existing nodes UI self.listNodesWidgets = {} # Check if MtoA is loaded pluginsRunning = pc.pluginInfo(query=True, listPlugins=True) if 'mtoa' not in pluginsRunning: raise Exception("MtoA is not loaded! Please load it first then restart the script.") # Build the UI self.UI_Build() # Populate the shader list self.UI_refreshShaders() # Displays main window pc.showWindow(self.globalWidgets['window'])
def __init__(self, *args, **kwargs ): # Make sure that the bakeLayer plugin is loaded if not ( pmc.pluginInfo( 'bake_layer_init.py', q = True, loaded = True ) ): raise Exception( 'Bake Layer Plugin is not currently loaded' ) # Create the MEL Global var for the currently selected bake layer pmc.MelGlobals.initVar('string[]', 'selected_bake_layers') self.__window = pmc.window( self, title = "Bake Layer Editor" ) pmc.scriptJob( permanent = True, parent = self.__window, event = [ 'NewSceneOpened', self.new_scene ] ) pmc.scriptJob( permanent = True, parent = self.__window, event = [ 'SceneOpened', self.open_scene ] ) self.menu_dict = { } self.build( ) self.refresh( ) self.__window.show( )
def createSubdivApproxNode(): ''' copy of createApproxNode from mentalrayApproxEditor.mel node will be named "mathildaSubdivApprox" ''' # delete existing node if exists nodeName = 'mathildaSubdivApprox' # make sure mental ray is loaded first if not pm.pluginInfo('Mayatomr', q=True, loaded=True): pm.loadPlugin('Mayatomr', qt=True) # create approx node approxNode = pm.createNode('mentalraySubdivApprox', n=nodeName) # get listNode try: mrItemsListNode = pm.ls(type='mentalrayItemsList')[0] except IndexError: mrItemsListNode = pm.createNode('mentalrayItemsList', n='mentalrayItemsList') # connect approx to list pm.connectAttr(approxNode.message, mrItemsListNode.subdivApproxs, na=True) return approxNode
def DefaultSetupAE(pluginName, nodeType, translator, asShape=True): import pymel.core as pm if not pm.pluginInfo(pluginName, query=1, loaded=1): return try: import mtoa.ui.ae.templates as templates if not asShape: class DefaultNodeTemplate(templates.AttributeTemplate): def setup(self): self.addControl("aiUserOptions", label="User Options") templates.registerTranslatorUI(DefaultNodeTemplate, nodeType, translator) else: class DefaultShapeTemplate(templates.ShapeTranslatorTemplate): def setup(self): #self.renderStatsAttributes() self.commonShapeAttributes() self.addSeparator() #self.addControl("aiSssSampleDistribution", label="SSS Samples Distribution") #self.addControl("aiSssSampleSpacing", label="SSS Sample Spacing") self.addControl("aiSssSetname", label="SSS Set Name") self.addSeparator() self.addControl("aiUserOptions", label="User Options") self.addSeparator() templates.registerTranslatorUI(DefaultShapeTemplate, nodeType, translator) except Exception, e: print("scriptedTranslatorUtils.DefaultSetupAE: Failed\n%s" % e)
def load_ai(): try: if not pluginInfo('mtoa.mll', q=1, l=1): loadPlugin('mtoa.mll') return True except: print 'Error load Arnold Renderer'
def isMtoaNode(nodeType): """ return whether the passed node type was created by mtoa """ global _mtoaNodes if _mtoaNodes is None: _mtoaNodes = pm.pluginInfo('mtoa', query=True, dependNode=True) return nodeType in _mtoaNodes
def vrayLoaded(self): #Get list of all loaded plugIns plugInList = pm.pluginInfo( query=True, listPlugins=True ) #Return true if loaded else setStatus and return false if('vrayformaya' in plugInList): return True return False
def vrayLoaded(self, setStatusFunction = False): #Get list of all loaded plugIns plugInList = pm.pluginInfo( query=True, listPlugins=True ) #Return true if loaded else setStatus and return false if('vrayformaya' in plugInList): return True if(setStatusFunction): setStatusFunction('Vray for Maya Plugin not loaded') return False
def buildscene(): #scene building pm.newFile( f=True ) #anorld 가 laod 되어 있는지를 체크 한다. if not pm.pluginInfo('mtoa', q=True, loaded=True): pm.loadPlugin('mtoa') #랜더러를 anorld로 만들어 준다. defaultRenderGlobals = pm.PyNode('defaultRenderGlobals') defaultRenderGlobals.currentRenderer.set('arnold')
def loadPlugins(): try: log.debug("Loading Appleseed maya plugins") version = pm.about(v=True).split(" ")[0] pluginName = "appleseedTools_maya{0}".format(version) log.debug("Trying to load appleseedTools: {0}".format(pluginName)) if not pm.pluginInfo(pluginName, query=True, loaded=True): pm.loadPlugin(pluginName) except: traceback.print_exc(file=sys.__stderr__) log.error("Load plugins Appleseed FAILED")
def has_stereo_camera(self): """checks if the scene has a stereo camera setup returns True if any """ # check if the stereoCameraRig plugin is loaded if pm.pluginInfo('stereoCamera', q=True, l=True): return len(pm.ls(type='stereoRigTransform')) > 0 else: # return False because it is impossible without stereoCamera plugin # to have a stereoCamera rig return False
def loadPlugins(): python_plugins = ["loadshadersplugin.py"] currentPath = path.path(__file__).dirname() for plugin in python_plugins: try: log.debug("Loading additional plugin: {0}".format(plugin)) if not pm.pluginInfo(plugin, query=True, loaded=True): pm.loadPlugin(plugin) except: traceback.print_exc(file=sys.__stderr__) log.error("Loading of additional plugin: {0} failed.".format(pluginPath))
def initializePlugin(mobject): pm.loadPlugin("matrixNodes", quiet=True) pm.pluginInfo('matrixNodes', edit=True, autoload=True) mplugin = OpenMayaMPx.MFnPlugin(mobject) try: mplugin.registerCommand('openKrakenEditor', OpenKrakenEditorCommand.creator) except: sys.stderr.write('Failed to register commands: openKrakenEditor') raise try: mplugin.registerCommand('krakenUndoableCmd', KrakenUndoableCmd.creator) except: sys.stderr.write('Failed to register commands:krakenUndoableCmd') raise krakenLoadMenu = os.getenv('KRAKEN_LOAD_MENU', 'True') if krakenLoadMenu == 'True': setupKrakenMenu()
def unloadAndUnregister(): if pm.pluginInfo('mayatomantra', q = True, l=True): pm.unloadPlugin('mayatomantra', force = True) if pm.renderer(RENDERERNAME, q = True, exists = True): pm.renderer(RENDERERNAME, unregisterRenderer = True) pm.loadPlugin( 'mayatomantra' ) if len(pm.ls(type = GLOBALSNAME)) == 0: pm.createNode(GLOBALSNAME, name = GLOBALSNAME) else: log.info("mayaToMantraGlobals node exists, using old one")
def export_layer( layer ): layer_node = get_bake_layer( layer ) members = get_members( layer_node ) pmc.select( clear = True ) meshes = [ ] project_dir = pmc.workspace.getPath( ) data_dir = project_dir + r'/xn_bake_data' if not os.path.exists( data_dir ): os.mkdir( data_dir ) if not members == None: for orig_obj in members: new_obj = pmc.duplicate( orig_obj )[ 0 ] pmc.delete( new_obj, constructionHistory = True ) relatives = new_obj.listRelatives( ) for r in relatives: if r.nodeType( ) == 'mesh': meshes.append( new_obj ) bake_mesh = make_bake_mesh( meshes ) if bake_mesh == False: return False if not os.path.exists( data_dir + r'/xnezbake/' ): os.mkdir( data_dir + r'/xnezbake/' ) pmc.select( bake_mesh ) # Check that OBJ Export is enabled if not pmc.pluginInfo( 'objExport.mll', q = True, loaded = True ): pmc.loadPlugin( 'objExport.mll' ) output = pmc.exportSelected( data_dir + r'/xnezbake/' + layer_node.name( ) + '.obj', force = True, options = 'groups=0;ptgroups=0;materials=0;smoothing=1;normals=1', type = 'OBJexport' ) pmc.delete( ) return output
def initializePlugin(mobject): pm.loadPlugin("FabricMaya", quiet=True) pm.pluginInfo('FabricMaya', edit=True, autoload=True) pm.loadPlugin("matrixNodes", quiet=True) pm.pluginInfo('matrixNodes', edit=True, autoload=True) mplugin = OpenMayaMPx.MFnPlugin(mobject) try: mplugin.registerCommand('openKrakenEditor', OpenKrakenEditorCmd.creator) except: sys.stderr.write('Failed to register commands: openKrakenEditor') raise try: mplugin.registerCommand('krakenBipedBuildGuide', KrakenBipedBuildGuideCmd.creator) except: sys.stderr.write('Failed to register commands: krakenBipedBuildGuide') raise try: mplugin.registerCommand('krakenBipedBuildRig', KrakenBipedBuildRigCmd.creator, KrakenBipedBuildRigCmd.syntaxCreator) except: sys.stderr.write('Failed to register commands: krakenBipedBuildRig') raise try: mplugin.registerCommand('krakenBuildGuideFromRig', krakenBuildGuideFromRigCmd.creator, krakenBuildGuideFromRigCmd.syntaxCreator) except: sys.stderr.write('Failed to register commands: krakenBuildGuideFromRig') raise krakenLoadMenu = os.getenv('KRAKEN_LOAD_MENU', 'True') if krakenLoadMenu == 'True': setupKrakenMenu()
def createFgShooters(frames=[], offsets=[], current_camera=True): ''' Create fgshooter cameras for the render camera. Cameras can be fixed, current, or offset. ''' # Ensure that decomposeMatrix is loaded. if not pm.pluginInfo("decomposeMatrix", q=True, loaded=True): log.info("Loading \"decomposeMatrix\" plugin.") pm.loadPlugin("decomposeMatrix") # Make sure there are no duplicate frames or offsets. frames = set(frames) offsets = set(offsets) # Get the render Camera. render_cam = getRenderCamera() if render_cam is None: log.warning("Could not find non-default render camera.") return None # Get the mip_fgshooter shader connected to the render camera. fg_shooter = getFgShooter(render_cam) transform = fg_shooter.trans index = 0 # Create current fgshooter camera. if current_camera: fg_cam = currentCamera(render_cam) fg_cam.worldMatrix >> transform[index] index += 1 # Create fixed fgshooter cameras. for frame in frames: fg_cam = fixedCamera(render_cam, frame) fg_cam.worldMatrix >> transform[index] index += 1 # Create offset fgshooter cameras. for offset in offsets: if not isinstance(offset, int): log.warning("Offsets must be intergers. Skipping: %s", offset) continue if offset: fg_cam = offsetCamera(render_cam, offset) fg_cam.worldMatrix >> transform[index] index += 1
def load_mr(* args): mental_ray = pm.pluginInfo('Mayatomr', query= True, loaded= True) if mental_ray == 0: pm.loadPlugin('Mayatomr') pm.setAttr('defaultRenderGlobals.ren', 'mentalRay', type='string') ''' if pm.objExists('mentalrayGlobals'): pass else: pm.createNode('mentalrayGlobals') '''
def main(*args): plugins = [dir for dir in os.listdir( PLUGIN_PATH ) if not dir.startswith("_") and dir.endswith(".py")] loadedPlugins = pm.pluginInfo( query=True, listPlugins=True ) or [] for plugin in plugins: if plugin.split(".")[0] not in loadedPlugins: try : #python plugin pm.loadPlugin(os.path.join( PLUGIN_PATH, plugin)) logger.info('%s|| Plugin Loaded Successfully...' %plugin.ljust(30)) except Exception, error: logger.error('%s|| %s'%(plugin.ljust(30), str(error))) else: logger.info('%s|| Plugin Already Loaded...' %plugin.ljust(30))
def initialize(plugin): """Re-initialize specified plug in. @param plugin <string> Specify the plug-in name. """ cmds.file(new=True, force=True) repo_path = os.path.abspath(__file__).split('Maya')[0] print repo_path path = os.path.join(repo_path, 'Maya', 'plug-ins') if sys.platform == 'win32' or sys.platform == 'cygwin': plugin = '%s.mll' % plugin elif sys.platform == 'linux' or sys.platform == 'linux2': plugin = '%s.so' % plugin elif sys.platform == 'darwin' or sys.platform == 'os2': plugin = '%s.dmg' % plugin # end if get full plug in name if pm.pluginInfo(plugin, query=True, loaded=True): pm.unloadPlugin(plugin) # end if plug in is loaded unload it pm.loadPlugin(os.path.join(path, plugin))
def closest_point_on_mesh(mesh_xform, ref_xform, output_type=3): """ Take a transform with a mesh and a reference transform for position info Args: mesh_xform (pm.nt.Transform): transform with a mesh that we will query for UV values ref_Xform (pm.nt.Transform): transform to use to get the query position we want closest surface point to output_type (int): 1: position 2: normal 3: uv 4: closestFace 5: closestVert Returns (list): any output of the types listed in output_type Usage: closest_point_on_mesh(pm.ls(sl=True)[0], pm.ls(sl=True)[1]) """ # Just check that this isn't loaded (works in 2015, not tested since plugin changed names in others) if not pm.pluginInfo('matrixNodes', q=True, l=True): pm.loadPlugin('matrixNodes') # Create nodes and connections dm = pm.createNode('decomposeMatrix') cpom = pm.createNode('closestPointOnMesh') ref_xform.worldMatrix[0].connect(dm.inputMatrix) dm.outputTranslate.connect(cpom.inPosition) mesh_xform.worldMatrix[0].connect(cpom.inputMatrix) mesh_xform.getShape().outMesh.connect(cpom.inMesh) # Do a quick lookup for the attributes we're looking for and list comprehend the resulting info query_table = {'1': ['position'], '2': ['normal'], '3': ['parameterU','parameterV'], '4': ['closestFaceIndex'], '5': ['closestVertexIndex']} result = [cpom.attr(attr).get() for attr in query_table[str(output_type)]] # Cleanup pm.delete([cpom, dm]) return result
def addAOVLayout(self, aovReorder = None): '''Add an aov control for each aov registered for this node type''' aovAttrs = aovs.getNodeGlobalAOVData(nodeType=self.nodeType()) if aovReorder: #do some reordering based on the passed string list i = 0 aovMap = {} for aov in aovReorder: aovMap[aov] = i i += 1 aovAttrs = sorted(aovAttrs, key = lambda aov: aovMap[aov[0]]) if aovAttrs: self.beginLayout("AOV Names", collapse=True) # self.beginNoOptimize() # self.addControl('enableAOVs', label='Enable AOVs') # self.addControl('overrideAOVs', label='Override AOV Names') # self.endNoOptimize() dynamic = self.nodeType() not in set(pm.pluginInfo("mtoa", q=True, dependNode=True)) for name, attr, type in aovAttrs: if dynamic: attr = 'ai_' + attr if self.convertToMayaStyle: attr = toMayaStyle(attr) self.addAOVControl(attr) self.endLayout()
"""source: https://github.com/4degrees/segue/blob/master/source/segue/backend/host/maya.py""" import pymel.core as pm import os import errno #load plugin if not pm.pluginInfo('AbcExport', query=True, loaded=True): pm.loadPlugin('AbcExport') #selection selection = pm.ls(sl=True) if not selection: raise ValueError('Cannot save empty selection.') previouse_selection = selection #get frame range fstart = pm.playbackOptions(query=True, minTime=True) fend = pm.playbackOptions(query=True, maxTime=True) fcurrent = pm.currentTime() step = 1 # Ensure target folder exists target = (u'F:\local_WIP\pythonAbcExport') try: os.makedirs(target) except OSError as error: if error.errno != errno.EEXIST: raise #build filepath cache_path = os.path.join(target, 'cache.abc')
def load_plugin(): if not pm.pluginInfo("mayatoappleseed.mll", query=True, loaded=True): pm.loadPlugin("mayatoappleseed.mll")
#twClothSolverIOPaperBlockout Test Fixture #------------------------------------------------------------------------------------- import pymel.core as pm #reload plugin #---------------------------------- try: #load new scene without saving pm.mel.eval('file -f -new;') #if plugin is loaded unload and reload it, else reload if(pm.pluginInfo( 'twClothSolverBlockoutPlugins.py', query=True, loaded=True )): pm.unloadPlugin( 'twClothSolverBlockoutPlugins.py' ) pm.loadPlugin( 'twClothSolverBlockoutPlugins.py' ) print('Successfully reloaded plugin') else: pm.loadPlugin( 'twClothSolverBlockoutPlugins.py' ) print('Successfully loaded plugin') except: print('Error Reloading Plugin') #TwClothSolverIOPaperBlockout #---------------------------------- #----------------------------------
def exportAnimPackage(self, palName, shotName): """doc""" # get version info from [xgDogTag] version = self.getAnimBranch(palName) if not version: pm.error( '[XGen Hub] : Couldn\'t get ANIM branch name. Export process stop.' ) return None self.clearPreview() # add shotName attribute to xgen and save in xgen delta later if not xg.attrExists(self.xgShotAttr, palName): xg.addCustomAttr(self.xgShotAttr, palName) xg.setAttr(self.xgShotAttr, shotName, palName) # add nucleus startFrame attribute to xgen and save in xgen delta later if not xg.attrExists(self.xgRefFrame, palName): xg.addCustomAttr(self.xgRefFrame, palName) xg.setAttr(self.xgRefFrame, str(int(pm.PyNode('nucleus1').startFrame.get())), palName) # get resolved repo shotName path deltaPath = self.paletteDeltaDir(palName, version, shotName) if not os.path.exists(deltaPath): os.mkdir(deltaPath) deltaFile = '/'.join([deltaPath, palName + '.xgd']) # export delta xg.createDelta(palName, deltaFile) # get curves and export for desc in xg.descriptions(palName): curvesGrp = pm.ls(desc + '_hairSystemOutputCurves', type='transform') if curvesGrp and curvesGrp[0].listRelatives(): curves = curvesGrp[0].listRelatives() # cache curves, export as alembic if not pm.pluginInfo('AbcExport', q=1, l=1): pm.loadPlugin('AbcExport') start, end = self.getTimeSliderMinMax() abcCmds = '-frameRange %d %d -uvWrite -worldSpace -dataFormat ogawa ' % ( start, end) abcRoot = '-root ' + ' -root '.join( [cur.longName() for cur in pm.ls(curves)]) abcPath = '/'.join([deltaPath, desc + '.abc']) pm.mel.AbcExport(j=abcCmds + abcRoot + ' -file ' + abcPath) # export snapshot for i in range(5): tmpPath = self.snapshotTmp % (i + 1) if os.path.isfile(tmpPath): imgPath = self.snapshotImgPath(palName, version, str(i + 1), shotName) if not os.path.exists(os.path.dirname(imgPath)): os.mkdir(os.path.dirname(imgPath)) shutil.move(tmpPath, imgPath) self.refresh('Full') self.notifyMsg('Anim Result Export Complete !', 0) return True
def importGuides(self, palName, descName=None, version=None): """ """ self.clearPreview() if descName: descs = [descName] else: descs = xg.descriptions(palName) # copy groom dir from versionRepo if @version has given if version: # check exists guidesDesc = {} hasMissing = False for desc in descs: if self.descControlMethod(palName, desc) == 'Guides': abcPath = '/'.join([ self.paletteVerDir(palName, version), desc, 'curves.abc' ]) if os.path.isfile(abcPath): guidesDesc[desc] = abcPath else: hasMissing = True msg = '[XGen Hub] : palette [%s] description [%s] version [%s] NOT exists. -> %s' pm.warning(msg % (palName, desc, version, abcPath)) # copy file if no missing if not hasMissing: for desc in guidesDesc: src = guidesDesc[desc] dst = '/'.join( [self.paletteWipDir(palName), desc, 'curves.abc']) if os.path.isdir(dst): os.remove(dst) shutil.copyfile(src, dst) else: pm.error( '[XGen Hub] : Some .abc missing, Check ScriptEditor. guides import stopped.' ) return None # IMPORT GUIDES for desc in descs: # import alembic if not pm.pluginInfo('AbcImport', q=1, l=1): pm.loadPlugin('AbcImport') abcPath = xg.expandFilepath('${DESC}', desc) + 'curves.abc' if os.path.isfile(abcPath): pool = pm.group(em=1, n='curvesToGuide_processPoll') pm.mel.AbcImport(abcPath, mode='import', rpr=pool) # select curves curves = pm.listRelatives(pool, c=1) pm.select(curves, r=1) # curvesToGuides pm.mel.xgmCurveToGuide(d=desc, tsp=1.0, tsa=0.0, deleteCurve=True) self.notifyMsg('Guides Import Complete !', 0) return True
def exportFullPackage(self, palName, version, bake= False, anim= False): """ Export Palettes, Descriptions, Grooming, Guides, all together, even bake modifiers befoer export if needed. """ self.clearPreview() # bake modifiers generator = {} if bake: for desc in xg.descriptions(palName): # bake Noise modifiers # fxModules evals from bottom to top clumpModLast = '' for fxm in xg.fxModules(palName, desc): if xg.fxModuleType(palName, desc, fxm) == 'ClumpingFXModule': # set the top clumpingMod cvAttr to True, for anim modifiers which needs clump if clumpModLast: xg.setAttr('cvAttr', 'false', palName, desc, clumpModLast) xg.setAttr('cvAttr', 'true', palName, desc, fxm) clumpModLast = fxm if xg.fxModuleType(palName, desc, fxm) == 'NoiseFXModule': # temporarily turn off lod so we dont bake it in lod = xg.getAttr('lodFlag', palName, desc) xg.setAttr('lodFlag', 'false', palName, desc) # change mode for bake xg.setAttr('mode', '2', palName, desc, fxm) # bake the noise pm.mel.xgmNullRender(pb= desc) # restore xg.setAttr('lodFlag', lod, palName, desc) # change mode to baked xg.setAttr('mode', '1', palName, desc, fxm) # bake groom modifiers fxm = xg.addFXModule(palName, desc, 'BakedGroomManagerFXModule') xg.setAttr('active', 'true', palName, desc, fxm) xg.bakedGroomManagerBake(palName, desc) # set Generator to XPD generator[desc] = xg.getActive(palName, desc, 'Generator') xg.setActive(palName, desc, 'FileGenerator') # change to export version path and keep current workPath = xg.getAttr('xgDataPath', palName) workProj = xg.getAttr('xgProjectPath', palName) xg.setAttr('xgDataPath', self.paletteVerDir(palName, version, raw= True), palName) xg.setAttr('xgProjectPath', self.projPath, palName) # get resolved repo path dataPath = self.paletteVerDir(palName, version) # set [xgDogTag] attr for ANIM record branchName if anim: xg.setAttr('xgDogTag', version, palName) # export descriptions for desc in xg.descriptions(palName): dstDescDir = xg.expandFilepath('${DESC}', desc, True, True) expPath = dstDescDir + desc + '.xdsc' xg.exportDescription(palName, desc, expPath) # copy map files srcDescVar = workPath.replace('${PROJECT}', workProj) + '/${DESC}' srcDescDir = xg.expandFilepath(srcDescVar, desc) for mapDir in os.listdir(srcDescDir): srcMap = os.path.join(srcDescDir, mapDir) dstMap = os.path.join(dstDescDir, mapDir) if os.path.isdir(srcMap): dir_util.copy_tree(srcMap, dstMap) # export palettes expPath = dataPath + '/' + palName + '.xgen' xg.exportPalette(palName, expPath) # export grooming for desc in xg.descriptions(palName): igdesc = xg.getAttr('groom', palName, desc) if igdesc: expPath = xg.expandFilepath('${DESC}/groom', desc, True, True) tpu = 5 sampling = 1 igDescr = xg.igDescription(desc) # export Attribute Map try: pm.waitCursor(state= True) # may have .ptx file handle lock issue pm.mel.iGroom(exportMaps= expPath, texelsPerUnit= tpu, instanceMethod= sampling, description= igDescr) finally: pm.waitCursor(state= False) # export Mask try: pm.waitCursor(state= True) # may have .ptx file handle lock issue pm.mel.iGroom(exportMask= expPath, texelsPerUnit= tpu, description= igDescr) finally: pm.waitCursor(state= False) # export Region try: pm.waitCursor(state= True) # may have .ptx file handle lock issue pm.mel.iGroom(exportRegion= expPath, texelsPerUnit= tpu, description= igDescr) finally: pm.waitCursor(state= False) # export Settings jsonPath = expPath + 'groomSettings.json' groomSettings = {}.fromkeys(['density', 'length', 'width']) for key in groomSettings: groomSettings[key] = pm.getAttr(igdesc + '.' + key) with open(jsonPath, 'w') as jsonFile: json.dump(groomSettings, jsonFile, indent=4) # export guides with undoable('exportGuides'): for desc in xg.descriptions(palName): # listGuides guides = xg.descriptionGuides(desc) if not guides: continue expPath = xg.expandFilepath('${DESC}', desc) pm.select(guides, r= 1) # guides to curves curves = pm.mel.xgmCreateCurvesFromGuides(0, True) # export as alembic if not pm.pluginInfo('AbcExport', q= 1, l= 1): pm.loadPlugin('AbcExport') abcCmds = '-frameRange 1 1 -uvWrite -worldSpace -dataFormat ogawa ' abcRoot = '-root ' + ' -root '.join([cur.longName() for cur in pm.ls(curves)]) abcPath = expPath + 'curves.abc' pm.mel.AbcExport(j= abcCmds + abcRoot + ' -file ' + abcPath) pm.undo() if anim: # save out hairSystem preset presetMel = [] for nodeType in ['nucleus', 'hairSystem', 'nRigid']: presetDict = self.ioAttrPreset(nodeType, True) presetMel.extend(presetDict.values()) # move preset file to version repo presetRepo = self.nDynPresetPath(palName, version) if not os.path.exists(presetRepo): os.mkdir(presetRepo) for prs in presetMel: dstPath = '/'.join([presetRepo, os.path.basename(prs)]) shutil.move(prs, dstPath) # create empty _shot_ folder shotDir = self.paletteDeltaDir(palName, version, '') if not os.path.exists(shotDir): os.mkdir(shotDir) # export snapshot for i in range(5): tmpPath = self.snapshotTmp % (i+1) if os.path.isfile(tmpPath): imgPath = self.snapshotImgPath(palName, version, str(i+1)) if not os.path.exists(os.path.dirname(imgPath)): os.mkdir(os.path.dirname(imgPath)) shutil.move(tmpPath, imgPath) # restore dataPath xg.setAttr('xgDataPath', workPath, palName) xg.setAttr('xgProjectPath', workProj, palName) # restore modifiers if bake: for desc in xg.descriptions(palName): # bake Noise modifiers for fxm in xg.fxModules(palName, desc): if xg.fxModuleType(palName, desc, fxm) == 'NoiseFXModule': # restore to live mode xg.setAttr('mode', '0', palName, desc, fxm) # remove bake groom modifiers for fxm in xg.fxModules(palName, desc): if xg.fxModuleType(palName, desc, fxm) == 'BakedGroomManagerFXModule': xg.removeFXModule(palName, desc, fxm) # restore Generator xg.setActive(palName, desc, generator[desc]) self.refresh('Full') self.notifyMsg('Collection Export Complete !', 0) return True
def unload_plugin(): pm.newFile(force=True) if pm.pluginInfo("mayatoappleseed.mll", query=True, loaded=True): pm.unloadPlugin("mayatoappleseed.mll") pm.newFile(force=True)
def __plugin_unloader(plugin_name): if not pm.pluginInfo(plugin_name, q=1, loaded=1): logprint('unloading %s!' % plugin_name) pm.unloadPlugin(plugin_name) logprint('%s unloaded!' % plugin_name)
import os import functools import collections import numpy as np import cv2 import pymel.core as pm import pymel.core.nodetypes as nt material_dir = "C:/textures/materials" # location with material textures textures_dir = "C:/textures/textures" # location with AO, ID etc textures size = 1024 materials = {"red": (255, 0, 0), "green": (0, 255, 0), "blue": (0, 0, 255)} multiply_channels = "BaseColor", # channels to multiply with AO and shadows # not for edit if not pm.pluginInfo("vrayformaya.mll", q=True, loaded=True): pm.loadPlugin("vrayformaya.mll") material_node = collections.namedtuple("material", "file name channel") def loadMaterials(): mt_nodes = [] for file_name in os.listdir(material_dir): name, channel = os.path.splitext(file_name)[0].rsplit("_", 1) file_name = os.path.join(material_dir, file_name) mt_nodes.append(material_node(file_name, name, channel)) return mt_nodes def settings():
def __pluginUnloader(pluginName): if not pm.pluginInfo(pluginName, q=1, loaded=1): pm.unloadPlugin(pluginName)
import mtoa.ui.nodeTreeLister as nodeTreeLister import mtoa.ui.globals.common from mtoa.ui.globals.common import createArnoldRendererCommonGlobalsTab, updateArnoldRendererCommonGlobalsTab from mtoa.ui.globals.settings import createArnoldRendererGlobalsTab, updateArnoldRendererGlobalsTab, updateBackgroundSettings, updateAtmosphereSettings, createArnoldRendererOverrideTab, updateArnoldRendererOverrideTab from mtoa.ui.globals.settings import createArnoldRendererDiagnosticsTab, updateArnoldRendererDiagnosticsTab, createArnoldRendererSystemTab, updateArnoldRendererSystemTab from mtoa.ui.aoveditor import createArnoldAOVTab, updateArnoldAOVTab import mtoa.ui.ae.utils as aeUtils from mtoa.ui.arnoldmenu import createArnoldMenu import mtoa.cmds.arnoldRender as arnoldRender except: import traceback traceback.print_exc(file=sys.__stderr__) # goes to the console raise if not pm.about(batch=True): for nodeType in pm.pluginInfo('mtoa', q=1, dependNode=1): pm._factories.addMayaType(nodeType, 'kPluginDependNode') def _overrideMelScripts(): # for those procedures that we could not simply define overrides interactively, we keep edited files # per version of maya root = mtoaPackageRoot() maya_version = versions.shortName() meldir = os.path.join(root, maya_version, 'mel') meldir = mtoa.utils.convertToUnicode(meldir) pathsep = mtoa.utils.convertToUnicode(os.pathsep) maya_script_path = mtoa.utils.convertToUnicode( mtoa.utils.getEnvironmentVariable(u'MAYA_SCRIPT_PATH')) mtoa.utils.setEnvironmentVariable(u'MAYA_SCRIPT_PATH', meldir + pathsep + maya_script_path)
import getpass # Maya import pymel.core as pm from pymel.core import datatypes from pymel import versions # mgear import mgear import mgear.maya.utils from . import guide, component from mgear.maya import primitive, attribute, skin, dag, icon # check if we have loaded the necessary plugins if not pm.pluginInfo("mgear_solvers", q=True, loaded=True): try: pm.loadPlugin("mgear_solvers") except RuntimeError: pm.displayError("You need the mgear_solvers plugin!") if not pm.pluginInfo("matrixNodes", q=True, loaded=True): pm.loadPlugin("matrixNodes") COMPONENT_PATH = os.path.join(os.path.dirname(__file__), "component") TEMPLATE_PATH = os.path.join(COMPONENT_PATH, "templates") SYNOPTIC_PATH = os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir, "synoptic", "tabs")) SHIFTER_COMPONENT_ENV_KEY = "MGEAR_SHIFTER_COMPONENT_PATH"
import pymel.core as pm from RMPY.rig import rigBase from RMPY.core import dataValidators if 'matrixNodes' not in pm.pluginInfo(query=True, listPlugins=True): pm.loadPlugin('matrixNodes.so') class SurfaceInfoModel(rigBase.BaseModel): def __init__(self): super(SurfaceInfoModel, self).__init__() self.surface_info = None self.matrix = None self.decomposition = None class SurfaceInfo(rigBase.RigBase): def __init__(self, *args, **kwargs): kwargs['model'] = kwargs.pop('model', SurfaceInfoModel()) super(SurfaceInfo, self).__init__(*args, **kwargs) follow_v = kwargs.pop('follow_v', False) surface = dataValidators.as_pymel_nodes(args[0]) if pm.objectType(surface) != 'nurbsSurface': if pm.objectType(surface.getShapes()[0]) == 'nurbsSurface': surface = surface.getShapes()[0] else: raise AttributeError self.surface_info = pm.createNode('pointOnSurfaceInfo') self.name_convention.rename_name_in_format(self.surface_info, name='surfaceInfo')
if auto: # si se llama con autoload ponerlo pm.pluginInfo( plugin, q=True, autoload=True ) # pone el autoload else: # no esta registrado print 'ANTARUXA WARNING!!! No existe el plugin: ' + plugin def QAUnloadPlugin(plugin): if pm.pluginInfo(plugin, q=True, r = True): if pm.pluginInfo(plugin, q=True, loaded=True): # si está cargado pm.pluginInfo( plugin, edit=True, autoload=False ) # quitarle el autoload primero pm.unloadPlugin( plugin ) else: # no esta registrado print 'ANTARUXA WARNING!!! No existe el plugin: ' + plugin """ Listar plugins instalados """ pm.pluginInfo( query=True, listPlugins=True ) """ _____ _ _ _ _ _ ___ ___ _____ _____ / ___| | | | ___ | | | | (_) | \/ | / _ \ \ / / _ \ \ `--.| |__ __ _ __| | ___ _ __ ___ ( _ ) | |_ _____ _| |_ _ _ _ __ ___ ___ _ _ __ | . . |/ /_\ \ V / /_\ \ `--. \ '_ \ / _` |/ _` |/ _ \ '__/ __| / _ \/\ | __/ _ \ \/ / __| | | | '__/ _ \/ __| | | '_ \ | |\/| || _ |\ /| _ | /\__/ / | | | (_| | (_| | __/ | \__ \ | (_> < | || __/> <| |_| |_| | | | __/\__ \ | | | | | | | | || | | || || | | | \____/|_| |_|\__,_|\__,_|\___|_| |___/ \___/\/ \__\___/_/\_\\__|\__,_|_| \___||___/ |_|_| |_| \_| |_/\_| |_/\_/\_| |_/ """ """ Crear u asignar un shader a un objeto en mayaA """
def is_arnold_plugin_loaded(self): # type: () -> bool return pm.pluginInfo("mtoa", query=True, loaded=True)
def test_PluginLoading(): assert pCore.pluginInfo('metaNode.py', query=True, loaded=True)
def check_multiple_connections_for_textures(): """check if textures are only used in one material (not liking it very much but it is breaking ASS files. """ # load necessary plugins plugins = ['matrixNodes', 'quatNodes'] for plugin in plugins: if not pm.pluginInfo(plugin, q=1, l=1): pm.loadPlugin(plugin) v = staging.get('version') # skip if skip_types = ['character', 'animation', 'previs'] for t in v.naming_parents: for st in skip_types: if t.type and t.type.name.lower().startswith(st): return # get all the texture nodes from anima.env.mayaEnv import repr_tools reload(repr_tools) # try to find the material it is been used by walking up the connections nodes_with_multiple_materials = [] # by type nodes_to_ignore = pm.ls( type=[ 'hyperLayout', 'shadingEngine', 'materialInfo', 'time', 'unitConversion', 'hyperView' ] ) # by name nodes_to_ignore += pm.ls('lambert1') nodes_to_ignore += pm.ls('defaultShaderList*') nodes_to_ignore += pm.ls('defaultTextureList*') nodes_to_ignore += pm.ls('defaultRenderUtilityList*') all_nodes = pm.ls(type=repr_tools.RENDER_RELATED_NODE_TYPES) for node in nodes_to_ignore: if node in all_nodes: all_nodes.remove(node) for node in all_nodes: materials_connected_to_this_node = \ pm.ls(node.listHistory(future=True), mat=True) # remove self from all_nodes if node in materials_connected_to_this_node: materials_connected_to_this_node.remove(node) if len(materials_connected_to_this_node) > 1: nodes_with_multiple_materials.append(node) else: connections_out_of_this_node = node.outputs() [connections_out_of_this_node.remove(h) for h in nodes_to_ignore if h in connections_out_of_this_node] if len(set(connections_out_of_this_node)) > 1: nodes_with_multiple_materials.append(node) # if we find more than one material add it to the list # raise a PublishError if we have an item in the list if len(nodes_with_multiple_materials) > 0: pm.select(nodes_with_multiple_materials) raise PublishError( 'Please update the scene so the following nodes are connected <br>' 'to only <b>one material</b> (duplicate them):<br><br>%s<br><br>' % '<br>'.join(map(lambda x: x.name(), nodes_with_multiple_materials)) )
import pymel.core as pymel import maya.OpenMaya as OpenMaya import math import logging log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) """ Using reset vertex position plugin to store previous vertex position in an Undo step. If unable to the load the plugin, script will not be undoable. """ undoable = False try: if not pymel.pluginInfo('reset_vertex_position.py', query=True, loaded=True): pymel.loadPlugin('reset_vertex_position.py') undoable = True except Exception as ex: log.error('Could not load reset_vertex_position.py') pass def get_select_type(): if pymel.selectType(vertex=True, query=True): return 'vertex' elif pymel.selectType(facet=True, query=True): return 'face' elif pymel.selectType(edge=True, query=True): return 'edge'