def playblast(self): """ Run the playblast of the image. Will only work if the layer has been pushed. """ # Set up the camera pm.modelEditor(self.playblast_panel, edit=True, camera=self.camera, displayAppearance='flatShaded') pm.playblast(**self.playblast_args)
def main(): prefRun() #get all renderable cameras in scene allCamShapes = pm.ls( type='camera') cams = [] for cam in allCamShapes: if pm.getAttr(cam+".renderable"): cams.append(pm.listRelatives(cam, p=1)) print cams #Get the current frame range from the timeslider startTime = pm.playbackOptions(q=True, min=True ) endTime = pm.playbackOptions(q=True, max=True ) print "Playblasting Cameras:", #generate playblast for each renderable cam for cam in cams: pm.playblast( cam, startTime=startTime, endTime=endTime, viewer=0, #filename="X:/Projects/GREY11_ANM71_Rewe_Starzone/GR11A71_Shots/GR11A71_Animatic/Animatic_Maya/data/test"+cam[0]) ) print "for range: %04d - %04d" % (startTime,endTime)
def saveName(*pArgs): #save the vertex positions currentSelection = getVertexPositions() storedList = open( 'EqualRealityData\SavedVertexPositions%s.txt' % (globalGender[0]), 'a') storedList.write('\r\n\r\n') for item in currentSelection: storedList.write('%s|' % (item)) storedList.close() #save the name myText = cmds.textField("Name_Textfield", query=True, text=True) myNames = open('EqualRealityData\EyeShapes%s.txt' % (globalGender[0]), 'a') myNames.write('\r\n%s' % (myText)) myNames.close() shaderSwitch('Flat') myWindow = pm.window('Icon Render') form = pm.formLayout() editor = pm.modelEditor() column = pm.columnLayout('true') pm.formLayout(form, edit=True, attachForm=[(column, 'top', 0), (column, 'left', 0), (editor, 'top', 0), (editor, 'bottom', 0), (editor, 'right', 0)], attachNone=[(column, 'bottom'), (column, 'right')], attachControl=(editor, 'left', 0, column)) myCam = 'IconRendererShape' pm.modelEditor(editor, activeView=True, camera=myCam, displayTextures=True, edit=True, displayAppearance='smoothShaded') pm.showWindow(myWindow) pm.select('Body_%s' % (globalGender[0])) pm.playblast(completeFilename="%s_%s.iff" % (myText, globalGender[0]), viewer=False, showOrnaments=False, frame=[1], percent=100, format="image", width=84, height=84) shaderSwitch('Normal') pm.deleteUI(myWindow) cmds.deleteUI('popupID') globalEyeKey = [] rolloutParameters(names=['modellingToolkit', 'EyeShapes'], edit=True) createUI('Poly Morph')
def eval_playblast(self, fileName, width, height, fp): try: pm.playblast(format='iff',sequenceTime=0,clearCache=1,viewer=0,\ showOrnaments=1,fp=fp,percent=100,compression="jpg",\ widthHeight=(width,height),\ forceOverwrite=1,quality=100,filename=fileName) except: self.Log.error('eval_playblast error') self.Log.error(traceback.format_exc())
def eval_playblast(self,fileName,width,height,fp): try: pm.playblast(format='iff',sequenceTime=0,clearCache=1,viewer=0,\ showOrnaments=1,fp=fp,percent=100,compression="jpg",\ widthHeight=(width,height),\ forceOverwrite=1,quality=100,filename=fileName) except: self.Log.error('eval_playblast error') self.Log.error(traceback.format_exc())
def bs_playblast(): """ @ create playblast with headsUpDisplays. Returns: playblastPath. """ bs_addHeadsUpDisplay() epi, seq, shot, stage = bs_pathGenerator.bs_shotDetailsCheckAndReturn() outPath = bs_pathGenerator.bs_animFilePath(epi, seq, shot)[stage][:-3] shotCam = pm.PyNode('shot_cam') # add resolution gates. pm.camera(shotCam, e=True, filmFit='overscan') pm.camera(shotCam, e=True, dsa=True, dfc=False, displayFilmGate=False, displayResolution=True, displaySafeTitle=False) pm.setAttr(shotCam + '.displayGateMaskOpacity', 1) pm.setAttr(shotCam + '.displayGateMaskColor', [0, 0, 0], type='double3') pm.setAttr(shotCam + '.displayGateMask', 1) # get Sound File. soundFile = pm.windows.timeControl('timeControl1', q=True, s=True) # playblast. if soundFile: vidPath = pm.playblast(f=outPath, format='avi', s=soundFile, sequenceTime=0, forceOverwrite=True, clearCache=1, viewer=1, showOrnaments=1, fp=4, percent=100, quality=70, widthHeight=[960, 540]) else: vidPath = pm.playblast(f=outPath, format='avi', sequenceTime=0, forceOverwrite=True, clearCache=1, viewer=1, showOrnaments=1, fp=4, percent=100, quality=70, widthHeight=[960, 540]) bs_removeHeadsUpDisplay() bs_qui.bs_displayMessage('success', '{0}'.format(vidPath)) return vidPath
def saveImageCreate(self, mayaFalse): pm.playblast(completeFilename=str(pm.sceneName()).rstrip('.ma') + '.png', format='image', compression='png', frame=[pm.currentTime()], forceOverwrite=True, viewer=False, width=100, height=100, showOrnaments=False, p=100, os=True)
def pcBlast(savepath, startf, endf): #this runs the actual playblast pm.playblast(format="image", filename=savepath, startTime=startf, endTime=endf, compression="jpg", widthHeight=[1920, 1080], percent=100, framePadding=3, showOrnaments=False, viewer=False)
def createIcons(self): print "CREATE ICONS" formatOrig = pm.getAttr("defaultRenderGlobals.imageFormat") for style in SimpleCurves.STYLES: iPath = os.path.join(self.iconPath, "%s.png"%(style)) pm.setAttr("defaultRenderGlobals.imageFormat", 32) newCurve = self.simpleCurve(style) pm.viewFit(all=True) pm.playblast(frame=1, format = "image", cf = iPath, wh = (100,100), p=100) newCurve.delete() pm.setAttr("defaultRenderGlobals.imageFormat", formatOrig) ControlUI(self.iconPath)
def create_icon(self, model=Model()): pmc.viewFit() # set img format as jpg pmc.setAttr('defaultRenderGlobals.imageFormat', 8) pmc.playblast(completeFilename=model.icon, forceOverwrite=True, format='image', width=200, height=200, showOrnaments=False, startTime=1, endTime=1, viewer=False)
def cycle_time_line(rig_ctrl, increment): """ :param rig_ctrl: pynode of the rig ctrl to change proportion :param increment: time line increment to cycle test. 1 will test every frame Loops though timeline. Will print out clipping info and take a screen shot if clipping is above threshold """ #: Query time line length anim_time = int(pm.playbackOptions(q=True, animationEndTime=True)) #: retrieves scene base name scene_name = pm.system.sceneName().basename().replace('.ma', '') #: Get sting name of proportion set. proportion = rig_ctrl.getAttr('Proportion', asString=True) for i in range(int(anim_time / increment)): time = pm.currentTime(i * increment) clipping = gather_collision_spheres(group=collision_group) if clipping and clipping[0] > clipping_threshold: #: Output name of image image_output = '{}--{}--{}-{}Percent_Clipping_With-{}--FRAME'.format( scene_name, proportion, clipping[1], clipping[0], clipping[2]) #: Output log info output_log = '{0}\n{1}\n{2} {3}\n{4}\n{5} {6}'.format( 50 * "-", scene_name, clipping[0], "Percent is Clipping", proportion, clipping[1], clipping[2]) pm.playblast(filename=str(path) + "/clipping/" + image_output, startTime=time, endTime=time, format='image', compression='jpg', quality=100, viewer=False, framePadding=0, widthHeight=(1024, 1024), showOrnaments=False, clearCache=True, percent=100, forceOverwrite=True) print output_log pm.currentTime(0)
def screen_shot(target_name): final_path = str(path) + "/ScreenShot/" + target_name pymel.playblast(filename=final_path, startTime=0, endTime=0, format='image', compression='png', quality=100, viewer=False, framePadding=0, widthHeight=(2000, 2000), showOrnaments=False, clearCache=True, percent=100)
def createPlayblast(filename1): #search for local movies folder #moviesFolder=pm.workspace(query=True, active=True)+'/movies/'+filename1[4]+'/'+filename1[5]+'/' moviesFolder = pm.workspace(query=True, active=True) + '/movies/' print 'Playblast location is : ' + moviesFolder panelnow = cmds.getPanel(wf=True) cmds.modelEditor(panelnow, e=1, displayLights='default', cme=False) thingstoHide = [ 'nurbsCurves', 'joints', 'motionTrails', 'locators', 'ikHandles' ] # for loop to check through all 4 items on top. for thing in thingstoHide: kwargs = {'query': True, thing: True} thingCheck = cmds.modelEditor(panelnow, **kwargs) if thingCheck == True: kwargs = {'edit': True, thing: False} cmds.modelEditor(panelnow, **kwargs) else: print "Playblast : %s is already hidden " % thing return pm.playblast(format='qt', cc=True, filename=moviesFolder + filename1[6], fo=True, percent=100, compression='H.264', quality=100, width=960, height=540)
def __init__( self, parent = pyside_util.get_maya_window(), *args ): super( MultiBlastUI, self ).__init__( parent ) self.setupUi( self ) self.setWindowTitle( '{0} {1}'.format( WINDOW_TITLE, str( WINDOW_VERTION ) ) ) #self.mayaFilesTableWidget.itemDoubleClicked.connect( self.bdToggleFile ) self.mayaFilesPathBtn.clicked.connect(lambda: self.bdGetPath('maya')) self.blastsPathBtn.clicked.connect(lambda: self.bdGetPath('avi')) self.camPathBtn.clicked.connect(lambda: self.bdGetPath('cam')) self.rigPathBtn.clicked.connect(lambda: self.bdGetPath('rig')) self.playblastBtn.clicked.connect(self.bdPlayblastFolder) self.mayaFilesTableWidget.itemDoubleClicked.connect( self.bdToggleStatus ) self.formatComboBox.currentIndexChanged.connect(self.bdFormatChanged) self.lastVersion.stateChanged.connect(self.bdGetLastVersion) self.mayaFilesTableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.mayaFilesTableWidget.customContextMenuRequested.connect(self.handleHeaderMenu) layout = mui.MQtUtil.fullName(long(shiboken.getCppPointer(self.playblastOptionGrp)[0])) formats = pm.playblast(q=1,format=1) self.formatComboBox.addItems(formats) selectedFormat = self.formatComboBox.currentText() cmd = 'playblast -format "' + selectedFormat + '" -q -compression' compression = pm.mel.eval(cmd) self.encodingComboBox.clear() self.encodingComboBox.addItems(compression) self.progressBar.hide() self.show()
def __init__(self, parent=pyside_util.get_maya_window(), *args): super(MultiBlastUI, self).__init__(parent) self.setupUi(self) self.setWindowTitle('{0} {1}'.format(WINDOW_TITLE, str(WINDOW_VERTION))) # self.mayaFilesTableWidget.itemDoubleClicked.connect( self.bdToggleFile ) self.mayaFilesPathBtn.clicked.connect(lambda: self.bdGetPath('maya')) self.blastsPathBtn.clicked.connect(lambda: self.bdGetPath('avi')) self.camPathBtn.clicked.connect(lambda: self.bdGetPath('cam')) self.rigPathBtn.clicked.connect(lambda: self.bdGetPath('rig')) self.playblastBtn.clicked.connect(self.bdPlayblastFolder) self.mayaFilesTableWidget.itemDoubleClicked.connect( self.bdToggleStatus) self.formatComboBox.currentIndexChanged.connect(self.bdFormatChanged) self.lastVersion.stateChanged.connect(self.bdGetLastVersion) self.mayaFilesTableWidget.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) self.mayaFilesTableWidget.customContextMenuRequested.connect( self.handleHeaderMenu) layout = mui.MQtUtil.fullName( long(shiboken.getCppPointer(self.playblastOptionGrp)[0])) formats = pm.playblast(q=1, format=1) self.formatComboBox.addItems(formats) selectedFormat = self.formatComboBox.currentText() cmd = 'playblast -format "' + selectedFormat + '" -q -compression' compression = pm.mel.eval(cmd) self.encodingComboBox.clear() self.encodingComboBox.addItems(compression) self.progressBar.hide() self.show()
def snapshot(resolution=conf.presetGeo["resolution"], snapLocation=op.join(os.getenv("tmp"), str(int(util.randomNumber() * 100000)))): image_format = pc.getAttr("defaultRenderGlobals.imageFormat") pc.setAttr("defaultRenderGlobals.imageFormat", 8) pc.playblast(frame=pc.currentTime(q=True), format='image', cf=snapLocation.replace('\\', '/'), orn=0, v=0, wh=resolution, p=100, viewer=0, offScreen=1) pc.setAttr("defaultRenderGlobals.imageFormat", image_format) return snapLocation
def bs_getScreenShot(imageOutPath): """ @ frame all views and get off screen screen shot using maya playblast. Args: imageOutPath (str): output path should be in '.jpg' format. Returns: image output path. """ if pm.about(batch=True): return False # make screenshot dir if not exist. if not os.path.exists(os.path.dirname(imageOutPath)): os.makedirs(os.path.dirname(imageOutPath)) perspCam = pm.PyNode('persp') perspCam.t.set(28.0, 21.0, 28.0) perspCam.r.set(-27.9383527296, 45.0, 0) pm.language.mel.eval('FrameAllInAllViews') return pm.playblast(frame=[pm.currentTime()], format="image", viewer=False, cf=imageOutPath, os=True, compression='jpg', wh=[250, 250], quality=100, percent=100)
def bdPerformPlayblast(self,folder,outFolder,characterRig, blastFormat, blastCompression, referenceCam): animDir = folder animFiles = [] for i in range(self.mayaFilesTableWidget.rowCount()): status = self.mayaFilesTableWidget.item(i,0).text() if status == 'Yes': animFiles.append(self.mayaFilesTableWidget.item(i,1).text()) #pm.mel.eval('setAllMainWindowComponentsVisible 0;') for f in sorted(animFiles): pathFile = animDir + '/' + f if outFolder == '': pathMovie = 'movies/' + f[:-3] else: pathMovie = outFolder + '/' +f[:-3] if os.path.isfile(pathFile): print pathFile else: print 'no file' return checkFileCallbackId = OM.MSceneMessage.addCheckFileCallback(OM.MSceneMessage.kBeforeReferenceCheck, self.bdReplaceRig) pm.newFile(f=1) pm.openFile(pathFile,f=1) #pm.mel.eval('setNamedPanelLayout "Four View"; updateToolbox();') ''' openWin = pm.lsUI(windows=1) for win in openWin: if 'MayaWindow' not in win.name() and WINDOW_NAME not in win.name() and 'scriptEditorPanel' not in win.name(): pm.deleteUI(win) ''' pm.setAttr("defaultResolution.width",1280) pm.setAttr("defaultResolution.height",720) OM.MMessage.removeCallback(checkFileCallbackId) self.bdSetCamera(referenceCam) print folder,outFolder,characterRig, blastFormat, blastCompression, referenceCam try: self.mayaFilesTableWidget.item(row,0).setBackground(QtGui.QColor(255,100,150)) self.mayaFilesTableWidget.item(row,1).setBackground(QtGui.QColor(255,100,150)) pm.playblast(format = blastFormat, filename = pathMovie,forceOverwrite=1,sequenceTime=0,clearCache=0,viewer=0,showOrnaments=1,fp=4,percent = 100,compression = blastCompression,quality=100, widthHeight= [1280, 720]) except: print "WTF!!!!!!!!!!!" progress = (float(animFiles.index(f) + 1.0) / float(len(animFiles)) ) * 100.0 self.progressBar.setValue(int(progress)) row = animFiles.index(f)
def do_playblast(self, imageName=None): ''' do plabyBlast ''' if not imageName: #set temp images name fd, imageName = tempfile.mkstemp(prefix='PlayBlast') fObj = os.fdopen(fd, 'w') fObj.write('') fObj.close() self.Images = imageName print 'self.Images:%s' % self.Images pm.playblast(format='iff',sequenceTime=0,clearCache=1,viewer=0,\ showOrnaments=1,fp=1,percent=100,compression="jpg",\ widthHeight=(self.Width,self.Height),\ forceOverwrite=1,quality=100,filename=self.Images)
def setCamPlaybackRange(): modelPanel = pm.playblast(activeEditor=True).split('|')[-1] activeCam = pm.PyNode( pm.modelPanel( modelPanel, q=True, camera=True ) ) startFrame = activeCam.startFrame.get() endFrame = activeCam.endFrame.get() pm.playbackOptions(min=endFrame, max=startFrame)
def playblast(data): pc.playblast(st=data['start'], et=data['end'], f=data['path'], fo=True, quality=100, w=1280, h=720, compression='MS-CRAM', percent=100, format='avi', sequenceTime=0, clearCache=True, viewer=False, showOrnaments=True, fp=4, offScreen=True)
def renderScreen(self): ''' Render function to make the screenshot. Playblast a single frame. ''' # return camera / viewport currentCamera = self.checkCamera() originalCam = self.getViewport() resScreen = self.getScreenRes() if resScreen: # temp disable undo pm.undoInfo(openChunk=True, stateWithoutFlush=False) # switch current view to camera pm.lookThru(currentCamera) # file path info from UI inputs completeFile = UI.saveLocation + self.getFileNameStyle( includeFormat=True) # playblast without scale settings, to prevent visual glitches pm.playblast(frame=pm.currentTime(), widthHeight=(resScreen[0], resScreen[1]), offScreen=True, clearCache=True, fp=4, p=100, fo=True, cf=completeFile, format="image", viewer=False, c=str(UI.fileExt_dropdwn.currentText())) # reset camera back to original viewport pm.lookThru(originalCam) pm.undoInfo(openChunk=False, closeChunk=True, stateWithoutFlush=True) # log info to the user if not self.errorMsg: api.MGlobal.displayInfo('[#] Log successful ' + str(datetime.datetime.now().time()))
def do_playblast(self,imageName=None): ''' do plabyBlast ''' if not imageName: #set temp images name fd,imageName = tempfile.mkstemp(prefix='PlayBlast') fObj = os.fdopen(fd,'w') fObj.write( '' ) fObj.close() self.Images = imageName print 'self.Images:%s' % self.Images pm.playblast(format='iff',sequenceTime=0,clearCache=1,viewer=0,\ showOrnaments=1,fp=1,percent=100,compression="jpg",\ widthHeight=(self.Width,self.Height),\ forceOverwrite=1,quality=100,filename=self.Images)
def do_playblast(self): self.do_backup() pm.setFocus(self.viewport) data = dict(filename=self.playblast_path, widthHeight=self.output_dimentions, forceOverwrite=True, format='qt', quality=100, percent=100, compression='H.264', clearCache=True, showOrnaments=True, offScreen=True) pm.playblast(**data) if pm.modelPanel(self.viewport, exists=True): cmds.deleteUI(self.viewport, panel=True) self.close()
def playblast(*a): def __incrVersion(backup_path, version, name): backup_name = name + '_' + str(int(version)).zfill(4) + '.mov' if os.path.exists(os.path.join(backup_path, backup_name)): version += 1 backup_name = __incrVersion(backup_path, version, name) return backup_name # Frame range frame_range = ( pm.playbackOptions( q=True, min=True ), pm.playbackOptions( q=True, max=True ) ) file_name, project_path = project.getProject() # v:\DELIVERABLE\qt\DELIVERABLE_ANIM.mov qt_folder = os.path.join(project_path, 'qt') backup_folder = os.path.join(qt_folder, 'backup') output_path = os.path.join(qt_folder, file_name+'.mov') if os.path.exists(output_path): backup_path = __incrVersion(backup_folder, 1, file_name) #print os.path.join(backup_folder, backup_path) os.rename(output_path, os.path.join(backup_folder, backup_path)) pm.Mel.eval('setCurrentFrameVisibility(1);') pm.playblast( startTime = frame_range[0], endTime = frame_range[1], filename = output_path, forceOverwrite = True, format = 'qt', compression = 'H.264', orn = False, width = 960, height = 540, percent = 100, quality = 70, clearCache = True )
def takeScreenshotForPoseBtn(filepath, filename, filesizeW, filesizeH): defaultRenderGlobalsNode = pm.PyNode('defaultRenderGlobals') #Get Current imageFormat from renderglobals currentImageFormat = pm.getAttr(defaultRenderGlobalsNode.name()+'.imageFormat') #Set new imageFormat to jpg defaultRenderGlobalsNode.setAttr('imageFormat', 8) #Create Playblast image #create playblast image path playblastImagePath = filepath +filename + '.jpg' pm.playblast(cf = playblastImagePath, fr = [pm.currentTime()],wh = (filesizeW, filesizeH), fmt = 'image',o = False, orn = False, v = False, p = 100) #Reset imageFormat to old one defaultRenderGlobalsNode.setAttr('imageFormat', currentImageFormat)
def ar_playblast(fileName, width, height, startTime=None, endTime=None): """ pcg_playblast using custom setting. :param fileName: string (file path) :param width: int :param height: int :param startTime: float :param endTime: float :return: pcg_playblast """ # cam = pm.ls('*:cameraHD', typ='transform')[0] # noinspection PyTypeChecker aPlayBackSlider = mel.eval('$tmpVar=$gPlayBackSlider') soundFile = pm.windows.timeControl(aPlayBackSlider, q=True, s=True) if startTime and endTime: pm.playbackOptions(min=startTime) pm.playbackOptions(ast=startTime) pm.playbackOptions(max=endTime) pm.playbackOptions(aet=endTime) if soundFile: playblast = pm.playblast(f=fileName, format='qt', s=soundFile[0], sqt=0, fo=True, cc=True, p=100, compression="H.264", quality=100, height=height, width=width) else: playblast = pm.playblast(f=fileName, format='qt', sqt=0, fo=True, cc=True, p=100, compression="H.264", quality=100, height=height, width=width) return playblast
def bdPlayblastFolderVP2(folder,outFolder,codec, cleanName=0): animDir = folder animFiles = [os.path.splitext(f)[0] for f in sorted(os.listdir(animDir)) if f.endswith('.mb')] if not cleanName: lastVersions = [] temp = [] for f in animFiles: if '_v' in f: fileName = f[:-4] temp.append(fileName) temp1 = list(set(temp[:])) for t in temp1: lastVersions.append(t + '_v0' + str(temp.count(t))) animFiles = lastVersions for f in sorted(animFiles): pathFile = animDir + f + '.mb' if outFolder == '': pathMovie = 'movies/' + f else: pathMovie = outFolder + f if os.path.isfile(pathFile): print pathFile else: print 'no file' #checkFileCallbackId = OM.MSceneMessage.addCheckFileCallback(OM.MSceneMessage.kBeforeReferenceCheck, bdReplaceRig) pm.mel.eval('ActivateViewport20') pm.openFile(pathFile,f=1) pm.mel.eval('setCameraNamesVisibility 0') pm.select('zoo:body') pm.hyperShade(assign = 'zoo:cat_body_linkSHD') pm.select(cl=1) pm.setAttr("defaultResolution.width",1280) pm.setAttr("defaultResolution.height",720) bdSetCameraVP2('cam:cameraShape1') pm.playblast(format = 'avi', filename = pathMovie,forceOverwrite=1,sequenceTime=0,clearCache=0,viewer=0,showOrnaments=1,fp=4,percent = 100,compression=codec, quality=100, widthHeight= [1280, 720])
def playBlast(self): self.get_scene_name() if self.Scene_Name: self.get_pb_name() #set temp dir for xp #tempfile.tempdir = 'c:/Windows/Temp' self.Images = tempfile.mkstemp(prefix='PlayBlast')[1] #playblast -format avi -sequenceTime 0 -clearCache 0 -viewer 1 -showOrnaments 1 -fp 4 -percent 50 -compression "none" -quality 70; #playblast -format iff -filename "D:/mhxy/scenes/shot/seq001/shot053a/simPlayblast/mhxy_seq001_shot053a_anim_fin" -sequenceTime 0 -clearCache 1 -viewer 1 -showOrnaments 1 -fp 4 -percent 50 -compression "jpg" -quality 100; pm.playblast(format='iff',sequenceTime=0,clearCache=1,viewer=0,\ showOrnaments=1,fp=1,percent=100,compression="jpg",\ forceOverwrite=1,quality=100,filename=self.Images) print self.PB_Name # convert sequence info for start and end self.get_frames_info() # make movie self.make_mov()
def batch_playblast(self): file_list, _ = QFileDialog.getOpenFileNames(self) for f in file_list: if not f.endswith(".ma") and not f.endswith(".mb"): continue pm.openFile(f, 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, showOrnaments=0, percent=100, compression="png", quality=100, forceOverwrite=1)
def takeSnapShot(itemMData=None, thumbPath=None): if itemMData and not thumbPath: itemDir = database.getPath(itemMData, ext='thumb') thumbDir = os.path.join(itemDir[0], 'thumb') if not os.path.exists(thumbDir): os.makedirs(thumbDir) thumbPath = os.path.join(thumbDir, itemDir[1]) pm.playblast(frame=1, format="image", compression="jpg", orn=False, cf=thumbPath, v=False, fo=True, wh=[100, 100], p=100, os=True)
def save_icon(object, filename, imageFormat): """ Take picture of object, render using playblast for later use as a QT Button icon. """ path = os.path.join(save_folder, "{}.png".format(filename)) # Store all hidden items items = pm.hide(allObjects=True, returnHidden=True) # Show only object we want to focus on and fit view pm.showHidden(object) pm.viewFit() # PNG is 32 in the imageFormat enum. pm.setAttr("defaultRenderGlobals.imageFormat", imageFormat) pm.playblast(completeFilename=path, forceOverwrite=True, format='image', width=200, height=200, showOrnaments=False, startTime=1, endTime=1, viewer=False) # Show all the items we hid a while back. pm.showHidden(items) # Return camera to previous view. pm.viewSet(previousView=True)
def poseScreenShot(self, name, directory=dirFiles): path = os.path.join(directory, '%s.png' % name) pm.modelEditor("modelPanel4", edit=True, allObjects=False) pm.modelEditor("modelPanel4", edit=True, polymeshes=True) pm.setAttr('defaultRenderGlobals.imageFormat', 32) pm.playblast(completeFilename=path, forceOverwrite=True, format='image', width=500, height=400, showOrnaments=False, startTime=1, endTime=1, viewer=False) pm.modelEditor("modelPanel4", edit=True, allObjects=True) return path
def blastIt(paths, mode='copy', *args): pm.mel.eval( 'setCurrentFrameVisibility(!`optionVar -q currentFrameVisibility`);') fr_start = pm.playbackOptions( q=True, min=True, ) fr_end = pm.playbackOptions( q=True, max=True, ) pm.playblast(startTime=fr_start, endTime=fr_end, filename=paths['version_file'], forceOverwrite=False, format='avi', viewer=True, widthHeight=(960, 540), p=100, orn=True, c='none', qlt=100) pm.mel.eval( 'setCurrentFrameVisibility(!`optionVar -q currentFrameVisibility`);') if mode == 'copy': if not os.path.exists(paths['copy_dir']): os.makedirs(paths['copy_dir']) shutil.copy(paths['version_file'] + '.avi', paths['copy_file']) if mode == 'nocopy': pm.warning( 'Because you made an alt version of your playblast, no copy was sent to the /CURRENT/ folder.' ) pm.warning('Here is where your file went: ' + paths['version_file'].replace('/', '\\') + '.avi')
def playbast_org(self): currentSceneName = pm.sceneName().split('/')[-1] videoName = currentSceneName.split('.')[0] version = '000' pm.playblast(fp=4, offScreen=1, clearCache=0, format='qt', sequenceTime=0, showOrnaments=1, percent=100, filename='{}/{}.{}'.format(self.playbast_path, videoName, version), viewer=1, forceOverwrite=1, quality=100, useTraxSounds=1, compression="png") self.updateData() sys.stdout.write('Playblast is done! {}/{}.{} \n'.format( self.playbast_path, videoName, version))
def bdPlayblastFolder(folder,outFolder,characterRig,codec, camera, referenceCam='', cleanName=0): CHARACTER_RIG = characterRig print CHARACTER_RIG animDir = folder animFiles = [os.path.splitext(f)[0] for f in sorted(os.listdir(animDir)) if f.endswith('.ma')] if not cleanName: lastVersions = [] temp = [] for f in animFiles: if '_v' in f: fileName = f[:-4] temp.append(fileName) temp1 = list(set(temp[:])) for t in temp1: lastVersions.append(t + '_v0' + str(temp.count(t))) animFiles = lastVersions for f in sorted(animFiles): pathFile = animDir + f + '.ma' if outFolder == '': pathMovie = 'movies/' + f else: pathMovie = outFolder + f if os.path.isfile(pathFile): print pathFile else: print 'no file' checkFileCallbackId = OM.MSceneMessage.addCheckFileCallback(OM.MSceneMessage.kBeforeReferenceCheck, bdReplaceRig) pm.openFile(pathFile,f=1) pm.setAttr("defaultResolution.width",1280) pm.setAttr("defaultResolution.height",720) bdSetCamera(camera,referenceCam) pm.playblast(format = 'avi', filename = pathMovie,forceOverwrite=1,sequenceTime=0,clearCache=0,viewer=0,showOrnaments=1,fp=4,percent = 100,compression=codec,quality=100, widthHeight= [1280, 720]) OM.MMessage.removeCallback(checkFileCallbackId)
def setTimeline(): #get current camera activeView = pm.playblast(activeEditor=1) activeCamera = pm.modelEditor(activeView, q=1, camera=1).name() camNameParts = activeCamera.split("_") startTime = int(camNameParts[-2]) endTime = int(camNameParts[-1]) pm.playbackOptions( animationEndTime=endTime, animationStartTime=startTime, maxTime=endTime, minTime=startTime )
def makePreviwe(self, percent, width, height): fileName = self.tempDir + self.getScene() + '.mov' aPlayBackSliderPython = pm.mel.eval('$tmpVar=$gPlayBackSlider') soundFile = pm.timeControl( aPlayBackSliderPython, q=True, sound=True) previewFile = pm.playblast(fp=4, format='qt', sound = soundFile, forceOverwrite=True, percent=percent, filename = fileName , viewer=0, quality=100, widthHeight=(width, height), compression="PNG") qtPath = 'C:\\Program Files (x86)\\QuickTime\\QuickTimePlayer.exe' subprocess.Popen([qtPath, previewFile])
def __createPlayblast(self, **overridePlayblastParams): localPlayblastPath = self.localPlayblastPath # setting playback range originalPlaybackRange = (pm.playbackOptions(query=True, minTime=True), pm.playbackOptions(query=True, maxTime=True)) startTime = pm.playbackOptions(query=True, animationStartTime=True) endTime = pm.playbackOptions(query=True, animationEndTime=True) pm.playbackOptions(edit=True, minTime=startTime, maxTime=endTime) # get playblast parameters from hook playblastParams = self._app.execute_hook("hook_setup_window", action="playblast_params", data=localPlayblastPath) # get window and editor parameters from hook createWindow = self._app.execute_hook("hook_setup_window", action='create_window') # with the created window, do a playblast with createWindow(): playblastParams.update(overridePlayblastParams) playblastSuccessful = False while not playblastSuccessful: try: # set required visibleHUDs from hook visibleHUDs = self._app.execute_hook("hook_setup_window", action="hud_set") print '\nparameters:', playblastParams resultPlayblastPath = pm.playblast(**playblastParams) playblastSuccessful = True except RuntimeError, e: result = QtGui.QMessageBox.critical( None, u"Playblast Error", "%s\n\n... or just close your QuickTime player, and Retry." % unicode(e), QtGui.QMessageBox.Retry | QtGui.QMessageBox.Abort) if result == QtGui.QMessageBox.Abort: self._app.log_error("Playblast aborted") return finally: # restore HUD state self._app.execute_hook("hook_setup_window",
def createCamSolidBG( camera=None ): ''' 카메라 백으로 사용할 솔리드한 Plane을 세움, 카메라 이름을 명시하거나, 모델패털을 포커스한 상태에서 실행. Version : 2015-02-24 >>> camSolidBG() (nt.Transform(u'persp_camSolidBG_grp'), nt.Transform(u'persp_camSolidBG_mesh'), nt.SurfaceShader(u'persp_camSolidBG_surfaceShader'), nt.ShadingEngine(u'persp_camSolidBG_SG')) >>> camSolidBG( camera='side' ) (nt.Transform(u'side_camSolidBG_grp'), nt.Transform(u'side_camSolidBG_mesh'), nt.SurfaceShader(u'side_camSolidBG_surfaceShader'), nt.ShadingEngine(u'side_camSolidBG_SG')) ''' if not camera: camera = pm.modelPanel( pm.playblast(activeEditor=True).split('|')[-1], q=True, camera=True ) mesh = pm.polyPlane(sh=1, sw=1, ch=False)[0] grp = pm.group() pm.parentConstraint(camera, grp) mesh.t.set(0,0,-500) mesh.r.set(90,0,0) mesh.s.set(150,150,150) shader, SG = pm.createSurfaceShader('surfaceShader') shader.outColor.set(0.5,0.5,0.5) pm.select(mesh) pm.hyperShade(assign=shader) mesh.castsShadows.set(False) mesh.receiveShadows.set(False) mesh.motionBlur.set(False) mesh.smoothShading.set(False) mesh.visibleInReflections.set(False) mesh.visibleInRefractions.set(False) grp. rename('%s_camSolidBG_grp' % camera) mesh. rename('%s_camSolidBG_mesh' % camera) shader.rename('%s_camSolidBG_surfaceShader' % camera) SG. rename('%s_camSolidBG_SG' % camera) return grp, mesh, shader, SG
def createFallowCam( ): ''' 캐릭터를 따라다니는 카메라 생성 ''' # 선택한 물체에서 네임 스페이스 얻어옴. ns = '' sel = pm.selected() if sel: ns = sel[0].namespace() # 컨스트레인 걸 대상 리스트 확보 jnts = ['Hips','Spine*','*Leg','*Foot'] #jnts = ['Spine*','*Foot'] targets = [] for j in jnts: targets.extend( pm.ls( ns + j, exactType='joint' ) ) # 확보 안됨 끝. if not targets: print u'캐릭터의 일부를 선택하세요.' return # 카메라와 그룹 생성 cam = pm.camera(n='followCam')[0] grp = pm.group( cam, n='followCam_grp' ) # 컨스트레인 const = pm.pointConstraint( targets, grp ); pm.delete(const) # 우선 위치에 배치하고 #pm.pointConstraint( targets, grp, skip='y' ) # 컨스트레인 pm.pointConstraint( targets, grp ) # 컨스트레인 # 카메라 조정 cam.tz.set(1200) cam.focalLength.set(100) cam.centerOfInterest.set(1200) cam.filmFit.set(2) # vertical # 패널 조정 activePanel = pm.playblast( activeEditor=True ).split('|')[-1] pm.modelPanel( activePanel, edit=True, camera=cam )
def writePB(fileNameFull, type): if type == 'mov': # Turn ON HUD pm.headsUpDisplay( rp = ( 6 , 1 ) ) # Delete HUD if exists by position hud = pm.headsUpDisplay ( 'HUD', section = 6, block = 1, blockSize = 'medium', label = codeProject.upper(), labelFontSize='large', command = dataFrame, attachToRefresh = True) if pm.ls(type = 'audio') == []: # make PB without sound pm.playblast(format = 'qt', compression = 'Sorenson Video 3',showOrnaments = 1, quality = 100, percent = 100, f = fileNameFull, width = 999, height = 540, forceOverwrite = 1 ) else: # make PB with sound audio = pm.ls(type = 'audio')[0] pm.playblast(format = 'qt', compression = 'Sorenson Video 3', s = audio, showOrnaments = 1, offScreen = 1, quality = 100, percent = 100, f = fileNameFull, width = 999, height = 540, forceOverwrite = 1 ) print 'PLAYBLAST DONE: ' + str(fileNameFull) elif type == 'jpg': pm.playblast(frame = pm.env.getTime(), format = 'image', compression = 'jpg', viewer = 0, showOrnaments = 0, quality = 100, percent = 100, completeFilename = fileNameFull, width = 999, height = 540, forceOverwrite = 1 ) shot = ftrack.getShotFromPath([codeProject, codePart, codeSequence, 'SHOT_' + str(codeShot) ]) thumbnail = shot.createThumbnail(fileNameFull) shot.setThumbnail(thumbnail) print 'SCREENSHOT SET IN FTRACK: ' + str(fileNameFull)
def __createPlayblast(self, **overridePlayblastParams): localPlayblastPath = self.localPlayblastPath # setting playback range originalPlaybackRange = ( pm.playbackOptions( query=True, minTime=True ), pm.playbackOptions( query=True, maxTime=True )) startTime = pm.playbackOptions( query=True, animationStartTime=True ) endTime = pm.playbackOptions( query=True, animationEndTime=True ) pm.playbackOptions( edit=True, minTime=startTime, maxTime=endTime ) # get playblast parameters from hook playblastParams = self._app.execute_hook("hook_setup_window", action="playblast_params", data=localPlayblastPath) # get window and editor parameters from hook createWindow = self._app.execute_hook("hook_setup_window", action='create_window') # with the created window, do a playblast with createWindow(): playblastParams.update(overridePlayblastParams) playblastSuccessful = False while not playblastSuccessful: try: # set required visibleHUDs from hook visibleHUDs = self._app.execute_hook("hook_setup_window", action="hud_set") resultPlayblastPath = pm.playblast( **playblastParams ) playblastSuccessful = True except RuntimeError, e: result = QtGui.QMessageBox.critical(None, u"Playblast Error", "%s\n\n... or just close your QuickTime player, and Retry." % unicode(e), QtGui.QMessageBox.Retry | QtGui.QMessageBox.Abort) if result==QtGui.QMessageBox.Abort: self._app.log_error("Playblast aborted") return finally: # restore HUD state self._app.execute_hook("hook_setup_window", action="hud_unset", data=visibleHUDs)
def playblast(self, options=None): """creates the selected shot playblasts """ # template vars sequence = self.sequence try: handle = self.handle.get() except AttributeError: # no handle is created probably the shot setup has not been done # correctly self.set_handle() handle = self.handle.get() start_frame = self.sequenceStartFrame.get() - handle end_frame = self.sequenceEndFrame.get() + handle width = self.wResolution.get() height = self.hResolution.get() extra_frame = 0 if platform.system() == 'Windows': # windows version of Maya 2014 drops 1 frame from end whereas # Linux doesn't do that if pm.versions.shortName() == '2014': extra_frame = 1 # store track track = self.track.get() try: movie_full_path = os.path.join( tempfile.gettempdir(), '%s.mov' % self.full_shot_name ).replace('\\', '/') except AttributeError: # this is an error I keep getting, somehow the extension is not # able to call full_shot_name # so as a workaround copy & paste the full_shot_name code here seq = self.sequence sm = seq.manager camera = self.currentCamera.get() version = sm.get_version() template = sm.get_shot_name_template() # replace template variables template = template \ .replace('<Sequence>', '%(sequence)s') \ .replace('<Shot>', '%(shot)s') \ .replace('<Version>', '%(version)s') \ .replace('<Camera>', '%(camera)s') rendered_template = template % { 'shot': self.shotName.get(), 'sequence': seq.sequence_name.get(), 'version': version, 'camera': camera.name() if camera else None } movie_full_path = os.path.join( tempfile.gettempdir(), '%s.mov' % rendered_template ).replace('\\', '/') # set the output of this shot self.set_output(movie_full_path) # mute all other shots sequence.mute_shots() self.unmute() default_options = { 'fmt': 'qt', 'sequenceTime': 1, 'forceOverwrite': 1, 'clearCache': 1, 'showOrnaments': 1, 'percent': 50, 'offScreen': 1, 'viewer': 0, 'compression': 'MPEG-4 Video', 'quality': 85, 'startTime': start_frame, 'endTime': end_frame + extra_frame, 'filename': movie_full_path, 'wh': [width, height], 'useTraxSounds': True, } if options: # offset end time by one frame if t his is windows if 'endTime' in options: options['endTime'] += extra_frame default_options.update(options) # include handles with self.include_handles: pm.system.dgdirty(a=True) # if a sound node is specified remove useTraxSounds flag import pprint pprint.pprint(default_options) result = pm.playblast(**default_options) sequence.unmute_shots() # restore track self.track.set(track) return result
def main(): prefRun() renderWidth = pm.getAttr("defaultResolution.width") renderHeight = pm.getAttr("defaultResolution.height") current_selection = pm.selected() currentState = toggleSpeakers(1) #toggle display color pm.displayRGBColor("background", 0.0, 0.0, 0.0) #get current camera activeView = pm.playblast(activeEditor=1) activeCamera = pm.modelEditor(activeView, q=1, camera=1).name() camNameParts = activeCamera.split("_") pbVersion ="" for camNamePart in camNameParts: if camNamePart[0] == "v": pbVersion = camNamePart startTime = int(camNameParts[-2]) endTime = int(camNameParts[-1]) setTimeline() pm.select(cl=1) pathWithVersion = "X:/Projects/GREY11_ANM71_Rewe_Starzone/GR11A71_Shots/GR11A71_Animatic/Animatic_Maya/data/%s/" % pbVersion playblastPath = pathWithVersion+activeCamera #make playblast pm.playblast( filename = playblastPath, format = "movie", width = renderWidth, height = renderHeight, percent = 100, compression = "none", quality = 100, forceOverwrite = 1, offScreen = 1, framePadding = 4, startTime = startTime, endTime = endTime, showOrnaments=0 ) pm.displayRGBColor("background", 0.632, 0.632, 0.632) pm.select(current_selection, r=1) toggleSpeakers(currentState)
def playblasting(newTake=False, takeGen=None): #validate input if newTake and takeGen is not None: raise ValueError, 'cannot specify takeGen with newTake set to True' if not newTake and takeGen is None: raise ValueError, 'takeGen is not specified' #fetch data from scene info project = cmds.getAttr('sceneInfo.projName', asString=True) projectCode = cmds.getAttr('sceneInfo.projCode', asString=True) episode = cmds.getAttr('sceneInfo.episodeName', asString=True) shot = cmds.getAttr('sceneInfo.shotName', asString=True) frameCount = int(cmds.getAttr('sceneInfo.frameCount', asString=True)) #validate cam existance if not cmds.objExists('cam'): raise StandardError, 'No cam group exists within scene file.' #upload file normally uploadSeq() #generate general path genPath = SEQUENCE_ROOT+'/'+project+'/PLAYBLAST/'+episode #generate localTemp variable time = timestamp() localTemp = WIN_ROOT+'workspace/'+episode+'_'+shot+'_'+time+'.mov' #generating takeGen if user want to set new take if newTake: searchStr = str(projectCode)+'_'+str(episode)+'_'+str(shot)+'_TK' playblasts = [] for item in os.listdir(genPath+'/playblast'): if item.find(searchStr) != -1: playblasts.append(item) takeGen = str(len(playblasts)+1) #playblasting if takeGen is not None: #impose frameCount cmds.playbackOptions(min=101, max=101+(int(frameCount)-1)) winpbt = cmds.window('playblaster', t='Playblast', s=False) cmds.columnLayout(w=int(PLB_RESWIDTH), h=int(PLB_RESHEIGHT)) cmds.paneLayout(w=int(PLB_RESWIDTH), h=int(PLB_RESHEIGHT)) tmppnl = cmds.modelPanel(cam='shotCAM',mbv=False) cmds.modelEditor(cam='shotCAM', mp=tmppnl, dtx=True, j=False,\ ca=False, nc=False, pm=True, da='smoothShaded', lt=False) cmds.showWindow() cmds.setFocus(tmppnl) #playblasting mel.eval("setDisplaySmoothness 3;") pc.playblast(f=localTemp,\ fo=True,\ fmt=PLB_FORMAT,\ c=PLB_CODEC,\ p=80,\ qlt=100,\ uts=True,\ wh=[int(PLB_RESWIDTH)/1,int(PLB_RESHEIGHT)/1]) mel.eval("setDisplaySmoothness 1;") cmds.deleteUI('playblaster', window=True) #playblast file operation if os.path.isdir(genPath+'/playblast') == False:os.makedirs(genPath+'/playblast') shutil.copy(localTemp, genPath+'/playblast/'+projectCode+'_'+episode+'_'+shot+'_TK'+takeGen+'.mov') os.remove(localTemp) #save take file [continue from here] if not os.path.isdir(genPath+'/file'):os.makedirs(genPath+'/file') currentName = cmds.file(q=True, sn=True) shutil.copy(currentName, genPath+'/file/'+projectCode+'_'+episode+'_'+shot+'_TK'+takeGen+'.ma') #open playblast file os.startfile(genPath+'/playblast/'+projectCode+'_'+episode+'_'+shot+'_TK'+takeGen+'.mov') return
def viewportCapture(cls, camera_node, model_panel, path=None, toSquare=False, height=600, width=960, file_format='jpg'): from tempfile import NamedTemporaryFile file_path = NamedTemporaryFile(suffix=".%s" % file_format, delete=False) pmc.setFocus(model_panel) pmc.modelPanel( model_panel, edit=True, camera=camera_node ) pmc.modelEditor( model_panel, edit=True, allObjects=False, polymeshes=True, wireframeOnShaded=False, displayAppearance='smoothShaded' ) pmc.camera( camera_node, edit=True, displayFilmGate=False, displayResolution=False, overscan=1 ) # Capture image pmc.playblast( frame=pmc.currentTime(query=True), format="image", completeFilename=file_path.name, compression=file_format, percent=100, quality=100, viewer=False, height=height, width=width, offScreen=True, showOrnaments=False ) # Store img var and delete file q_image = QtGui.QImage(file_path.name) image_width = q_image.size().width() image_height = q_image.size().height() file_path.close() os.unlink(file_path.name) # Crop image if toSquare is True: rect = cls.get_containedSquare(image_width, image_height) else: rect = QtCore.QRect(0, 0, image_width, image_height) cropped = q_image.copy(rect) # Save image File if path is not None: cropped.save(fullPath, file_format, quality) return cropped, path, rect
def playblast(self, options=None): """creates the selected shot playblasts """ # template vars sequence = self.sequence try: handle = self.handle.get() except AttributeError: # no handle is created probably the shot setup has not been done # correctly self.set_handle() handle = self.handle.get() start_frame = self.sequenceStartFrame.get() - handle end_frame = self.sequenceEndFrame.get() + handle width = self.wResolution.get() height = self.hResolution.get() extra_frame = 0 if platform.system() == 'Windows': # windows Maya version drops 1 frame from end where as Linux # doesn't do that extra_frame = 1 # store track track = self.track.get() movie_full_path = os.path.join( tempfile.gettempdir(), '%s.mov' % self.full_shot_name ).replace('\\', '/') # set the output of this shot self.set_output(movie_full_path) # mute all other shots sequence.mute_shots() self.unmute() default_options = { 'fmt': 'qt', 'sequenceTime': 1, 'forceOverwrite': 1, 'clearCache': 1, 'showOrnaments': 1, 'percent': 50, 'offScreen': 1, 'viewer': 0, 'compression': 'MPEG-4 Video', 'quality': 85, 'startTime': start_frame, 'endTime': end_frame + extra_frame, 'filename': movie_full_path, 'wh': [width, height], 'useTraxSounds': True, } if options: # offset end time by one frame if t his is windows if 'endTime' in options: options['endTime'] += extra_frame default_options.update(options) # include handles with self.include_handles: pm.system.dgdirty(a=True) # if a sound node is specified remove useTraxSounds flag import pprint pprint.pprint(default_options) result = pm.playblast(**default_options) sequence.unmute_shots() # restore track self.track.set(track) return result