Ejemplo n.º 1
0
def refresh_engine(engine_name, prev_context, menu_name):
    """
    refresh the current engine
    """    
    current_engine = tank.platform.current_engine()
    
    # first make sure that the disabled menu is reset, if it exists...
    if pm.menu("ShotgunMenuDisabled", exists=True):
        pm.deleteUI("ShotgunMenuDisabled")
    
    # if the scene opened is actually a file->new, then maintain the current
    # context/engine.
    if pm.sceneName() == "":
        return current_engine

    new_path = pm.sceneName().abspath()
    
    # this file could be in another project altogether, so create a new Tank
    # API instance.
    try:
        tk = tank.tank_from_path(new_path)
    except tank.TankError, e:
        OpenMaya.MGlobal.displayInfo("Shotgun: Engine cannot be started: %s" % e)
        # render menu
        create_tank_disabled_menu(menu_name)
        
        # (AD) - this leaves the engine running - is this correct?        
        return current_engine
Ejemplo n.º 2
0
def refresh_engine(engine_name, prev_context, menu_name):
    """
    refresh the current engine
    """
    current_engine = tank.platform.current_engine()

    if not current_engine:
        # If we don't have an engine for some reason then we don't have
        # anything to do.
        return

    if pm.sceneName() == "":
        # This is a File->New call, so we just leave the engine in the current
        # context and move on.
        return

    # determine the tk instance and ctx to use:
    tk = current_engine.sgtk

    # loading a scene file
    new_path = pm.sceneName().abspath()

    # this file could be in another project altogether, so create a new
    # API instance.
    try:
        tk = tank.tank_from_path(new_path)
    except tank.TankError, e:
        OpenMaya.MGlobal.displayInfo("Shotgun: Engine cannot be started: %s" % e)
        # build disabled menu
        create_sgtk_disabled_menu(menu_name)
        return
Ejemplo n.º 3
0
def refresh_engine(engine_name, prev_context, menu_name):
    """
    refresh the current engine
    """    
    current_engine = tank.platform.current_engine()
    
    # first make sure that the disabled menu is removed, if it exists...
    menu_was_disabled = remove_sgtk_disabled_menu()
    
    # determine the tk instance and ctx to use:
    tk = current_engine.sgtk
    ctx = prev_context
    if pm.sceneName() == "":
        # if the scene opened is actually a file->new, then maintain the current
        # context/engine.
        if not menu_was_disabled:
            # just return the current engine - no need to restart it!
            return current_engine
    else:
        # loading a scene file
        new_path = pm.sceneName().abspath()
    
        # this file could be in another project altogether, so create a new
        # API instance.
        try:
            tk = tank.tank_from_path(new_path)
        except tank.TankError, e:
            OpenMaya.MGlobal.displayInfo("Shotgun: Engine cannot be started: %s" % e)
            # build disabled menu
            create_sgtk_disabled_menu(menu_name)
            return current_engine

        # and construct the new context for this path:
        ctx = tk.context_from_path(new_path, prev_context)
Ejemplo n.º 4
0
def fileTokenScene(path, tokens, **kwargs):
    import pymel.core as pm
    if '<Scene>' in path and 'Scene' not in tokens:
        sceneName = pm.sceneName().namebase
        if sceneName == '':
            sceneName = 'untitled'
        tokens['Scene'] = sceneName
Ejemplo n.º 5
0
def _Load_ChairMAsset_Simple(force=True):
    _file = "\\\\SERVER9\\Maya-Tools\\testFiles\\eMetaData\\ChairMAsset_Simple.mb"
    if pCore.sceneName() == _file:
        if force:
            pCore.openFile(_file, f=True)
    else:
        pCore.openFile(_file, f=True)
Ejemplo n.º 6
0
 def __init__(self):
     self.name = "MusterSubmitClass"
     self.widgets = {}
     self.pools = []
     self.userPass = {}
     self.renderers = []
     self.cameras = pm.ls(ca = True)
     self.scene = pm.sceneName()
     self.priority = self.__class__.defaults['priority']
     self.childrenTabs = []
     
     self.startFrame = pm.SCENE.defaultRenderGlobals.startFrame.get()
     self.endFrame = pm.SCENE.defaultRenderGlobals.endFrame.get()
     
     self.mustertool = None
     
     self._saveUser = None
     self._saveRenderer = None
     self._savePool = None
     
     self.fileInfo = PT.PRAFileInfo(self.scene)
     try:
         self.output = os.path.join(self.__class__.renderDrive, self.fileInfo.getProject(), self.fileInfo.getEpShotName()).replace("\\","/")
     except TypeError: #file info returned None
         self.output = ''
     
     try:
         self._getData() #this bit is slow. use threadding maybe?
     except:
         pm.confirmDialog(title = "Confirm", Message = "Error connecting to muster database / executable. Speak to your IT helpdesk. \nContinuing using Demo mode", buttonm = ['OK'] )
