示例#1
0
 def __init__(self, parent=maya_widget()):
     super(CameraViewManagerWindow, self).__init__(parent)
     pm.loadPlugin('AbcExport', quiet=True)
     pm.loadPlugin('AbcImport', quiet=True)
     # 패널을 삭제해주는 MEL을 로딩한다.
     mel.eval('source deletePanel')
     self.ui()
示例#2
0
    def __init__(self, baseGeo=None, targetGeo=None):
        self.baseGeo = None
        self.targetGeo = None
        self.outGeo = None
        self.rampBS = None
        self.centerPlane = None
        self.leftBorderPlane = None
        self.rightBorderPlane = None
        self.refPlaneRootGrp = None
        self.targetGeoBoundingBox = None
        self.numOfShapes = None

        if not pm.pluginInfo('rampBlendShape', q=True, loaded=True):
            pm.loadPlugin('rampBlendShape')

        if not baseGeo or not targetGeo:
            selLs = pm.ls(sl=True)
            if not len(selLs) == 2:
                raise RuntimeError('Select baseGeo and targetGeo')
            self.baseGeo = selLs[0]
            self.targetGeo = selLs[1]
        else:
            if isinstance(baseGeo, basestring):
                baseGeo = pm.PyNode(baseGeo)
            if isinstance(targetGeo, basestring):
                targetGeo = pm.PyNode(targetGeo)

            self.baseGeo = baseGeo
            self.targetGeo = targetGeo
示例#3
0
 def handle_plugin_attr(self, attr_name):
     if attr_name.startswith('mi_'):
         if 'Mayatomr' in pm.pluginInfo(q=1, ls=1):
             if not pm.pluginInfo('Mayatomr', q=1, l=1):
                 pm.loadPlugin('Mayatomr', qt=1)
         else:
             return
示例#4
0
def load_dlSnapToMeshNOde_plugin():

    plugin_path = os.path.join(os.path.dirname(__file__),
                               'dlSnapToMeshNode.py')
    pm.loadPlugin(plugin_path.replace("\\", "/"))

    source_ae_template()
示例#5
0
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
示例#6
0
def export_maya_file():
    '''
    Test method to use headless maya to open and export a Maya file to FBX from outside of Maya
    '''
    import os
    import sys

    environ_str = ""
    for key, value in os.environ.iteritems():
        environ_str = environ_str + key + " : " + value + "; \n"
    path_str = ""
    for path in sys.path:
        path_str = path_str + path + "; \n"

    file = open(r"C:\Users\micahz\Documents\temp\log.txt", "w")
    file.writelines([sys.executable, "\n\n", environ_str, "\n", path_str])
    file.close()

    import maya.standalone

    maya.standalone.initialize(name='python')
    import pymel.core as pm
    pm.loadPlugin("fbxmaya")
    pm.openFile(
        r"D:\v1\content\Robogore\Data\Levels\Cinematics\Gravcycle_Intro\Gravcycle_Rig.ma"
    )
    pm.select(all=True)
    pm.mel.FBXExport(f=r"C:\Users\micahz\Documents\temp\headless_maya.fbx")
    maya.standalone.uninitialize()
示例#7
0
文件: mesh.py 项目: bloodycube/Raven
def resetMesh(mesh=None):
    # 입력이 있으면 입력된 노드를 선택
    if mesh:
        pm.select(mesh)

    # 입력이 없어도 선택된 오브젝트로 입력 대체
    sel = pm.selected(o=True)

    # 입력값이 없으면 에러
    if not sel:
        raise

    # obj플러그인 로드
    if not pm.pluginInfo('objExport', q=True, loaded=True):
        pm.loadPlugin('objExport')

    # obj임시 저장 위치
    tmpfile = os.path.expanduser('~') + "/tmpObj.obj"

    # obj Export
    pm.select(mesh)
    pm.exportSelected(
        tmpfile,
        typ="OBJexport",
        options="groups=0;ptgroups=0;materials=0;smoothing=0;normals=0",
        f=True)

    # obj Import
    newMesh, newMeshShape = pm.importFile(tmpfile, rnn=True)  # @UnusedVariable

    # 임시저장 파일 삭제
    os.remove(tmpfile)

    pm.select(newMesh)
