def mkexportAllSaveVrimg(nuke): Fromat = "1280,720" files = cmds.file(query=1, list=1, withoutCopyNumber=1) shotname = files[0].split( '.' ) shotname = shotname[0] thumbFileName = files[0].replace( '.mb', '.vrimg' ) batFileName = files[0].replace( '.mb', '.bat' ) batfile = ("%s")%batFileName VrayScene = mkVrayVrscene("1") vrayCmd = "vray.exe -sceneFile="+VrayScene+' -display = 1 -autoClose=0 -verboseLevel = 4 -displaySRGB = 0 -imgFile= %s'%(thumbFileName) vrayRender(vrayCmd) t = 0 while (t < 3 ): try: os.rename (thumbFileName,thumbFileName) except: time.sleep(5) t+=1 vrimg2exr(thumbFileName,batfile) exrimg = thumbFileName.replace( '.vrimg', '.exr' ) time.sleep(2) if os.path.exists( exrimg ) == True: cmds.sysFile(batfile, delete = True) cmds.sysFile(thumbFileName, delete = True) if nuke ==1: mkopenNuke(exrimg,shotname,Fromat)
def mkexportAllSaveVrimg(nuke): Fromat = "1280,720" files = cmds.file(query=1, list=1, withoutCopyNumber=1) shotname = files[0].split('.') shotname = shotname[0] thumbFileName = files[0].replace('.mb', '.vrimg') batFileName = files[0].replace('.mb', '.bat') batfile = ("%s") % batFileName VrayScene = mkVrayVrscene("1") vrayCmd = "vray.exe -sceneFile=" + VrayScene + ' -display = 1 -autoClose=0 -verboseLevel = 4 -displaySRGB = 0 -imgFile= %s' % ( thumbFileName) vrayRender(vrayCmd) t = 0 while (t < 3): try: os.rename(thumbFileName, thumbFileName) except: time.sleep(5) t += 1 vrimg2exr(thumbFileName, batfile) exrimg = thumbFileName.replace('.vrimg', '.exr') time.sleep(2) if os.path.exists(exrimg) == True: cmds.sysFile(batfile, delete=True) cmds.sysFile(thumbFileName, delete=True) if nuke == 1: mkopenNuke(exrimg, shotname, Fromat)
def Renamepose(read1,*args): filename = os.path.basename(read1).split('.')[0] print filename dirname = os.path.dirname(read1) seltab = mc.shelfTabLayout('Poses',q=1,st=1) PoseRename = mc.promptDialog( title='PoseRename', message='PoseRename:', text = filename, button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if PoseRename=='OK': newposename = mc.promptDialog (query=True, text=True) renampose= dirname+'/'+ newposename+'.anim' renameimg= dirname+'/'+ newposename+'.bmp' read2=read1.replace('.anim','.bmp') mc.sysFile(read1,rename= renampose) mc.sysFile(read2,rename= renameimg) Refresh_UI(savepathini) print'Pose name changed successfully' else: return mc.shelfTabLayout('Poses',e=1,st=seltab)
def submit(self,*args): self.info("starting submit") self.config = self.readAllInputs() _write_config("submit",self.config) for label in ["sharedPath","baseURL","username","password"]: if not self.config[label]: self.message('%s is not set' % (label)) return if not check_saved(): self.message( "Project must be saved first") return if not cmds.file(query=True, sceneName=True).startswith(self.config["sharedPath"]) or not self.project_directory(): self.message('Project is not saved on shared path') return if os.path.exists(submit_path): if cmds.confirmDialog(message='File was already submitted, submit again? (overwrites submitted file)', button=["Yes","No"], defaultButton="No", dismissString="No", cancelButton="No") == "No": return cmds.sysFile(submit_path, delete=True) if not make_paths_relative(): return src_path = cmds.file(query=True, sceneName=True) frame_start = int(cmds.playbackOptions(query=True, ast=True)) frame_end = int(cmds.playbackOptions(query=True, aet=True)) self.message(submit_to_dire.submit_to_dire(config, src_path, frame_start, frame_end))
def checkTexLocalPath(self): import maya.cmds as mc # mel用 dirInfo = self.checkShotInfo() localPathTex = ('D:/Info_Temp/temp/texTemp/' + str(dirInfo[1]) + '/') mc.sysFile(localPathTex, makeDir=True) return localPathTex
def checkTX2AnimRenderLocalPath(self): import maya.cmds as mc dirInfo = self.checkShotInfo() localPathCache = ('D:/Info_Temp/temp/tx2AnimRenderTemp/' + dirInfo[0] + '/' + str(dirInfo[1]) + '/' + str(dirInfo[2]) + '/') mc.sysFile(localPathCache, makeDir=True) return localPathCache
def Renameanim(posefile,*args): filename = os.path.basename(posefile).split('.')[0] dirname = os.path.dirname(posefile) seltab = mc.shelfTabLayout('Animation',q=1,st=1) AnimRename = mc.promptDialog( title='AnimRename', message='AnimRename:', text = filename, button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if AnimRename=='OK': newanimname = mc.promptDialog (query=True, text=True) renamanim= dirname+'/'+ newanimname+'.anim' renamimag= dirname+'/'+ newanimname+'.bmp' animimg = posefile.replace('.anim','.bmp') print animimg mc.sysFile(posefile,rename= renamanim) mc.sysFile(animimg,rename= renamimag) Refresh_UI(savepathini) print'Anim name changed succesfully' else: return mc.shelfTabLayout('Animation',e=1,st=seltab)
def prepareExport(defaultName, customName): # base destDir destDir = storage.values.exportFolder generatedElement = defaultName if customName == "" else customName # create folder if there are multiple elements if not storage.values.exportAsOneObject: destDir += "\\" + generatedElement if not cmds.file(destDir, q=True, exists=True): cmds.sysFile(destDir, makeDir=True) if storage.values.displayInfo: ui.info( "Info", "The script export your scene as individual meshes and stores them into:\n" + "'" + destDir + "'") # Export meshes if not storage.values.exportAsOneObject: for mesh in storage.meshes: cmds.select(clear=True) cmds.select(mesh, add=True) exportObjects(destDir, mesh) # as one object else: exportObjects(destDir, generatedElement, True)
def HbChangeReSets2(self, projectInfo): try: TheSc = "" TheFileName = mc.file(q=1, l=1) for TheFiles in TheFileName: if TheFiles.split(".")[-1] == "mb": try: TheFile = TheFiles.split("/")[-1].split("_")[1] if TheFile[0] == "s" and TheFile[1] == "s": TheSc = TheFile else: TheSc = TheFile except: pass TheAnFileName = mc.file(q=1, shn=1, sn=1) if TheAnFileName.find("an") != -1: questEP = TheAnFileName.split("_")[1] if TheAnFileName.find("an") == -1: # questEP="201" questEP = "301" questSets = TheSc mc.sysFile("//file-cluster/GDC/Projects/" + projectInfo + "/" + projectInfo + "_Scratch/TD/SetCam/" + questEP + "/" + questSets + "/images/", makeDir=True) mc.optionMenu("EPNUM", label='SETS', e=1, v=questSets) mc.optionMenu("EP", label='EP', e=1, v=questEP) questEP = mc.optionMenu("EP", q=True, v=True) questSets = mc.optionMenu("EPNUM", q=True, v=True) except: pass self.HbChangeReSets(projectInfo) self.HbShowDateLibSc(projectInfo)
def Newtab(*args): sel_tab = mc.shelfTabLayout('tabs',q=1,st=1) crnt_tab= mc.shelfTabLayout(sel_tab,q=1,ca=1) Newtab = mc.promptDialog( title='Create New Tab', message='New Tab Name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if Newtab == 'OK': n_text = mc.promptDialog(query=True, text=True) if n_text == '': mc.confirmDialog (title='Error' ,message= 'Sorry, The name entered is not valid', button=['OK'] ,defaultButton='Yes') else: if crnt_tab: for each in crnt_tab: if each == n_text: mc.confirmDialog (title='Error' ,message= 'Sorry, The name entered is already exists', button=['OK'] ,defaultButton='Yes') return #else: if sel_tab == 'Animation': Nw_tab=savepathini+'Savepose/Animation/'+n_text+'/' mc.shelfLayout(n_text,w=450,h=200,bgc=(0.3,0.3,0.3),p=Animation) mc.sysFile(Nw_tab, makeDir=True ) else: mc.shelfLayout(n_text,w=450,h=200,bgc=(0.3,0.3,0.3),p=Poses) Nw_tab=savepathini+'Savepose/Poses/'+n_text+'/' mc.sysFile(Nw_tab, makeDir=True ) mc.shelfTabLayout(sel_tab,e=1,st=n_text)
def snapshotClose(self, *args): if os.path.exists(self.imageSnapShotPth) is True: cmds.sysFile(self.imageSnapShotPth, delete=True) if os.path.exists(self.imagepublishPth) is True: cmds.sysFile(self.imagepublishPth, delete=True) if cmds.window('ssWinID', exists=True): cmds.deleteUI('ssWinID')
def checkLayerInfoLocalPath(self, LayerType='RGB', layerName='myRGB'): import maya.cmds as mc # python用 shotInfo = self.checkShotInfo() localPathAnim = ('D:\\Info_Temp\\Project_Render_Info\\' + shotInfo[0] + '\\' + LayerType + '\\' + layerName + '\\') mc.sysFile(localPathAnim, makeDir=True) return localPathAnim
def remove(self, name, directory=DIRECTORY): mayapath = os.path.join(directory, '%s.ma' % name) jsonpath = os.path.join(directory, '%s.json' % name) imagepath = os.path.join(directory, '%s.jpg' % name) items = [mayapath, jsonpath, imagepath] for item in items: cmds.sysFile(item, delete=True)
def renametab(*args): seltab = mc.tabLayout('tabs',q=1,st=1) alltabs = mc.tabLayout('Animation',q=1,st=1) alltabs1 = mc.tabLayout('Poses',q=1,st=1) if seltab == 'Animation': if alltabs=='': mc.confirmDialog (title='Error',message='No tabs to rename', button='OK',defaultButton='Yes') else: newname = mc.promptDialog( text=alltabs, title='Rename Tab', message='New Tab Name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if newname == 'OK': newtabname = mc.promptDialog (query=True, text=True) if newtabname =='': mc.confirmDialog (title='Error' ,message= 'Sorry, The name entered is not valid', button=['OK'] ,defaultButton='Yes') return else : oldname = mc.tabLayout('Animation',q=1,st=1) mc.tabLayout ('Animation',e=True,tl=((oldname, newtabname))) Ren_tab =savepathini+'Savepose/Animation/'+oldname Ren_tab1=savepathini+'Savepose/Animation/'+newtabname mc.sysFile(Ren_tab,rename=Ren_tab1) return else: return else: if alltabs1 == '': mc.confirmDialog (title='Error',message='No tabs to rename', button='OK',defaultButton='Yes') else: newname = mc.promptDialog( title='Rename Tab', message='New Tab Name:', tx = alltabs1, button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if newname == 'OK': newtabname = mc.promptDialog (query=True, text=True) if newtabname =='': mc.confirmDialog (title='Error' ,message= 'Sorry, The name entered is not valid', button=['OK'] ,defaultButton='Yes') return else: oldname = mc.tabLayout('Poses',q=1,st=1) mc.tabLayout ('Poses',e=True,tl=((oldname, newtabname))) Ren_tab =savepathini+'Savepose/Poses/'+oldname Ren_tab1=savepathini+'Savepose/Poses/'+newtabname mc.sysFile(Ren_tab,rename=Ren_tab1) return else: return
def mayaFolder(self, *args): curPth = cmds.workspace(q=True, rd=True) maya_Ls = [ 'scenes', 'images', 'sourceimages', 'clips', 'renderData', 'scripts', 'data', 'apps', 'cache' ] i = 0 for i in range(len(maya_Ls)): cmds.sysFile(curPth + "/" + maya_Ls[i], md=True) i = i + 1
def HbChangeReSets4(self, projectInfo): questSets = mc.optionMenu("EPNUM", q=True, v=True) questEP = mc.optionMenu("EP", q=True, v=True) for m in range(1000): mc.menuItem("TheMenuItem" + str(m), e=1, en=0, label=" ") TheFileList = mc.getFileList(folder="//file-cluster/GDC/Projects/" + projectInfo + "/" + projectInfo + "_Scratch/TD/SetCam/" + questEP + "/") if TheFileList != None: for i in range(len(TheFileList)): mc.menuItem("TheMenuItem" + str(i), e=1, en=1, label=TheFileList[i]) questEP = mc.optionMenu("EP", q=True, v=True) questSets = mc.optionMenu("EPNUM", q=True, v=True) for m in range(0, 100): mc.iconTextButton("Temp" + str(m), e=1, visible=0 , style='iconAndTextVertical', image1="sphere.xpm") # popupMenu("ThePopup"+str(m)) mc.menuItem("TheObMenu" + str(m), e=1) mc.menuItem("Cancle" + str(m), e=1) mc.sysFile("//file-cluster/GDC/Projects/" + projectInfo + "/" + projectInfo + "_Scratch/TD/SetCam/" + questEP + "/" + questSets + "/images/", makeDir=True) try: TheUpDateSc = os.listdir("//file-cluster/GDC/Projects/" + projectInfo + "/" + projectInfo + "_Scratch/TD/SetCam/" + questEP + "/" + questSets + "/images/") TheBmp = [] for i in range(len(TheUpDateSc)): if TheUpDateSc[i].split(".")[-1] == "bmp": TheBmp.append(TheUpDateSc[i]) for j in range(len(TheBmp)): theCommand = 'HbImportReCam(\"' + TheBmp[j] + '\")' theCommand2 = 'HbImageOk(\"' + TheBmp[j] + '\")' theCommand3 = 'HbCancleHook(\"' + TheBmp[j] + '\")' mc.iconTextButton("Temp" + str(j) , e=1, visible=1, bgc=(1, 1, 1), style='iconAndTextVertical', image1=("//file-cluster/GDC/Projects/" + projectInfo + "/" + projectInfo + "_Scratch/TD/SetCam/" + questEP + "/" + questSets + "/images/" + TheBmp[j]), label=TheBmp[j].split(".")[0], c=theCommand) mc.menuItem("TheObMenu" + str(j), e=1, l="This Camera is ok", c=theCommand2) mc.menuItem("Cancle" + str(j), e=1, l="cancle the hook", c=theCommand3) mc.text("TheNumber", e=1, bgc=(1, 0.9, 0.9), label=str(len(TheBmp)), align='center') questTheNum = mc.intField("TheNumber", q=1, v=1) if float(questTheNum) != 0: TheStr = str(float(len(TheBmp)) / float(questTheNum) * 100) + "%" mc.text("part", e=1, bgc=(0, 1, 0), label=TheStr, align='center') if float(questTheNum) == 0: mc.text("part", e=1, bgc=(0, 1, 0), label="erro", align='center') try: TheOKDateSc = os.listdir("//file-cluster/GDC/Projects/" + projectInfo + "/" + projectInfo + "_Scratch/TD/SetCam/" + questEP + "/" + questSets + "/images/old/") mc.text("TheOkNumber", e=1, bgc=(1, 0.9, 0.9), label=len(TheOKDateSc), align='center') except: mc.text("TheOkNumber", e=1, bgc=(1, 0.9, 0.9), label=0, align='center') except: pass self.HbShowDateLibSc(projectInfo)
def Deleteanim(posefile,*args): confirm=mc.confirmDialog (title='Confirm Delete pose',message=' Are you sure......?',ma='right',button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No') if confirm=='Yes': seltab = mc.shelfTabLayout('Animation',q=1,st=1) imgpose = posefile.replace('.anim','.bmp') mc.sysFile(posefile,delete=1) mc.sysFile(imgpose,delete=1) filename = os.path.basename(posefile).split('.')[0] Refresh_UI(savepathini) print filename + ' anim deleted..' mc.shelfTabLayout('Animation',e=1,st=seltab)
def checkRenderLayerLocalPath(self, shotType=2): import maya.cmds as mc dirInfo = self.checkShotInfo() localPathCache = ('D:/Info_Temp/renderLayerFile/' + dirInfo[0] + '/' + str(dirInfo[1]) + '/' + str(dirInfo[2]) + '/') if shotType == 3: localPathCache = ('D:/Info_Temp/renderLayerFile/' + dirInfo[0] + '/' + str(dirInfo[1]) + '/' + str(dirInfo[2]) + '/' + str(dirInfo[3]) + '/') mc.sysFile(localPathCache, makeDir=True) return localPathCache
def checkCacheLocalPath(self, shotType=2): import maya.cmds as mc # mel用 dirInfo = self.checkShotInfo() localPathCache = ('D:/Info_Temp/temp/geoCacheTemp/' + dirInfo[0] + '/' + str(dirInfo[1]) + '/' + str(dirInfo[2]) + '/') if shotType == 3: localPathCache = ('D:/Info_Temp/temp/geoCacheTemp/' + dirInfo[0] + '/' + str(dirInfo[1]) + '/' + str(dirInfo[2]) + '/' + str(dirInfo[3]) + '/') mc.sysFile(localPathCache, makeDir=True) return localPathCache
def CreateDIRs(): workDirName = PromptDialogue('working dir name', 'add working dir') workDir = workDirName + '\\' # создаю подкатегории workDirList = GetInfo.workDirs.split() for dirName in workDirList: cmds.sysFile(GetInfo.workPath + workDir + dirName, md = True) # создаю файл, который будет содеражть список анимаций animListName = GetInfo.workPath + workDir + workDirName + '_anim_list.txt' animListFile = open(animListName, 'w') animListFile.close()
def deletetab(*args): alltabs = mc.tabLayout ('tabs',q=1,st=1) chktabs = mc.tabLayout ('Animation',q=1,st=1) chktabs1= mc.tabLayout ('Poses',q=1,st=1) if alltabs == 'Animation': seltab = mc.tabLayout('Animation',q=1,st=1) mc.deleteUI(seltab) Del_tab=savepathini+'Savepose/Animation/'+seltab Del1_in=Del_tab+'/' list_in=mc.getFileList(fld=Del1_in) for i in range(len(list_in)): mc.sysFile(Del1_in+'/'+list_in[i],delete=1) mc.sysFile(Del_tab,red=1) if chktabs=='': mc.confirmDialog (title='Error',message='No tabs to delete', button='OK',defaultButton='Yes') # else : # return else : seltab = mc.tabLayout('Poses',q=1,st=1) mc.deleteUI(seltab) Del_tab=savepathini+'Savepose/Poses/'+seltab Del1_in=Del_tab+'/' list_in=mc.getFileList(fld=Del1_in) for i in range(len(list_in)): mc.sysFile(Del1_in+'/'+list_in[i],delete=1) mc.sysFile(Del_tab,red=1) if chktabs1=='': mc.confirmDialog (title='Error',message='No tabs to delete', button='OK',defaultButton='Yes') else : return
def checkFinalLayoutLocalPath(self, shotType=2): import maya.cmds as mc # mel用 dirInfo = self.checkShotInfo() localPathFinalLayout = ('D:/Info_Temp/temp/finalLayoutTemp/' + dirInfo[0] + '/' + str(dirInfo[1]) + '/' + str(dirInfo[2]) + '/') if shotType == 3: localPathFinalLayout = ('D:/Info_Temp/temp/finalLayoutTemp/' + dirInfo[0] + '/' + str(dirInfo[1]) + '/' + str(dirInfo[2]) + '/' + str(dirInfo[3]) + '/') mc.sysFile(localPathFinalLayout, makeDir=True) return localPathFinalLayout
def imgRename(self): '''Post frame script. Renames current render frame output to desired format''' # Run file name function to get variables self.getFileName() # Rename if no _temp if os.path.isfile(self.newFile): cmds.sysFile(self.newFile, rename=self.newName) print 'Renaming to: ' + self.newName # Rename if _temp tempName = self.newFile.rpartition(".")[0] + "_tmp." + self.newFile.rpartition(".")[2] print tempName if os.path.isfile(tempName): cmds.sysFile(tempName, rename=self.newName) print 'Renaming Temp name to: ' + self.newName
def CopyTexture(self): allFile=mc.ls(type="file") fullPath=mc.workspace(expandName="sourceimages") filePath="" fileName="" fileNames="" for files in allFile: buf=[] path=mc.getAttr("%s.fileTextureName"%files) if path=="": continue path = path.replace('\\','/') filePath=os.path.dirname(path) fileName=os.path.basename(path) if mc.getAttr("%s.useFrameExtension"%files): fileNames=fileName.split(".") buffers=mc.getFileList(filespec=(os.path.dirname(path)+"/*")) for buffer in buffers: NewFile = filePath+"/"+buffer if os.path.isfile(NewFile): buf.append(NewFile) # ==========2018.12.11===========add by zhangben ========== fix the file nodes use the tilling mode,the tool can't copy all maps= elif mc.attributeQuery('uvTilingMode', node=files, exists=True) and mc.getAttr('{}.uvTilingMode'.format(files)) == 3: fileNames = fileName.split(".") buffers = mc.getFileList(filespec=(os.path.dirname(path) + "/*")) for eamap in buffers: map_bnm = re.sub(u'_\d+', '', fileNames[0]) if eamap.find(map_bnm) != -1 and eamap.split('.')[-1] == fileNames[-1]: mapPath = filePath + "/" + eamap buf.append(mapPath) # =============================================================================================================================== else: buf.append(path) paths=filePath.split("/")[-1] for i in buf: fileNames=os.path.basename(i) if not os.path.isdir(fullPath+"/"+paths): os.makedirs(fullPath+"/"+paths) mc.sysFile(i,copy=(fullPath+"/"+paths+"/"+fileNames)) else: if not os.path.exists(fullPath+"/"+paths+"/"+fileNames) or (os.path.exists(fullPath+"/"+paths+"/"+fileNames) and os.path.getsize(fullPath+"/"+paths+"/"+fileNames) != os.path.getsize(i)): mc.sysFile(i,copy=(fullPath+"/"+paths+"/"+fileNames)) if os.path.isfile(fullPath+"/"+paths+"/"+fileName): print (fullPath+"/"+paths+"/"+fileName) mc.setAttr("%s.fileTextureName"%files,(fullPath+"/"+paths+"/"+fileName),type="string")
def takeSnapShot(targetObj, renderPath, rotX=-30.0, rotY=45.0, rotZ=0.0, resX=300, resY=300, useBoundingBox=False): ''' Take a snapshot of the selected object using the Maya renderer then move the image to a directory ''' # build the bounding box and find it's centre bBox = targetObj if useBoundingBox is True: bBox = buildBoundingBoxGeo(targetObj, noChildren=False, ignoreInv=True) focusPoint = cmds.xform(bBox, query=True, ws=True, t=True) # build the camera the move and orient it tempCam = cmds.camera(ar=True, ff=3, fl=35) camName = tempCam[1] cmds.setAttr(camName+'.renderable', True) cmds.setAttr(camName+'.displayFilmGate', True) cmds.setAttr(camName+'.displayResolution', True) cmds.setAttr(camName+'.backgroundColor', 0.5, 0.5, 0.5, type='double3') #transform cmds.move(focusPoint[0], focusPoint[1], focusPoint[2], tempCam, ws=True) cmds.rotate( rotX, rotY, rotZ, tempCam, ws=True) # build the bounding box then fit the camera cmds.select(bBox, r=True) cmds.viewFit(camName, an = False, f = 0.9 ) if useBoundingBox is True: cmds.delete(bBox) # set the render globals cmds.currentTime(1) cmds.setAttr('defaultRenderGlobals.imageFormat', 8) cmds.setAttr('defaultRenderQuality.edgeAntiAliasing', 0) cmds.setAttr('defaultRenderQuality.shadingSamples', 2) cmds.setAttr('defaultRenderQuality.maxShadingSamples', 8) cmds.setAttr('defaultRenderQuality.useMultiPixelFilter', 1) cmds.setAttr('defaultRenderQuality.enableRaytracing', 0) # build the lightrig lightRigGrp = cmds.group(em=True, name='lightRigGroup') lightMain = cmds.directionalLight(rotation=(-20, -45, 0), intensity=0.8) lightFill = cmds.directionalLight(rotation=(-20, 45, 0), intensity=0.4) lightUnder = cmds.directionalLight(rotation=(75, 0, 0), intensity=0.15) lightKey = cmds.directionalLight(rotation=(-25, 145, 0), intensity=4.0) cmds.parent([lightMain, lightFill, lightUnder, lightKey], lightRigGrp) cmds.rotate( rotX, rotY, rotZ, lightRigGrp, ws=True) # select everything, build the special shader, render, then delete everything cmds.select([targetObj, lightRigGrp], r=True) renderLayerName = cmds.createRenderLayer(name='tempSnapShot_rlayer', mc=True) shaderNodes = buildReverseNormalShader() #build the shader cmds.sets(targetObj, e=True, forceElement=shaderNodes[0]) #adding the shader here means it's in the render layer tempImage= cmds.render(camName, layer=renderLayerName, x=resX, y=resY) cmds.editRenderLayerGlobals(currentRenderLayer='defaultRenderLayer') cmds.delete([lightRigGrp, tempCam[0], renderLayerName, shaderNodes[0], shaderNodes[1], shaderNodes[2], shaderNodes[3]]) # copy the thumbnail to the desired location output = cmds.sysFile(tempImage, rename=renderPath) if output==True: print 'Path for thumbnail: ' + renderPath return renderPath return None
def snapShot(cam, objs, renderPath): # build the lightrig lightRigGrp = cmds.group(em=True, name='lightRigGroup') lightMain = cmds.directionalLight(rotation=(-20, -45, 0), intensity=0.8) lightFill = cmds.directionalLight(rotation=(-20, 45, 0), intensity=0.4) lightUnder = cmds.directionalLight(rotation=(75, 0, 0), intensity=0.15) lightKey = cmds.directionalLight(rotation=(-25, 145, 0), intensity=4.0) cmds.parent([lightMain, lightFill, lightUnder, lightKey], lightRigGrp) # select everything, build the special shader, render, then delete everything renderLayerName = cmds.createRenderLayer(name='tempSnapShot_rlayer', empty=True, mc=True) cmds.editRenderLayerMembers(renderLayerName, objs) cmds.editRenderLayerMembers(renderLayerName, lightRigGrp) shaderNodes = buildTempShader() #build the shader cmds.sets(objs, e=True, forceElement=shaderNodes[0]) #adding the shader here means it's in the render layer tempImage= cmds.render(cam, layer=renderLayerName) cmds.editRenderLayerGlobals(currentRenderLayer='defaultRenderLayer') cmds.delete(lightRigGrp, cam, renderLayerName) cmds.delete(shaderNodes) # copy the thumbnail to the desired location output = cmds.sysFile(tempImage, rename=renderPath) if output==True: print 'Path for thumbnail: ' + renderPath return renderPath return None
def exportCFX(chars, begin, end): 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( begin, end, tran.name(long=True), os.path.normpath( os.path.join( cfx, '{}.abc'.format(tran.name().split(':')[0])))) print cmd mc.sysFile(cfx, md=True) pm.AbcExport(j=cmd)
def checkAnimLocalPath(self, shotType=2, rebuild=0): import maya.cmds as mc # python用 animInfo = 'animInfoTemp' if rebuild: animInfo = 'animRebuild' shotInfo = self.checkShotInfo() localPathAnim = ('D:\\Info_Temp\\temp\\' + animInfo + '\\' + shotInfo[0] + '\\' + str(shotInfo[1]) + '\\' + str(shotInfo[2]) + '\\') if shotType == 3: localPathAnim = ('D:\\Info_Temp\\temp\\' + animInfo + '\\' + shotInfo[0] + '\\' + str(shotInfo[1]) + '\\' + str(shotInfo[2]) + '\\' + str(shotInfo[3]) + '\\') mc.sysFile(localPathAnim, makeDir=True) return localPathAnim
def rpr_render(case): logging('Render image') mel.eval('fireRender -waitForItTwo') start_time = time.time() mel.eval('renderIntoNewWindow render') cmds.sysFile(path.join(WORK_DIR, 'Color'), makeDir=True) test_case_path = path.join(WORK_DIR, 'Color', case['case']) cmds.renderWindowEditor('renderView', edit=1, dst='color') cmds.renderWindowEditor('renderView', edit=1, com=1, writeImage=test_case_path) test_time = time.time() - start_time reportToJSON(case, test_time)
def CleanGeo(): Uiinfo = myclass() if Uiinfo.result == 0: # Apply sourceObjects = Uiinfo.dlg.getValue("Load Objects") sourceObjects = sourceObjects.split(",") exportOnly = Uiinfo.dlg.getValue("Export Only") for entry in sourceObjects: cmds.select(clear = True) cmds.select(entry) if os.path.exists(TEMP_PATH+"/"+entry+"_clean.obj" ) == True: cmds.sysFile(TEMP_PATH+"/"+entry+"_clean.obj", delete = True) cmds.file(TEMP_PATH+"/"+entry+"_clean.obj", es = True, type = "OBJexport" ) cmds.setAttr (entry + ".visibility" , 0) cmds.file(TEMP_PATH+"/"+entry+"_clean.obj", i = True , type = "OBJ", ) cmds.rename(entry+"_clean_"+entry, entry+"_clean") cmds.sysFile(TEMP_PATH+"/"+entry+"_clean.obj", delete = True)
def daztomayaMenuFix(self): #Source Files: fileDaztomayaNew = os.path.expanduser("~/maya/plug-ins/IKMAX_Files/fix_dtm.py") fileDaztomayaMenuNew = os.path.expanduser("~/maya/plug-ins/IKMAX_Files/fix_dtmmenu.pyc") #Target to Overwrite: fileDaztomayaOld = os.path.expanduser("~/maya/plug-ins/DazToMaya.py") fileDaztomayaMenuOld = os.path.expanduser("~/maya/plug-ins/DazToMaya_Files/ikmax_menu.pyc") #Check if DazToMaya files found, overwrite them. if os.path.isfile(fileDaztomayaOld): try: cmds.sysFile( fileDaztomayaNew, copy=fileDaztomayaOld )# Windows cmds.sysFile( fileDaztomayaMenuNew, copy=fileDaztomayaMenuOld )# Windows except: pass
def objExport(selected, path): ''' Creates .obj files from a selection of objects @param: selected - a list of strings representing the geometry @param: path - a string to the path of the directory for .obj files to go @return: a list of strings that contain the full paths to all of the .obj files that were created @post: directory for 'path' is created if it wasn't already ''' # load the objExport plugin mc.loadPlugin("objExport") # Create directory if it doesn't exist if not os.path.exists(path): os.makedirs(path) size = len(selected) mc.sysFile(path, makeDir=True) optionsStr = "groups=0;ptgroups=0;materials=0;smoothing=0;normals=0;uvs=1" exportType = "OBJexport" objfiles = [] for geo in selected: mc.select(geo, r=True) geoName = geo + ".obj" # geoName = geoName.replace("Shape", "") # geoName = geoName.replace(":", "_") # geoName = geoName.replace("|", "_") geoName = formatFilename(geoName) filename = os.path.join(path, geoName) print("Exporting \'" + filename + "\'...") mc.file(filename, force=True, options=optionsStr, type=exportType, preserveReferences=True, exportSelected=True) print("\tCOMPLETED") objfiles.append(filename) return objfiles
def Pose_obj1(Animpose_name,currentImagePath): frameNumber = mc.currentTime(q=1) frameNumber =int(frameNumber) iconTmp = currentImagePath + "iconTmp." + str(frameNumber)+ ".bmp" print ("\niconTmp = " + iconTmp) Currnt_path=savepathini+'SavePose/' newposename=Animpose_name seltab1 = mc.shelfTabLayout('Poses',q=1,st=1) posefold=savepathini+'SavePose/Poses/'+seltab1+'/'+ newposename+'.anim' poseimg_path=savepathini+'SavePose/Poses/'+seltab1+'/' newPoseIconFile = poseimg_path + newposename +".bmp" if mc.file(posefold,q=1,ex=1): Overrite = mc.confirmDialog( title='Confirm Save Pose', message='Overwrite the existing pose: '+newposename+'?', button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if Overrite =='No': return mc.sysFile(iconTmp,copy=newPoseIconFile) files=open(posefold,'w') sel_obj = mc.ls(sl=1) for each in sel_obj: splitter = each.split(':') attrs =mc.listAttr(each,k=1,u=1) if(len(attrs)>0): if len(splitter)==1: files.write('obj '+splitter[0]+'\n') else: files.write('obj '+splitter[1]+'\n') for eachattr in attrs: locked = mc.getAttr((each+'.'+eachattr),l=1) if not locked: valStr = mc.getAttr((each+'.'+eachattr)) files.write(eachattr + " " +str(valStr) + '\n') files.close() print "Pose Saved" mc.shelfButton(newposename,i=newPoseIconFile,w=110,h=80,l=newposename,bgc=(.6, .2, .2),st='iconAndTextVertical',p=(seltab1),c=partial(Pose_rtn,posefold)) Refresh_UI(savepathini) mc.shelfTabLayout('tabs',e=1,st=Poses) mc.shelfTabLayout('Poses',e=1,st=seltab1) animposewinclose()
def RenderVray(): VrayMode = vrayStndAloneUI() if VrayMode == "standard": VrayScene = mkVrayVrscene() vrayCmd = "vray.exe -sceneFile=" + VrayScene + ' -display = 1 -autoClose=0 -verboseLevel = 4 -displaySRGB = 1 ' vrayRender(vrayCmd) elif VrayMode == "preview": VrayScene = mkVrayVrscene() vrayCmd = "vray.exe -sceneFile=" + VrayScene + ' -display = 1 -imgHeight = 405 -imgWidth = 720 -autoClose=0 -verboseLevel = 4 -displaySRGB = 1 ' vrayRender(vrayCmd) elif VrayMode == "draft": VrayScene = mkVrayVrscene() VrayCmd = "vray.exe -sceneFile=" + VrayScene + ' -display=1 -autoClose=0 -imgHeight = 405 -imgWidth = 720 -verboseLevel = 20 -rtEngine = 1 -rtNoise =.1 -displaySRGB = 1 ' vrayRender(VrayCmd) elif VrayMode == "SaveExr": files = cmds.file(query=1, list=1, withoutCopyNumber=1) shotname = files[0].split('.') shotname = shotname[0] shotID = shotname.split('/') shotID = shotID[6] thumbFileName = files[0].replace('.mb', '.vrimg') batFileName = files[0].replace('.mb', '.bat') batfile = ("%s") % batFileName VrayScene = mkVrayVrscene() vrayCmd = "vray.exe -sceneFile=" + VrayScene + ' -display = 1 -autoClose=0 -verboseLevel = 4 -displaySRGB = 0 -imgFile= %s' % ( thumbFileName) vrayRender(vrayCmd) t = 0 while (t < 3): try: os.rename(thumbFileName, thumbFileName) except: time.sleep(5) t += 1 vrimg2exr(thumbFileName, batfile) exrimg = thumbFileName.replace('.vrimg', '.exr') time.sleep(2) if os.path.exists(exrimg) == True: cmds.sysFile(batfile, delete=True) cmds.sysFile(thumbFileName, delete=True) elif VrayMode == False: print "Canceled" else: print "Unexpected VrayMode: %s" % VrayMode
def take_render_screenshot(self, renderer, output_path, extension, use_view_transform=True): """ Take a render. """ string_ext, id_ext = extension self.set_current_id_extension(int(id_ext)) cmds.setAttr("defaultRenderGlobals.imageFilePrefix", output_path, type="string") camera = self.get_camera() layer = "-layer defaultRenderLayer " if self.is_color_management_available(renderer): self.activate_color_management(use_view_transform) if renderer == "mayaSoftware": command = "render" tmp_output_path = mel.eval(command + layer + camera) cmds.sysFile(tmp_output_path, rename=output_path) elif renderer == "arnold": from mtoa.cmds.arnoldRender import arnoldRender string_ext = "jpeg" if string_ext == "jpg" else string_ext cmds.setAttr("defaultArnoldDriver.ai_translator", string_ext, type="string") path_without_extension = os.path.splitext(output_path)[0] cmds.setAttr("defaultArnoldDriver.pre", path_without_extension, type="string") arnoldRender(1920, 1080, True, True, camera, layer) elif renderer == "your_favourite_renderer": # Launch the render... pass else: raise RenderNotSupported( "The %s renderer is currently not supported. " "But you can still adapt the code to make the render accessible. " "You might want to look at the file %s" % (renderer, __file__))
def RenderVray(): VrayMode = vrayStndAloneUI() if VrayMode == "standard": VrayScene = mkVrayVrscene() vrayCmd = "vray.exe -sceneFile="+VrayScene+' -display = 1 -autoClose=0 -verboseLevel = 4 -displaySRGB = 1 ' vrayRender(vrayCmd) elif VrayMode == "preview": VrayScene = mkVrayVrscene() vrayCmd = "vray.exe -sceneFile="+VrayScene+' -display = 1 -imgHeight = 405 -imgWidth = 720 -autoClose=0 -verboseLevel = 4 -displaySRGB = 1 ' vrayRender(vrayCmd) elif VrayMode == "draft": VrayScene = mkVrayVrscene() VrayCmd = "vray.exe -sceneFile="+VrayScene+' -display=1 -autoClose=0 -imgHeight = 405 -imgWidth = 720 -verboseLevel = 20 -rtEngine = 1 -rtNoise =.1 -displaySRGB = 1 ' vrayRender(VrayCmd) elif VrayMode == "SaveExr": files = cmds.file(query=1, list=1, withoutCopyNumber=1) shotname = files[0].split( '.' ) shotname = shotname[0] shotID = shotname.split( '/' ) shotID = shotID[6] thumbFileName = files[0].replace( '.mb', '.vrimg' ) batFileName = files[0].replace( '.mb', '.bat' ) batfile = ("%s")%batFileName VrayScene = mkVrayVrscene() vrayCmd = "vray.exe -sceneFile="+VrayScene+' -display = 1 -autoClose=0 -verboseLevel = 4 -displaySRGB = 0 -imgFile= %s'%(thumbFileName) vrayRender(vrayCmd) t = 0 while (t < 3 ): try: os.rename (thumbFileName,thumbFileName) except: time.sleep(5) t+=1 vrimg2exr(thumbFileName,batfile) exrimg = thumbFileName.replace( '.vrimg', '.exr' ) time.sleep(2) if os.path.exists( exrimg ) == True: cmds.sysFile(batfile, delete = True) cmds.sysFile(thumbFileName, delete = True) elif VrayMode == False: print "Canceled" else: print "Unexpected VrayMode: %s" % VrayMode
def run(): path_obj = pft.PathDetails.parse_path(mc.file(q=1, sn=1)) startTime = int(mc.playbackOptions(ast=True, q=True)) endTime = int(mc.playbackOptions(aet=True, q=True)) cam_PublishFullPath_abc = defaultPath + '\{}\{}'.format( path_obj.seq, path_obj.shot) + '\{}'.format( path_obj.task) + '\\' + 'cam_{}_{}.abc'.format( path_obj.seq, path_obj.shot) mc.sysFile(os.path.dirname(cam_PublishFullPath_abc), md=True) cam = plb.getCameraInShot() if len(cam) == 1: mel.eval( 'AbcExport -j "-frameRange {} {} -stripNamespaces -worldSpace -root {} -file {}"' .format( str(startTime), str(endTime), mc.ls(mc.listRelatives(cam[0], p=True), l=True)[0], os.path.normpath(cam_PublishFullPath_abc).replace('\\', '/'))) else: mc.warning(u'请检查场景相机,有问题存在')
def ndPyLibExportCam(isImagePlane, isFbx, isAbc, frameHandle, CameraScale): if cmds.file(q=True, modified=True) == 1: ndPyLibPlatform('please save scene file...') else: filepath = cmds.file(q=True, sceneName=True) filename = os.basename(filepath) project = cmds.match('P:/Project/[a-zA-Z0-9]+/', filepath) roll = cmds.match('/roll[a-zA-Z0-9]+/', filepath) roll = cmds.match('roll[a-zA-Z0-9]+', roll) sequence = cmds.match('/s[0-9]+[a-zA-Z]*/', filepath) sequence = cmds.match('s[0-9]+[a-zA-Z]*/', filepath) shot = cmds.match('/c[0-9]+[a-zA-Z_]*/', filepath) shot = cmds.match('c[0-9]+[a-zA-Z_]*/', shot) shotpath = os.path.join(project, 'shots', roll, sequence, shot) publishpath = os.path.join(shotpath, 'publish', 'Cam', filename) oFilename = os.path.join(sequence, shot, '_cam') ndPyLibPlatform('project : ' + project) ndPyLibPlatform('roll : ' + roll) ndPyLibPlatform('sequence : ' + sequence) ndPyLibPlatform('shot : ' + shot) ndPyLibPlatform('filename : ' + filename) if os.exists(shotpath) != 1: ndPyLibPlatform('no exist folder...') else: if not os.exists(publishpath): os.mkdir(publishpath, md=True) outputfiles = ndPyLibExportCam_exportCamera( publishpath, oFilename, isImagePlane, isFbx, isAbc, frameHandle, CameraScale) for o in outputfiles: ndPyLibPlatform('output file : ' + o) for o in outputfiles: destFile = os.path.dirname( os.path.dirname(o)) + '/' + os.path.basename(o, '') cmds.sysFile(o, copy=destFile)
def merge(self,sourcePath,prfxToReplace,newModuleName): ## ------------------------------- first create temp module ## ------------------------------- then name elements properly scrpDir = mc.internalVar(userScriptDir=True) localModuleToMerge = os.path.join(scrpDir,newModuleName+'.01.ma') archive = zipfile.ZipFile(sourcePath, 'r') jsonFile = archive.open('data.ma') outputFile = open(localModuleToMerge, "w") for line in jsonFile: if prfxToReplace in line: nwLn = line.replace(prfxToReplace,newModuleName) outputFile.writelines( nwLn) else: outputFile.writelines(line) archive.close() outputFile.close() ## ------------------------------- inject it in your scene mc.file(localModuleToMerge,i=True) mc.sysFile(localModuleToMerge,delete=True) #now list new imported module content = mc.ls(type='transform') attributeList = ['foodType','uuID'] nwNode = [] for obj in content: idx = 0 for index, attr in enumerate(attributeList): if mc.attributeQuery(attributeList[index],node=obj,ex=True) == True: idx += 1 if idx > 1: nwNode.append(obj) mc.setAttr(nwNode[0] +'.uuID',l=False) mc.deleteAttr(nwNode[0] +'.uuID') foodTpe = mc.getAttr(nwNode[0] +'.foodType') OpenMaya.MGlobal.displayInfo( '**The %s dish %s was successfully merge in your scene'% (foodTpe, newModuleName) ) return nwNode[0]
def clear(*args): posesel=[] seltab = mc.shelfTabLayout('tabs',q=1,st=1) seltab1= mc.shelfTabLayout(seltab,q=1,st=1) seltab2= mc.shelfLayout(seltab1,q=1,ca=1) if seltab2==None : NoTab(seltab) else: confirm=mc.confirmDialog(message='Do you want to delete all '+seltab+' in the selected tab ?', ma='center', button=['Yes','No'] ,defaultButton='Yes',cancelButton='No',dismissString='No') if confirm=='Yes': seltab1= mc.shelfTabLayout(seltab,q=1,st=1) #seltab2= mc.shelfLayout(seltab1,q=1,ca=1) posesel= mc.shelfLayout(seltab1,q=1,ca=1) for i in range (len(posesel)): print posesel[i] mc.deleteUI(posesel[i]) #return deletefold=savepathini+'savepose/'+seltab+'/'+seltab1+'/' seltab1= mc.shelfTabLayout(seltab,q=1,st=1) list_in=mc.getFileList(fld=deletefold) for i in range(len(list_in)): mc.sysFile(deletefold+list_in[i],delete=1)
def mkMoveToIngDir(zipFile,thumbnail): zipfileName = zipFile.split("/") zipfileName = zipfileName[-1] depotFolder = zipfileName.replace( ".zip", "" ) dst = depotIngPath +"/"+ depotFolder if os.path.exists( dst ) == False: cmds.sysFile( dst, makeDir=True ) dstFile = dst+"/"+zipfileName cmds.sysFile( zipFile, move = dstFile ) thmbFile = thumbnail.split("/") thmbFile = thmbFile[-1] thumDstFile = dst+"/"+thmbFile cmds.sysFile( thumbnail, move = thumDstFile ) return dstFile
def createAsset(self): f = cmds.optionMenu("assetsList", q=1, value=1) #to create the selected asset in the required scene folder - will be mentioned in csv file for i in range(len(self.list)): if self.list[i][1]==f: dept=self.list[i][0] scenenum=self.list[i][2].zfill(3) #make sure its always 3 digits del self.list[i] break pathf = os.path.join(rootpath, dept, 'scene'+scenenum) path = os.path.join(pathf, f.replace(" ", "_")+'_v000.ma') #to create version _v000 bool = cmds.sysFile( pathf, makeDir=True ) #make it a directory cmds.file(rn=path); cmds.file(save=1) #renaming and saving have to be done seperately csvfile = open('D:\Work.Area\Siddharth-ShotManager\data.csv', 'wb') #open csv in write mode - will overwrite the file's contents #this is to rewrite the file to erase the already opened file writer = csv.writer(csvfile, delimiter=',') for row in self.list: writer.writerow(row) self.changeRequests() #show change in the list
def snapshots(*args, **kwargs): """ in GUI mode, renders snapshots of the model views returns reportsDir render_snapshots() -> string """ t0 = float(time.time()) try: verbose = kwargs["verbose"] except KeyError: verbose = False if cmds.optionVar(exists="checkmateVerbosity"): verbose = cmds.optionVar(query="checkmateVerbosity") else: pass # check that we;re running in GUI mode if cmds.about(batch=True): print "You can't create a render view in batch mode" return 1 # turn off the heads-up diplay cmds.headsUpDisplay(layoutVisibility=False) # clear selection cmds.select(clear=True) _userWorkspaceDir = cmds.internalVar(userWorkspaceDir=True) scene = cmds.file(query=True, sn=True, shn=True) or "unknown.mb" (root, ext) = os.path.splitext(scene) fullscenepath = cmds.file(query=True, sn=True, shn=False) or "unknown.mb" fullscenedirname = os.path.dirname(fullscenepath) if fullscenedirname == "": fullscenedirname = os.path.join(_userWorkspaceDir, "reports") reportname = "".join([root, ext.replace(".", "_")]) img_dir = os.path.join(fullscenedirname, reportname) # before we render, save render globals presets cmds.nodePreset(save=("defaultRenderQuality", "ttRestorePreviousDefaultRenderViewPreset")) cmds.nodePreset(save=("defaultRenderGlobals", "ttRestorePreviousDefaultRenderViewPreset")) cmds.nodePreset(save=("defaultResolution", "ttRestorePreviousDefaultRenderViewPreset")) # override the user settings cmds.setAttr("defaultRenderGlobals.imageFormat", 32) ext = ".png" # set resolution ot 320x240 cmds.setAttr("defaultResolution.width", 320) cmds.setAttr("defaultResolution.height", 240) cmds.setAttr("defaultResolution.deviceAspectRatio", (float(320) / float(240))) # set file format to png cmds.setAttr("defaultRenderGlobals.imageFormat", 32) ext = ".png" # bring up the render view if not cmds.window("renderViewWindow", exists=True): cmds.RenderViewWindow() # cameras to render cameras = ["top", "front", "side", "persp"] for camera in cameras: mel.eval("".join(["renderWindowRenderCamera snapshot renderView ", camera])) image = "".join([camera, ext]) # we can get the path from the report class instance imagepath = os.path.join(img_dir, image) if verbose: print "imagepath : %s " % imagepath # delete the images before saving cmds.sysFile(imagepath, delete=True) cmds.renderWindowEditor("renderView", edit=True, writeImage=imagepath) # restore the node presets # globalsNodes = cmds.renderer( 'mayaSoftware', query=True, globalsNodes=True) try: cmds.nodePreset(load=("defaultRenderQuality", "ttRestorePreviousDefaultRenderViewPreset")) except LockedAttrError: print "Cannot restore defaultRenderQuality to defaults" try: cmds.nodePreset(load=("defaultRenderGlobals", "ttRestorePreviousDefaultRenderViewPreset")) except LockedAttrError: print "Cannot restore defaultRenderGlobals to defaults" try: cmds.nodePreset(load=("defaultResolution", "ttRestorePreviousDefaultRenderViewPreset")) except LockedAttrError: print "Cannot restore defaultRenderGlobals to defaults" # turn the heads-up diplay back on cmds.headsUpDisplay(layoutVisibility=True) print "%-24s : %.6f seconds" % ("render.snapshots()", (float(time.time()) - t0)) return img_dir
def _ExportAsFBX(assets, isUnity=False, postfix="", *args): global _ToolUI, _path #select the assets cmds.select(assets) if(_path): #get all the necessary attributes folder=cmds.textField(_ToolUI["txt_folderName"], q=True, text=True) if not cmds.file("%s/%s" % (_path, folder), q=True, exists=True): cmds.sysFile("%s/%s" % (_path, folder), makeDir=True) pass assetName = cmds.textField(_ToolUI["txt_assetName"], q=True, text=True) if not assetName: log.warning("Asset Name is empty") return #load fbx pluginif it is not loaded if not cmds.pluginInfo("fbxmaya", q=True, l=True): cmds.loadPlugin("fbxmaya") #set FBXExport options mel.eval("FBXExportSmoothingGroups -v true") mel.eval("FBXExportHardEdges -v false") mel.eval("FBXExportTangents -v false") mel.eval("FBXExportSmoothMesh -v true") mel.eval("FBXExportInstances -v false") mel.eval("FBXExportReferencedContainersContent -v false") # Animation mel.eval("FBXExportAnimationOnly -v false") #mel.eval("FBXExportBakeComplexAnimation -v false") #mel.eval("FBXExportBakeComplexStart -v 0") #mel.eval("FBXExportBakeComplexEnd -v 24") #mel.eval("FBXExportBakeComplexStep -v 1") #mm.eval("FBXExportBakeResampleAll -v true") mel.eval("FBXExportUseSceneName -v false") mel.eval("FBXExportQuaternion -v euler") mel.eval("FBXExportShapes -v true") mel.eval("FBXExportSkins -v true") # Constraints mel.eval("FBXExportConstraints -v false") # Cameras mel.eval("FBXExportCameras -v false") # Lights mel.eval("FBXExportLights -v false") # Embed Media mel.eval("FBXExportEmbeddedTextures -v false") # Connections mel.eval("FBXExportInputConnections -v false") # Axis Conversion mel.eval("FBXExportUpAxis y") #mel.eval('FBXExport -f "%s" -s' % (path + "/" + folder + "/" + assetName + ".fbx")) # catch any exceptions during the process try: #make a string with all the attributes file = (_path + "/" + folder + "/" + assetName + postfix + ".fbx") #export the assets mel.eval('FBXExport -f "%s" -s' % file) #display where the file is exported log.info ("file " + cmds.file(file, q=True, loc=True) + " exported" ) except Exception as e: #display any exception that occurs during the process cmds.confirmDialog( title='FBX export Exception', message='The export failed due to %s' % e.message, button=['OK'], defaultButton='OK', icn="critical" ) else: log.warning("Unity Project Directory not selected") pass
def Anim_obj1(Animpose_name,currentImagePath): Val1=mc.floatField('Start_F',q=1,v=1) Val2=mc.floatField('End_F',q=1,v=1) Val1=str(Val1);Val2=str(Val2) frm_rang="("+str(Val1)+'-'+str(Val2)+")" frameNumber = mc.currentTime(q=1) frameNumber =int(frameNumber) iconTmp = currentImagePath + "iconTmp." + str(frameNumber)+ ".bmp" print ("\niconTmp = " + iconTmp) Currnt_path=savepathini+'SavePose/' Anim_newname=Animpose_name+frm_rang testpath = savepathini seltab5 = mc.shelfTabLayout('Animation',q=1,st=1) animpath = (testpath + 'SavePose/Animation/'+seltab5+'/') animpath1= animpath animpath2= animpath1 + Anim_newname + '.anim' newAnimIconFile = animpath1 + Anim_newname +".bmp" if mc.file(animpath2,q=1,ex=1): Overrite = mc.confirmDialog( title='Confirm Save Anim', message='Overwrite the existing anim: '+Anim_newname+'?', button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if Overrite =='No': return mc.sysFile(iconTmp,copy=newAnimIconFile) sel_obj = mc.ls(sl=1) chkanim=mc.listConnections(sel_obj,t='animCurve',d=0) if chkanim==None: mc.confirmDialog (title='Error' ,message= 'Selected object has no anim', button=['OK'] ,defaultButton='Yes') return print '\nWriting Animation Curves...\n' fileID = open(animpath2,'w') fileID.write('#Generated by Anim_Poselib.py\n#\n#poselib written by Sreekanth.S.R\n#[email protected]\n#\n') if ":" in sel_obj[0]: ref_name = sel_obj[0].split(':')[0] else: ref_name = sel_obj[0] fileID.write('Asst_name '+ ref_name+'\n') fileID.write('frameRange '+Val1+'\n') for item in sel_obj: shortItem= mc.ls(item,sl=1) channels = mc.listConnections(item,t='animCurve', d = 0) if channels: for chan in channels: connects= mc.listConnections(chan,p=1) curattr = connects[0].split('.') num = len(curattr) buffer=curattr num = num - 1 node='' for i in range(num): if i==0: node=buffer[i] else: node=node+'.'+buffer[i] nodeTemp=[] nodeTemp = mc.ls(node) attr = buffer[num] node = nodeTemp[0] nodeTemp = mc.listRelatives(node,p=1) if nodeTemp != None : parent1 = 1 elif nodeTemp == None : parent1 = 0 testit =mc.listAnimatable(connects) # if Val1==Val2: # testit2=mc.keyframe(chan,q=1) # else: testit2=mc.keyframe(chan,q=1,time=(Val1,Val2)) if testit and testit2: evalme = mc.getAttr(chan + '.preInfinity') if evalme == 0: preIn = 'constant' if evalme == 1: preIn = 'linear' if evalme == 2: preIn = 'constant' if evalme == 3: preIn = 'cycle' if evalme == 4: preIn = 'cycleRelative' if evalme == 5: preIn = 'oscillate' evalme = mc.getAttr (chan + '.postInfinity') if evalme == 0: postIn = 'constant' if evalme == 1: postIn = 'linear' if evalme == 2: postIn = 'constant' if evalme == 3: postIn = 'cycle' if evalme == 4: postIn = 'cycleRelative' if evalme == 5: postIn = 'oscillate' evalme = mc.getAttr (chan + '.weightedTangents') weighted = evalme fileID.write('anim ' + attr + ' ' + attr + ' ' + node + ' ' + str(parent1) + ' 0 0\n' ) fileID.write('animData \n') fileID.write(' weighted ' + str(weighted) + '\n') fileID.write(' preInfinity ' + preIn + '\n') fileID.write(' postInfinity ' + postIn + '\n') fileID.write(' keys {\n') breakDown=[] # if Val1==Val2: # keys = mc.keyframe(chan,q=1) # values = mc.keyframe (chan,q=1,vc=1) # inTan = mc.keyTangent(chan,q=1,itt=1) # outTan = mc.keyTangent(chan,q=1,ott=1) # tanLock= mc.keyTangent (chan,q=1,lock=1) # weightLock=mc.keyTangent(chan,q=1,weightLock=1) # breakDown= mc.keyframe (chan,q=1,breakdown=1) # inAngle= mc.keyTangent (chan,q=1,inAngle=1) # outAngle= mc.keyTangent (chan,q=1,outAngle=1) # inWeight= mc.keyTangent (chan,q=1,inWeight=1) # outWeight= mc.keyTangent (chan,q=1,outWeight=1) # else: keys = mc.keyframe(chan,q=1,time=(Val1,Val2)) values = mc.keyframe (chan,q=1,vc=1,time=(Val1,Val2)) inTan = mc.keyTangent(chan,q=1,itt=1,time=(Val1,Val2)) outTan = mc.keyTangent(chan,q=1,ott=1,time=(Val1,Val2)) tanLock= mc.keyTangent (chan,q=1,lock=1,time=(Val1,Val2)) weightLock=mc.keyTangent(chan,q=1,weightLock=1,time=(Val1,Val2)) breakDown= mc.keyframe (chan,q=1,breakdown=1,time=(Val1,Val2)) inAngle= mc.keyTangent (chan,q=1,inAngle=1,time=(Val1,Val2)) outAngle= mc.keyTangent (chan,q=1,outAngle=1,time=(Val1,Val2)) inWeight= mc.keyTangent (chan,q=1,inWeight=1,time=(Val1,Val2)) outWeight= mc.keyTangent (chan,q=1,outWeight=1,time=(Val1,Val2)) for i in range (len(keys)): bd=0 if breakDown!=None: for bd_item in breakDown: if bd_item == keys[i]: bd=1 fileID.write(' ' + str(keys[i]) + ' ' + str(values[i])+ ' ' + str(inTan[i]) + ' ' + str(outTan[i]) + ' ' + str(tanLock[i]) + ' ' + str(weightLock[i]) + ' ' + str(bd)) if inTan[i]=='fixed': fileID.write(' ' + str(inAngle[i]) + ' ' + str(inWeight[i])) if outTan[i]=='fixed': fileID.write(' ' + str(outAngle[i]) + ' ' + str(outWeight[i])) fileID.write('\n') fileID.write(' }\n}\n') staticChans = mc.listAnimatable(item) for staticChan in staticChans: curAttr = staticChan curattr = curAttr.split('.') num = len(curattr) buffer=curattr num = num - 1 node='' for i in range(num): if i==0: node=buffer[i] else: node=node+'.'+buffer[i] nodeTemp=[] nodeTemp = mc.ls(node) attr = buffer[num] node = nodeTemp[0] nodeTemp = mc.listRelatives(node,p=1) if nodeTemp != None : parent1 = 1 elif nodeTemp == None : parent1 = 0 staticChan = (node + "." + attr) testit = mc.keyframe (staticChan,q=1) connected = mc.listConnections(staticChan,d=0) if not testit and not connected : fileID.write('static ' + attr + ' ' + attr + ' ' + node + ' ' + str(parent1) + ' ' + str(mc.getAttr(staticChan)) + '\n') fileID.write('End of Anim') fileID.close() mc.select(clear = True) for item in sel_obj: mc.select(item, toggle = True) print "\nDone Writing Animation Curves\n" #print frm_rang mc.shelfButton(Anim_newname,i1=newAnimIconFile,w=110,h=80,l=Anim_newname,bgc=(.2,.6,.3),st='iconAndTextVertical',p=(seltab5),c=partial(Importanim,animpath2)) Refresh_UI(savepathini) mc.shelfTabLayout('tabs',e=1,st=Animation) mc.shelfTabLayout('Animation',e=1,st=seltab5) animposewinclose()
def setupScene(): global util errormsgs = [] util = Utils.utils() chks = ['keychk', 'rimchk','colchk','occchk','rgbachk','gshchk','matchk'] chkstats = [mc.checkBox(x, q = True, v = True) for x in chks] if not 1 in chkstats: mc.confirmDialog(t='Warning', m = 'No layers are selected', b='OK', ma = "center") return #get dict of assets in their respective render layer groups grpDict = findGrpDict() layergrps = grpDict.keys() layergrps.sort() #find the path of the file, check naming of file and query the timeline filepath = mc.file(q = True, sn = True) filename = os.path.basename(filepath) fildir = os.path.dirname(filepath) refcut = mc.checkBox("refchk", q = True, v = True) try: shotname = filename.split("_")[1] except: mc.confirmDialog(t='Warning', m = 'Scene name is not correct', b='OK', ma = "center") return shstart = mc.playbackOptions(q = True, ast = True) shend = mc.playbackOptions(q = True, aet = True) #query the camera and the camera group cam = mc.optionMenu('camlite', q = True, v = True) #setup the name of the new files clfile = filename[:-9] + "cl" + filename[-7:] #check the file exists, then change to vesion folder curr_path = fildir+'/' clfilepath=curr_path+clfile if mc.file(clfilepath,q=1,ex=1): Overrite = mc.confirmDialog( title='Confirm ', message='Overwrite the existing file? ', button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if Overrite =='No': return chkpath=mc.getFileList (folder=curr_path) ver_count=chkpath.count('ver') verpath= curr_path+'ver/' if not ver_count: mc.sysFile(verpath,makeDir=1) # else: # verpath= curr_path+'ver/' files = [ f for f in os.listdir(verpath) if (os.path.isfile (os.path.join(verpath,f))) and f[len(f)-3:len(f)]=='.ma'] if files: ver = str(len(files)+1) else: ver='01' newpath=verpath+clfile mc.sysFile(filepath,copy=newpath) newname=clfile[:19]+'%s.ma'%ver.zfill(2) chgname=verpath+newname mc.sysFile(newpath,rename=chgname) #select all the assets specified in the setup window to export to a new file selasts = [] refcutmiss = [] for each in layergrps: for ast in grpDict[each]: selasts.append(ast) #add the camera to the selection selasts.append(cam) #add the ground and matte groups to the selection if they exist, else warn that they have not been setup gndmteobjs = ["Grp_Ground", "Grp_Matte"] if mc.objExists("Grp_Ground"): gndmteobjs.pop(gndmteobjs.index("Grp_Ground")) selasts.append("Grp_Ground") if mc.objExists("Grp_Matte"): gndmteobjs.pop(gndmteobjs.index("Grp_Matte")) selasts.append("Grp_Matte") if gndmteobjs: gndmtemsg = "\n".join(gndmteobjs) rslt = mc.confirmDialog(t='Warning', m="Ground/Matte Objects dont\nexist or havent been set up", b=['Continue', 'Cancel'], db='Continue', cb='Cancel', ds='Cancel', ma = 'center') if rslt == 'Cancel': return else: pass mc.select(selasts, r = True) #cmfile = filename[:-9] + "cm" + filename[-7:] #export all selected assets, cameras and ground/matte groups to a new _cl_v00 file mc.file((fildir + "/" + clfile), op = "v=0", typ = "mayaAscii", pr = True, es = True, f=True ) #force open the new _cl_v00 file without saving the old one mc.file((fildir + "/" + clfile), op = "v=0", typ = "mayaAscii", lrd = "all", o = True, f = True) #select camera and export selected camera to a new _cm_v00 file #mc.select(cam, r = True) #mc.file((fildir + "/" + cmfile), op = "v=0", typ = "mayaAscii", pr = True, es = True) mc.select(cl = True) #set the timeline and render globals, and move assets to their respective groups mc.playbackOptions(e = True, ast = shstart) mc.playbackOptions(e = True, aet = shend) setrendglobals(shotname, shstart, shend) try: Utils.moveAssetsToGrps() except: pass #setup the useBackground shader and assign it to the ground/matte objects if they exist gndusebg = "groundmatteuseBGshader" if mc.objExists(gndusebg): mc.delete(gndusebg) gndusebg = mc.shadingNode("useBackground", asShader = True, n = gndusebg) mc.setAttr((gndusebg + ".specularColor"), 0, 0, 0, type = "double3") mc.setAttr((gndusebg + ".reflectivity"), 0) mc.setAttr((gndusebg + ".reflectionLimit"), 0) mc.setAttr((gndusebg + ".shadowMask"), 0) if mc.objExists("Grp_Ground"): mc.select("Grp_Ground", r = True) mc.hyperShade(assign = gndusebg) if mc.objExists("Grp_Matte"): mc.select("Grp_Matte", r = True) mc.hyperShade(assign = gndusebg) #query the rim/key light required and import the relevant light file from /assets/lighting locquery = mc.optionMenu('Location', q = True, v = True) rmkylight = mc.optionMenu('Time', q = True, v = True) camquery = mc.optionMenu('camlite', q = True, v = True) rmkyfile = "%s/%s/Location/%s/%s_rimkey.ma"%(util.path, util.litePath,locquery,rmkylight) rimliteL = "%s:rimL"%rmkylight rimliteR = "%s:rimR"%rmkylight #refdoom = "%s:ref_doom"%rmkylight keylite = "%s:key"%rmkylight #fillite = "%s:fill"%rmkylight #eyespec = "%s:eyespc"%rmkylight if os.path.exists(rmkyfile): if mc.objExists(rimliteL): mc.delete(rimliteL) if mc.objExists(rimliteR): mc.delete(rimliteR) #if mc.objExists(fillite): #mc.delete(fillite) if mc.objExists(keylite): mc.delete(keylite) mc.file(rmkyfile, i = True, typ = "mayaAscii", ra = True, ns = rmkylight, op = "v=0;p=17", pr = True) else: mc.confirmDialog(t='Warning', m = '%s file is not accessible'%rmkylight, b='OK', ma = "center") return #find the names of the imported rim/key lights in the scene and parent them to the 'Rim_key' group if mc.objExists("LIGHTS"): mc.delete("LIGHTS") sclites = mc.ls(type = "light") for each in sclites: if ":rimL" in each: rimliteL = mc.listRelatives(each, p = True)[0] elif ":rimR" in each: rimliteR = mc.listRelatives(each, p = True)[0] #elif ":fill" in each: #fillite = mc.listRelatives(each, p = True)[0] elif ":key" in each: keylite = mc.listRelatives(each, p = True)[0] keygrp = "%s:key_set"%rmkylight mc.group(n = "LIGHTS", em = True) mc.parent(keygrp,"LIGHTS" ) #query common lights required and import the relevant light file from /assets/lighting/commonlights commonfile = "%s/%s/common_lights/common_lights.ma"%(util.path, util.litePath) commonlight="commonlight" #litequery=mc.optionMenu('amblite',q=True,v=True) #GIrAMB = "%s:%s"%(commonlight,litequery) if os.path.exists(commonfile): if mc.objExists(commonlight): mc.delete(commonlight) mc.file(commonfile, i = True, typ = "mayaAscii", ra = True, ns = commonlight, op = "v=0;p=17", pr = True) else: mc.confirmDialog(t='Warning', m = '%s file is not accessible'%commonlight, b='OK', ma = "center") return #mc.parent("commonlight:commonLight_sets","LIGHTS" ) #spclite_parnt=mc.parent(spclite,camquery) #find shape node of key light if mc.objExists(keylite): keyliteshp = mc.listRelatives(keylite, c = True, s = True) #setup the mat shaders rgbashaders = rgbashader(shotname) mc.select(cl = True) myShader = mc.shadingNode('lambert', asShader=True) mc.setAttr (myShader+".colorR", 0.886) mc.setAttr (myShader+".colorG" ,0.961) mc.setAttr (myShader+".colorB" ,0.961) # assign cam folder if camquery[14:] =='Ct': camname = "Center" elif camquery[14:]=='Lt': camname = "Left" else: camname = "Right" #remove all existing render layers mc.editRenderLayerGlobals(crl = "defaultRenderLayer") renlyrs = mc.ls(type = "renderLayer") for each in renlyrs: if not "defaultRenderLayer" in each: mc.delete(each) #cut the references of all assets if marked so in the light setup options for each in layergrps: for ast in grpDict[each]: if refcut: try: cutref(ast) except: refcutmiss.append(ast) #main loop for creating all the render layers with their respective settings working on each render layer group per loop sqname = shotname[:5] shname = shotname[5:] matindex = 0 for lyr in layergrps: asts = grpDict[lyr] #create key layer, add key light if mc.checkBox("keychk", q = True, v = True): keylayer = (lyr + 'key') mc.select(asts, r = True) mc.select(keylite, add = True) #mc.select(refdoom, add = True) #mc.select(eyespec, add = True) if mc.objExists("Grp_Ground"): mc.select("Grp_Ground", add = True) if mc.objExists("Grp_Matte"): mc.select("Grp_Matte", add = True) mc.createRenderLayer(mc = True, n = keylayer) mc.editRenderLayerAdjustment(gndusebg + ".shadowMask") mc.setAttr(gndusebg + ".miOcclusionMask", 0) mc.connectAttr(keylayer+'.renderPass', 'diff.owner',nextAvailable=True) mc.connectAttr(keylayer+'.renderPass', 'amb.owner', nextAvailable=True) mc.connectAttr(keylayer+'.renderPass', 'sha.owner', nextAvailable=True) mc.connectAttr(keylayer+'.renderPass', 'spc.owner', nextAvailable=True) mc.connectAttr(keylayer+'.renderPass', 'inc.owner',nextAvailable=True) fileprefix = "%s/%s/%s/ch/%s/<RenderLayer>/<RenderPass>/%s%s_<RenderLayer>_<RenderPass>_v01"%(sqname,shname,camname,lyr,sqname,shname) mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix") mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string") mc.editRenderLayerAdjustment('miDefaultOptions.rayTracing') mc.setAttr('miDefaultOptions.rayTracing',1) mc.editRenderLayerAdjustment( 'miDefaultOptions.maxReflectionRays' ) mc.setAttr('miDefaultOptions.maxReflectionRays', 3) mc.editRenderLayerAdjustment( 'miDefaultOptions.maxRefractionRays' ) mc.setAttr('miDefaultOptions.maxRefractionRays', 0) mc.editRenderLayerAdjustment( 'miDefaultOptions.maxRayDepth') mc.setAttr('miDefaultOptions.maxRayDepth',20) #create rim layer, add rimlight if mc.checkBox("rimchk", q = True, v = True): rimlayer = (lyr + 'rim') mc.select(asts, r = True) mc.select(rimliteL, add = True) mc.select(rimliteR, add = True) mc.createRenderLayer(mc = True, n = rimlayer) rimsh='%s:Rimshader'%commonlight #mc.shadingNode("lambert", asShader = True, n = rimsh ) #mc.setAttr((rimsh+'.color'),1, 1, 1, type = "double3") #mc.setAttr((rimsh+'.diffuse'),1) mc.select(rimsh) mel.eval('hookShaderOverride("%s","","%s")'%(rimlayer,rimsh)) fileprefix = "%s/%s/%s/ch/%s/<RenderLayer>/%s%s_<RenderLayer>_v01"%(sqname, shname,camname,lyr, sqname, shname) mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix") mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string") mc.editRenderLayerAdjustment('miDefaultOptions.rayTracing') mc.setAttr('miDefaultOptions.rayTracing',0) #create col layer,add amb light if mc.checkBox("colchk",q= True,v = True): collayer= (lyr+ 'col') mc.select(asts, r = True) Col_light='%s:colLight'%commonlight mc.select(Col_light,add=True) mc.createRenderLayer(mc = True, n = collayer) mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix") mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string") #create occ layer if mc.checkBox("occchk",q=True,v=True): occlayer = (lyr + 'occ') mc.select(asts,r=True) if mc.objExists("Grp_Ground"): mc.select("Grp_Ground", add = True) if mc.objExists("Grp_Matte"): mc.select("Grp_Matte", add = True) mc.createRenderLayer(mc = True, n = occlayer) mel.eval("renderLayerBuiltinPreset occlusion %s "%occlayer) ShaderList=mc.ls (sl=1) Mib_Amb=mc.listConnections(ShaderList,t='mib_amb_occlusion') mc.setAttr(Mib_Amb[0]+'.samples',64) mc.setAttr(Mib_Amb[0]+'.spread',0.8) mc.setAttr(Mib_Amb[0]+'.max_distance',20) fileprefix = "%s/%s/%s/ch/%s/<RenderLayer>/%s%s_<RenderLayer>_v01"%(sqname, shname,camname,lyr, sqname, shname) mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix") mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string") #create mat layer and assign r, g and b shaders in turn using matindex, turn off raytracing using layer override if mc.checkBox("rgbachk", q = True, v = True): rgbalayer = (lyr + 'rgba') mc.select(asts, r = True) mc.createRenderLayer(mc = True, n = rgbalayer) for i in range(len(asts)): shindex = matindex%4 matindex += 1 mc.select(asts[i], r = True) mc.hyperShade(assign = rgbashaders[shindex]) fileprefix = "%s/%s/%s/ch/%s/<RenderLayer>/%s%s_<RenderLayer>_v01"%(sqname, shname,camname,lyr, sqname, shname) mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix") mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string") mc.setAttr('miDefaultOptions.rayTracing',0) #create ground shadow layer, add key light and turn on shadow mask of useBG shader using layer override if mc.checkBox("gshchk", q = True, v = True): gshlayer = (lyr + 'gsh') mc.select(asts, r = True) mc.select(keylite, add = True) if mc.objExists("Grp_Ground"): mc.select("Grp_Ground", add = True) if mc.objExists("Grp_Matte"): mc.select("Grp_Matte", add = True) mc.createRenderLayer(mc = True, n = gshlayer) mc.editRenderLayerAdjustment(gndusebg + ".shadowMask") mc.setAttr(gndusebg + ".shadowMask", 1) fileprefix = "%s/%s/%s/ch/%s/<RenderLayer>/%s%s_<RenderLayer>_v01"%(sqname, shname,camname,lyr, sqname, shname) mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix") mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string") mc.editRenderLayerAdjustment('miDefaultOptions.rayTracing') mc.setAttr('miDefaultOptions.rayTracing',1) mc.editRenderLayerAdjustment( 'miDefaultOptions.maxReflectionRays' ) mc.setAttr('miDefaultOptions.maxReflectionRays', 0) mc.editRenderLayerAdjustment( 'miDefaultOptions.maxRefractionRays' ) mc.setAttr('miDefaultOptions.maxRefractionRays', 0) mc.editRenderLayerAdjustment( 'miDefaultOptions.maxRayDepth') mc.setAttr('miDefaultOptions.maxRayDepth',20) #turn off receive shadows and primary visibility of the all the assets using changespreadattr() for ast in asts: changespreadattr(ast, "receiveShadows", 0) changespreadattr(ast, "primaryVisibility", 0) #create mat layer if mc.checkBox("matchk",q= True, v = True): matlayer = (lyr + 'mat') mc.select(asts, r = True) Zdep='%s:Zdepthshader'%commonlight mc.select(asts, r = True) mc.createRenderLayer(mc = True, n = matlayer) mc.select(Zdep) mel.eval('hookShaderOverride("%s","","%s")'%(matlayer,Zdep)) mc.connectAttr(matlayer+'.renderPass', 'camnml.owner', nextAvailable=True) mc.connectAttr(matlayer+'.renderPass', 'nml.owner', nextAvailable=True) fileprefix = "%s/%s/%s/ch/%s/<RenderLayer>/<RenderPass>/%s%s_<RenderLayer>_<RenderPass>_v01"%(sqname,shname,camname,lyr,sqname,shname) mc.editRenderLayerAdjustment ("defaultRenderGlobals.imageFilePrefix") mc.setAttr("defaultRenderGlobals.imageFilePrefix", fileprefix, type = "string") mc.editRenderLayerAdjustment('miDefaultOptions.rayTracing') mc.setAttr('miDefaultOptions.rayTracing',0) mc.editRenderLayerAdjustment( 'miDefaultOptions.maxReflectionRays' ) mc.setAttr('miDefaultOptions.maxReflectionRays', 1) mc.editRenderLayerAdjustment( 'miDefaultOptions.maxRefractionRays' ) mc.setAttr('miDefaultOptions.maxRefractionRays', 1) mc.editRenderLayerAdjustment( 'miDefaultOptions.maxRayDepth') mc.setAttr('miDefaultOptions.maxRayDepth',1) mc.editRenderLayerGlobals(crl = "defaultRenderLayer") mc.setAttr("defaultRenderLayer.renderable",0) mc.select(cl = True) # mc.checkBoxGrp ('enableColorProfile',e=1,v1=1) # mc.optionMenuGrp('inputColorProfile',e=1,enable=1) # mc.optionMenuGrp('outputColorProfile',e=1,enable=1) # mc.optionMenuGrp('inputColorProfile',e=1 ,sl=1 ) # mc.optionMenuGrp('outputColorProfile',e=1 ,sl=2) # mc.setAttr ("defaultRenderGlobals.inputColorProfile",1) # mc.setAttr ("defaultRenderGlobals.outputColorProfile",2) mc.confirmDialog(t='Message', m = 'Scene setup completed successfully', b='OK', ma = "center")
def submit(self,*args): self.info("starting submit") self.config = self.readAllInputs() _write_config("submit",self.config) for label in ["sharedPath","baseURL","username","password"]: if not self.config[label]: self.message('%s is not set' % (label)) return if not check_saved(): self.message( "Project must be saved first") return if not cmds.file(query=True, sceneName=True).startswith(self.config["sharedPath"]) or not self.project_directory(): self.message('Project is not saved on shared path') return login_url = urlparse.urljoin(self.config['baseURL'], 'admin/') add_url = urlparse.urljoin(login_url, 'tasks/mayaproject/add/') cookies = urllib2.HTTPCookieProcessor() urlopen = urllib2.build_opener(cookies) csrftoken = '' self.info(login_url) try: page = urlopen.open(login_url) except urllib2.HTTPError as e: self.info("HTTP Error code: " + str(e.code)) raise for cookie in cookies.cookiejar: if cookie.name == 'csrftoken': csrftoken = cookie.value params = urllib.urlencode([('csrfmiddlewaretoken', csrftoken), ('username', self.config['username']), ('password', self.config['password']), ('this_is_the_login_form', '1'), ('next', '/admin/')]) page = urlopen.open(login_url, params) content = page.read() if "Welcome," not in content: self.message('Login unsuccessful') return submit_path = self.submit_path() self.info( "Submit Path: " + submit_path ) if os.path.exists(submit_path): if cmds.confirmDialog(message='File was already submitted, submit again? (overwrites submitted file)', button=["Yes","No"], defaultButton="No", dismissString="No", cancelButton="No") == "No": return cmds.sysFile(submit_path, delete=True) if not make_paths_relative(): return #copy project file to submit_path src = cmds.file(query=True, sceneName=True) cmds.sysFile(src, copy=submit_path) post_hook = '' if self.config['transcode_result']: post_hook = '0' post_hook_options = {'fps': self.config['fps']} if self.config['proxy']: post_hook_options['proxy'] = True if self.config['h264']: post_hook_options['h264'] = True if self.config['prores']: post_hook_options['prores'] = True if self.config['dnxhd']: post_hook_options['dnxhd'] = True post_hook_options = json.dumps(post_hook_options) params = [('csrfmiddlewaretoken', csrftoken), ('tasks-job-content_type-object_id-TOTAL_FORMS', '1'), ('tasks-job-content_type-object_id-INITIAL_FORMS', '0'), ('tasks-job-content_type-object_id-0-status', '0'), ('tasks-job-content_type-object_id-0-priority', '50'), ('tasks-job-content_type-object_id-0-pool', '1'), ('tasks-job-content_type-object_id-0-post_hook', post_hook), ('tasks-job-content_type-object_id-0-post_hook_options', post_hook_options), ('project_file', self.relative_path()), ('project_directory', self.project_directory()), ('block_size', self.config['blockSize']), ('frame_start', str(int(cmds.playbackOptions(query=True, ast=True)))), ('frame_end', str(int(cmds.playbackOptions(query=True, aet=True)))), ('_save', 'Save')] page = urlopen.open(add_url, urllib.urlencode(params)) content = page.read() if 'added successfully' not in content: self.info(content) self.message('Job submission failed') return self.message('Job submission successful')
def BatchAnimExport(): ''' алгоритм работы скрипта, который создает ref позы для персонажей проверяет, существует ли ref .fbx если да копирует .fbx в работу папку если нет создает .fbx копирует в рабочую папку ''' # coding=1251 import maya.cmds as cmds import maya.mel as mel import os import re import sys # вызываю окно, куда вписываю имя рабочей папки, 'case_dialogue' result = cmds.promptDialog( title='working dir name', message='add working dir', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if result == 'OK': workingName = cmds.promptDialog(query=True, text=True) workingDirName = workingName.upper() + '\\' if result == 'Cancel': sys.exit('Cancelled') # задаю рабочий каталог workDirPath = 'e:\SH8\.dialogues\\' # задаю рабочий каталог для настроеных персонажей animChrPath = 'e:\SH8\.dialogues\.crhs\\' # задаю рабочий каталог для настроеных персонажей refFbxDir = 'e:\SH8\.dialogues\.crhs\.fbx_ref\\' # задаю путь, где хранятся .fbx анимации animFBXDir = 'anims_FBX\\' # задаю путь, где хранятся .fbx анимации animMBDir = 'anims_MB\\' # задаю приставку для названия ref анимаций refPrefix = '_face_10_fr_ref.fbx' log = '\n---------- export log:----------\n' # папкарабочего диалога animListDir = workDirPath + workingDirName # путь к файлу, где содержится список анимаций animListName = animListDir + workingName + '_anim_list.txt' # путь к папке .fbx анимаций рабочего диалога animFBXPath = workDirPath + workingDirName + animFBXDir # путь к папке .mb анимаций рабочего диалога animMBPath = workDirPath + workingDirName + animMBDir # составляю список из файлов, настроеных chr templates chrMBList = cmds.getFileList(fs = '*.mb', fld = animChrPath) # составляю список из файлов, .fbx ref анимаций chr templates refAnimList = cmds.getFileList(fs = '*.fbx', fld = refFbxDir) # составляю список из файлов, .fbx ref анимаций chr templates animMBList = cmds.getFileList(fs = '*.mb', fld = animMBPath) # создаю список для лицевых контроллеров ctrlsList = cmds.ls('*_ctrl') # получаю длину списка анимаций для проверки кол-ва выполненых действий animListForLen = open(animListName,'r') animLenLines = animListForLen.readlines() animListLen = len(animLenLines) animListForLen.close() # функция, которая определяет, какие персонажи используются в диалоге по anim_list.txt и списку chr templates def CompareLists(searchInList, searchForList): searchList = '' for searchInString in searchInList: for searchForString in searchForList: searchForString = searchForString.split('.') if searchForString[0].lower() in searchInString: if not searchForString[0].lower() in searchList: if searchList == '': searchList += searchForString[0].lower() else: searchList += ' ' + searchForString[0].lower() return searchList # сохраняю результат в переменную crhsInDialogue = CompareLists(animLenLines, chrMBList) # копирую в рабочу .fbx папку .fbx ref anims for chr in crhsInDialogue.split(' '): if os.path.exists(refFbxDir + chr + refPrefix): cmds.sysFile(refFbxDir + chr + refPrefix, cp = animFBXPath + chr + refPrefix) # если .fbx ref anim не сущетсвует, создаю его if not os.path.exists(refFbxDir + chr + refPrefix): cmds.file(animChrPath + chr + '.mb', o = True, f = True) # запекаю анимации на timeline для всех костей fullSkeletonList = cmds.ls(type = 'joint') cmds.select(fullSkeletonList) cmds.cutKey() cmds.bakeResults(fullSkeletonList, t=(0,10), simulation=True, sb=1) # делаю экспорт выделенных костей в .fbx с именем файла cmds.select(fullSkeletonList) mel.eval('string $refFbxDir = `python "refFbxDir"`;') mel.eval('string $chrName = `python "chr"`;') mel.eval('string $refPrefix = `python "refPrefix"`;') mel.eval('FBXExportConstraints -v 0') mel.eval('FBXLoadExportPresetFile -f "c:/Users/user/Documents/maya/FBX/Presets/2014.1/export/AnimationOnly.fbxexportpreset"') mel.eval('FBXExport -f ($refFbxDir + $chrName + $refPrefix) -s') cmds.sysFile(refFbxDir + chr + refPrefix, cp = animFBXPath + chr + refPrefix) # export animation for animMB in animMBList: if '_face_' in animMB: animFBX = animMB[:-3] if not os.path.exists(animFBXPath + animFBX + '.fbx'): cmds.file(animMBPath + animMB, o = True, f = True) # отделяю имя анимации от пути и расширенния и имени персонажа fullPathName = cmds.file(q = True, exn = True) fullPathName = fullPathName.split('/') fileName = fullPathName[-1] fileName = fileName[:-3] # создаю переменные, где храню значение начала и конца timeline currEndTime = cmds.playbackOptions( q=True, maxTime=True ) currStartTime = cmds.playbackOptions( q=True, minTime=True ) endTimeScaled = round(currEndTime/2) cmds.select('*_ctrl') cmds.currentTime(currStartTime, edit=True) cmds.setKeyframe('*_ctrl') cmds.currentTime(currEndTime, edit=True) cmds.setKeyframe('*_ctrl') # сжимаю анимацию в два раза, чтобы она соответствовала реальному времени cmds.select('*_ctrl') cmds.scaleKey(iub = False, ts = 0.5, tp = 1, fs = 0.5, fp = 1, vs = 1, vp = 0) cmds.playbackOptions(maxTime = int(endTimeScaled)) # Удаляю группу и локаторы костей языка # Временно, пока не настроил их if cmds.objExists('tongue_1_GRP'): cmds.delete('tongue_1_GRP', 'tongue_2_GRP') # выделяю все лицевые контроллеры cmds.select('*_ctrl') # смещаю ключи на 10 кадров вперед относительно их позиции cmds.keyframe(edit=True, relative = True, timeChange = (0 + 10)) # задаю новые границы timeline currEndTime = cmds.playbackOptions( q=True, maxTime=True ) currEndTime += 20 cmds.playbackOptions( minTime=0, maxTime=currEndTime ) # создаю функцию, которая обнуляю все каналы объектов из списка def SetKeysToZero(): cmds.select('*_ctrl') ctrlsList = cmds.ls(sl = True) for ctrl in ctrlsList: attrs = cmds.listAttr(ctrl, k=True) #создает список атрибутов для каждого из выделенных объектов for attr in attrs: #для каждого атрибута из списка атрибутов if attr != "visibility": #если он не называется cmds.setAttr(ctrl + "." + attr, 0) #имя объекта+точка+название атрибута равняется нулю # ставлю нулевые ключи лицевых контроллеров вначале и конце timeline cmds.currentTime(currStartTime, edit=True) SetKeysToZero() cmds.currentTime(currEndTime, edit=True) SetKeysToZero() # запекаю анимации на timeline для всех костей fullSkeletonList = cmds.ls(type = 'joint') cmds.select(fullSkeletonList) cmds.bakeResults(fullSkeletonList, t=(currStartTime,currEndTime), simulation=True, sb=1) # перевожу переменные pytjon в mel mel.eval('string $animName = `python "fileName"`;') mel.eval('string $animFBXPath = `python "animFBXPath"`;') # делаю экспорт выделенных костей в .fbx с именем файла fullSkeletonList = cmds.ls(type = 'joint') cmds.select(fullSkeletonList) mel.eval('FBXExportConstraints -v 0') mel.eval('FBXLoadExportPresetFile -f "c:/Users/user/Documents/maya/FBX/Presets/2014.1/export/AnimationOnly.fbxexportpreset"') mel.eval('FBXExport -f ($animFBXPath + $animName + ".fbx") -s') # создаю лог работы if os.path.exists(animFBXPath + fileName + '.fbx'): log += fileName + '.fbx exported \n' else: log += fileName + '.fbx NOT exported \n' print log
def AnimPoseLib(): global tabs,Animation,Poses,pathfolders,pathfolder,savepathini,User_Name,tmpfile,seltabs,seltab if mc.window ('MainWin',q=True,exists =1): mc.deleteUI ('MainWin') if mc.windowPref ('MainWin',q=True,exists = 1): mc.windowPref ('MainWin',remove = 1) posewin=mc.window('MainWin',menuBar=True, title="SR_AnimPoseLib",width=400,mxb=0) User_Name = os.getenv('USERNAME') savepathini='C:/Documents and Settings/'+ User_Name + '/My Documents/' mc.menu( label='File', tearOff=True ) mc.menuItem( label='Open Savepose Folder',c=lambda event:openfolder(savepathini)) mc.menuItem( label='Refresh',c=lambda event:Refresh_UI(savepathini)) mc.menu( label='Tabs', tearOff=True ) mc.menuItem( label='New Tab',c=partial(Newtab)) mc.menuItem( label='Delete Tab',c=partial(deletetab)) mc.menuItem( label='Rename Tab',c=partial(renametab)) mc.menuItem( label='Clear All ',c=partial(clear)) mc.menu('chgFld',label='Folder',tearOff=True) mc.menuItem(label='Change Savepose Folder ',c=lambda event:savefolder(savepathini)) mc.menuItem(d=True) newpath=[savepathini] mc.menuItem( label='My Douments ',c=partial(changepath,newpath)) mc.menu( label='Help', helpMenu=True,tearOff=True ) mc.menuItem( label='About..!' ,c=partial(About)) mc.frameLayout( label='',fn='boldLabelFont', borderStyle='etchedIn') mc.separator(style='none',height = 2 ) mc.rowColumnLayout(numberOfColumns=5,cw=[(1,70),(2,60),(3,70),(4,40),(5,125)],cs=[(1,30),(5,40)]) mc.text('ST',label='Start frame:') Start_F = mc.floatField('Start_F',precision=2) mc.text( 'ET',label='End frame:') End_F = mc.floatField('End_F',precision=2) mc.floatField('Start_F', edit=True, enterCommand=('mc.setFocus(\"' + End_F + '\")') ) mc.floatField('End_F', edit=True, enterCommand=('mc.setFocus(\"' + Start_F + '\")') ) mc.button(label='Save (Anim/Pose)',c=partial(savepose),h=35 ) mc.setParent( '..' ) mc.rowColumnLayout(numberOfColumns=2,cw=[(1,130)]) mc.text(label='Location : ',align='right',fn='boldLabelFont') mc.text('Path',label=' Local Folder',align='left',fn='smallFixedWidthFont') mc.setParent( '..' ) form = mc.formLayout() tabs = mc.shelfTabLayout('tabs',innerMarginWidth=5, innerMarginHeight=5,cc=partial(vis)) mc.formLayout(form,edit=True, attachForm=((tabs, 'top', 0), (tabs, 'left', 15), (tabs, 'bottom', 15), (tabs, 'right', 15)) ) Animation = mc.shelfTabLayout('Animation',innerMarginWidth=5, innerMarginHeight=5,bgc=(0.3,0.3,0.3),h=237) mc.setParent('..') Poses = mc.shelfTabLayout('Poses',innerMarginWidth=5, innerMarginHeight=5,bgc=(0.3,0.3,0.3),h=237,p=tabs) mc.setParent('..') mc.setParent('..') mc.setParent('..') mc.text(l='Sreekanth.S.R ',fn="smallBoldLabelFont",al='right') mc.window (posewin,e=1,wh=(500,410)) mc.showWindow() shelfpath=[] posepath=[] savepath =(savepathini + 'SavePose/') mc.sysFile(savepath, makeDir=True ) shelfpath= mc.getFileList (folder=savepath) Anim_count=shelfpath.count('Animation') Pose_count=shelfpath.count('Poses') Tmp_count =shelfpath.count('tmp.anim') if not Tmp_count: tmpfile=savepath+'tmp.anim' field=open(tmpfile,'w') field.write('Currnt dir \n'+savepathini) field.close() if Tmp_count: tmpfile=savepath+'tmp.anim' field=open(tmpfile,'r+') line=field.readline() if line[0:3]=='Cur' : line=field.readline() savepathini=line.strip() line=field.readline() if line[0:3]=='Run': line=field.readline() while(line != '}'): mc.menuItem(label=line.strip(),p='chgFld',c=partial(savedpath,line)) line=field.readline() field.close() Refresh_UI(savepathini)
def Refresh_UI(savepathini,*args): mc.text('Path',e=1,l=savepathini) S_val=mc.playbackOptions(q=1,min=1) E_val=mc.playbackOptions(q=1,max=1) mc.floatField('End_F',e=1,v=E_val) mc.floatField('Start_F',e=1,v=S_val) savepath =(savepathini + 'SavePose/') #imgpath = savepath + 'tmp_images/' mc.sysFile(savepath, makeDir=True ) posepath = (savepath + 'Animation/') posepath1= (savepath + 'Poses/') shelfpath= mc.getFileList (folder=savepath) Anim_count=shelfpath.count('Animation') Pose_count=shelfpath.count('Poses') if Anim_count==0 or Pose_count==0: mc.confirmDialog (title='Warning',message='No saved poses exist. A Default folders will\n be created when you save for the first time', button='OK',defaultButton='Yes') tabsanim,tabsanim1=[],[] tabsanim=mc.getFileList(folder=posepath) tabsanim1=mc.getFileList(folder=posepath1) Anim_tabs=mc.shelfTabLayout('Animation',q=1,ca=1) Pose_tabs=mc.shelfTabLayout('Poses',q=1,ca=1) if Anim_tabs or Pose_tabs : mc.deleteUI(Anim_tabs,Pose_tabs) if tabsanim: for each in tabsanim: sh=mc.shelfLayout(each,p=Animation,st="iconAndTextVertical") mc.setParent('..') posetabs=(posepath + each + "/") poses = mc.getFileList (fld =posetabs,fs="*.anim") # imges = mc.getFileList (fld =posetabs,fs="*.bmp") icon_name='ghost.xpm' for j in range(len(poses)): butname = poses[j].replace(".anim","") img_name=poses[j].replace(".anim",".bmp") icon_name=posetabs + img_name posefile = posetabs + poses[j] mc.setParent() mc.shelfButton(i1=icon_name,w=110,h=80,l=butname,bgc=(.2,.6,.3),st='iconAndTextVertical',p=each,c=partial(Importanim,posefile)) mc.popupMenu() mc.menuItem(l='Import anim',en=1,c=partial(Importanim,posefile)) mc.menuItem(d=True) mc.menuItem(l='Rename anim',en=1,c=partial(Renameanim,posefile)) mc.menuItem(d=True) mc.menuItem(l='Delete anim',en=1,c=partial(Deleteanim,posefile)) mc.setParent('..') else: if mc.shelfLayout('Default',q=True,exists=True): mc.deleteUI ('Default') shelftmp = mc.shelfLayout('Default',w=450,h=200,bgc=(0.3,0.3,0.3),p=Animation) mc.sysFile(posepath+'Default/', makeDir=True ) if tabsanim1: for each in tabsanim1: sh=mc.shelfLayout(each,p=Poses,st="iconAndTextVertical") mc.setParent('..') posetabs1 = (posepath1 + each + "/") poses1 = mc.getFileList (fld =posetabs1,fs="*.anim") icon_name1='ghostOff.xpm' for j in range(len(poses1)): butname1 = poses1[j].replace(".anim","") img_name1= poses1[j].replace(".anim",".bmp") icon_name1=posetabs1 + img_name1 posefile1 = posetabs1 + poses1[j] mc.setParent() mc.shelfButton(i1=icon_name1,w=110,h=80,l=butname1,fn= "fixedWidthFont" ,bgc=(.9, .4, .0),st='iconAndTextVertical',p=each,c=partial(Pose_rtn,posefile1)) mc.popupMenu() mc.menuItem(l='Import Pose',en=1,c=partial(Pose_rtn,posefile1)) mc.menuItem(d=True) mc.menuItem(l='Rename Pose',en=1,c=partial(Renamepose,posefile1)) mc.menuItem(d=True) mc.menuItem(l='Delete Pose',en=1,c=partial(Deletepose,posefile1)) mc.setParent('..') else: if mc.shelfLayout('Default1',q=True,exists=True): mc.deleteUI ('Default1') shelftmp1 = mc.shelfLayout('Default1',w=450,h=200,bgc=(0.3,0.3,0.3),p=Poses) mc.sysFile(posepath1+'Default1/', makeDir=True )
searchForString = searchForString.split('.') if searchForString[0].lower() in searchInString: if not searchForString[0].lower() in searchList: if searchList == '': searchList += searchForString[0].lower() else: searchList += ' ' + searchForString[0].lower() return searchList # сохраняю результат в переменную crhsInDialogue = CompareLists(animLenLines, chrMBList) # копирую в рабочу .fbx папку .fbx ref anims for chr in crhsInDialogue.split(' '): if os.path.exists(refFbxDir + chr + refPrefix): cmds.sysFile(refFbxDir + chr + refPrefix, cp = animFBXPath + chr + refPrefix) # если .fbx ref anim не сущетсвует, создаю его if not os.path.exists(refFbxDir + chr + refPrefix): cmds.file(animChrPath + chr + '.mb', o = True, f = True) # запекаю анимации на timeline для всех костей fullSkeletonList = cmds.ls(type = 'joint') cmds.select(fullSkeletonList) cmds.cutKey() cmds.bakeResults(fullSkeletonList, t=(0,10), simulation=True, sb=1) # делаю экспорт выделенных костей в .fbx с именем файла cmds.select(fullSkeletonList) mel.eval('string $refFbxDir = `python "refFbxDir"`;') mel.eval('string $chrName = `python "chr"`;') mel.eval('string $refPrefix = `python "refPrefix"`;') mel.eval('FBXExportConstraints -v 0') mel.eval('FBXLoadExportPresetFile -f "c:/Users/user/Documents/maya/FBX/Presets/2014.1/export/AnimationOnly.fbxexportpreset"')