Ejemplo n.º 7
0
    def updateFileNamePrefix(self, *args):
        if self.rendererTabUiDict.has_key("common"):
            uiDict = self.rendererTabUiDict["common"]
        prefix = uiDict["fileNamePrefixField"].getText()

        sceneName = ".".join(pm.sceneName().basename().split(".")[:-1])
        if len(prefix) == 0:
            prefix = sceneName
            uiDict["imgname"].setLabel("File Name: " + sceneName)

        settings = pm.api.MCommonRenderSettingsData()
        pm.api.MRenderUtil.getCommonRenderSettings(settings)

        cams = [cam for cam in pm.ls(type="camera") if cam.renderable.get()]
        if len(cams) < 1:
            log.error("No renderable camera. please make at least one camera renderable.")
            prefix = ""
            for c in pm.ls(type="camera"):
                if "perspShape" in c:
                    cams.append(c)
                    break
        prefix = prefix.replace("<Camera>", cams[0].name())

        prefix = prefix.replace("<Scene>", sceneName)

        ext = self.renderNode.imageFormat.getEnums().keys()[self.renderNode.imageFormat.get()].lower()
        numberFormat = ""
        paddedFrameString = "{0:0" + str(settings.framePadding) + "d}."
        if settings.isAnimated():
            numberFormat = paddedFrameString.format(int(pm.SCENE.defaultRenderGlobals.startFrame.get()))
        completeFileName = "{prefix}.{numbering}{ext}".format(prefix=prefix, numbering=numberFormat, ext=ext)
        uiDict["imgname"].setLabel("File Name: " + completeFileName)
        """
Ejemplo n.º 8
0
    def scan_scene(self):
    
        # first let's look at maya references
        for x in pm.listReferences():
            node_name = x.refNode.longName()
        
            # get the path and make it platform dependent
            # (maya uses C:/style/paths)
            maya_path = x.path.replace("/", os.path.sep)
            self.refs.append( {"node": node_name, "type": "reference", "path": maya_path})
        
        # now look at file texture nodes
        for file_node in cmds.ls(l=True, type="file"):
            # ensure this is actually part of this scene and not referenced
            if cmds.referenceQuery(file_node, isNodeReferenced=True):
                # this is embedded in another reference, so don't include it in the breakdown
                continue
        
            # get path and make it platform dependent (maya uses C:/style/paths)
            path = cmds.getAttr("%s.fileTextureName" % file_node).replace("/", os.path.sep)
        
            self.refs.append( {"node": file_node, "type": "file", "path": path})

        # Append scene file
        self.refs.append( {"node": None, "type": "scene", "path": pm.sceneName()})
        
        return self.refs
Ejemplo n.º 9
0
def anilizeCurrent(assetField,textPublisher,fieldGEO, fieldRIG, fieldFUR, fieldMAT, fieldEDA):
    print '<<  ANALIZING CURRENT ASSET  >>'  
    fileNameFull = pm.sceneName()
    dataFileName = dna.fileActs(fileNameFull) # Get filename details (name, ver, ext etc) 
    phase = dataFileName['filePhase'] # Get PHASE (MODELLING, RENDER, LOOKDEV etc)
    key = dataFileName['filePrefix']
    # Get asset DATA from FTRACK
    assetName = dataFileName['assetName']
    assetType = dataFileName['assetType']
    assetCat = dataFileName['assetCat']    
    # RUN SETUP
    if phase == 'ASSETS': # SETUP ASSETS
        if key == 'ENV': # SETUP <<  ENVIRONMENT  >>
            print 'assetType: <<  ENVIRONMENT  >>'
            value = dataFileName['fileNameFull'] 
            textPublisher(assetName, 'GEO', value, type, assetField, fieldGEO, fieldRIG, fieldFUR, fieldMAT, fieldEDA)                
        elif key == 'FUR' or key == 'GEO' or key == 'RIG': # SETUP <<  CHARACTERS + DYNAMIC PROPS + EDA  >>
            if assetType == 'characters':
                print 'assetType: <<  CHARACTERS  >>'
                value = dataFileName['fileNameFull'] 
                textPublisher(assetName,key,value,type,assetField,fieldGEO, fieldRIG, fieldFUR, fieldMAT, fieldEDA)
            elif assetType == 'props':
                print 'assetType: <<  DYNAMIC PROPS  >>'
                value = '{0}/{1}/{2}'.format(assetCat, key, dataFileName['fileNameFull'])
                textPublisher(assetName,key,value,type,assetField,fieldGEO, fieldRIG, fieldFUR, fieldMAT, fieldEDA)
            elif assetType == 'eda':
                print 'assetType: <<  ENVIRONMENT DYNAMIC ASSET  >>'
                value = fileNameFull.split('{0}{1}'.format(rootScene, envPath))[-1]
                textPublisher(assetName,key,value,type,assetField,fieldGEO, fieldRIG, fieldFUR, fieldMAT, fieldEDA)
                        
    elif phase == 'LOOKDEV': # SETUP MATERIALS
        print 'assetType: <<  MTERIAL LIBRARY  >>'  
        value = dataFileName['fileNameFull'] 
        textPublisher(assetName,key,value,type,assetField,fieldGEO, fieldRIG, fieldFUR, fieldMAT, fieldEDA)
Ejemplo n.º 10
0
	def setWipFolder(self):
		currentScene = pm.sceneName()
		if currentScene:
			projectPath,fileName = os.path.split(currentScene)
			wipFolder = ''
			try:
				wipFolder = pm.fileDialog2(dir=projectPath,ds=2,fm=3,okc='Select Folder')[0]
			except:
				pm.warning('No folder was selected')

			if wipFolder:
				self.wipFolderEdit.setText(wipFolder)
				self.wipFolderPath = wipFolder
				self.bdPopulateFiles()
		else:
			projectPath = pm.workspace.path
			charactersFolder = os.path.abspath(os.path.join(projectPath,'scenes','characters'))
			path = ''
			try:
				path = pm.fileDialog2(dir=charactersFolder,ds=2,fm=3,okc='Select Folder')[0]
			except:
				pm.warning('No folder was selected')
			if path:
				self.wipFolderEdit.setText(path)
				self.wipFolderPath = path
				self.bdPopulateFiles()
Ejemplo n.º 11
0
def _collect_info():
    lines = []
    lines.append('Scene Info')
    lines.append('  Maya Scene: ' + pmc.sceneName())

    lines.append('Maya/Python Info')
    lines.append('  Maya Version: ' + pmc.about(version=True))
    lines.append('  Qt Version: ' + pmc.about(qtVersion=True))
    lines.append('  Maya64: ' + str(pmc.about(is64=True)))
    lines.append('  PyVersion: ' + sys.version)
    lines.append('  PyExe: ' + sys.executable)

    lines.append('Machine Info')
    lines.append('  OS: ' + pmc.about(os=True))
    lines.append('  Node: ' + platform.node())
    lines.append('  OSRelease: ' + platform.release())
    lines.append('  OSVersion: ' + platform.version())
    lines.append('  Machine: ' + platform.machine())
    lines.append('  Processor: ' + platform.processor())

    lines.append('Environment Info')
    lines.append('  EnvVars')
    for k in sorted(os.environ.keys()):
        lines.append('    %s: %s' % (k, os.environ[k]))
    lines.append('  SysPath')
    for p in sys.path:
        lines.append('    ' + p)
    return lines
Ejemplo n.º 12
0
	def openSelectedFile(self):
		try:
			item = self.previewAnimTable.selectedItems()[0]
			if item.column() == 0:
				self.openMayaFile(item.text(),'preview')
			elif item.column() == 2:
				if item.text() == 'Yes':
					filename = self.previewAnimTable.item(item.row(),0).text()
					self.openMovFile(filename,'preview')
		except:
			pass
		
		try:
			item = self.wipAnimTable.selectedItems()[0]
			if item.column() ==0:
				self.openMayaFile(item.text(),'wip')
			elif item.column() == 2:
				if item.text() == 'Yes':
					filename = self.wipAnimTable.item(item.row(),0).text()
					self.openMovFile(filename)
		except:
			pass
		currentFile = pm.sceneName()
		pm.optionVar(stringValueAppend=('RecentFilesList', currentFile))
		pm.optionVar(stringValueAppend=('RecentFilesTypeList', 'mayaAscii'))
		
		self.bdPopulateFiles()
Ejemplo n.º 13
0
    def setImageName(self):
        self.renderGlobalsNode.basePath.set(pm.workspace.path)
        try:
            self.renderGlobalsNode.imagePath.set(pm.workspace.path + pm.workspace.fileRules['images'])
        except:
            self.renderGlobalsNode.imagePath.set(pm.workspace.path + 'images')
        sceneName = ".".join(pm.sceneName().basename().split(".")[:-1])

        # get rid of the number extension which is created by maya if we start a batchrendering from the UI
        numberPart = sceneName.split("__")[-1]
        try:
            number = int(numberPart)
            if number > 999:
                sceneName = sceneName.replace("__" + numberPart, "")
        except:
            pass
        imageName = sceneName
        prefix = pm.SCENE.defaultRenderGlobals.imageFilePrefix.get()
        if prefix:
            if len(prefix) > 0:
                settings = pm.api.MCommonRenderSettingsData()
                pm.api.MRenderUtil.getCommonRenderSettings(settings)

                cams = [cam for cam in pm.ls(type='camera') if cam.renderable.get()]
                if len(cams) < 1:
                    log.error("No renderable camera.")
                    prefix = ""
                prefix = prefix.replace("<Camera>", cams[0].name())
                prefix = prefix.replace("<Scene>", sceneName)
                imageName = prefix

        self.renderGlobalsNode.imageName.set(imageName)
Ejemplo n.º 14
0
def SNV(*args):
	sceneNameFull = pm.sceneName() # full scene name with path, version, ext
	scenePath = os.path.dirname(sceneNameFull) # scene path
	sceneNameVerExt = sceneNameFull.split('/')[-1] # scene name with version an ext
	sceneNameVer, ext = sceneNameVerExt.split('.') # get EXT
	ver = sceneNameVer.split('_')[-1] # get VERSION
	verNext = int(ver) + 1
	partQnt = len(sceneNameVer.split('_')) - 1 # get quantity of scene name parts, separated with '_'
	sceneNameParts = sceneNameVer.split('_')[0 : partQnt]
	sceneName = '' # recreate scene name from parts
	for i in range (0 , partQnt):
		sceneName += sceneNameParts[i] + '_'

	sceneNameFullNew = '{0}/{1}{2:0>3}.{3}'.format(scenePath, sceneName, verNext, ext)
	if os.path.exists(sceneNameFullNew):
		confirm = pm.confirmDialog ( title = 'File exists!', message=  'Overwrite file?' + '\r\n\r\n' + str('{0}{1:0>3}.{2}'.format( sceneName, verNext, ext)), button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
		if confirm == 'Yes':
			pm.saveAs(sceneNameFullNew)
			pm.mel.addRecentFile (sceneNameFullNew, 'mayaBinary')
			print 'File overrited: ' + str(sceneNameFullNew)
		else:
			sys.exit()
	else:
		pm.saveAs(sceneNameFullNew)
		pm.mel.addRecentFile (sceneNameFullNew, 'mayaBinary')
		print 'File saved: ' + str(sceneNameFullNew)
Ejemplo n.º 15
0
def saveSceneForVersion():
    filePath = _pmCore.sceneName()
    fileID = _Database.getIDByFilePath(filePath)[0]
    _pmCore.saveFile()
    versionNum, _, thumbnailPath = _Database.addVersion(filePath, _os.environ.get('AM_USERNAME'))
    _makeThumbnail(128, 128, thumbnailPath)
    return fileID, versionNum, thumbnailPath
Ejemplo n.º 16
0
	def playblastCurrent(self):
		playblastFormat = self.animFormatComboBox.currentText()
		print playblastFormat 
		qtPlayblastMelCmd = 'playblast  -format qt -sequenceTime 0 -clearCache 1 -viewer 1 -showOrnaments 1 -fp 4 -percent 100 -compression "H.264" -quality 100 -widthHeight 1280 720;';
		xvidPlayblastMelCmd  = 'playblast  -format avi -sequenceTime 0 -clearCache 1 -viewer 1 -showOrnaments 1 -fp 4 -percent 100 -compression "XVID" -quality 100 -widthHeight 1280 720;';
		uncommpresedPlayblastMelCmd = 'playblast  -format avi -sequenceTime 0 -clearCache 1 -viewer 1 -showOrnaments 1 -fp 4 -percent 100 -compression "none" -quality 100 -widthHeight 1280 720;';
		tempFile = ''
		if playblastFormat == 'mov':
			tempFile = pm.mel.eval(qtPlayblastMelCmd)
		elif playblastFormat == 'avi':
			tempFile = pm.mel.eval(xvidPlayblastMelCmd)
		elif playblastFormat == 'uncompressed':
			tempFile = pm.mel.eval(uncommpresedPlayblastMelCmd)
		
		if os.path.isfile(tempFile):
			path,fileName = os.path.split(pm.sceneName())
			extension = '.mov'
			if playblastFormat == 'avi' or playblastFormat == 'uncompressed':
				extension  = '.avi'

			movFile = fileName.split('.')[0] + extension
			try:
				shutil.copy2(tempFile, os.path.join(path,movFile))
			except:
				pm.error("Coulnd't copy the temp blast")
			self.updatePlayblastStatus(fileName)
Ejemplo n.º 17
0
def _get_shotgun_fields_from_file_name_():
    import sgtk
    libUtilities.pyLog.info('Getting info from Shotgun')
    path = pm.sceneName()
    tk = sgtk.sgtk_from_path(path)
    template_obj = tk.template_from_path(path)
    fields = template_obj.get_fields(path)
    return template_obj, fields, tk
Ejemplo n.º 18
0
def bdGetMapping():
    animScene = pm.sceneName()
    fileName = animScene.split('/')[-1]
    shadowAnimFile = animScene.replace(fileName,'') + 'shadowAnim/tsm2_to_rsmg.map'
    if os.path.isfile(shadowAnimFile):
        f = open(shadowAnimFile,'r')
        mapping = f.read().split(' ')
        f.close()
        return mapping
Ejemplo n.º 19
0
	def getWipFolder(self):
		currentSceneName = pm.sceneName()
		if 'wip' in currentSceneName:
			path,sceneName = os.path.split(currentSceneName)
			self.wipFolderEdit.setText(path)
			self.wipFolderPath = path
			self.bdPopulateFiles()
		else:
			projectPath = pm.workspace.name
			charactersFolder = os.path.join(projectPath,'scenes','characters')
			self.wipFolderEdit.setText(charactersFolder)
Ejemplo n.º 20
0
def setRelativeReferences():
    """
    Changes unresolved paths of references to relative paths.
    """
    scene_path = pm.sceneName().parent

    for ref_node in pm.listReferences():
        rel_path = scene_path.relpathto( ref_node.path.realpath() )
        if ref_node.unresolvedPath() != rel_path:
            ref_node.load( rel_path )
            print "// set relative (%s)" % rel_path
Ejemplo n.º 21
0
def realSceneName(doDot=False):
    snel = pm.sceneName().basename().split(".")
    sn = snel[0]
    if len(sn.split("__")) > 1:
        elements = sn.split("__")
        num = elements[1]
        if num.isdigit():
            log.debug("Scene has pattern name__number.xx seems to be a batchrender scene, deleting number.")
            sn = elements[0]
    if doDot:
        sn += "." + snel[1]
    return sn
Ejemplo n.º 22
0
	def playblastCurrent(self):
		playblastMelCmd = 'playblast  -format qt -sequenceTime 0 -clearCache 0 -viewer 1 -showOrnaments 1 -fp 4 -percent 100 -compression "H.264" -quality 100';
		tempFile = pm.mel.eval(playblastMelCmd)
		
		if os.path.isfile(tempFile):
			path,fileName = os.path.split(pm.sceneName())
			movFile = fileName.split('.')[0] + '.mov'
			try:
				shutil.copy2(tempFile, os.path.join(path,movFile))
			except:
				pm.error("Couln't copy the temp blast")
			self.updatePlayblastStatus(fileName)
Ejemplo n.º 23
0
Archivo: core.py Proyecto: etic/mayabox
	def _getExportPaths(self, node, subdir, ext):
		# get export path
		mf = MayaFile(pm.sceneName())
		exportDir = mf.package.subdirPath(subdir)
		exportName = '{0}_{1}{2}'.format(mf.baseName, node.nodeName(), ext)
		exportPath = cleanJoin(exportDir, exportName)
		# get export history path
		exportHistoryDir = mf.package.subdirPath('{0}/history'.format(subdir))
		exportHistoryBasePath = cleanJoin(exportHistoryDir, exportName)
		historyVersion = versions.getLatestVersion(exportHistoryBasePath) + 1
		exportHistoryPath = versions.setVersion(exportHistoryBasePath, historyVersion)
		return exportPath, exportHistoryPath
Ejemplo n.º 24
0
def openAsset():
    try:
        QtGui.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
        container = sandbox.get(pm.workspace.path)[0]
    except:
        container = None
    finally:
        QtGui.QApplication.restoreOverrideCursor()

    dialog = BrowserDialog(modal=True)
    dialog.setBrowseType(BrowserDialog.BrowseRevisions)
    dialog.setHintText("Select a revision.")
    dialog.setCwd(pm.workspace.path)
    dialog.setSelectedItem(container)

    if dialog.exec_() == QtGui.QDialog.Accepted:
        revision = dialog.selectedItem()

        if not revision:
            return

        container = revision.container

        work_root = sandbox.get_path(container)

        # set the project
        mayautils.setProject(work_root)

        # check if the user has saved
        if cmds.file(query=True, anyModified=True):
            result = pm.confirmDialog(title="Save Changes",
                                           message="Save changes to " + pm.sceneName() + "?",
                                           button=["Save", "Don't Save", "Cancel"],
                                           defaultButton="Save",
                                           cancelButton="Cancel",
                                           dismissString="Don't Save")
            if result == "Cancel":
                return
            elif result == "Save":
                cmds.file(save=True, force=True)
            else: # "Don"t Save"
                pass

        # get revision path
        tank_path = revision.system.vfs_full_paths[0]
#            tank_root, tank_filename = os.path.split(tank_path)
#            tank_filename, tank_ext = os.path.splitext(tank_filename)
#
#            # remove "-v006-1451_96" from end of filename
#            tank_filename = re.sub(r"-v[0-9]+-[0-9_]+$", "", tank_filename)
#
        # open revision
        pm.openFile(tank_path, force=True)
Ejemplo n.º 25
0
def set_publish_info():
    try:
        import sgtk
    except:
        shotgunErrorBox = libPySide.QCriticalBox()
        shotgunErrorBox.setText("Shotgun toolkit not loaded")
        shotgunErrorBox.setWindowTitle("Shotgun Module")
        shotgunErrorBox.exec_()
        return
    # # Evaluate the path
    path = pm.sceneName()
    #
    # # Get the toolkit
    tk = sgtk.sgtk_from_path(path)

    # # Get the nuke published area
    nukePublishFolderTemplate = tk.templates['shot_publish_area_nuke']
    #
    # Deconstruct the maya scene
    mayaTemplate = tk.template_from_path(path)
    fields = mayaTemplate.get_fields(path)
    nukePublishFolder = nukePublishFolderTemplate.apply_fields(fields)
    #
    publishNukeFile = [fileName for fileName in libFile.listfiles(nukePublishFolder) if fileName.endswith(".nk")]
    currentPublishedNuke = libFile.search_pattern_in_folder(".nk", nukePublishFolder)
    #
    # increments the version
    fields["version"] = len(publishNukeFile) + 1

    # Get the maya scene file
    mayaPublishFolderTemplate = tk.templates['maya_shot_render_folder']
    mayaPublishVersion = "v%s" % str(fields["version"]).zfill(3)
    mayaPublishVersionFolder = mayaPublishFolderTemplate.apply_fields(fields)
    mayaShotTemplate = tk.templates['shot_publish_area_maya']
    mayaProjectFolder = mayaShotTemplate.apply_fields(fields)
    mayaFileName = "%s_%s" % (fields['Shot'], mayaPublishVersion)

    renderer = pm.PyNode("defaultRenderGlobals")
    renderer.currentRenderer.set("vray")

    # Setup Vray
    _set_vray_()
    vraySettings = pm.PyNode("vraySettings")
    vraySettings.fileNamePrefix.set(mayaFileName)

    info = {"jobName": mayaFileName,
            "imagesFolder": mayaPublishVersionFolder,
            "projectFolder": mayaProjectFolder

            }
    # Set the meta data
    set_render_meta_data(vraySettings, tk)
    return info
Ejemplo n.º 26
0
def importAbcInFolder():
	
	# Get base directory
	basedir = pm.sceneName().parent
	basedir = basedir.lower()
	
	# Get scene name
	sceneName = cmds.file(q=True, sceneName=True, shn=True)
	alembicName = abcMB[sceneName]
	
	# Load Abc file
	pm.AbcImport(basedir + '/' + alembicName)
Ejemplo n.º 27
0
    def generate_job_name(cls):
        """generates a job name according to the current scene
        """
        # first check if it is a Stalker Project
        from anima.env import mayaEnv
        m = mayaEnv.Maya()
        v = m.get_current_version()
        if v is not None:
            from stalker import Version
            assert isinstance(v, Version)
            return '%s:%s_v%03i%s' % (
                v.task.project.code,
                v.nice_name,
                v.version_number,
                v.extension
            )

        try:
            # check if it is a oyProjectManager job
            from oyProjectManager.environments import mayaEnv
            m = mayaEnv.Maya()
            v = m.get_current_version()
            if v is not None:
                from oyProjectManager.models.version import Version
                assert isinstance(v, Version)
                # get asset or shot
                versionable = v.version_of

                from oyProjectManager.models.asset import Asset
                from oyProjectManager.models.shot import Shot

                first_part = None
                if isinstance(versionable, Asset):
                    first_part = '%s:%s' % (
                        versionable.project.code,
                        versionable.code
                    )
                elif isinstance(versionable, Shot):
                    first_part = '%s:%s' % (
                        versionable.project.code,
                        versionable.sequence.code
                    )

                return '%s:%s' % (
                    first_part,
                    '%s_%s_%s_v%03i_%s%s' % (
                        v.base_name, v.take_name, v.type.code, v.version_number,
                        v.created_by.initials, v.extension
                    )
                )
        except ImportError:
            return os.path.basename(pm.sceneName())
Ejemplo n.º 28
0
	def __init__(self):
		
		self.title = "Shader Linker .9"
		self.name = "shaderLinker"
		self.help = self.name + "Help"

		self.instructions = "Export Links: Writes all the shader links into a sql file" + "\n\n" + "Link Shaders: Links the shaders to the meshes according to the sql file specified in the Links path." + "\n\n" + "Links: Path to the sql file which holds the links" + "\n\n" + "Shaders: Path to the .mb file which holds the shaders. Can be empty to no import any shaders." + "\n\n" + "Use Selection: Link only the selected mesh" + "\n\n" + "Workflow: " + "\n" + "1. Export all links into a .db file of choice. A new file must be specified each time." + "\n" + "2. To link all the shaders a path to the .db file must be specified." + "\n" + "Optional: Shaders can be imported into the scene via the shader path."

		# Set base directory
		self.basedir = pm.sceneName().parent
		self.basedir = self.basedir.lower()

		self.buildGUI()
Ejemplo n.º 29
0
 def setImageName(self):
     self.renderGlobalsNode.basePath.set(pm.workspace.path)
     self.renderGlobalsNode.imagePath.set(pm.workspace.path + pm.workspace.fileRules['images'])
     imageName = pm.sceneName().basename().replace(".ma", "").replace(".mb", "")
     # check for mayabatch name like sceneName_number 
     numberPart = imageName.split("__")[-1]
     try:
         number = int(numberPart)
         if number > 999:
             imageName = imageName.replace("__" + numberPart, "")
     except:
         pass
     self.renderGlobalsNode.imageName.set(imageName)        
Ejemplo n.º 30
0
 def export_to_ma(self):
     '''
     # this exports to a new ma file if True
     '''
     if self.export == True:
         if self.group== True:
             pm.select(clear= True)
             pm.select(self.main_group)
             current_scene = pm.sceneName()
             dir_name = os.path.dirname(current_scene)
             new_scene_name = os.path.join(dir_name, self.name)
             try:
                 pm.exportSelected(new_scene_name, force= True, channels= True,
                               type=  'mayaAscii')
             except:
                 pm.exportSelected(new_scene_name, force= True, channels= True,
                               type=  'mayaBinary')
         if self.group == False:
             joints = []
             geometry = []
             for bound_geo in self.bound_geo_instances:
                 joint = bound_geo.get_joint()
                 joints.append('%s' % (joint))
                 
             for bound_geo in self.bound_geo_instances:
                 geo = bound_geo.get_bound_geo()
                 geometry.append(geo)
                 
             pm.select(clear= True)
             pm.select(joints, geometry)
             current_scene = pm.sceneName()
             dir_name = os.path.dirname(current_scene)
             new_scene_name = os.path.join(dir_name, self.name)
             try:
                 pm.exportSelected(new_scene_name, force= True, channels= True,
                               type=  'mayaAscii')
             except:
                 pm.exportSelected(new_scene_name, force= True, channels= True,
                               type=  'mayaBinary')
Ejemplo n.º 31
0
def main(scene_path='', img_dir='', mov_dir='', shot_name='', pb_offscreen=True,    \
         cut_in=None, cut_out=None, enable_audio=True, img_only=False, play_on_finish=True, \
         display_elements={'dynamics':True, 'nParticles':True}, img_compression='png', \
         widthHeight=[2048,858], camera_grp='|cameras', clean_images=True, renderers='base_OpenGL_Renderer'):
    '''
        scene_path should be a path to a maya file with .ma or .mb extension, or will be filled with current scene name
        automatically if not specified. this maya file name will be used to create mov name:
            my_scene.ma --> my_scene.stereo.mov
        
        Care must be taken that you need install rv player to convert from images to mov,
        if rv player is not available, you could disable converting by set img_only to True, but still generates images.
        
        if img_dir and mov_dir are absent, then the images and mov will be put under the subfolders named as images and data
        in the same path with the scene file
    '''
    
    # get rv path if any
    rv = cf.getRVPath(use_old_version=False)
    rvio = rv['rvio']
    opener = rv['opener']
    player = rv['player']
    rvls = rv['rvls']
    rv_shell = rv['rv_shell']

    if not os.path.isfile(rvio):
        pm.warning('Failed to find rvio path, the left and right images will not be converted to mov file.')

    # Get current maya file path
    file_path = pm.system.Path(scene_path) if scene_path else pm.sceneName()
    file_path = cf.osPathConvert(file_path)
    print 'file_path', file_path
    if not file_path:
        pm.confirmDialog(message ='Invalid scene name or scene path!')
        return

    # prepare to get proj and shot info
    tokens = file_path.split('/')
    file_name = tokens[-1]
    if not file_name.endswith('.ma') and not file_name.endswith('.mb'):
        pm.confirmDialog(message = file_name+': file name should be a maya scene file with .ma or .mb extension')
        return

    # prepare mov name
    mov_file_name = file_name[:-3] + '.stereo.mov'

    if renderers=='vp2Renderer':
        # if we use viewport2(vp2) render, the images contain alpha channel, 
        # then we simply use imconvert to composite images instead of chrome keying in nuke
        # but imconvert can not recognize tif image, so we change the default tif to png
        img_compression = 'png'

    # get shot name
    if not shot_name:
        if 'shot' in tokens:
            i = tokens.index('shot')
            shot_name = tokens[i+2]

    proj_name = dept_name = '' 

    img_dir = cf.osPathConvert(img_dir)
    if not img_dir or not os.path.isdir(img_dir):
        img_dir = os.path.dirname(file_path) + '/images/' + file_name + '/'
    img_dir = img_dir+'/' if not img_dir.endswith('/') else img_dir

    if not os.path.isdir(img_dir):
        try:
            os.makedirs(img_dir)
        except:
            pm.confirmDialog(message = 'Failed to create folder: '+img_dir)
            return
    else:
        # delete old images
        img_left_list = glob.glob(img_dir+file_name[:-3]+'.left.*.%s' % img_compression)
        img_right_list = glob.glob(img_dir+file_name[:-3]+'.right.*.%s' % img_compression)
        try:
            if clean_images:
                for img in img_left_list+img_right_list:
                    if os.path.isfile(img):
                        os.remove(img)
        except:
            pm.confirmDialog(message = 'Failed to remove old images at '+img_dir)
            cmd_str = '"' + opener + '" ' + img_dir
            os.system(cmd_str)
            return

    mov_dir = cf.osPathConvert(mov_dir)
    if not mov_dir or not os.path.isdir(mov_dir):
        mov_dir = os.path.dirname(file_path) + '/data/'
    mov_dir = mov_dir+'/' if not mov_dir.endswith('/') else mov_dir
    if not os.path.isdir(mov_dir):
        try:
            os.makedirs(mov_dir)
        except:
            pm.confirmDialog(message = 'Failed to create folder: '+mov_dir)
            return

    # get cut in and cut out
    if cut_in is None or cut_out is None:
        cut_in = pm.animation.playbackOptions(q=True, minTime=True)
        cut_out = pm.animation.playbackOptions(q=True, maxTime=True)

    print 'cut_in', cut_in
    print 'cut_out', cut_out

    # get audio file if any, we only grab the first audio track
    audios = [a for a in pm.ls(type='audio')]
    audio_path = ''
    if audios and enable_audio:
        audio_node = audios[0]
        slider = pm.mel.eval('$tmpVar=$gPlayBackSlider')
        pm.timeControl(slider, edit=True, displaySound=True, sound=audio_node)
        audio_path = cf.osPathConvert( audio_node.attr('filename').get() )
        if not os.path.isfile(audio_path):
            audio_path = ''

    # get image width and height
    if widthHeight[0]==0 or widthHeight[1]==0:
        widthHeight = [pm.PyNode('defaultResolution').attr('width').get(), pm.PyNode('defaultResolution').attr('height').get()]

    # playblast!
    pb_stereo(img_dir+file_name[:-3], cut_in, cut_out, pb_offscreen=pb_offscreen, display_elements=display_elements, ext=img_compression, widthHeight=widthHeight, camera_grp=camera_grp, renderers=renderers)

    if img_only:
        print 'Playblasted left and right images at: ', img_dir
        return img_dir

    # prepare rv converting command string
    # get left and right image path, check the image sequence
    img_left = img_dir+file_name[:-3]+'.left.#.%s' % img_compression
    img_right = img_dir+file_name[:-3]+'.right.#.%s' % img_compression
    img_left_list = sorted( glob.glob(img_left.replace('#','*')) )    # glob doesn't recognize # symbol
    img_right_list = sorted( glob.glob(img_right.replace('#','*')) )
    if not ( img_left_list and len(img_left_list)==len(img_right_list) ):
        pm.confirmDialog( title='Error', message='Failed to find images or the length of left image is not equal to the right: \n'+img_left+'\n'+img_right )
        return
    cut_in_img = int(img_left_list[0].split('.')[-2])
    cut_out_img = int(img_left_list[-1].split('.')[-2])
    # rvio command
    if audio_path == '':
        cmd_str = '"' + rvio + '" [ ' + img_left + ' ' + img_right + ' ] -outstereo -o ' + mov_dir + mov_file_name
    else:
        cmd_str = '"' + rvio + '" [ ' + img_left + ' ' + img_right + ' ' +audio_path+' ] -audiorate 48000 -outstereo -o ' + mov_dir + mov_file_name
    cmd_str += ' -outfps 24'
    cmd_str += ' -outparams comment="%s-%s %s %s"' % (cut_in_img, cut_out_img, file_path, audio_path)   # store custom contents in comment attribute
    cmd_str += ' timecode=%s' % cut_in_img          # encode timecode
    if shot_name and rv['version']>=6:
        cmd_str += ' reelname=%s' % shot_name   # encode reelname
    os.environ['RV_ENABLE_MIO_FFMPEG'] = '1'    # RV_ENABLE_MIO_FFMPEG needs to be enable to encode comment attribute

    # execute rvio command
    print 'Cmd: \n', cmd_str
    p = subprocess.Popen(cmd_str, shell=rv_shell)
    (out, err) = p.communicate()
    print 'out', out
    print 'err', err
    print 'Done'
        
    cmd_str = '"'+player+ '" -stereo scanline ' + mov_dir + mov_file_name
    if play_on_finish:
        print 'Cmd:', cmd_str
        p = subprocess.Popen(cmd_str, shell=rv_shell)
        (out, err) = p.communicate()
        print 'out', out
        print 'err', err
        print 'Done'

    return
Ejemplo n.º 32
0
def resolveAOVsInPath(path, layer, cam, framePadder='?'):
    paths = []
    renderer = currentRenderer()

    if renderer == 'redshift':
        tokens = OrderedDict()

        tokens['<beautypath>'] = op.dirname(path).replace('\\', r'\\')

        basename = op.basename(path)
        number = ''
        if isAnimationOn():
            basename, number = removeLastNumber(basename, '')
        basename = op.splitext(basename)[0]
        if basename.endswith('.'):
            basename = basename[:-1]
        tokens['<beautyfile>'] = basename
        if cam:
            camera = re.sub(r'\.|:', '_', str(cam.firstParent()))
        else:
            camera = ''

        tokens['<camera>'] = camera
        tokens['<layer>'] = re.sub(r'\.|:', '_', str(layer))
        tokens['<renderlayer>'] = tokens['<layer>']

        sceneName, _ = op.splitext(op.basename(pc.sceneName()))
        if not sceneName:
            sceneName = pc.untitledFileName()
        tokens['<scene>'] = sceneName

        beauty = renderpass_re.sub('Beauty', path)
        beauty = aov_re.sub('Beauty', beauty)
        beauty = replaceTokens(tokens, beauty)
        paths.append(beauty)

        renderpasses = set()
        for aov in filter(lambda x: x.enabled.get(),
                          pc.ls(type='RedshiftAOV')):
            newpath = aov.filePrefix.get()
            extIndex = aov.fileFormat.get()

            if pc.attributeQuery('name', n=aov, exists=True):
                renderpass = aov.attr('name').get()
            else:
                renderpass = aov.aovType.get().replace(' ', '')
                count = 1
                rp = renderpass
                while rp in renderpasses:
                    rp = renderpass + str(count)
                    count += 1
                renderpass = rp
                renderpasses.add(renderpass)

            exts = ['.iff', '.exr', '.tif', '.png', '.tga', '.jpg']
            tokens['<renderpass>'] = tokens['<aov>'] = renderpass
            newpath = replaceTokens(tokens, newpath)
            newpath = newpath + ('.'
                                 if number else '') + number + exts[extIndex]
            paths.append(newpath)

    elif renderer == 'arnold':
        if not renderpass_re.search(path):
            return [path]
        passes = getRenderPassNames()
        if not passes:
            passes = ['']
        for pas in passes:
            paths.append(renderpass_re.sub(pas, path))

    else:
        paths.append(aov_re.sub('', renderpass_re.sub('', path)))

    return paths
Ejemplo n.º 33
0
def update_rig_file():
    '''
    Update a rig file from an FBX that the user is prompted to choose.  Keeps current rig settings and inserts the updated
    character skeleton/model from the chosen FBX file.
    '''
    current_character_node = metadata.network_core.MetaNode.get_all_network_nodes(metadata.network_core.CharacterCore)[0]
    current_character_network = metadata.network_core.MetaNode.create_from_node(current_character_node)
    character_namespace = current_character_network.group.namespace()
    character_name = current_character_network.node.character_name.get()
    character_root_path = current_character_network.node.root_path.get()
    character_sub_paths = current_character_network.node.sub_paths.get()

    file_path = get_first_or_default(pm.fileDialog2(ds = 1, fm = 1, ff = "FBX (*.fbx *.FBX)", cap = "Load Character FBX"))
    file_path = file_path.replace('\\', '\\\\') if file_path else ''

    folder_path_list = current_character_network.character_folders
    folder_path_list = [x for x in folder_path_list if os.path.exists(x)]
    settings_file_dict = {}
    for folder in folder_path_list:
        for file in rigging.file_ops.get_settings_files(folder, "rig"):
            settings_file_dict[file] = (os.path.join(folder, file))

    settings_file = None
    if len(settings_file_dict) == 1:
        settings_file = get_first_or_default(settings_file_dict.values())
    else:
        settings_file = get_first_or_default(pm.fileDialog2(ds = 1, fm = 1, ff = "JSON (*.json)", dir = folder_path_list[0], cap = "Load Settings File"))

    if file_path and settings_file:
        checkoutList = System.Collections.Generic.List[str]()
        checkoutList.Add(str(pm.sceneName()))
        try:
            Freeform.Core.Helpers.Perforce.CheckoutFiles(checkoutList)
        except:
            pass

        current_obj_list = pm.ls(assemblies = True)
        maya_utils.fbx_wrapper.FBXImport(f = file_path)
        new_obj_list = [x for x in pm.ls(assemblies = True) if x not in current_obj_list]

        new_joint = get_first_or_default([x for x in new_obj_list if isinstance(x, pm.nt.Joint)])
        # If we don't find any top level joints, look for top level objects with 'root' in the name
        if not new_joint:
            new_joint = get_first_or_default([x for x in new_obj_list if 'root' in x.name().lower()])
        new_root = rigging.skeleton.get_root_joint(new_joint)

        updated_character_network = characterize_skeleton(new_root, name = character_name)
        rigging.file_ops.load_settings_from_json(updated_character_network.group, settings_file)
        rigging.rig_base.Component_Base.delete_character(current_character_network.node)

        updated_character_network.node.root_path.set(character_root_path)
        updated_character_network.node.sub_paths.set(character_sub_paths if character_sub_paths else "")

        # new_root might have been deleted by characterize_skeleton if it wasn't a joint, for safety we get the root
        # connected to the character network
        new_root = updated_character_network.get_downstream(metadata.network_core.JointsCore).root
        jnt_layer_list = new_root.drawOverride.listConnections()
        character_obj_list = [updated_character_network.group] + updated_character_network.group.listRelatives(ad=True)

        mesh_list = [x for x in character_obj_list if not isinstance(x, pm.nt.Joint) and isinstance(x, pm.nt.Transform)]
        mesh_layer_list = []
        for mesh in mesh_list:
            mesh_layer_list = mesh.drawOverride.listConnections()
            if mesh_layer_list:
                break

        if not pm.namespace(exists = character_namespace):
            pm.namespace(add = character_namespace[:-1])

        for obj in character_obj_list + jnt_layer_list + mesh_layer_list:
            obj.rename(character_namespace + obj.name())
    
        for jnt in pm.ls(type='joint'):
            jnt.radius.set(2)
    else:
        dialog_message = "Failed to update Rig file.  Either FBX or Settings file were invalid"
        v1_shared.usertools.message_dialogue.open_dialogue(dialog_message, title="Failed To Update")
Ejemplo n.º 34
0
    def launch(self, *args, **kwargs):
        """launch renderer command
        """
        # do nothing if there is no window (called externally)
        if not self.window:
            return

        # warn the user about the ignore settings
        try:
            dAO = pm.PyNode('defaultArnoldRenderOptions')

            ignore_attrs = [
                'ignoreSubdivision', 'ignoreDisplacement', 'ignoreBump',
                'ignoreMotionBlur'
            ]

            attr_values = [(attr, dAO.getAttr(attr)) for attr in ignore_attrs
                           if dAO.getAttr(attr) is True]

            if any(attr_values):
                msg_text = '<br>'.join(
                    map(lambda x: '%s: %s' % (x[0], x[1]), attr_values))

                response = pm.confirmDialog(
                    title='Ignore These Settings?',
                    message=
                    'You have ignored:<br><br>%s<br><br><b>Is that ok?</b>' %
                    msg_text,
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No')

                if response == 'No':
                    return
        except pm.MayaNodeError:
            # no Arnold
            pass

        # check if rendering with persp camera
        try:
            wrong_camera_names = [
                'perspShape',
                'topShape',
                'sideShape',
                'fontShape',
                'persp1Shape',
                'perspShape1',
            ]
            renderable_cameras = [
                node for node in pm.ls(type='camera')
                if node.getAttr('renderable')
            ]
            if any(
                    map(lambda x: x.name() in wrong_camera_names,
                        renderable_cameras)):
                response = pm.confirmDialog(
                    title='Rendering with Persp?',
                    message=
                    'You are rendering with <b>Persp Camera<b><br><br>Is that ok?</b>',
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No')

                if response == 'No':
                    return

            if len(renderable_cameras) > 1:
                response = pm.confirmDialog(
                    title='Rendering more than one Camera?',
                    message=
                    'You are rendering <b>more than one camera<b><br><br>Is that ok?</b>',
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No')

                if response == 'No':
                    return
            elif len(renderable_cameras) == 0:
                pm.confirmDialog(
                    title='No <b>Renderable</b> camera!!!',
                    message='There is no <b>renderable camera<b>!!!',
                    button=['Ok'],
                    defaultButton='Ok',
                    cancelButton='Ok',
                    dismissString='Ok')
                return

        except pm.MayaNodeError:
            # no default render globals node
            pass

        drg = pm.PyNode('defaultRenderGlobals')
        render_engine = drg.getAttr('currentRenderer')
        # RENDERER SPECIFIC CHECKS

        if render_engine == 'redshift':
            # if the renderer is RedShift
            # check if unifiedDisableDivision is 1 which will take too much time
            # to render
            dro = pm.PyNode('redshiftOptions')
            if dro.unifiedDisableDivision.get() == 1:
                response = pm.confirmDialog(
                    title=
                    "Enabled **Don't Automatically Reduce Samples of Other Effects**",
                    message=
                    'It is not allowed to render with the following option is enabled:<br>'
                    '<br>'
                    "Don't Automatically Reduce Samples of Other Effects: Enabled<br>"
                    "<br>"
                    "Please DISABLE it!",
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK')
                return

            # Check dome light backgrounds
            domes_to_fix = []
            rs_domes = pm.ls(type='RedshiftDomeLight')
            if rs_domes:
                for rs_dome in rs_domes:
                    if rs_dome.getAttr('background_enable') == 1 \
                       or rs_dome.getAttr('backPlateEnabled') == 1:
                        domes_to_fix.append(rs_dome.name())

            if domes_to_fix:
                message = 'Some DomeLights have <b>BackGround Render ' \
                          'Enabled</b>:' \
                          '<br><br>%s<br><br>' \
                          'Are you Sure?' % '<br>'.join(domes_to_fix)

                response = pm.confirmDialog(
                    title='Dome Lights with Background Enabled?',
                    message=message,
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No')
                if response == 'No':
                    return

            # abort on license fail
            dro.abortOnLicenseFail.set(1)

        elif render_engine == 'arnold':
            # check if the samples are too high
            dAO = pm.PyNode('defaultArnoldRenderOptions')

            aa_samples = dAO.AASamples.get()
            diff_samples = dAO.GIDiffuseSamples.get()
            try:
                glossy_samples = dAO.GIGlossySamples.get()
            except AttributeError:
                glossy_samples = dAO.GISpecularSamples.get()
            if int(pm.about(v=1)) >= 2017:
                sss_samples = dAO.GISssSamples.get()
            else:
                sss_samples = dAO.sssBssrdfSamples.get()

            total_diff_samples = aa_samples**2 * diff_samples**2
            total_glossy_samples = aa_samples**2 * glossy_samples**2
            total_sss_samples = aa_samples**2 * sss_samples**2

            max_allowed_diff_samples = 225
            max_allowed_glossy_samples = 100
            max_allowed_sss_samples = 800

            if total_diff_samples > max_allowed_diff_samples:
                pm.confirmDialog(
                    title="Too Much Diffuse Samples!!!",
                    message='You are using too much DIFFUSE SAMPLES (>%s)<br>'
                    '<br>'
                    'Please either reduce AA samples of Diffuse '
                    'Samples!!!' % max_allowed_diff_samples,
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK')
                return

            if total_glossy_samples > max_allowed_glossy_samples:
                pm.confirmDialog(
                    title="Too Much Glossy Samples!!!",
                    message='You are using too much GLOSSY SAMPLES (>%s)<br>'
                    '<br>'
                    'Please either reduce AA samples of Glossy '
                    'Samples!!!' % max_allowed_glossy_samples,
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK')
                return

            if total_sss_samples > max_allowed_sss_samples:
                pm.confirmDialog(
                    title="Too Much SSS Samples!!!",
                    message='You are using too much SSS SAMPLES (>%s)<br>'
                    '<br>'
                    'Please either reduce AA samples of SSS '
                    'Samples!!!' % max_allowed_sss_samples,
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK')
                return

            # check Light Samples
            # check point lights with zero radius but more than one samples
            all_point_lights = pm.ls(type='pointLight')
            ridiculous_point_lights = []
            for point_light in all_point_lights:
                if point_light.aiRadius.get(
                ) < 0.1 and point_light.aiSamples.get() > 1:
                    ridiculous_point_lights.append(point_light)

            if ridiculous_point_lights:
                pm.confirmDialog(
                    title="Unnecessary Samples on Point Lights!!!",
                    message='You are using too much SAMPLES (>1)<br>'
                    '<br>'
                    'on <b>Point lights with zero radius</b><br>'
                    '<br>'
                    'Please reduce the samples to 1',
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK')
                return

            # Check area lights with more than 2 samples
            all_area_lights = pm.ls(type=['areaLight', 'aiAreaLight'])
            ridiculous_area_lights = []
            for area_light in all_area_lights:
                if area_light.aiSamples.get() > 2:
                    ridiculous_area_lights.append(area_light)

            if ridiculous_area_lights:
                pm.confirmDialog(
                    title="Unnecessary Samples on Area Lights!!!",
                    message='You are using too much SAMPLES (>2) on<br>'
                    '<br>'
                    '<b>Area Lights</b><br>'
                    '<br>'
                    'Please reduce the samples to 2',
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK')
                return

            # Check directional lights with angle == 0 and samples > 1
            all_directional_lights = pm.ls(type='directionalLight')
            ridiculous_directional_lights = []
            dir_sample_attr_name = 'aiSamples'
            # if pm.about(v=1) == "2014":
            #     dir_sample_attr_name = 'aiSamples'

            for directional_light in all_directional_lights:
                if directional_light.aiAngle.get(
                ) == 0 and directional_light.attr(
                        dir_sample_attr_name).get() > 1:
                    ridiculous_directional_lights.append(directional_light)

            if ridiculous_directional_lights:
                pm.confirmDialog(
                    title="Unnecessary Samples on Directional Lights!!!",
                    message='You are using too much SAMPLES (>1) on <br>'
                    '<br>'
                    '<b>Directional lights with zero angle</b><br>'
                    '<br>'
                    'Please reduce the samples to 1',
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK')
                return

        # get values
        start_frame = pm.intField('cgru_afanasy__start_frame', q=1, v=1)
        end_frame = pm.intField('cgru_afanasy__end_frame', q=1, v=1)
        frames_per_task = \
            pm.intField('cgru_afanasy__frames_per_task', q=1, v=1)
        by_frame = pm.intField('cgru_afanasy__by_frame', q=1, v=1)
        hosts_mask = pm.textField('cgru_afanasy__hosts_mask', q=1, text=True)
        hosts_exclude = pm.textField('cgru_afanasy__hosts_exclude',
                                     q=1,
                                     text=True)
        separate_layers = \
            pm.radioButtonGrp('cgru_afanasy__separate_layers', q=1, sl=1)
        pause = pm.checkBox('cgru_afanasy__paused', q=1, v=1)
        life_time = pm.intField('cgru_afanasy__life_time', q=1, v=1)
        annotation = pm.textField('cgru_afanasy__annotation', q=1, text=True)
        submit_multiple_times = pm.intField(
            'cgru_afanasy__submit_multiple_times', q=1, v=1)
        errors_avoid_host = pm.intField('cgru_afanasy__errors_avoid_host',
                                        q=1,
                                        v=1)
        errors_retries = pm.intField('cgru_afanasy__errors_retries', q=1, v=1)
        errors_task_same_host = pm.intField(
            'cgru_afanasy__errors_task_same_host', q=1, v=1)
        errors_forgive_time = pm.intField('cgru_afanasy__errors_forgive_time',
                                          q=1,
                                          v=1)

        # check values
        if start_frame > end_frame:
            temp = end_frame
            end_frame = start_frame
            start_frame = temp

        frames_per_task = max(1, frames_per_task)
        by_frame = max(1, by_frame)

        # store without quota sign
        hosts_mask = hosts_mask.replace('"', '')
        hosts_exclude = hosts_exclude.replace('"', '')

        # store field values
        pm.optionVar['cgru_afanasy__start_frame_ov'] = start_frame
        pm.optionVar['cgru_afanasy__end_frame_ov'] = end_frame
        pm.optionVar['cgru_afanasy__frames_per_task_ov'] = frames_per_task
        pm.optionVar['cgru_afanasy__by_frame_ov'] = by_frame
        pm.optionVar['cgru_afanasy__hosts_mask_ov'] = hosts_mask
        pm.optionVar['cgru_afanasy__hosts_exclude_ov'] = hosts_exclude
        pm.optionVar['cgru_afanasy__separate_layers_ov'] = separate_layers
        pm.optionVar['cgru_afanasy__life_time_ov'] = life_time
        pm.optionVar['cgru_afanasy__annotation_ov'] = annotation

        pm.optionVar[
            'cgru_afanasy__submit_multiple_times_ov'] = submit_multiple_times
        pm.optionVar['cgru_afanasy__errors_avoid_host_ov'] = errors_avoid_host
        pm.optionVar['cgru_afanasy__errors_retries_ov'] = errors_retries
        pm.optionVar[
            'cgru_afanasy__errors_task_same_host_ov'] = errors_task_same_host
        pm.optionVar[
            'cgru_afanasy__errors_errors_forgive_time_ov'] = errors_forgive_time

        # get paths
        scene_name = pm.sceneName()
        datetime = '%s%s' % (time.strftime('%y%m%d-%H%M%S-'),
                             str(time.time() - int(time.time()))[2:5])

        filename = '%s.%s.mb' % (scene_name, datetime)

        project_path = pm.workspace(q=1, rootDirectory=1)

        # outputs = \
        #     pm.renderSettings(fullPath=1, firstImageName=1, lastImageName=1)

        # get output paths, set the RenderPass token to Beauty,
        # this will at least guarantee to get something
        outputs = \
            pm.renderSettings(
                fullPath=1, firstImageName=1, lastImageName=1,
                leaveUnmatchedTokens=1, customTokenString="RenderPass=Beauty"
            )

        # job_name = os.path.basename(scene_name)
        job_name = self.generate_job_name()

        logger.debug('%ss %se %sr' % (start_frame, end_frame, by_frame))
        logger.debug('scene                 = %s' % scene_name)
        logger.debug('file                  = %s' % filename)
        logger.debug('job_name              = %s' % job_name)
        logger.debug('project_path          = %s' % project_path)
        logger.debug('outputs               = %s' % outputs)
        logger.debug('annotation            = %s' % annotation)
        logger.debug('separate_layers       = %s' % separate_layers)
        logger.debug('errors_avoid_host     = %s' % errors_avoid_host)
        logger.debug('errors_retries        = %s' % errors_retries)
        logger.debug('errors_task_same_host = %s' % errors_task_same_host)
        logger.debug('errors_forgive_time   = %s' % errors_forgive_time)

        if pm.checkBox('cgru_afanasy__close', q=1, v=1):
            pm.deleteUI(self.window)

        stored_log_level = None
        if render_engine == 'arnold':
            # set the verbosity level to warning+info
            aro = pm.PyNode('defaultArnoldRenderOptions')
            stored_log_level = aro.getAttr('log_verbosity')
            aro.setAttr('log_verbosity', 2)
            # set output to console
            aro.setAttr("log_to_console", 1)
        elif render_engine == 'redshift':
            # set the verbosity level to detailed+info
            redshift = pm.PyNode('redshiftOptions')
            stored_log_level = redshift.logLevel.get()
            redshift.logLevel.set(2)

        # save file
        pm.saveAs(filename, force=1, type='mayaBinary')

        # rename back to original name
        pm.renameFile(scene_name)

        # create the render command
        mrc = MayaRenderCommandBuilder(name=job_name,
                                       file_full_path=filename,
                                       render_engine=render_engine,
                                       project=project_path,
                                       by_frame=by_frame)

        # submit renders
        jobs = []
        blocks = []

        #
        # separate_layers:
        # 1 -> None  -> submit one job with a single block with all layers
        # 2 -> Block -> submit one job with multiple blocks
        # 3 -> Job   -> submit multiple jobs with a single block per layer
        #
        if separate_layers in [1, 2]:
            job = af.Job(job_name)
            jobs.append(job)

        if separate_layers in [2, 3]:
            # render each layer separately
            rlm = pm.PyNode('renderLayerManager')
            layers = [
                layer for layer in rlm.connections() if layer.renderable.get()
            ]

            for layer in layers:
                mrc_layer = copy.copy(mrc)
                layer_name = layer.name()
                mrc_layer.name = layer_name
                mrc_layer.render_layer = layer_name

                # create a new block for this layer
                block = af.Block(
                    layer_name,
                    renderer_to_block_type.get(render_engine, 'maya'))

                # Fix the output path for this layer
                # by replacing the "masterLayer" with the layer name
                # without rs_ at the beginning
                layer_outputs = outputs
                if layer_name != 'defaultRenderLayer':
                    layer_outputs[0] = outputs[0].replace(
                        'masterLayer', layer_name.replace('rs_', ''))
                    layer_outputs[1] = outputs[1].replace(
                        'masterLayer', layer_name.replace('rs_', ''))

                outputs_split = afcommon.patternFromDigits(
                    afcommon.patternFromStdC(
                        afcommon.patternFromPaths(
                            layer_outputs[0], layer_outputs[1]))).split(';')

                block.setFiles(outputs_split)

                block.setNumeric(start_frame, end_frame, frames_per_task,
                                 by_frame)
                command = mrc_layer.build_command()

                block.setErrorsAvoidHost(errors_avoid_host)
                block.setErrorsRetries(errors_retries)
                block.setErrorsTaskSameHost(errors_task_same_host)
                block.setErrorsForgiveTime(errors_forgive_time)

                block.setCommand(command)

                if separate_layers == 2:
                    blocks.append(block)
                else:
                    job = af.Job('%s - %s' % (job_name, layer_name))
                    # add blocks
                    job.blocks = [block]
                    jobs.append(job)

        else:
            # create only one block
            block = af.Block('All Layers',
                             renderer_to_block_type.get(render_engine, 'maya'))

            block.setFiles(
                afcommon.patternFromDigits(
                    afcommon.patternFromStdC(
                        afcommon.patternFromPaths(outputs[0],
                                                  outputs[1]))).split(';'))
            block.setNumeric(start_frame, end_frame, frames_per_task, by_frame)
            command = mrc.build_command()
            block.setCommand(command)

            blocks.append(block)

        for job in jobs:
            job.setAnnotation(annotation)
            job.setFolder('input', os.path.dirname(filename))
            job.setFolder('output', os.path.dirname(outputs[0]))
            job.setHostsMask(hosts_mask)
            job.setHostsMaskExclude(hosts_exclude)
            if life_time > 0:
                job.setTimeLife(life_time * 3600)
            else:
                job.setTimeLife(240 * 3600)

            job.setCmdPost('deletefiles -s "%s"' % os.path.abspath(filename))
            if pause:
                job.offline()

            # add blocks
            if separate_layers in [1, 2]:
                job.blocks.extend(blocks)

            for i in range(submit_multiple_times):
                orig_job_name = job.data['name']
                job.setName('%s - %03i' % (orig_job_name, i + 1))
                status, data = job.send()

                # restore job name
                job.setName(orig_job_name)
                if not status:
                    pm.PopupError('Something went wrong!')

        # restore log level
        if render_engine == 'arnold':
            aro = pm.PyNode('defaultArnoldRenderOptions')
            aro.setAttr('log_verbosity', stored_log_level)
            # disable set output to console
            aro.setAttr("log_to_console", 0)
        elif render_engine == 'redshift':
            redshift = pm.PyNode('redshiftOptions')
            redshift.logLevel.set(stored_log_level)

            # disable abort on license fail
            redshift.abortOnLicenseFail.set(0)
Ejemplo n.º 35
0
def send_current_file(
        scene=True,
        suffix='_vn',
        lastest=True,
        render=False,
        tex=True,
        extras=['psd', 'uv', 'zbr', 'pattern'],
        version=1,
        verbose=True):
    src = pm.sceneName()
    scene_src = src.dirname()
    path_root = ''
    status = []
    todayFolder = pm.date(f='YYMMDD')
    if version>1:
        todayFolder = "{}_{:02d}".format(todayFolder,int(version))
    status.append('Send File to {}'.format(todayFolder))
    scene_dest = pm.util.path(scene_src.replace('Works','to/{}/Works'.format(todayFolder))).truepath()
    files = scene_src.files('*.mb')
    files.extend(scene_src.files('*.ma'))
    #print files
    files.sort(key=lambda f:f.getmtime())
    lastestfile = files[-1]
    try:
        status.append('Scene Sending status:')
        if lastest:
            src = lastestfile
            status.append('send latest file')
        dest = scene_dest.__div__(src.basename().replace(src.ext,'{}{}'.format(suffix, src.ext)))
        if scene:
            check_dir(dest)
            pm.sysFile(src, copy=dest)
            status.append("%s copy to %s" % (src,dest))
        if render:
            render_str = ['rend','Render','render','Rend']
            rend_src = []
            print src.dirname().dirs()
            for test_str in render_str:
                for dir in src.dirname().dirs():
                    if test_str in dir.basename():
                        print dir.basename()
                        rend_src = dir
                        break
                break
            if rend_src:
                rend_dest = dest.dirname().__div__(test_str)
                status.append(sys_cop(rend_src, rend_dest))
    except (IOError, OSError, shutil.Error) as why:
        msg = "Scene Copy Error\n{}".format(','.join(why))
        status.append(msg)
    if tex or extras:
        if all([src.dirname().dirname().dirname().basename() != d for d in ['CH','BG','CP']]) and \
                src.dirname().dirname().basename()!='CP':
            scene_src = scene_src.dirname()
            scene_dest = scene_dest.dirname()
            print scene_src
        tex_src = pm.util.path(scene_src.replace('scenes','sourceimages')).truepath()
        tex_files = tex_src.files('*.jpg')
        tex_extra = {}
        for extra in extras:
            tex_extra[extra] = tex_src.__div__(extra)
        tex_dest = pm.util.path(scene_dest.replace('scenes','sourceimages'))
        status.append('Texture Sending status:')
        try:
            if tex:
                for tex_file in tex_files:
                    src = tex_file
                    dest = tex_dest.__div__(tex_file.basename())
                    check_dir(dest)
                    pm.sysFile(src, copy=dest)
                    status.append("%s copy to %s" % (src,dest))
            if extras:
                for name, path in tex_extra.items():
                    status.append('%s Sending status:'%name)
                    dest = tex_dest.__div__(name)
                    status.append(sys_cop(path,dest))
        except (IOError, OSError, shutil.Error) as why:
            msg = "Tex Copy Error:\n{}".format(','.join(why))
            status.append(msg)
    pm.informBox(title='Send File Status', message = '\n'.join(status))
Ejemplo n.º 36
0
    def _upload_review(self):
        ### permission to upload review
        sg = shotgun_api3.Shotgun(
            'https://jibjab.shotgunstudio.com', 'versionUpdate',
            '738afb3552cce7dc5bf998996dd98d2b5e8f7cc0a4ea5db58f39415d3a98970b')

        ### define workspace and the project and all information to upload

        # maya scene name

        sceneName = pm.sceneName()
        tk = sgtk.sgtk_from_path(sceneName)

        # get entity information
        _context = tk.context_from_path(sceneName)

        # task
        filters = [[
            'project', 'is', {
                'type': _context.project['type'],
                'id': _context.project['id']
            }
        ],
                   [
                       'entity', 'is', {
                           'type': _context.entity['type'],
                           'id': _context.entity['id']
                       }
                   ], ['step.Step.code', 'is', _context.step['name']]]

        _task = sg.find_one('Task', filters)

        # version code name
        _work_filename = os.path.split(sceneName)[1]
        _version_name = os.path.splitext(_work_filename)[0] + ".mov"

        # user
        _user = sgtk.util.get_current_user(tk)

        # comment
        comment = self._comment

        # path to frame
        _path_to_frames = None

        # playblast path
        _movie_file = str(os.path.normpath(self._file))

        ##### project #####
        args = {
            "project": _context.project,
            "user": _user,
            "description": comment,
            "sg_path_to_frames": _path_to_frames,
            "sg_path_to_movie": _movie_file,
            "code": _version_name,
            "sg_status_list": "rev",
            "entity": _context.entity,
            "sg_task": _task,
            "sg_first_frame": 0,
            "sg_work_file_location": sceneName
        }

        version = sg.find_one("Version", [["code", "is", args["code"]]])

        if version:
            result = sg.update('Version', version["id"], args)
        else:
            result = sg.create('Version', args)

        _upload = sg.upload("Version",
                            result["id"],
                            _movie_file,
                            field_name="sg_uploaded_movie")
Ejemplo n.º 37
0
def saveScene(**kwargs):

    sSceneType = ""

    sCurScnPath = pm.sceneName()
    if not sCurScnPath:
        sCurScnPath = "untitled"
        sSceneName = "untitled scene"
        sSceneTypeList = ['mayaAscii', 'mayaBinary']
    else:
        sSceneName = sCurScnPath
        sExt = osp.splitext(sCurScnPath)[1].lower()

        sSceneTypeList = []
        if sExt:
            if sExt == ".ma":
                sSceneTypeList = ['mayaAscii']
            elif sExt == ".mb":
                sSceneTypeList = ['mayaBinary']

        if not sSceneTypeList:
            raise ValueError("Invalid maya scene extension: '{}'".format(sExt))
            #sSceneTypeList = mc.file(q=True, type=True)

        if len(sSceneTypeList) > 1:
            raise RuntimeError, 'Saving "{0}" : More than one type matches this file : {1}'\
                                .format(sCurScnPath, sSceneTypeList)
        else:
            sSceneType = sSceneTypeList[0]

    sWantedSceneType = kwargs.get('fileType', kwargs.get('ft', ''))

    if sWantedSceneType and (sWantedSceneType != sSceneType):

        if sWantedSceneType not in ('mayaAscii', 'mayaBinary'):
            raise ValueError(
                'Invalid file type: "{0}"'.format(sWantedSceneType))

        sSceneType = sWantedSceneType
    else:
        if not mc.file(q=True, modified=True):
            pm.displayWarning(
                "Current scene has NO changes to save: '{}'.".format(
                    sSceneName))
            return sCurScnPath

    bPrompt = kwargs.get("prompt", True)
    if bPrompt:
        if kwargs.get("discard", True):
            buttonList = ("Save", "Don't Save", "Cancel")
            sDismiss = "Don't Save"
            sConfirmEnd = "?"
        else:
            buttonList = ("Save", "Cancel")
            sDismiss = "Cancel"
            sConfirmEnd = "!"

        sMsg = 'Save changes to :\n\n{0} {1}'.format(sSceneName, sConfirmEnd)
        sConfirm = pm.confirmDialog(
            title="DO YOU WANT TO...",
            message=sMsg,
            button=buttonList,
            defaultButton="Cancel",
            cancelButton="Cancel",
            dismissString=sDismiss,
            icon="question",
        )
    else:
        sConfirm = "Save"

    if sConfirm == "Cancel":
        logMsg("Cancelled !", warning=True)
        return ""

    elif sConfirm == "Don't Save":
        return sCurScnPath

    elif sConfirm == "Save":

        bNoFileCheck = kwargs.pop("noFileCheck", True)

        if (not sCurScnPath) or sCurScnPath == "untitled":

            sFileList = chooseMayaScene(ff=sSceneTypeList)
            if not sFileList:
                return ""

            if bNoFileCheck:
                pmu.putEnv("DAVOS_FILE_CHECK", "")

            return pm.saveAs(sFileList[0], force=True)

        else:
            if bNoFileCheck:
                pmu.putEnv("DAVOS_FILE_CHECK", "")

            if kwargs.get("checkError", True):
                try:
                    assertCurrentSceneReadWithoutDataLoss()
                except AssertionError:
                    return ""

            if sSceneType:
                return pm.saveFile(force=True, type=sSceneType)
            else:
                return pm.saveFile(force=True)
Ejemplo n.º 38
0
def ishiiCheckFunc(*mayaFalse):

    fileIndex = open(
        '//p.sv/Prism/project/SER/user/chew/ref/ishiiCheck_index.ref', 'rb')
    indexDump = fileIndex.read().decode("UTF-8")
    charaNameIndex = {}
    for i in indexDump.split('\n'):  #assigning character names to index
        charaNameIndex[i[:3]] = i.split('_')[1].rstrip('\r')
    fileIndex.close()

    todaydate = datetime.datetime.now().strftime("%y%m%d")
    fileName = pm.sceneName().split('/')[-1].rstrip(
        '.ma'
    )  #cmds.file(q = True, sceneName = True, shortName = True).rstrip('.mb').rstrip('.ma')
    saveName = fileName[1:3] + '_' + charaNameIndex[fileName[:3]]

    savePath = u"//p.sv/Prism/project/SER/check/motion/%s/インゲーム/%s" % (
        todaydate, saveName)
    specialSavePath = u"//p.sv/Prism/project/SER/check/motion/%s/必殺技/" % (
        todaydate)

    if 'Idle' in fileName:
        if not os.path.exists(savePath):
            print(u'パスは存在していないので、作ります')
            os.makedirs(savePath)
        print fileName[:11]
        pm.playblast(
            format='qt',
            filename=u"//p.sv/Prism/project/SER/check/motion/%s/インゲーム/%s/%s.mov"
            % (todaydate, saveName, fileName[:11]),
            forceOverwrite=True,
            clearCache=True,
            viewer=False,
            showOrnaments=True,
            fp=4,
            percent=100,
            compression="H.264",
            quality=50,
            startTime=animAPI.MAnimControl.minTime().value(),
            endTime=animAPI.MAnimControl.maxTime().value(),
            widthHeight=[960, 540])
        #cmds.file(r"//p.sv/Prism/project/SER/check/motion/%s/%s/%s" %(todaydate, saveName, fileName[:11]), force = True, options = 'v=0;', type = 'FBX export', pr = True, ea = True)
        mel.eval(
            u'FBXExportBakeComplexAnimation -v 1;FBXExportBakeComplexAnimation -q; FBXExportEmbeddedTextures -v true; FBXExportEmbeddedTextures -q;'
        )
        mel.eval(
            u'FBXExport -f "//p.sv/Prism/project/SER/check/motion/%s/インゲーム/%s/%s";'
            % (todaydate, saveName, fileName[:11]))
    elif 'Attack' in fileName:
        if not os.path.exists(savePath):
            print(u'パスは存在していないので、作ります')
            os.makedirs(savePath)
        print fileName[:13]
        pm.playblast(
            format='qt',
            filename=u"//p.sv/Prism/project/SER/check/motion/%s/インゲーム/%s/%s.mov"
            % (todaydate, saveName, fileName[:13]),
            forceOverwrite=True,
            clearCache=True,
            viewer=False,
            showOrnaments=True,
            fp=4,
            percent=100,
            compression="H.264",
            quality=50,
            startTime=animAPI.MAnimControl.minTime().value(),
            endTime=animAPI.MAnimControl.maxTime().value(),
            widthHeight=[960, 540])
        #cmds.file(r"//p.sv/Prism/project/SER/check/motion/%s/%s/%s" %(todaydate, saveName, fileName[:13]), force = True, options = 'v=0;', type = 'FBX export', pr = True, ea = True)
        mel.eval(
            u'FBXExportBakeComplexAnimation -v 1;FBXExportBakeComplexAnimation -q; FBXExportEmbeddedTextures -v true; FBXExportEmbeddedTextures -q;'
        )
        mel.eval(
            u'FBXExport -f "//p.sv/Prism/project/SER/check/motion/%s/インゲーム/%s/%s";'
            % (todaydate, saveName, fileName[:13]))
    elif 'Special' in fileName:
        print fileName[:16]
        pm.playblast(
            format='qt',
            filename=u"//p.sv/Prism/project/SER/check/motion/%s/必殺技/%s_%s.mov"
            % (todaydate, fileName[:16], todaydate[2:]),
            forceOverwrite=True,
            clearCache=True,
            viewer=False,
            showOrnaments=True,
            fp=4,
            percent=100,
            compression="H.264",
            quality=50,
            startTime=animAPI.MAnimControl.minTime().value(),
            endTime=animAPI.MAnimControl.maxTime().value(),
            widthHeight=[960, 540])
Ejemplo n.º 39
0
 def __init__(self, fujiArg, parent=None):
     super(MainWindow, self).__init__(parent)
     self.setupUi(self)
     self.fuji = fujiArg #creating an exception for Fujihara-san for his path
     
     self.setParent(mayaMainWindow)#parent to maya
     self.setWindowFlags(Qt.Window)#parent to maya
     
     self.fileName = cmds.file(q = True, sceneName = True, shortName = True).rstrip('.mb').rstrip('.ma')
     self.fileNameSplit = self.fileName.rstrip('.ma').split('_')
     
     #radio buttons
     self.ingameExport = self.ingameButton1 #ingame
     self.camExport = self.ingameButton2 #camera
     #self.cutsceneExport = self.ingameButton3 #cutscene motion DELETE LATER
     
     
     if self.fileNameSplit[0] == 'SER': #charaModel
         self.fileType = 'charaModel'
         self.charaNumber = self.fileNameSplit[1]
         self.weaponNumber = None
         #print('charaModel') #for debugging purposes
     elif len(self.fileNameSplit[0]) == 2 and self.fileNameSplit[1] == 'Resonize':
         self.fileType = 'kyojinCommonStep'
         self.charaNumber = None
         self.weaponNumber = self.fileNameSplit[0]
     elif self.fileNameSplit[0] == 'CutScene' and self.fileNameSplit[1] == 'Chain':
         self.fileType = 'chain'
         self.charaNumber = '0'
         self.weaponNumber = '0'
     elif len(self.fileNameSplit[0]) == 2 and self.fileNameSplit[1] == 'CutScene' and self.fileNameSplit[2] == 'Chain':
         self.fileType = 'chain'
         self.charaNumber = '0'
         self.weaponNumber = self.fileNameSplit[0]
     elif len(self.fileNameSplit[0]) == 2 and self.fileNameSplit[1] != 'Resonize' and self.fileNameSplit[1] != 'CutScene' :
         self.fileType = 'commonMotion'
         self.charaNumber = None
         self.weaponNumber = self.fileNameSplit[0]
         #print('commonMotion') #for debugging purposes
     elif len(self.fileNameSplit[0]) == 3 and self.fileNameSplit[1] == '00':
         self.fileType = 'kyojinStep'
         self.charaNumber = self.fileNameSplit[0]
         self.weaponNumber = self.fileNameSplit[1]
     elif len(self.fileNameSplit[0]) == 3 and self.fileNameSplit[0] != 'SER' and self.fileNameSplit[0] != 'Gun' and self.fileNameSplit[0] != 'Bow':
         if len(self.fileNameSplit[1]) == 4:
             self.fileType = 'cutScene'
             self.charaNumber = self.fileNameSplit[0]
             self.weaponNumber = self.fileNameSplit[1][:2]
         else:
             self.fileType = 'charaMotion'
             self.charaNumber = self.fileNameSplit[0]
             #print('charaMotion') #for debugging purposes
             if self.fileNameSplit[1][:8] == 'Resonize':
                 self.fileType = 'kyojinMotion'
                 self.weaponNumber = 're'
             else:
                 self.weaponNumber = self.fileNameSplit[1]
         if self.fileNameSplit[1][:13] == 'ResonizeIntro':
             self.fileType = 'kyojinIntro'
             self.weaponNumber = 'rIntro'
             
     elif self.fileNameSplit[0] == 'CutScene' and self.fileNameSplit[1] == 'ResonizeStep':
         self.fileType = 'kyojinCommonStep'
         self.charaNumber = None
         self.weaponNumber = self.fileNameSplit[0]
     
     elif self.fileNameSplit[0] == 'CutScene' and self.fileNameSplit[1] == 'ResonizeFinish':
         self.fileType = 'kyojinCommonFinish'
         self.charaNumber = None
         self.weaponNumber = self.fileNameSplit[0]
     
     else:#in this case, file is assumed to be a weapon
         self.fileType = 'weaponModel'
         self.charaNumber = None
         self.weaponNumber = 'WP'#pm.sceneName().rstrip('.mb').rstrip('.ma').split('/')[-3].split('_')[1]
     
     
     self.currentAddress = cmds.file(q = True, location = True).rstrip(self.fileName)
     
     
     #loading character names and weapon index
     fileIndex = open('//p.sv/Prism/project/SER/user/chew/ref/charaIndex.ref', 'rb')
     indexDump = fileIndex.read().decode("UTF-8")
     self.charaNameIndex = {}
     self.charaWeaponIndex = {}
     for i in indexDump.split('\n'):#assigning character names to index
         self.charaNameIndex[i[:3]] = i.split('_')[1].rstrip('\r')
     for i in indexDump.split('\n'):#assigning weapon to index
         self.charaWeaponIndex[i[:3]] = i.split('_')[2].rstrip('\r')
     fileIndex.close()
     #loading weapon names and index
     fileIndex = open('//p.sv/Prism/project/SER/user/chew/ref/weaponIndex.ref', 'r')
     indexDump = fileIndex.read()
     self.weaponIndex = {}
     for i in indexDump.split('\n'):
         self.weaponIndex[i[:2]] = i.rstrip('\r')
     fileIndex.close()
     #loading weapon paths
     if self.fileType == 'commonMotion': #this weapon path is only needed if the file is a common motion
         pathRead = open('//p.sv/Prism/project/SER/user/chew/ref/weaponPath.ref', 'rb')
         pathDump = pathRead.read().decode('UTF-8')
         self.weaponPathIndex = {}
         for i in pathDump.split('\n'):
             self.weaponPathIndex[i.split()[0]] = i.split()[1]
         self.commonMotionExportPath = self.weaponPathIndex[self.fileName[:2]] #assigning weapon export path as export path
         pathRead.close()
     
     #declaring output paths
     if self.fuji == 0:
         self.boneFBX = 'D:/SER/SVN/Unity/motion/fbx_yard/Assets/Models_Characters'
     if self.fuji == 1:
         self.boneFBX = 'D:/SER/SER_SVN/Unity/motion/fbx_yard/Assets/Models_Characters'
     self.polyFBX = '//p.sv/Prism/project/SER/check/motion'
     self.maFiles = 'D:/SER/SVN/MAYA/motion/maya'
     
     
     #defining chara name and weapon name with chara number and weapon number
     if self.fileType == 'charaMotion':
         self.charaNameText = self.charaNameIndex[self.charaNumber]  #charaMotion
         self.weaponNameText = self.weaponIndex[self.weaponNumber]
     elif self.fileType == 'kyojinMotion':
         self.charaNameText = self.charaNameIndex[self.charaNumber]  #kyojinMotion
         self.weaponNameText = self.weaponIndex[self.weaponNumber].lstrip('re_')
     elif self.fileType == 'charaModel':
         self.charaNameText = self.charaNameIndex[self.charaNumber]  #charaModel
         self.weaponNameText = None
         if self.fileNameSplit[2] == 'n':
             self.kyojinka = '_001_'
         elif len(self.fileNameSplit[2]) != 1:
             self.kyojinka = '_0' + self.fileNameSplit[2][1:] + '_'
         else:
             self.kyojinka = '_000_'
     elif self.fileType == 'commonMotion':
         self.charaNameText = u'武器共通モーション'                   #commonMotion
         self.weaponNameText = self.weaponIndex[self.weaponNumber]   #commonMotion
     elif self.fileType == 'cutScene':
         self.charaNameText = self.charaNameIndex[self.charaNumber]                   #cutScene
         self.weaponNameText = u'必殺技'#cutScene
         self.helperShadowBox.setChecked(False) #setting the hissatsuwaza states
         self.HelperShadowExp.setChecked(True)
     elif self.fileType == 'chain':
         self.charaNameText = u'連携'
         self.weaponNameText = self.weaponIndex[self.weaponNumber] 
     elif self.fileType == 'kyojinIntro':
         self.charaNameText = self.charaNameIndex[self.charaNumber]  #kyojinIntro
         self.weaponNameText = 'Resonize Intro'
     elif self.fileType == 'kyojinStep':
         self.charaNameText = self.charaNameIndex[self.charaNumber] #kyojin character step
         self.weaponNameText = 'Resonize Step'
     elif self.fileType == 'kyojinCommonStep':
         self.charaNameText = u'キョウジン通常ステップ'                   #kyojin common step
         self.weaponNameText = 'Resonize Step'
     elif self.fileType == 'kyojinCommonFinish':
         self.charaNameText = u'キョウジン通常Finish'                   #kyojin common step
         self.weaponNameText = 'Resonize Finish'
     elif self.fileType == 'weaponModel':
         self.charaNameText = None
         self.weaponNameText = self.weaponIndex[self.weaponNumber]  #weaponModel
     
     if self.fileType == 'charaMotion' and self.fileNameSplit[2] != 'Special' or self.fileType == 'commonMotion':
         self.ingame = True
     
     else:
         self.ingame = False
     
     '''
     #defining weapon name
     if self.fileType == 'charaMotion':
         self.weaponNameText
     
     if self.fileType == 'commonMotion':
         self.weaponNameText = self.weaponIndex[self.fileName.split('_')[0]]
     else:
         try:
             self.weaponNameText = self.weaponIndex[self.fileName.split('_')[1]]
         except:
             pass
     '''
     
     #defining export path
     if self.fileType == 'charaMotion':
         self.exportPathText = self.boneFBX + '/' + self.charaNumber + '/Motions/' + self.weaponIndex[self.weaponNumber]
     elif self.fileType == 'kyojinMotion':
         self.exportPathText = self.boneFBX + '/' + self.charaNumber + '/Motions/' + self.weaponIndex[self.weaponNumber].lstrip('re_')
     elif self.fileType == 'commonMotion': #weapon common motion
         self.exportPathText = self.weaponPathIndex[self.weaponNumber]
         if self.fuji == 1:
             self.exportPathText = 'D:/SER/SER_SVN' + self.weaponPathIndex[self.weaponNumber][10:]
         if self.fileNameSplit[1][:8] == 'Resonize':
             self.exportPathText = r'D:/SER/SVN/Unity/motion/fbx_yard/Assets/Models_Characters/_Animations/00_Common'
     elif self.fileType == 'charaModel':
         self.exportPathText = 'D:/SER/SVN/MAYA/model/' + 'SER_0' + self.charaNumber[1:] + '_' + self.fileNameSplit[2] + '/FBX'
     elif self.fileType == 'cutScene':
         self.exportPathText = self.boneFBX + '/' + self.charaNumber + '/Motions/' + self.weaponIndex[self.weaponNumber]
     elif self.fileType == 'chain':
         if self.fuji == 1:
             self.exportPathText = r'D:/SER/SER_SVN/Unity/motion/fbx_yard/Assets/Models_Characters/_Animations/' + self.weaponIndex[self.weaponNumber]
             if self.weaponNumber == '00':
                 self.exportPathText = r'D:/SER/SER_SVN/Unity/motion/fbx_yard/Assets/Models_Characters/_Animations/00_Common'
         else:
             self.exportPathText = r'D:/SER/SVN/Unity/motion/fbx_yard/Assets/Models_Characters/_Animations/' + self.weaponIndex[self.weaponNumber]
             if self.weaponNumber == '00':
                 self.exportPathText = r'D:/SER/SER_SVN/Unity/motion/fbx_yard/Assets/Models_Characters/_Animations/00_Common'
     elif self.fileType == 'kyojinIntro':
         self.exportPathText = r'D:/SER/SVN/Unity/motion/fbx_yard/Assets/Models_Characters/%s/Motions/Resonize' %self.fileNameSplit[0]
     elif self.fileType == 'kyojinCommonStep':
         self.exportPathText = r'D:/SER/SVN/Unity/motion/fbx_yard/Assets/Models_Characters/_Animations/00_Common'
     elif self.fileType == 'kyojinStep':
         self.exportPathText = self.boneFBX + '/' + self.charaNumber + '/Motions/' + self.weaponIndex[self.weaponNumber].lstrip('00_')
     elif self.fileType == 'kyojinCommonFinish':
         self.exportPathText = r'D:/SER/SVN/Unity/motion/fbx_yard/Assets/Models_Characters/_Animations/00_Common'
     elif self.fileType == 'weaponModel':
         self.exportPathText = 'D:/SER/SVN/MAYA/model/' + pm.sceneName().rstrip('.mb').rstrip('.ma').split('/')[-3] + '/FBX'
     '''
     INPUTS ########################################################################################################################################################
     '''
     #motion
     if self.fileType == 'charaMotion' or self.fileType == 'commonMotion' or self.fileType == 'kyojinMotion' or self.fileType == 'cutScene' or self.fileType == 'chain' or self.fileType == 'kyojinIntro' or self.fileType == 'kyojinCommonStep' or self.fileType == 'kyojinCommonFinish' or self.fileType == 'kyojinStep':
         self.charaName = self.charaNameInput
         self.charaName.setText(self.charaNameText)
         self.weaponName = self.weapNameInput
         self.weaponName.setText(self.weaponNameText)
         self.exportPath = self.exportPathInput
         self.exportPath.setText(self.exportPathText)
         self.exportName = self.motionInput
         self.exportName.setText(self.fileName)
         #print 'animTab' #for debugging purposes
         self.ExporterTab.setCurrentIndex(0)#setting animation(0) tab to be switched whenever the tool is loaded
     
     #model
     elif self.fileType == 'charaModel' or self.fileType == 'weaponModel':
         if self.fileType == 'charaModel':
             self.charaNameInput_2.setText(self.charaNameText) #same as motion
         else:
             self.charaNameInput_2.setText(self.weaponNameText.split('_')[1]) #same as motion
         self.exportPathInput_2.setText(self.exportPathText) #
         #print 'modelTab' #for debugging purposes
         self.ExporterTab.setCurrentIndex(1)#setting model(1) tab to be switched whenever the tool is loaded
         
     
     #export buttons
     self.animExportButton.clicked.connect(self.animExpButton)
     self.modelExportButton.clicked.connect(self.modelExport)
     
     
     
     #radio button change
     self.ingameExport.toggled.connect(self.ingameClicked)
     self.camExport.toggled.connect(self.camClicked)
     
     print(self.fileType, self.fileNameSplit[1])
Ejemplo n.º 40
0
    def publish(self):
        self.test_run()
        if False in self.global_result:
            QtGui.QMessageBox.warning(
                self, 'Warning',
                'Can not publish,\nfix the problems and try!...',
                QtGui.QMessageBox.Ok)
            logging.warning('Can not publish, fix the problems and try!...')
            return
        if not self.type:
            self.type = self.combobox_input.currentText()
        if self.type not in resource.getPublishTypes():
            QtGui.QMessageBox.warning(
                self, 'Warning',
                'Can not find publish type called <%s>!...' % self.type,
                QtGui.QMessageBox.Ok)
            logging.warning(
                'Can not find publish type called <%s>!...' % self.type, )
            return
        tag = str(self.combobox_tag.currentText())
        if not tag or tag == '':
            QtGui.QMessageBox.warning(self, 'Warning',
                                      'Can not find name (tag)!...',
                                      QtGui.QMessageBox.Ok)
            logging.warning('Can not find name (tag)!...')
            return

        crowd_publish = crowdPublish.Connect(type=self.type)
        crowd_publish.type = crowd_publish.getDependency()
        dependency_tags = crowd_publish.getTags()

        # to check find dependency publish
        if self.type != crowd_publish.type:
            if tag not in dependency_tags:
                replay = QtGui.QMessageBox.warning(
                    self, 'Warning',
                    'Not found dependency publish called type <%s> tag <%s>' %
                    (crowd_publish.type, tag), QtGui.QMessageBox.Ok)
                return

        crowd_publish.type = self.type
        result = True
        if crowd_publish.isExists(tag):
            replay = QtGui.QMessageBox.question(
                self, 'Question', 'Already exist <%s> in the data base!...%s' %
                (tag, '\nAre you sure to overwrite?...'),
                QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
            if replay == QtGui.QMessageBox.No:
                logging.warning('Abort!...')
                return False

        if not result:
            warnings.warn('Not able to replace exists publish <%s>' % tag,
                          Warning)
            return

        scene_name = str(core.sceneName())
        if not scene_name:
            QtGui.QMessageBox.warning(self, 'Warning',
                                      'Can not save your scene!...',
                                      QtGui.QMessageBox.Ok)
            logging.warning('Can not save your scene!...')
            return

        description = 'This data contain information about <%s> publish' % self.type
        self.comment.type = self.type
        self.comment.tag = tag
        self.comment.description = description
        self.comment.scene_name = scene_name
        self.comment.extract = self.global_extract
        self.comment.show()
        self.close()
Ejemplo n.º 41
0
Author: Ehsan HM ( [email protected] )

Script Name: ExportImportCache()

Version: 1.0

What does this do: exports and imports geometry caches of selected objects.


'''

import pymel.core as pm
import sys
import os

currentFilePath = pm.sceneName()
import pymel.core as pm
from functools import partial


class ImportCache():
    def __init__(self, *args, **kwargs):

        if args or kwargs:
            self.ImportCache(*args, **kwargs)
        else:
            self.UI()

    def UI(self):

        # create window
Ejemplo n.º 42
0
def publish_xml():
    dets = pft.PathDetails.parse_path(pm.sceneName())
    dets.name = 'layout'
    xmlfile = dets.getFullPath()
    xmlpub = dets.getPublishFullPath(ext='xml')
    pft.copyFile(xmlfile, xmlpub, force=True)
Ejemplo n.º 43
0
 def scene_path(self):
     return pm.sceneName()
Ejemplo n.º 44
0
    def _do_playblast(self):

        MODEL_EDITOR_PARAMS = {
            "activeView": True,
            "cameras": False,
            "controlVertices": False,
            "deformers": False,
            "dimensions": False,
            "displayAppearance": "smoothShaded",
            "displayLights": "default",
            "displayTextures": True,
            "dynamicConstraints": False,
            "fogging": False,
            "follicles": False,
            "grid": False,
            "handles": False,
            "headsUpDisplay": True,
            "hulls": False,
            "ignorePanZoom": False,
            "ikHandles": False,
            "imagePlane": True,
            "joints": False,
            "lights": False,
            "locators": False,
            "manipulators": False,
            "nurbsCurves": False,
            "nurbsSurfaces": True,
            "pivots": False,
            "planes": False,
            "selectionHiliteDisplay": False,
            "shadows": False,
            "sortTransparent": True,
            "strokes": True,
            "textures": True,
            "useDefaultMaterial": False,
            "wireframeOnShaded": False,
        }

        windowName = "review_blast"

        try:
            _current_panel = pm.getPanel(wf=True)
            if pm.modelEditor(_current_panel, q=True, fogging=True) == True:
                MODEL_EDITOR_PARAMS["fogging"] = True
        except:
            pass

        try:
            if pm.windowPref(windowName, exists=True):
                pm.windowPref(windowName, remove=True)
                pm.deleteUI(windowName)
        except:
            pass

        _window = pm.window(windowName,
                            titleBar=True,
                            iconify=True,
                            leftEdge=100,
                            topEdge=100,
                            width=800,
                            height=600,
                            sizeable=False)

        _layout = pm.formLayout()
        _editor = pm.modelEditor(**MODEL_EDITOR_PARAMS)

        pm.formLayout(_layout,
                      edit=True,
                      attachForm=((_editor, "left", 0), (_editor, "top", 0),
                                  (_editor, "right", 0), (_editor, "bottom",
                                                          0)))

        # Legacy viewport used
        try:
            mel.eval("setRendererInModelPanel ogsRenderer {};".format(_editor))
        except:
            cmds.confirmDialog(
                message=
                'You need to change your viewport as the legacy version',
                dismissString='No')

        # viewport 2.0 used
        # mel.eval( "setRendererInModelPanel \"vp2Renderer\" {};".format( _editor))

        pm.setFocus(_editor)
        pm.lookThru(_editor, self._shot_cam)

        cmds.refresh()

        _labelColor = cmds.displayColor('headsUpDisplayLabels',
                                        q=True,
                                        dormant=True)
        _labelValue = cmds.displayColor('headsUpDisplayValues',
                                        q=True,
                                        dormant=True)

        visibleHUDs = [
            f for f in pm.headsUpDisplay(listHeadsUpDisplays=True)
            if pm.headsUpDisplay(f, query=True, visible=True)
        ]
        map(lambda f: pm.headsUpDisplay(f, edit=True, visible=False),
            visibleHUDs)

        for h in pm.headsUpDisplay(listHeadsUpDisplays=True):
            if pm.headsUpDisplay(h, q=1, s=1) == 7:
                if pm.headsUpDisplay(h, q=1, b=1) == 5:
                    try:
                        pm.headsUpDisplay(h, rem=True)
                    except:
                        pass

        for h in pm.headsUpDisplay(listHeadsUpDisplays=True):
            if pm.headsUpDisplay(h, q=1, s=1) == 7:
                if pm.headsUpDisplay(h, q=1, b=1) == 6:
                    try:
                        pm.headsUpDisplay(h, rem=True)
                    except:
                        pass

        cmds.displayColor('headsUpDisplayValues', 17, dormant=True)
        cmds.displayColor('headsUpDisplayLabels', 16, dormant=True)

        def hudShot():
            _nameTemp = cmds.file(q=1, ns=1).split(".")[0]
            return _nameTemp.rsplit("_", 1)[0]

        def hudName():
            return getpass.getuser()

        pm.headsUpDisplay('HUDCurrentFrame',
                          edit=True,
                          visible=True,
                          labelFontSize="large",
                          dataFontSize="large",
                          section=5,
                          block=1)
        #cmds.headsUpDisplay('HUDA',s=7,b=6, blockAlignment='center', dataFontSize='large', command=hudShot)
        #cmds.headsUpDisplay('HUDB',s=7,b=5, blockAlignment='center', dataFontSize='large', label="Artist:", labelFontSize="large", command=hudName)

        pm.setFocus(_editor)

        #if pm.headsUpDisplay('HUDCurrentFrame', query=True, visible=False):
        #    print "works 111"
        #    pass
        #else:
        _mov_file = os.path.splitext(self._file)[0]
        # print _mov_file
        # __audios = pm.ls(type="audio")
        __audios = pm.ls(type="audio")

        if len(__audios) > 0:
            __audio = str(__audios[0])
        else:
            __audio = False

        # frame catching min, max, current
        _min_frame = pm.playbackOptions(q=1, min=1)
        _max_frame = pm.playbackOptions(q=1, max=1)
        _current_frame = pm.currentTime(q=1)
        pm.currentTime(_min_frame)

        ### playblast option ###
        # play_args = "playblast -format avfoundation -filename \"{}\" -sound \"{}\" -sequenceTime 0 -clearCache 1 -viewer 1 -forceOverwrite -showOrnaments 1 -offScreen -fp 4 -percent 100 -compression \"H.264\" -quality 70 -widthHeight {} {};".format( self._file, __audio, self.resolution_size[0], self.resolution_size[1])

        try:

            _temp_path, _temp_file = os.path.split(self._file)
            _temp_mov_path = _temp_path + "/.temp"

            _temp_file_01 = os.path.splitext(_temp_file)
            _temp_mov_file = _temp_file_01[0] + "_uncomp" + _temp_file_01[1]

            _full_temp_mov_file = os.path.join(_temp_mov_path, _temp_mov_file)

            print _full_temp_mov_file

            try:
                if not os.path.exists(_temp_mov_path):
                    os.makedirs(_temp_mov_path)

                if os.path.exists(_full_temp_mov_file):
                    os.remove(_full_temp_mov_file)
            except:
                raise

            ### making playblast
            play_args = "playblast -format qt -filename \"{}\" -sound \"{}\" -sequenceTime 0 -clearCache 1 -viewer 0 -showOrnaments 1 -compression \"H.264\" -offScreen -fp 4 -percent 100 -quality 100 -widthHeight {} {};".format(
                _full_temp_mov_file, __audio, self.resolution_size[0],
                self.resolution_size[1])
            mel.eval(play_args)
            pm.currentTime(_current_frame)

            sceneName = pm.sceneName()
            tk = sgtk.sgtk_from_path(sceneName)

            # get entity information
            _context = tk.context_from_path(sceneName)

            _date = datetime.date.today()
            _task = _context.step["name"]
            _shot_name = _context.entity["name"]
            _png_file = os.path.normpath(
                _temp_mov_path + "/" +
                _context.user["name"].translate(None, string.whitespace) +
                ".png")

            try:
                if not os.path.exists(_temp_mov_path):
                    os.makedirs(_temp_mov_path)

                if os.path.exists(_png_file):
                    os.remove(_png_file)
            except:
                raise

            ### write information on png file ###
            _copylight = "Copyright (C) {} JibJab Studios - All Rights Reserved".format(
                _date.year)
            _img = Image.new('RGBA', (1920, 1080), (0, 0, 0, 0))
            _slate_image = ImageDraw.Draw(_img)
            _type_shot_asset = ImageFont.truetype('/Library/Fonts/arial.ttf',
                                                  30)
            _type_copyright = ImageFont.truetype('/Library/Fonts/arial.ttf',
                                                 15)
            _type_task = ImageFont.truetype('/Library/Fonts/arial.ttf', 18)

            _slate_image.text((820, 1000),
                              _shot_name,
                              font=_type_shot_asset,
                              fill=(255, 255, 255, 128))
            _slate_image.text((780, 1060),
                              _copylight,
                              font=_type_copyright,
                              fill=(255, 255, 255, 128))
            _slate_image.text((910, 1035),
                              "Task : {}".format(_task),
                              font=_type_task,
                              fill=(255, 255, 255, 128))
            # _slate_image.text((1610, 1060), _review_file, font=_type_copyright, fill=(255,255,255,80))

            _img.save(_png_file, 'PNG')

            ### convert uncomppresed file to h.264
            #t = os.system("/Volumes/public/StoryBots/production/series/ask_the_storybots/03_shared_assets/01_cg/05_maya_tools/pipeline/module/ffmpeg/ffmpeg -y -i " + _full_temp_mov_file + " -vcodec libx264 -pix_fmt yuv420p -preset slower -crf 0 -vf eq=brightness=0.04 -g 1 -acodec copy " + self._file)
            t = os.system(
                "/Volumes/public/StoryBots/production/series/ask_the_storybots/03_shared_assets/01_cg/05_maya_tools/pipeline/module/ffmpeg/ffmpeg -y -i "
                + _full_temp_mov_file + " -i " + _png_file +
                " -vcodec libx264 -pix_fmt yuv420p -preset slow -crf 22 -filter_complex \"overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2\" -g 0 -acodec copy "
                + self._file)
            ######################################
            #### This is RV open with mov file ###
            ######################################

            _mov_path_RV, _mov_file_RV = os.path.split(self._file)
            os.chdir(_mov_path_RV)
            subprocess.Popen(self._RV_path + _mov_file_RV, shell=True)

            if os.path.exists(_full_temp_mov_file):
                os.remove(_full_temp_mov_file)

            if os.path.exists(_png_file):
                os.remove(_png_file)

        except:
            pm.confirmDialog(
                title="Playblast Error",
                message=
                "Close your RV or deselect the file.\nYour file is being used from other application",
                defaultButton="Yes")
            raise

        # playblast  -format avfoundation -sound "ATS_301_sq020_020" -sequenceTime 0 -clearCache 1 -viewer 1 -showOrnaments 0 -offScreen  -fp 4 -percent 80 -compression "H.264" -quality 70 -widthHeight 1920 1080;
        #pm.showWindow( _window )
        pm.headsUpDisplay('HUDCurrentFrame',
                          edit=True,
                          visible=False,
                          section=5,
                          block=1)
        # cmds.headsUpDisplay( 'HUDA', rem=True )
        # cmds.headsUpDisplay( 'HUDB', rem=True )
        # delete playblast window
        pm.deleteUI(_window)
        # revive HOD modes

        cmds.displayColor('headsUpDisplayValues', _labelColor, dormant=True)
        cmds.displayColor('headsUpDisplayLabels', _labelValue, dormant=True)
        map(lambda f: pm.headsUpDisplay(f, edit=True, visible=True),
            visibleHUDs)
Ejemplo n.º 45
0
def arnoldlogname():
    import pymel.core as pym
    import os
    current = pym.nodetypes.RenderLayer.currentLayer().name()
    scene = os.path.splitext(os.path.basename(pym.sceneName()))[0]
    aiARO = pym.PyNode("defaultArnoldRenderOptions")
    logfile = aiARO.log_filename.get()
    print "DEBUG: arnoldlog:", current, logfile
    newlogfile = os.path.join(os.path.dirname(logfile),
                              "{0}_{1}.log".format(scene, current))
    aiARO.log_filename.set(newlogfile)
    print "DEBUG: newlog:", newlogfile


pym.ls("::*Arnold*")
aiARO = pym.PyNode("defaultArnoldRenderOptions")
aiARO.listAttr()
for attr in (attr for attr in aiARO.listAttr()
             if "log" in attr.name().lower()):
    print attr.name()
print aiARO.log_filename.get()
pym.nodetypes.RenderLayer.currentLayer().name()
pym.sceneName()

arnoldlogname()

import os
print "\n".join(os.environ["PYTHONPATH"].split(";"))
print os.environ["MAYA_CMD_FILE_OUTPUT"]
Ejemplo n.º 46
0
def convert_to_education():
    pm.FileInfo()['license'] = 'education'
    fileName = pm.sceneName()
    pm.saveFile()
Ejemplo n.º 47
0
def characterize_skeleton(jnt, name = None, update_ui = True, freeze_skeleton = True):
    '''
    Sets up the MetaNode graph for a V1 character and loads all rigging necessary information onto a skeleton in the Maya scene.
    Zero translate and rotate values are saved off at the time of characterization and stored on custom attributes on each joint

    Args:
        jnt (PyNode): Maya scene joint that is part of the skeleton hierarchy for a character
        name (str): Name of the character, if None is provided the user will be prompted to enter one

    Returns:
        PyNode. The CharacterCore MetaNode created for the character
    '''
    config_manager = v1_core.global_settings.ConfigManager()

    rigging.skeleton.clean_skeleton(jnt)

    character_network = metadata.network_core.MetaNode.get_first_network_entry(jnt, metadata.network_core.CharacterCore)
    if character_network:
        v1_shared.usertools.message_dialogue.open_dialogue("This Skeleton is already characterized -- {0}".format(character_network.character_name.get()), title="Already Characterized")
        return

    if not name:
        result = pm.promptDialog(title="Characterize Skeleton",
                                 message="Enter Name:",
                                 button=['OK', 'Cancel'],
                                 defaultButton='OK',
                                 cancelButton='Cancel',
                                 dismissString='Cancel')

        if result == 'OK':
            name = pm.promptDialog(query=True, text=True)
        else:
            return None

    skeleton_root = rigging.skeleton.get_root_joint(jnt)
    replaced_joint_list = rigging.skeleton.replace_transforms_with_joints([skeleton_root] + pm.listRelatives(skeleton_root, ad=True, type='transform'))

    # Ideally we'd check if skeleton_root was deleted by replace_transforms_with_joints(), but pm.objExists returns True
    # while simultaneously throwing a warning that the skeleton_root does not exist if it was deleted above.
    skeleton_root = rigging.skeleton.get_root_joint(replaced_joint_list[0])

    character_namespace = skeleton_root.namespace()
    root_parent = skeleton_root.getParent()

    character_network = metadata.network_core.CharacterCore(node_name = name, namespace = character_namespace)

    root_folder = pm.sceneName().dirname()
    if config_manager.check_project():
        root_folder = v1_core.environment.get_project_root().split(os.sep)[-1]
        root_folder = ".." + pm.sceneName().dirname().split(root_folder)[-1]

    character_network.set('root_path', root_folder)

    rig_core = metadata.network_core.RigCore(parent = character_network.node, namespace = character_namespace, character_group = character_network.group)
    joints_core = metadata.network_core.JointsCore(parent = character_network.node, namespace = character_namespace, root_jnt = skeleton_root)
    regions_core = metadata.network_core.RegionsCore(parent = character_network.node, namespace = character_namespace)

    if root_parent and rigging.skeleton.is_animated([root_parent], False):
        skeleton_root.setParent(None)
        temp_constraint = pm.parentConstraint(root_parent, skeleton_root, mo=False)
        maya_utils.baking.bake_objects([skeleton_root], True, True, True, use_settings = False, simulation = False)
        pm.delete(temp_constraint)

    joint_list = [joints_core.root]
    joint_list += pm.listRelatives(joints_core.root, ad=True, type='joint')

    for jnt in joint_list:
        rigging.skeleton.setup_joint(jnt, joints_core)

    character_network.group.rename(character_namespace + character_network.group.name())
    joints_core.root.rename(character_namespace + joints_core.root.stripNamespace())
    joints_core.root.setParent(character_network.group)

    mesh_group = pm.group(name=character_namespace + "{0}_meshes".format(name), empty=True)
    mesh_group.setParent(character_network.group)
    pm.select(None)

    if freeze_skeleton:
        rigging.rig_tools.freeze_xform_rig(character_network)

    if update_ui:
        scene_tools.scene_manager.SceneManager().run_by_string('UpdateRiggerInPlace')

    return character_network
Ejemplo n.º 48
0
    def launch(self, *args, **kwargs):
        """launch renderer command
		"""
        # do nothing if there is no window (called externally)
        if not self.window:
            return

        # get values
        start_frame = pm.intField('cgru_afanasy__start_frame', q=1, v=1)
        end_frame = pm.intField('cgru_afanasy__end_frame', q=1, v=1)
        frames_per_task = \
         pm.intField('cgru_afanasy__frames_per_task', q=1, v=1)
        by_frame = pm.intField('cgru_afanasy__by_frame', q=1, v=1)
        separate_layers = \
         pm.checkBox('cgru_afanasy__separate_layers', q=1, v=1)
        pause = pm.checkBox('cgru_afanasy__paused', q=1, v=1)

        # check values
        if start_frame > end_frame:
            temp = end_frame
            end_frame = start_frame
            start_frame = temp

        frames_per_task = max(1, frames_per_task)
        by_frame = max(1, by_frame)

        # store field values
        pm.optionVar['cgru_afanasy__start_frame_ov'] = start_frame
        pm.optionVar['cgru_afanasy__end_frame_ov'] = end_frame
        pm.optionVar['cgru_afanasy__frames_per_task_ov'] = frames_per_task
        pm.optionVar['cgru_afanasy__by_frame_ov'] = by_frame
        pm.optionVar['cgru_afanasy__separate_layers'] = separate_layers

        # get paths
        scene_name = pm.sceneName()
        datetime = '%s%s' % (time.strftime('%y%m%d-%H%M%S-'),
                             str(time.time() - int(time.time()))[2:5])

        filename = '%s.%s.mb' % (scene_name, datetime)

        project_path = pm.workspace(q=1, rootDirectory=1)

        outputs = ','.join(
            pm.renderSettings(fullPath=1, firstImageName=1, lastImageName=1))

        job_name = os.path.basename(scene_name)

        logger.debug('%ss %se %sr' % (start_frame, end_frame, by_frame))
        logger.debug('scene        = %s' % scene_name)
        logger.debug('file         = %s' % filename)
        logger.debug('job_name     = %s' % job_name)
        logger.debug('project_path = %s' % project_path)
        logger.debug('outputs      = %s' % outputs)

        if pm.checkBox('cgru_afanasy__close', q=1, v=1):
            pm.deleteUI(self.window)

        cmd_buffer = [
            '"%(filename)s"', '%(start)s', '%(end)s', '-by %(by_frame)s',
            '-fpt %(fpt)s', '-name "%(name)s"', '-proj "%(proj)s"',
            '-images "%(images)s"', '-deletescene'
        ]

        kwargs = {
            'filename': filename,
            'start': start_frame,
            'end': end_frame,
            'by_frame': by_frame,
            'fpt': frames_per_task,
            'name': job_name,
            'proj': project_path,
            'images': outputs
        }

        drg = pm.PyNode('defaultRenderGlobals')
        if drg.getAttr('currentRenderer') == 'mentalRay':
            cmd_buffer.append('-type maya_mental')

        if pause:
            cmd_buffer.append('-pause')

        # save file
        pm.saveAs(filename, force=1, type='mayaBinary')

        # rename back to original name
        pm.renameFile(scene_name)

        cmds = []

        # submit renders
        if separate_layers:
            # render each layer separately
            rlm = pm.PyNode('renderLayerManager')
            layers = [
                layer for layer in rlm.connections() if layer.renderable.get()
            ]

            for layer in layers:
                layer_name = layer.name()
                kwargs['name'] = '%s:%s' % (job_name, layer_name)

                tmp_cmd_buffer = copy.copy(cmd_buffer)
                tmp_cmd_buffer.append('-take %s' % layer.name())

                # create one big command
                afjob_cmd = ' '.join([
                    os.environ['CGRU_PYTHONEXE'],
                    '"%s/python/afjob.py"' % os.environ['AF_ROOT'],
                    '%s' % ' '.join(tmp_cmd_buffer) % kwargs
                ])
                cmds.append(afjob_cmd)

        else:
            # create one big command
            afjob_cmd = ' '.join([
                os.environ['CGRU_PYTHONEXE'],
                '%s/python/afjob.py' % os.environ['AF_ROOT'],
                '%s' % ' '.join(cmd_buffer) % kwargs
            ])
            cmds.append(afjob_cmd)

        # call each command separately
        for cmd in cmds:
            print(cmds)

            os.system(cmd)
# coding:utf-8
import pymel.core as pm
import previewShaderInAnim as ps
import os
import pixoLibs.pixoFileTools as pft
import maya.cmds as mc

path_obj = pft.PathDetails.parse_path(pm.sceneName())
publishdir = os.path.dirname(path_obj.getPublishFullPath())
cfx = os.path.normpath(os.path.join(publishdir, 'CFX'))


def getChar():
    char = []
    for x in pm.listReferences():
        asset = os.path.basename(x.path).split('_')[1]
        if ps.get_asset_type_by_name(asset)[1] == 'Character':
            char.append(asset)
    return char


def exportCFX(chars):
    for char in chars:
        possibleName = char + '*:' + char + '_CFX'
        trans = pm.ls(possibleName)
        if trans:
            for tran in trans:
                # begin = pm.playbackOptions(q=True, ast=True)
                end = pm.playbackOptions(q=True, aet=True)
                cmd = '-frameRange {} {} -stripNamespaces -uvWrite -root {} -file {}'.format(
                    950, end, tran.name(long=True),
Ejemplo n.º 50
0
def opendir(x):
    path_obj = pft.PathDetails.parse_path(pm.sceneName())
    asset_name = path_obj.shot
    pub_dir = "%s/%s" % (x, asset_name)
    os.startfile(pub_dir.encode('gbk'))
Ejemplo n.º 51
0
def get_skindata_path():
    scene_path = pm.sceneName()
    dir_path = os.path.dirname(scene_path)
    return dir_path
Ejemplo n.º 52
0
"""