示例#8
0
def load_mimic_plugins():
    """
    Loads required python plugins into Maya from a directory.
    These are Dependency Graph and Command plugins that should be loaded into
    Maya's plugin manager
    :return:
    """
    # Plugin is dependent on the following scripts
    required_plugins = [
        'robotAccumRot',
        'robotIK',
        'robotLimitRot',
        'snapTransforms'
    ]
    # Check to see if each plug-in is loaded
    for plugin in required_plugins:
        # If the plug-in is not loaded:
        if not pm.pluginInfo(plugin, query=True, loaded=True):
            try:
                # Try loading it (and turn on autoload)
                pm.loadPlugin(plugin)
                pm.pluginInfo(plugin, autoload=True)
                print '{} Plug-in loaded'.format(plugin)
            except Exception:  # Unknown error
                pass
示例#9
0
 def exportAnim(self, outFilePath, *args):
     #loads maya fbx plugin in order to correctly export file
     pm.loadPlugin("fbxmaya")
     mel.eval('FBXResetExport')
     #indicates the object to export is animated
     mel.eval('FBXExportBakeComplexAnimation -v true')
     #excludes cameras
     mel.eval('FBXExportCameras -v false')
     #tells maya to export the texture with the fbx
     mel.eval('FBXExportEmbeddedTextures -v true')
     #tells maya to ignore any leftover constraints
     mel.eval('FBXExportConstraints -v false')
     #forces the use of fbx 2016, which is the current version that works with unreal
     mel.eval('FBXExportFileVersion -v FBX201600')
     #includes Input Connections
     mel.eval('FBXExportInputConnections -v true')
     #excludes lights
     mel.eval('FBXExportLights -v false')
     #includes deformer shapes
     mel.eval('FBXExportShapes -v true')
     #includes skeleton
     mel.eval('FBXExportSkeletonDefinitions -v true')
     #includes skin
     mel.eval('FBXExportSkins -v true')
     #includes smoothing groups
     mel.eval('FBXExportSmoothingGroups -v true')
     #triangulate
     mel.eval('FBXExportTriangulate -v true')
     #exports selected with above settings
     pm.exportSelected(outFilePath,
                       force=True,
                       shader=True,
                       type='FBX export')
示例#10
0
    def createWindow(cls, restore=False):
        if restore:
            parent = mui.MQtUtil.getCurrentParent()

        # create instance if it doesn't exists
        if not cls.INSTANCE:

            # load required plugins
            if cls.REQUIRED_PLUGINS:
                for plugin in cls.REQUIRED_PLUGINS:
                    pm.loadPlugin(plugin, quiet=True)

            cls.INSTANCE = cls()

        if restore:
            mixinPtr = mui.MQtUtil.findControl(cls.INSTANCE.objectName())
            mui.MQtUtil.addWidgetToMayaLayout(long(mixinPtr), long(parent))
        else:
            uiScript = cls.UI_SCRIPT.format(module=cls.WINDOW_MODULE,
                                            cls=cls.__name__)
            closeScript = cls.CLOSE_SCRIPT.format(module=cls.WINDOW_MODULE,
                                                  cls=cls.__name__)

            cls.INSTANCE.show(dockable=True,
                              uiScript=uiScript,
                              closeCallback=closeScript,
                              requiredPlugin=cls.REQUIRED_PLUGINS)

        return cls.INSTANCE
示例#11
0
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
示例#12
0
def load_additional_plugins():
    if pm.about(win64=True):
        system_dir = "win64"
    elif pm.about(li=True):
        system_dir = "linux"
    elif pm.about(macOS=True):
        system_dir = "macOS"
    else:
        luna.Logger.error("Unable to load plugins for system: {0}".format(
            pm.about(os=True)))
        return
    maya_version = pm.about(version=True)
    plugins_dir = os.path.join(directories.PLUGINS_DIR_PATH, maya_version,
                               system_dir)
    if not os.path.isdir(plugins_dir):
        return
    for file_name in os.listdir(plugins_dir):
        if not file_name.endswith(".mll"):
            continue
        full_path = os.path.join(plugins_dir, file_name)
        if pm.pluginInfo(file_name, q=True, loaded=True):
            continue
        try:
            pm.loadPlugin(full_path)
            luna.Logger.info("Loaded plugin: {0}".format(file_name))
        except Exception:
            luna.Logger.exception(
                "Failed to load plugin: {0}".format(file_name))