from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

__author__ = 'timmyliang'
__email__ = '*****@*****.**'
__date__ = '2020-09-25 15:45:54'

import os
from pymel import core as pm


capture_path = os.path.dirname(pm.sceneName())

for p in os.listdir(capture_path):
    path = os.path.join(capture_path,p)
    if not path.endswith("ma"):
        continue
    pm.openFile(path,f=1)

    png = "%s.png" % os.path.splitext(pm.sceneName())[0]

    pm.playblast(completeFilename=png,
                format="image",
                sequenceTime=0,
                frame=[1],
                clearCache=1,
                viewer=0,
Ejemplo n.º 53
0
	def BakeGeometry( self, deleteAnimatedGeos=True, *args ):	

		# disable timewarps before caching
		self.getTimeWarpStates()


		objs = pm.ls( sl=True )
		bakedGeos = []
		blendNodes = []
		
		fileName = pm.sceneName()
		if not fileName:
			pm.error('Please save the file before baking.')
		
		cacheFolderPath = fileName.replace('.mb', '_cache' )
		cacheFolderPath = cacheFolderPath.replace('.ma', '_cache' )
		
		pm.sysFile( cacheFolderPath , makeDir=True )
		
		for obj in objs:
			if not obj.getShape().type()=='mesh':
				continue
			# create a duplicate for each object
			objName= obj.name()
			pm.rename( obj, '%s_NotBaked'%objName )
			dup = pm.duplicate( obj )[0]
			pm.rename( dup, objName )
			UnlockUnhideAttrs( dup )
			
			# hide animted geometry
			self.removeConnections(  objs = obj )
			obj.visibility.set(0)

			try:
				pm.parent( dup, world=True )
			except:
				pass
			blendNode = pm.blendShape( obj, dup, origin='world')[0]
			pm.blendShape( blendNode, edit=True, w=[(0, 1)] )
			blendNodes.append( blendNode )
			
			bakedGeos.append( dup )
		
		# hide objects before point cache
		IsolateSelected(  state=True, showSelected=False ) 
		
		# create cache
		pm.select( bakedGeos )
		mel.eval( 'doCreateGeometryCache 6 { "2", "1", "10", "OneFile", "1", "%s","1","","0", "add", "1", "1", "1","0","1","mcc","0" } ;' %cacheFolderPath  )
		#cacheFiles = pm.cacheFile( fileName='%s_cache'%obj, st=getTimeRange()[0], et=getTimeRange()[1], points=obj.getShape() , directory=cacheFolderPath )
			
		
		# delete main geometries and blendNode
		pm.delete( blendNodes )

		if deleteAnimatedGeos:
			pm.delete( objs )
		
		
		# group cached geometires
		pm.group( bakedGeos, name='bakedGeos_grp' )
		
		
		# set scene timewarp state to their previous state
		self.restoreTimeWarpStates()
		


		# show all objects
		IsolateSelected( state=False )
Ejemplo n.º 54
0
	def importPalette(self, palName, version, binding= False, anim= False, asDelta= False, delta= []):
		"""
		** NOT SUPPORT NAMESPACE **
		XGen palette will imported without validator.
		[!!!] When importing [BAKED] palette, @binding set to False should be fine.
		"""
		xgenFileName = palName + '.xgen'
		xgenFile = str('/'.join([self.paletteVerDir(palName, version), xgenFileName]))
		if not os.path.isfile(xgenFile):
			self.notifyMsg('.xgen file is not exists.', 2)
			pm.error('[XGen Hub] : .xgen file is not exists. -> ' + xgenFile)
			return None
		if asDelta and not pm.sceneName():
			self.notifyMsg('Please save the scene.', 2)
			return None
		
		self.clearPreview()
		
		# check if palette exists in current scene
		if palName in xg.palettes():
			# delete current palette folder
			palDir = xg.expandFilepath(xg.getAttr('xgDataPath', palName), '')
			if os.path.isdir(palDir):
				try:
					dir_util.remove_tree(palDir)
				except:
					pm.warning('[XGen Hub] : Dir may not remove. -> ' + palDir)
			# delete current palette
			# this action might cry about 'None type object has no attr "previewer"'
			# when there is no xgen ui panel
			xg.deletePalette(palName)
		
		# IMPORT PALETTE
		palName = base.importPalette(xgenFile, delta, '')
		# update the palette with the current project
		xg.setAttr('xgProjectPath', str(pm.workspace(q= 1, rd= 1)), palName)
		dataPath = xg.paletteRootVar() + '/' + palName
		xg.setAttr('xgDataPath', dataPath, palName)
		# create imported palette folder
		paletteRoot = xg.expandFilepath(dataPath, '', True, True)
		# create all imported descriptions folder
		msxgApi.setupDescriptionFolder(paletteRoot, palName)
		# wrap into maya nodes
		palName = str(pm.mel.xgmWrapXGen(pal= palName, wp= binding, wlg= binding, gi= binding))
		# copy maps from source
		descNames = xg.descriptions(palName)
		msxgApi.setupImportedMap(xgenFile, palName, descNames, self.projPath)
		# bind grooming descriptions to geometry
		if binding:
			for desc in descNames:
				igdesc = xg.getAttr('groom', palName, desc)
				if igdesc:
					# get groom dag node
					igdesc = xg.igActivateDescription(desc)
					# bind groom to geo
					pm.mel.igBindFromXGen(desc)
					# set groom density and sampling method
					pm.setAttr(igdesc + '.density', 1)
					pm.setAttr(igdesc + '.interpStyle', 1)
					# set all groom visible on
					xg.igSetDescriptionVisibility(True)
					# sync primitives tab attritube map path with auto export path
					xg.igSyncMaps(desc)

			# import grooming as well
			self.importGrooming(palName)

		# import as anim, build hairSystem
		if anim:
			# build hairSystem
			self.linkHairSystem(palName)
			# check preset dir exists
			presetLocalDir = str(pm.internalVar(userPresetsDir= 1))
			presetRepo = self.nDynPresetPath(palName, version)
			if os.path.exists(presetRepo):
				# copy preset
				for prs in os.listdir(presetRepo):
					dstPath = presetLocalDir + prs
					prs = '/'.join([presetRepo, prs])
					shutil.copyfile(prs, dstPath)
				# load preset
				# [note] nucleus preset will not be loaded during current devlope
				presetMel = []
				for nodeType in ['hairSystem', 'nRigid']:
					presetDict = self.ioAttrPreset(nodeType, False)
					presetMel.extend(presetDict.values())
				# dump preset
				for prs in presetMel:
					if os.path.isfile(prs):
						os.remove(prs)
			else:
				pm.warning('[XGen Hub] : nDynamic attribute presets folder not found.')

		if asDelta:
			dataPath = xg.getAttr('xgDataPath', palName)
			dataPath = dataPath + ';' + self.paletteVerDir(palName, version, raw= True)
			xg.setAttr('xgDataPath', dataPath, palName)
			# save scenes
			pm.saveFile(f= 1)
			# set export delta
			pm.setAttr(palName + '.xgExportAsDelta', 1)

		pm.warning('[XGen Hub] : Collection Import Complete !')
		self.notifyMsg('Collection Import Complete !', 0)

		return palName
Ejemplo n.º 55
0
def convert2mov(img_input, mov_output, copyInfoFrom=''):
    '''
        the input images should use %04d or #### for frame padding
        if copyInfoFrom presents, this function will try to copy comment from the presented mov
    '''
    img_input = cf.osPathConvert(img_input)
    mov_output = cf.osPathConvert(mov_output)
    copyInfoFrom = cf.osPathConvert(copyInfoFrom)

    img_dir = os.path.dirname(img_input)
    img_name = os.path.basename(img_input)
    if not os.path.isdir(img_dir):
        print 'Invalid img_input: '+img_input
        return

    left_img = sorted(glob.glob(img_input.replace('%V','left').replace('%04d','*').replace('####','*')))
    right_img = sorted(glob.glob(img_input.replace('%V','right').replace('%04d','*').replace('####','*')))

    if not left_img or not right_img or len(left_img)!=len(right_img):
        print 'Failed to find left or right images, or the length of left is not equal to the right'
        return

    if not mov_output.endswith('.mov') and os.path.isdir(mov_output):
        mov_output = os.path.join( mov_output, '.'.join(img_name.split('.')[:4])+'.stereo.mov' )

    start_frame = int(left_img[0].split('.')[-2])
    end_frame = int(left_img[-1].split('.')[-2])
    reelname = img_name.split('.')[0]

    rv = cf.getRVPath()
    info = {'comment':None, 'audio':None, 'isStereo':True, 'reelname':reelname, 'start_frame':start_frame}

    if copyInfoFrom and os.path.isfile(copyInfoFrom):
        tmp = get_comment_from_mov(copyInfoFrom, rv['rvls'])
        info['comment'] = tmp['comment']
        if '.wav' in tmp['comment']:
            audio_path = [a.strip() for a in tmp['comment'].split(' ') if a.endswith('.wav')]
            if audio_path and os.path.isfile(audio_path):
                info['audio'] = audio_path[0]
    else:
        ma = str(pm.sceneName())
        slider = pm.mel.eval('$tmpVar=$gPlayBackSlider')
        audios = [a for a in pm.ls(type='audio') if reelname in a.name()]
        audio_path = ''
        if audios:
            audio_node = audios[0]
            #slider = pm.mel.eval('$tmpVar=$gPlayBackSlider')
            pm.timeControl(slider, edit=True, displaySound=True, sound=audio_node)
            audio_path = cf.osPathConvert( audio_node.attr('filename').get() )
        info['comment'] = str(start_frame)+'-'+str(end_frame)+' '+ma+' '+('' if not os.path.isfile(audio_path) else audio_path+' ')+str(start_frame)
        if os.path.isfile(audio_path):
            info['audio'] = audio_path

    cmd_str = ''
    if audio_path == '':
        cmd_str = '"' + rv['rvio'] + '" [ ' + img_input.replace('%V', 'left') + ' ' + img_input.replace('%V', 'right') + ' ] -outstereo -o ' + mov_output
    else:
        cmd_str = '"' + rv['rvio'] + '" [ ' + img_input.replace('%V', 'left') + ' ' + img_input.replace('%V', 'right') + ' ' +audio_path + ' ] -audiorate 48000 -outstereo -o ' + mov_output

    cmd_str += ' -outparams comment="%s" timecode=%s' % (info['comment'],str(info['start_frame']))

    print 'Cmd:', cmd_str
    p = subprocess.Popen(cmd_str, shell=rv['rv_shell'])
    (out, err) = p.communicate()
 def process(self, context):
     if os.path.exists(pm.sceneName()):
         filename = context.create_instance(name=os.path.basename(pm.sceneName()))
         filename.data['family'] = 'Scene'
         filename.data['icon'] = 'tint'
         filename.data['path'] = pm.sceneName()
Ejemplo n.º 57
0
    def launch(self, *args, **kwargs):
        """launch renderer command
        """
        # do nothing if there is no window (called externally)
        if not self.window:
            return

        # warn the user about the ignore settings
        try:
            dAO = pm.PyNode('defaultArnoldRenderOptions')

            ignore_attrs = [
                'ignoreSubdivision', 'ignoreDisplacement', 'ignoreBump',
                'ignoreMotionBlur'
            ]

            attr_values = [(attr, dAO.getAttr(attr)) for attr in ignore_attrs
                           if dAO.getAttr(attr) is True]

            if any(attr_values):
                msg_text = '<br>'.join(
                    map(lambda x: '%s: %s' % (x[0], x[1]), attr_values))

                response = pm.confirmDialog(
                    title='Ignore These Settings?',
                    message=
                    'You have ignored:<br><br>%s<br><br><b>Is that ok?</b>' %
                    msg_text,
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No')

                if response == 'No':
                    return
        except pm.MayaNodeError:
            # no Arnold
            pass

        # check if rendering with persp camera
        try:
            wrong_camera_names = [
                'perspShape',
                'topShape',
                'sideShape',
                'fontShape',
                'persp1Shape',
                'perspShape1',
            ]
            renderable_cameras = [
                node for node in pm.ls(type='camera')
                if node.getAttr('renderable')
            ]
            if any(
                    map(lambda x: x.name() in wrong_camera_names,
                        renderable_cameras)):
                response = pm.confirmDialog(
                    title='Rendering with Persp?',
                    message=
                    'You are rendering with <b>Persp Camera<b><br><br>Is that ok?</b>',
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No')

                if response == 'No':
                    return

            if len(renderable_cameras) > 1:
                response = pm.confirmDialog(
                    title='Rendering more than one Camera?',
                    message=
                    'You are rendering <b>more than one camera<b><br><br>Is that ok?</b>',
                    button=['Yes', 'No'],
                    defaultButton='No',
                    cancelButton='No',
                    dismissString='No')

                if response == 'No':
                    return
            elif len(renderable_cameras) == 0:
                pm.confirmDialog(
                    title='No <b>Renderable</b> camera!!!',
                    message='There is no <b>renderable camera<b>!!!',
                    button=['Ok'],
                    defaultButton='Ok',
                    cancelButton='Ok',
                    dismissString='Ok')
                return

        except pm.MayaNodeError:
            # no default render globals node
            pass

        # get values
        start_frame = pm.intField('cgru_afanasy__start_frame', q=1, v=1)
        end_frame = pm.intField('cgru_afanasy__end_frame', q=1, v=1)
        frames_per_task = \
            pm.intField('cgru_afanasy__frames_per_task', q=1, v=1)
        by_frame = pm.intField('cgru_afanasy__by_frame', q=1, v=1)
        hosts_mask = pm.textField('cgru_afanasy__hosts_mask', q=1, text=True)
        hosts_exclude = pm.textField('cgru_afanasy__hosts_exclude',
                                     q=1,
                                     text=True)
        separate_layers = \
            pm.checkBox('cgru_afanasy__separate_layers', q=1, v=1)
        pause = pm.checkBox('cgru_afanasy__paused', q=1, v=1)

        # check values
        if start_frame > end_frame:
            temp = end_frame
            end_frame = start_frame
            start_frame = temp

        frames_per_task = max(1, frames_per_task)
        by_frame = max(1, by_frame)

        # store without quota sign
        hosts_mask = hosts_mask.replace('"', '')
        hosts_exclude = hosts_exclude.replace('"', '')

        # store field values
        pm.optionVar['cgru_afanasy__start_frame_ov'] = start_frame
        pm.optionVar['cgru_afanasy__end_frame_ov'] = end_frame
        pm.optionVar['cgru_afanasy__frames_per_task_ov'] = frames_per_task
        pm.optionVar['cgru_afanasy__by_frame_ov'] = by_frame
        pm.optionVar['cgru_afanasy__hosts_mask_ov'] = hosts_mask
        pm.optionVar['cgru_afanasy__hosts_exclude_ov'] = hosts_exclude
        pm.optionVar['cgru_afanasy__separate_layers'] = separate_layers

        # add quota sign
        hosts_mask = '"%s"' % hosts_mask
        hosts_exclude = '"%s"' % hosts_exclude

        # get paths
        scene_name = pm.sceneName()
        datetime = '%s%s' % (time.strftime('%y%m%d-%H%M%S-'),
                             str(time.time() - int(time.time()))[2:5])

        filename = '%s.%s.mb' % (scene_name, datetime)

        project_path = pm.workspace(q=1, rootDirectory=1)

        outputs = ','.join(
            pm.renderSettings(fullPath=1, firstImageName=1, lastImageName=1))

        # job_name = os.path.basename(scene_name)
        job_name = self.generate_job_name()

        logger.debug('%ss %se %sr' % (start_frame, end_frame, by_frame))
        logger.debug('scene        = %s' % scene_name)
        logger.debug('file         = %s' % filename)
        logger.debug('job_name     = %s' % job_name)
        logger.debug('project_path = %s' % project_path)
        logger.debug('outputs      = %s' % outputs)

        if pm.checkBox('cgru_afanasy__close', q=1, v=1):
            pm.deleteUI(self.window)

        cmd_buffer = [
            '"%(filename)s"',
            '%(start)s',
            '%(end)s',
            '-by %(by_frame)s',
            '-hostsmask %(msk)s',
            '-hostsexcl %(exc)s',
            '-fpt %(fpt)s',
            '-name "%(name)s"',
            '-pwd "%(pwd)s"',
            '-proj "%(proj)s"',
            '-images "%(images)s"',
            '-deletescene',
            '-exec "%(exec)s"',
            '-lifetime 864000'  # 10 days
        ]

        kwargs = {
            'filename': filename,
            'start': start_frame,
            'end': end_frame,
            'by_frame': by_frame,
            'msk': hosts_mask,
            'exc': hosts_exclude,
            'fpt': frames_per_task,
            'name': job_name,
            'pwd': project_path,
            'proj': project_path,
            'images': outputs,
            'exec': 'mayarender%s' % os.environ['MAYA_VERSION']
        }

        drg = pm.PyNode('defaultRenderGlobals')
        render_engine = drg.getAttr('currentRenderer')
        if render_engine == 'mentalRay':
            cmd_buffer.append('-type maya_mental')
        elif render_engine == 'arnold':
            cmd_buffer.append('-type maya_arnold')
            # set the verbosity level to warnin+info
            aro = pm.PyNode('defaultArnoldRenderOptions')
            aro.setAttr('log_verbosity', 1)

        if pause:
            cmd_buffer.append('-pause')

        # set output to console
        dARO = pm.PyNode('defaultArnoldRenderOptions')
        dARO.setAttr("log_to_console", 1)

        # save file
        pm.saveAs(filename, force=1, type='mayaBinary')

        # rename back to original name
        pm.renameFile(scene_name)

        # disable set output to console
        dARO.setAttr("log_to_console", 0)

        cmds = []

        # submit renders
        if separate_layers:
            # render each layer separately
            rlm = pm.PyNode('renderLayerManager')
            layers = [
                layer for layer in rlm.connections() if layer.renderable.get()
            ]

            filename = kwargs['filename']
            for layer in layers:
                layer_name = layer.name()
                kwargs['name'] = '%s:%s' % (job_name, layer_name)

                # for multiple render layers duplicate the file
                basename, ext = os.path.splitext(filename)
                kwargs['filename'] = '%s.%s%s' % (basename, layer_name, ext)

                # duplicate the file
                shutil.copy2(filename, kwargs['filename'])

                tmp_cmd_buffer = copy.copy(cmd_buffer)
                tmp_cmd_buffer.append('-take %s' % layer.name())

                # create one big command
                afjob_cmd = ' '.join([
                    os.environ['CGRU_PYTHONEXE'],
                    '"%s/python/afjob.py"' % os.environ['AF_ROOT'],
                    '%s' % ' '.join(tmp_cmd_buffer) % kwargs
                ])
                cmds.append(afjob_cmd)

            # delete the original file
            os.remove(filename)

        else:
            # create one big command
            afjob_cmd = ' '.join([
                os.environ['CGRU_PYTHONEXE'],
                '%s/python/afjob.py' % os.environ['AF_ROOT'],
                '%s' % ' '.join(cmd_buffer) % kwargs
            ])
            cmds.append(afjob_cmd)

        # call each command separately
        for cmd in cmds:
            print(cmds)
            print os.system(cmd)
Ejemplo n.º 58
0
 def __init__(self):
     self.fileName = pm.sceneName().split('/')[-1]
     pass
Ejemplo n.º 59
0
def get_current_file_name(full_path=False):
    if full_path:
        return str(pm.sceneName().abspath())
    return str(pm.sceneName().basename())
Ejemplo n.º 60
0
                pass
                
            if __name__=='__main__':
                main()
"""
# ----------------------------------------------------------------------
# Import
# ----------------------------------------------------------------------
import pymel.core as pm

# ----------------------------------------------------------------------
# Configuration
# ----------------------------------------------------------------------
lisRL = pm.ls(typ='renderLayer')

path_split = pm.sceneName().split('/')
path_join = os.path.join('G:/PROJECTS/Vampirina2/AssetsRepo/Shots/',
                         *path_split[-3:-1])
path_lc = os.path.join(path_join,
                       'LC_{}.vrlmap'.format(path_split[-2])).replace(
                           '\\', '/')

if os.path.exists(path_join):
    try:
        bgRL = pm.editRenderLayerGlobals(currentRenderLayer='BG_RL')
        if 'BG_RL' in lisRL and 'BG_RL_CACHE' not in lisRL:
            pm.editRenderLayerAdjustment('vraySettings.mode')
            pm.editRenderLayerAdjustment('vraySettings.lc_autoSaveFile')
            pm.editRenderLayerAdjustment('vraySettings.lc_fileName')
            pm.editRenderLayerAdjustment(
                'vraySettings.globopt_gi_dontRenderImage')