示例#13
0
def exportAtom(*a):
    ''' Exports the entire hierarchy below the current selection as an .atom file '''    
    sel = atomPreFlight()
    if not sel:
        return

    msg = 'Add a custom tag to the filename?  i.e. \'LOGO\', \'CAM\', or whatev.'
    export_path = getAnimPath('atom', msg, 1)

    # select the whole heirarchy
    pm.select(hierarchy=True)

    # export the .atom for the selected heirarchy
    try:
        # Load the atom plugin
        pm.loadPlugin("atomImportExport.mll")
        # Export the selection
        pm.exportSelected(
            export_path, 
            type='atomExport'
            )
        pm.warning('Export Atom  SUCCESS')
    except RuntimeError:
        pm.warning('Export Atom  ERROR During export. (Most likely there\'s no animation to export.)')
        return
    
    # Restore original selection.
    pm.select(sel)
示例#14
0
def alembicImport(filePath, mode, parent=None, nodes=None):
    ''' Imports Alembic File'''

    #making sure plugin is loaded
    pm.loadPlugin('AbcImport')
    abcNodes = []

    if mode == 'parent':
        abcNodes = pm.AbcImport(filePath,
                                mode="import",
                                ftr=True,
                                sts=True,
                                rpr=parent)

    elif mode == 'merge':
        nodesString = ''

        for node in nodes:
            nodesString += '-root ' + node + ' '
        abcNodes = pm.AbcImport(filePath,
                                mode="import",
                                ct=nodesString,
                                ftr=True,
                                sts=True)

    else:
        abcNodes = pm.AbcImport(filePath, mode="import", ftr=True, sts=True)

    return abcNodes
示例#15
0
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
示例#16
0
 def loadPlugin(self):
     try:
         pm.loadPlugin('frustumSelection', quiet=True)
         return True
     except:
         print "Unable to load frustumSelection plugin!"
         return False
示例#17
0
def load_plug_in(load_list):
    plug_dict = {}
    for plug in load_list:
        plug_dict[plug] = pm.pluginInfo(plug, q=True, loaded=True)
    for key in plug_dict:
        if not plug_dict[key]:
            pm.loadPlugin(key)
示例#18
0
def _load_plugins():
    '''
    Loads GraphEditorRedux for the version of Maya launched
    '''
    if hasattr(pm.versions,
               'v2018') and pm.versions.current() >= pm.versions.v2018:
        pm.loadPlugin('rb2018_GraphEditorReduxPlugin.py')
示例#19
0
def load_ai():
    try:
        if not pluginInfo('mtoa.mll', q=1, l=1):
            loadPlugin('mtoa.mll')
            return True
    except:
        print 'Error load Arnold Renderer'
示例#20
0
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')
    '''
示例#21
0
def loadQuatPlugin():
    global IS_QUAT_PLUGIN_LOADED
    if not IS_QUAT_PLUGIN_LOADED:
        try:
            pm.loadPlugin('quatNodes', quiet=True)
            IS_QUAT_PLUGIN_LOADED = True
        except:
            pass
示例#22
0
def load_plugin(plugin):
    # Don't call loadPlugin if the plugin is already loaded.  Even though it doesn't do anything,
    # it takes about half a second.
    if not pm.pluginInfo(plugin, q=True, loaded=True):
        pm.loadPlugin(plugin, quiet=True)

    if not pm.pluginInfo(plugin, q=True, registered=True):
        raise RuntimeError('Plugin "%s" isn\'t available.' % plugin)
示例#23
0
def QALoadPlugin(plugin, auto=True):
    if pm.pluginInfo(plugin, q=True, r = True):
        if not pm.pluginInfo(plugin, q=True, loaded=True): # si no está cargado
            pm.loadPlugin( plugin) # cargarlo
        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 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))
示例#25
0
def initVray(*args, **kwargs):
    try:
        pm.loadPlugin("vrayformaya.mll")
        pm.setAttr('defaultRenderGlobals.ren', 'vray', type='string')
        return True
    except:
        pm.warning("Could not initialize V-Ray for some reason")
        return False
示例#26
0
def __plugin_loader(plugin_name):
    if not pm.pluginInfo(plugin_name, q=1, loaded=1):
        start_time = time.time()
        logprint('loading %s!' % plugin_name)
        pm.loadPlugin(plugin_name)
        end_time = time.time()
        duration = end_time - start_time
        logprint('%s loaded! in %0.3f sec' % (plugin_name, duration))
示例#27
0
def loadMatrixPlugin():
    global IS_MATRIX_PLUGIN_LOADED
    if not IS_MATRIX_PLUGIN_LOADED:
        try:
            pm.loadPlugin('matrixNodes', quiet=True)
            IS_MATRIX_PLUGIN_LOADED = True
        except:
            pass
示例#28
0
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 )
示例#29
0
	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 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')
示例#31
0
 def load_cvwrap(self):
     # wrap face to head rig
     try:
         if not pm.pluginInfo("cvwrap", q=True, loaded=True):
             pm.loadPlugin("cvwrap")
             pm.displayInfo("cvrap plugin loaded!")
     except RuntimeError:
         pm.displayError("You need the cvWrap plugin!")
         raise
示例#32
0
    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')
示例#33
0
    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')
示例#34
0
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)
示例#35
0
    def clone_camera(self):
        pm.loadPlugin("AbcImport")
        self.type = Asset.CAMERA

        shot_list = self.project.list_existing_shots()
        self.item_gui = sfl.SelectFromList(l=shot_list,
                                           parent=maya_main_window(),
                                           title="Select a shot to clone")
        self.item_gui.submitted.connect(self.shot_results)
示例#36
0
    def wrapper(*args, **kwargs):
        try:
            # try to load houdini engine plug-in to make sliding pivot curve
            pm.loadPlugin('houdiniEngine', qt=True)
        except RuntimeError:
            pm.warning('Houdini Engine not found!')
            return

        return method(*args, **kwargs)
示例#37
0
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")
示例#38
0
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))
示例#39
0
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")
示例#40
0
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
示例#41
0
    def createGtoViz(self, podPath):

        ggcp = GtoGeometryCachePod.fromPodFile(podPath)
        startFrame = ggcp.startFrame
        endFrame = ggcp.endFrame
        cacheFilename = ggcp.cacheFilename

        pm.loadPlugin('TipGtoView', qt=True)
        gtoViz = pm.createNode('TipGtoView')#, n='%sVizShape_'%curChar)
        
        pm.setAttr('%s.filterPolys'%gtoViz, 1)
        pm.setAttr('%s.filterCurves'%gtoViz, 0)
        pm.setAttr('%s.filterNURBS'%gtoViz, 0)
        pm.setAttr('%s.filterPoints'%gtoViz, 0)
        pm.setAttr('%s.filterPattern'%gtoViz, '*body_ShapeN*')        
        
        pm.setAttr('%s.cacheStartFrame'%gtoViz, startFrame)
        pm.setAttr('%s.cacheEndFrame'%gtoViz, endFrame)
        pm.expression(s='%s.currentTime = frame'%gtoViz)
        
        pm.setAttr('%s.animFile'%gtoViz, cacheFilename)
        if ggcp.hasReference:
            pm.setAttr('%s.refFile'%gtoViz, ggcp.referenceFilename)
        else:
            pm.warning('No reference gto found. GtoViz will be slower.')
            pm.setAttr('%s.refFile'%gtoViz, cacheFilename)
        
        gtoViz.addAttr('originalName', dt="string")
        gtoViz.addAttr('podFile', dt="string")
        gtoViz.addAttr('originalSeq', dt="string")
        gtoViz.addAttr('originalChar', dt="string")
        pm.setAttr('%s.podFile'%gtoViz, podPath, type="string")
        curSeq=str(self.animLibComboBox.currentText())
        curChar=str(self.characterComboBox.currentText())
        pm.setAttr('%s.originalSeq'%gtoViz, curSeq)
        pm.setAttr('%s.originalChar'%gtoViz, curChar)
        gtoTrans = gtoViz.listRelatives(p=True)[0]
        pm.setAttr('%s.scaleX'%gtoTrans, l=True)
        pm.setAttr('%s.scaleY'%gtoTrans, l=True)
        pm.setAttr('%s.scaleZ'%gtoTrans, l=True)
        pm.setAttr('%s.rotateOrder'%gtoTrans, l=True)
        
        origName = NAMES_INFO[bdNamingConventions.getCharacterFromPod(podPath)]['fullname']
        pm.setAttr('%s.originalName'%gtoViz, origName, type="string")
        pm.setAttr('%s.label'%gtoViz, origName, type="string")
        
        vizName = curChar + '_' + curSeq + '_Viz_'
        gtoTrans.rename(vizName)
        
        updateWindow()
示例#42
0
def __checkMatrixConstrain__(setNameSpace=True):
    
    # check the version of maya
    # if the version of maya is 2013 the decomposeMatrix does no longer exist
    if pmc.versions.current() < 201300:
        # check if the plug in decompose matrix is load
        pmc.loadPlugin('decomposeMatrix', quiet=True)
    else:
        # check if the plug in decompose matrix is load
        pmc.loadPlugin('matrixNodes', quiet=True)

    # choose the right namespace
    if setNameSpace:
        pmc.namespace(set=':')
示例#43
0
def qClothCmd(*args, **kwargs):
    '''
    create qCloth
    
    step 1: Select an anim geo
    step 2: Duplicate a cloth geo and a output geo from the anim geo
    step 3: Do blendshape both anim geo and cloth geo with output geo
    step 4: Create QCloth on cloth geo
    '''
    
    try:
        pm.loadPlugin("qualoth-2014-x64.mll")
    except:
        pass
    
    sel = pm.ls(sl=1)
    
    outputGrpName = 'output_Grp'
    
    clothGrpName = 'cloth_Grp'
    
    if pm.objExists(outputGrpName):
        outputGrp = pm.PyNode(outputGrpName)
    else :
        outputGrp = pm.createNode('transform', name = outputGrpName)
    
    outputGrp.v.set(0)
    
    if pm.objExists(clothGrpName):
        clothGrp = pm.PyNode(clothGrpName)
    else :
        clothGrp = pm.createNode('transform', name = clothGrpName)
        
    outputGeos = [pm.duplicate(i, name = i.name().replace("_anim", "_output"))[0] for i in sel]
    
    [outputGeo.setParent(outputGrp) for outputGeo in outputGeos]
    
    [i.v.set(0) for i in sel]
    
    clothShape = []
    for i in sel:
        pm.select(i)
        clothShape.append(pm.mel.qlCreateCloth())
    
    clothGeos = [pm.PyNode(i).outputMesh.outputs(p=0)[0] for i in clothShape]
    
    [clothGeo.setParent(clothGrp) for clothGeo in clothGeos]
    
    blendNodes = [pm.blendShape(sel[i], clothGeos[i], outputGeos[i], w = [(0,0), (1,1)]) for i in range(len(sel))]
	def runPlugin(self):
		if self.mainObject.pathIsSet == 1:
			pm.loadPlugin(self.mainObject.pluginPath, name="DoremiEditor")
			self.ui.checkBoxDebug.setEnabled(True)
			self.ui.unloadPluginButton.setEnabled(True)
			self.ui.loadSceneButton.setEnabled(True)
			self.ui.unloadSceneButton.setEnabled(True)
			self.ui.resetMsgButton.setEnabled(True)
			self.ui.actionPluginLocation.setEnabled(True)
			self.ui.runFilemapButton.setEnabled(True)
			self.ui.stopFilemapsButton.setEnabled(True)
			self.ui.acceptFileNameButton.setEnabled(True)
			self.isRunning = 1
		else:
			print 'Plugin file path not set!'
示例#45
0
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
示例#46
0
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 __init__(self, *args, **kargs):
        print "init"
        pm.loadPlugin("cgfxShader.mll")
        # pm.loadPlugin('zoobe_maya_exporter.mll')
        pm.loadPlugin("fbxmaya.mll")

        self.name = kargs.setdefault("name", "MixamoChar")
        self.fbxFile = kargs.setdefault("path")

        self.characterPath = ""
        self.morphFiles = []
        self.backgroundFile = ""

        print self.fbxFile, self.name
        pm.mel.eval(' setProject "/home/zoobe/mixamo/testproject/"')
        self.createCharDirectories()
        # self.logger, self.logHdlr = self.createLogger()
        self.processCharacter()
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))            
示例#49
0
文件: plugin.py 项目: jonntd/Public
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))
示例#50
0
def alembicExport(startFrame,endFrame,filePath,nodes,attributes=None):
    ''' Exports alembic file '''
    
    #making sure plugin is loaded
    pm.loadPlugin('AbcExport')
    
    # defining variables
    nodesString=''
    
    # node loop
    for node in nodes:
        nodesString+='-root '+node+' '
        
    attrstring = ''
    if attributes!=None:
        if len(attributes)>0:
            for attr in attributes:
                attrstring+='-a '+ attr + ' '
    
    # export alembic file
    pm.AbcExport(j='-frameRange %s %s %s-stripNamespaces -uvWrite -worldSpace -wholeFrameGeo -writeVisibility %s-file %s' % (startFrame,endFrame,attrstring,nodesString,filePath))
示例#51
0
def alembicImport(filePath, mode, parent=None, nodes=None):
    ''' Imports Alembic File'''    
    
    #making sure plugin is loaded
    pm.loadPlugin('AbcImport')
    abcNodes=[]
    
    if mode=='parent':
        abcNodes = pm.AbcImport(filePath, mode="import", ftr=True, sts=True, rpr=parent) 
         
    elif mode=='merge':
        nodesString=''
                
        for node in nodes:
            nodesString+='-root '+node+' '
        abcNodes = pm.AbcImport(filePath, mode="import", ct=nodesString, ftr=True, sts=True)
        
    else:
        abcNodes = pm.AbcImport(filePath, mode="import", ftr=True, sts=True)

    return abcNodes
示例#52
0
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()
示例#53
0
 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
示例#54
0
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()
示例#55
0
def load_plugin():
    """
    Looks for and loads Sol Handle plugin.
    :return True if the plugin was loaded, False otherwise.
    """

    # Simple look up
    if is_plugin_loaded():
        return True

    # Try to get at this location
    path = "{}/{}".format(os.path.dirname(__file__), Vars.PLUGIN_FILE)
    if os.path.isfile(path):
        pmc.loadPlugin(path)
        if is_plugin_loaded():
            pmc.displayInfo("[SOL] SolHandle plugin loaded from " + path)
            return True

    # Try user prompt
    q = QtGui.QMessageBox.question(
        None, "Sol",
        "Sol Handle plugin was not found. Would you like to look for it ?",
        QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
    )

    if q == "Yes":
        f, _ = QtGui.QFileDialog.getOpenFileName(
            None, "Load Sol Handle Plugin",
            Vars.PLUGIN_FILE, "*.py"
        )
        if f:
            pmc.loadPlugin(f)
            return is_plugin_loaded()

    # If nothing worked
    return False
示例#56
0
 def test_save_as_sets_the_render_format_to_exr_for_mentalray(self):
     """testing if the save_as method sets the render format to exr
     """
     
     # load mayatomr plugin
     pm.loadPlugin("Mayatomr")
     
     # set the current renderer to mentalray
     dRG = pm.PyNode("defaultRenderGlobals")
     
     dRG.setAttr('currentRenderer', 'mentalRay')
     
     # dirty little maya tricks
     pm.mel.miCreateDefaultNodes()
     
     mrG = pm.PyNode("mentalrayGlobals")
     
     self.mEnv.save_as(self.version1)
     
     # now check if the render format is correctly set to exr with zip
     # compression
     self.assertEqual(dRG.getAttr("imageFormat"), 51)
     self.assertEqual(dRG.getAttr("imfkey"), "exr")
     self.assertEqual(mrG.getAttr("imageCompression"), 4)
示例#57
0
    def __init__(self,*args,**kargs):
        # These plugins are needed by the script, loading them just in case they are not
        pm.loadPlugin('mayaHIK.mll')
        pm.loadPlugin('mayaCharacterization.mll')
        pm.loadPlugin('fbxmaya.mll')
        pm.loadPlugin('zoobe_maya_exporter.mll')

        # The object needs only two arguments : the path to the fbx file and the character name 
        self.name = kargs.setdefault('name','MixamoChar')
        self.fbxFile = kargs.setdefault('path')
        
        self.hasMorphs = 0
        self.characterPath = ''
        self.morphFiles = []
        self.backgroundFile = ''
        pm.mel.eval(' setProject "' + PROJECT_PATH + '"' )

        # A folder structer is needed for the maya part ( rig and animations) and for the export part ( mesh and animation assets)
        self.createCharDirectories()
示例#58
0
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))
        )