def renderScene(self, *args): minFrame = cmds.intFieldGrp(self.renderFrames, q=True, value1=True) maxFrame = cmds.intFieldGrp(self.renderFrames, q=True, value2=True) if minFrame < 0 or maxFrame <= 0: cmds.confirmDialog(title='Error', message='Please enter a valid frame range.', button=['OK'], defaultButton='OK') else: cameraName = cmds.textField(self.cameraInput, q=True, tx=True) camList = cmds.ls(cameras=True) validCam = False for obj in camList: cam = obj[:-5] if cameraName == cam: validCam = True break if validCam == True: for i in range(minFrame, maxFrame + 1): cmds.currentTime(i, e=True, u=False) cmds.currentTime(i, e=True, u=True) cmds.render(cameraName) else: cmds.confirmDialog( title='Error', message='Please load valid camera or use default.', button=['OK'], defaultButton='OK')
def renderMaya(self, ts, te, outFile=""): print "\n\n\n" print " REND : ", ts, te, outFile, "_____!" print "\n\n\n" if len(outFile) == 0: print " renderMaya no OUT FILE ", outFile else: basename = os.path.basename(outFile) outDir = outFile[:-1 * len(basename)] outFileHeader = basename.split(".")[0] outFileExt = basename.split(".")[1] print " SimC Rend ! ", outDir, outFileHeader, outFileExt frStart = self.intOrVal(ts, 0) frEnd = self.intOrVal(te, 0) # ma = hou.node('out/mantra_ipr') # for fr in range (frStart, frEnd+1): # frZeros = self.strWithZeros( fr , 4 ) # outputFile = "{}{}.{}.{}".format( outDir , outFileHeader, frZeros, outFileExt) # ma.render( frame_range = (fr,fr) , output_file= outputFile ) # import time # time.sleep(2) import maya.cmds as cmx for fr in range(1, 70): cmx.currentTime(fr) cmx.refresh() fi = outFile[:-6] + "__" + self.strWithZeros( fr, 3) + ".jpg" #### hack rend print fi fi = fi.replace('\\', '/') print fi ##### maya 16 # editores = cmx.renderWindowEditor(q=True) #, editorName=True ) # if( len(editores) == 0 ): # editores = cmx.renderWindowEditor( "renderView" ) ##### maya 16 editores = cmx.renderWindowEditor("renderView", q=True) #, editorName=True ) if (editores == None): editores = cmx.renderWindowEditor("renderView", e=True) cmx.render('persp', x=800, y=450) cmx.setAttr('defaultRenderGlobals.imageFormat', 8) cmx.renderWindowEditor( editores, e=True, writeImage=fi) # currentCamera='persp',
def flat_render(c): mel.eval('select -r shirt;') mel.eval('shadingNode -asShader lambert;') mel.eval('rename lambert2 "shirt_mat";') mel.eval('sets -renderable true -noSurfaceShader true' + \ '-empty -name -shirt_matSG;') mel.eval('connectAttr -f shirt_mat.outColor shirt_matSG.surfaceShader;') mel.eval('setAttr "shirt_mat.color" -type double3 1 1 1;') mel.eval('setAttr "shirt_mat.ambientColor" -type double3 1 1 1;') mel.eval('select -r shirt ; sets -e -forceElement shirt_matSG;') cmds.render(c[0], x=RENDER_WIDTH, y=RENDER_HEIGHT)
def addCurrentToSelection(self, *args): currentTree = self.getCurrentWeights() self.generationSelection.append(currentTree) IMG_PATH = 'C:/Users/cs/Documents/maya/projects/rigGAShri/images/tmp/' SELECTION_SIZE = len(self.generationSelection) currentRenderFile = "GASelectionGen%i" % SELECTION_SIZE cmds.setAttr("defaultRenderGlobals.imageFilePrefix", currentRenderFile, type="string") cmds.render('renderCam') print "Rendering %s\n" % currentRenderFile selectionUI = 'selectionUI' if cmds.window(selectionUI, exists=True): cmds.deleteUI(selectionUI) cmds.window(selectionUI, width=300, height=100) cmds.columnLayout("allLayout", adjustableColumn=True) cmds.columnLayout("topLayout", parent="allLayout") cmds.button('selectAll', label='Select All', command=partial(self.changeAllSelection, True), parent="topLayout") cmds.button('clearAll', label='Clear All', command=partial(self.changeAllSelection, False), parent="topLayout") cmds.separator(parent="allLayout") cmds.gridLayout("gridLayout", numberOfColumns=6, cellWidthHeight=(256, 256), parent="allLayout") buttonList = [] for face in range(SELECTION_SIZE): currentImg = IMG_PATH + "GASelectionGen" + str(face + 1) + ".jpeg" print currentImg buttonName = 'button%i' % face buttonList.append(buttonName) print buttonList cmds.symbolCheckBox(buttonName, image=currentImg, parent="gridLayout") cmds.showWindow(selectionUI) self.buttonList = buttonList
def Render(k, *args): formatManager = createImageFormats.ImageFormats() formatManager.pushRenderGlobalsForDesc("JPEG") mc.render() global renderpath mc.renderWindowEditor(makeCamera.editor, crc=str(makeCamera.cam[0]), e=True, writeImage=str(renderpath[0] + '/testImage' + str(k) + '.jpg')) formatManager.popRenderGlobals()
def mkThumbNail(): # get file name and path for thumbnail files = maya.cmds.file(query=1, list=1, withoutCopyNumber=1) changeformat = 'setAttr "defaultRenderGlobals.imageFormat" 8;' thumbFileName = files[0].replace( '.mb', '.jpg' ) mel.eval(changeformat) currentCam = mkRenderCam() if currentCam == " ": cmds.warning ("no renderable camera") # render and save image cmds.render(currentCam[0], x= 720, y =405) editor = 'renderView' cmds.renderWindowEditor(editor, e = True, writeImage = thumbFileName) return thumbFileName
def mkThumbNail(): # get file name and path for thumbnail files = maya.cmds.file(query=1, list=1, withoutCopyNumber=1) changeformat = 'setAttr "defaultRenderGlobals.imageFormat" 8;' thumbFileName = files[0].replace('.mb', '.jpg') mel.eval(changeformat) currentCam = mkRenderCam() if currentCam == " ": cmds.warning("no renderable camera") # render and save image cmds.render(currentCam[0], x=720, y=405) editor = 'renderView' cmds.renderWindowEditor(editor, e=True, writeImage=thumbFileName) return thumbFileName
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 renderSnapShot(presetName="iconSnapShot_mec", width=50, height=50, iconName='icon', iconFormat=imageTypes['png'], presetOrginal=['defaultRenderQuality', 'defaultRenderGlobals', 'defaultResolution'], iconPath=currPath): state = createPresets( presetName, presetOrginal ) if( state ): mel.eval( 'unifiedRenderGlobalsRevertToDefault' ) renderConn = cmds.listConnections( 'defaultRenderGlobals.resolution' ) # bmp == 20, jpg == 8 # imgFormat = 20 cmds.setAttr( 'defaultRenderGlobals.imageFormat', imgFormat ) cmds.setAttr( '%s.width' %renderConn[0] , width ) cmds.setAttr( '%s.height' %renderConn[0] , height ) cmds.setAttr( 'defaultRenderGlobals.imageFilePrefix', iconName, type='string') fileName = cmds.render('camera1') loadRemovePreset( presetName ) # From here # dest = r'C:\Documents and Settings\mclavan\My Documents\maya\New_Project\tmp' # dest = os.path.join( dest, fileName ) # To There. # targ = r'C:\Documents and Settings\mclavan\Desktop\scenes' # targ = os.path.join( targ, fileName ) dest = fileName targ = os.path.join( iconPath, os.path.split(fileName)[-1] ) print("Dest: %s Targ: %s" %(dest, targ)) shutil.move( dest, targ ) else: print("Duplicate presetName... Try Again")
def save_image_with_camera_pos(csv_writer, mesh_name, file_ext, dest_dir, camera_pos, camera_interest_pos): camera_name, camera_shape = cmd.camera(p=camera_pos, wci=camera_interest_pos) cmd.setAttr(camera_shape+'.backgroundColor', back_color[0], back_color[1], back_color[2], type="double3") cmd.setAttr(camera_shape+".renderable", 1) focal_length = cmd.camera(camera_shape, q=True, fl=True) inches_to_mm = 25.4 app_horiz = cmd.camera(camera_shape, q=True, hfa=True) * inches_to_mm app_vert = cmd.camera(camera_shape, q=True, vfa=True) * inches_to_mm pixel_width = cmd.getAttr("defaultResolution.width") pixel_height = cmd.getAttr("defaultResolution.height") focal_length_x_pixel = pixel_width * focal_length / app_horiz focal_length_y_pixel = pixel_height * focal_length / app_vert # print cmd.camera(camera_shape, q=True, fs=True) # print focal_length # print app_horiz, app_vert # print focal_length_x_pixel, focal_length_y_pixel image_file = mesh_name+"."+file_ext image_src = cmd.render(camera_shape) image_dest = path.join(dest_dir, image_file) shutil.move(image_src, image_dest) save_camera_data_to_writer(csv_writer, mesh_name, camera_pos, camera_interest_pos, focal_length)
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 save_image_with_camera_pos(csv_writer, mesh_name, file_ext, dest_dir, camera_pos, camera_interest_pos): camera_name, camera_shape = cmd.camera(p=camera_pos, wci=camera_interest_pos) cmd.setAttr(camera_shape + '.backgroundColor', back_color[0], back_color[1], back_color[2], type="double3") cmd.setAttr(camera_shape + ".renderable", 1) focal_length = cmd.camera(camera_shape, q=True, fl=True) inches_to_mm = 25.4 app_horiz = cmd.camera(camera_shape, q=True, hfa=True) * inches_to_mm app_vert = cmd.camera(camera_shape, q=True, vfa=True) * inches_to_mm pixel_width = cmd.getAttr("defaultResolution.width") pixel_height = cmd.getAttr("defaultResolution.height") focal_length_x_pixel = pixel_width * focal_length / app_horiz focal_length_y_pixel = pixel_height * focal_length / app_vert # print cmd.camera(camera_shape, q=True, fs=True) # print focal_length # print app_horiz, app_vert # print focal_length_x_pixel, focal_length_y_pixel image_file = mesh_name + "." + file_ext image_src = cmd.render(camera_shape) image_dest = path.join(dest_dir, image_file) shutil.move(image_src, image_dest) save_camera_data_to_writer(csv_writer, mesh_name, camera_pos, camera_interest_pos, focal_length)
def mkThumbNail(fileName,zipfile): # get file name and path for thumbnail changeformat ='setAttr "defaultRenderGlobals.imageFormat" 8;' files = fileName thumbFileName = files[0].replace( '.mb', '.jpg' ) mel.eval(changeformat) currentCam =mkRenderCam() if currentCam == " ": cmds.warning ("no renderable camera") # render and save image cmds.render(currentCam[0], x= 720, y =405) editor = 'renderView' cmds.renderWindowEditor(editor, e = True, writeImage = thumbFileName) newFolder = mkIngestionDir(thumbFileName,'.jpg') mkIngestionDir(zipfile,'.zip') DepotIngestion() removeFolder(newFolder)
def reRender(*args): if currentRender == 'arnold': cmds.arnoldRender(cam=camera1) elif currentRender == 'vray': vrendCommand = 'vrend -camera %s' % (camera0) mel.eval(vrendCommand) elif currentRender == 'mentalRay': cmds.Mayatomr(pv=True, cam=camera0) else: cmds.warning( 'Render engine not supported. Rendering using Maya Software renderer.' ) cmds.render(camera1)
def main(path): # if(os.path.splitext(path)[1] == '.fbx'): # cmds.loadPlugin('fbxmaya.mll') cmds.file(path, o=True, f=True) cmds.viewSet('perspShape', p=True) cmds.viewFit('perspShape', all=True) cmds.viewSet('perspShape', p=True) meshes = cmds.ls(type='mesh') maxMeshes = 0 for mesh in meshes: numTris = cmds.polyEvaluate(mesh, t=True) if maxMeshes < numTris: maxMeshes = numTris cmds.select(mesh) cmds.viewFit('perspShape', fitFactor=1.0) a = cmds.getAttr('persp.translate') aa = a[0] cmds.viewFit('perspShape', fitFactor=0.7) b = cmds.getAttr('persp.translate') bb = b[0] result = [x + x - y for (x, y) in zip(aa, bb)] print(result) cmds.setAttr('persp.translateX', result[0]) cmds.setAttr('persp.translateY', result[1]) cmds.setAttr('persp.translateZ', result[2]) cmds.setAttr('perspShape.renderable', 1) cmds.setAttr('defaultRenderGlobals.enableDefaultLight', 1) cmds.setAttr('defaultResolution.width', 640) cmds.setAttr('defaultResolution.height', 480) cmds.setAttr('defaultRenderGlobals.imageFormat', 8) cmds.setAttr('defaultRenderGlobals.animation', 0) cmds.setAttr('defaultRenderGlobals.outFormatControl', 0) cmds.setAttr('defaultRenderGlobals.periodInExt', 0) cmds.setAttr('defaultRenderGlobals.putFrameBeforeExt', 1) # cmds.displayPref(wsa='none') # cmds.hide(cmds.ls(type='joint')) fixTexturePath(path) cmds.render(batch=True)
def renderShelfIcon(name='tmp', width=32, height=32): ''' This renders a shelf-sized icon and hopefully places it in your icon directory ''' imageName = name #getCamera cam = getCurrentCamera() #save these values for resetting currentRenderer = mc.getAttr('defaultRenderGlobals.currentRenderer') imageFormat = mc.getAttr('defaultRenderGlobals.imageFormat') mc.setAttr('defaultRenderGlobals.currentRenderer', 'mayaSoftware', type='string') mayaVersion = mm.eval('getApplicationVersionAsFloat') imageFormat = 50 #XPM if mayaVersion >= 2011: imageFormat = 32 #PNG mc.setAttr('defaultRenderGlobals.imageFormat', imageFormat) mc.setAttr('defaultRenderGlobals.imfkey', 'xpm', type='string') #here's the imageName mc.setAttr('defaultRenderGlobals.imageFilePrefix', imageName, type='string') mc.setAttr(cam + '.backgroundColor', 0.8, 0.8, 0.8, type='double3') #need to reset this afterward image = mc.render(cam, xresolution=width, yresolution=height) base = os.path.basename(image) #here we attempt to move the rendered icon to a more generalized icon location #we want the default user icon directory, so match up a directory in the icon invironment path appDir = os.environ['MAYA_APP_DIR'] for each in os.environ['XBMLANGPATH'].split(':'): #on some linux systems each path ends with %B, for some reason iconPath = each.replace('%B', '') if iconPath.startswith(appDir) and os.path.exists(iconPath): newPath = os.path.abspath(iconPath) newPath = '/'.join((newPath, base)) image = shutil.move(image, newPath) image = newPath break #reset mc.setAttr('defaultRenderGlobals.currentRenderer', currentRenderer, type='string') mc.setAttr('defaultRenderGlobals.imageFormat', imageFormat) return image
def render_image(self, camera_pos, camera_interest_pos, obj_key=None, mesh_filename=None): """ Creates a rendered image object for the mesh in |mesh_filename| """ # setup camera camera_name, camera_shape = cmd.camera(p=camera_pos, wci=camera_interest_pos, wup=[0, 0, 1], fl=self.focal_length_, hfa=self.app_horiz_, vfa=self.app_vert_) cmd.setAttr(camera_shape + '.backgroundColor', self.back_color_['r'], self.back_color_['g'], self.back_color_['b'], type="double3") cmd.setAttr(camera_shape + ".renderable", 1) camera_rot = cmd.camera(camera_shape, q=True, rotation=True) pixel_width = cmd.getAttr("defaultResolution.width") pixel_height = cmd.getAttr("defaultResolution.height") # render the image image_src = cmd.render(camera_shape) im = Image.open(image_src) im_arr = np.array(im) # optionally normalize the rendered image if self.normalize_: im_arr = self.normalize_image(im_arr) # crop the rendered images center = np.array(im_arr.shape) / 2.0 start_i = center[0] - self.output_image_height_ / 2.0 end_i = center[0] + self.output_image_height_ / 2.0 start_j = center[1] - self.output_image_width_ / 2.0 end_j = center[1] + self.output_image_width_ / 2.0 im_arr = im_arr[start_i:end_i, start_j:end_j] # optional save if mesh_filename is not None: image_filename = mesh_filename + self.file_type_ image_dest = path.join(self.dest_dir_, obj_key, image_filename) im = Image.fromarray(np.uint8(im_arr)) im.save(image_dest) # create rendered image rendered_image = ri.RenderedImage(im_arr, camera_pos, camera_rot, camera_interest_pos) return rendered_image
def render(cam, dst_path, width, height): tmp_path = cmd.render(cam, xresolution=width, yresolution=height) ext = splitext(tmp_path) parent_folder = dirname(dst_path) if not exists(parent_folder): makedirs(parent_folder) if exists(dst_path): unlink(dst_path) rename(tmp_path, dst_path) print('Saved to ' + dst_path)
def makeIcon() : # Making icon for Chima width = 1280 height = 720 ratio = 16.0000/9.0000 currWidth = mc.getAttr( 'defaultResolution.width' ) currHeight = mc.getAttr( 'defaultResolution.height' ) currRatio = mc.getAttr( 'defaultResolution.deviceAspectRatio' ) mc.setAttr( 'defaultResolution.lockDeviceAspectRatio' , 1 ) if currWidth == width and currHeight == height : mc.setAttr( 'defaultRenderQuality.shadingSamples' , 1 ) mc.setAttr( 'defaultRenderGlobals.imageFormat' , 32 ) currPath = mc.file( q=True , sn=True ) charName = currPath.split( '/' )[ -1 ].split( '_' )[ 0 ] iconPath = '' splitters = ( 'ref' , 'dev' ) currSplitter = '' for splitter in splitters : if splitter in currPath : currSplitter = splitter iconPath = '%simages/icon/%s.png' % ( currPath.split( currSplitter )[0] , charName ) mc.render() mm.eval( 'renderWindowSaveImageCallback "renderView" "%s" "PNG"' % iconPath ) print iconPath else : mc.setAttr( 'defaultResolution.width' , width ) mc.setAttr( 'defaultResolution.height' , height ) mc.setAttr( 'defaultResolution.deviceAspectRatio' , ratio )
def renderShelfIcon(name='tmp', width=32, height=32): ''' This renders a shelf-sized icon and hopefully places it in your icon directory ''' imageName=name #getCamera cam = getCurrentCamera() #save these values for resetting currentRenderer = mc.getAttr('defaultRenderGlobals.currentRenderer') imageFormat = mc.getAttr('defaultRenderGlobals.imageFormat') mc.setAttr('defaultRenderGlobals.currentRenderer', 'mayaSoftware', type='string') mayaVersion = mm.eval('getApplicationVersionAsFloat') imageFormat = 50 #XPM if mayaVersion >= 2011: imageFormat = 32 #PNG mc.setAttr('defaultRenderGlobals.imageFormat', imageFormat) mc.setAttr('defaultRenderGlobals.imfkey', 'xpm', type='string') #here's the imageName mc.setAttr('defaultRenderGlobals.imageFilePrefix', imageName, type='string') mc.setAttr(cam+'.backgroundColor', 0.8,0.8,0.8, type='double3') #need to reset this afterward image = mc.render(cam, xresolution=width, yresolution=height) base = os.path.basename(image) #here we attempt to move the rendered icon to a more generalized icon location newPath = getIconPath() newPath = os.path.join((newPath, base)) shutil.move(image, newPath) image = newPath #reset mc.setAttr('defaultRenderGlobals.currentRenderer', currentRenderer, type='string') mc.setAttr('defaultRenderGlobals.imageFormat', imageFormat) return image
def renderSnapShot(presetName="iconSnapShot_mec", width=50, height=50, iconName='icon', iconFormat=imageTypes['png'], presetOrginal=[ 'defaultRenderQuality', 'defaultRenderGlobals', 'defaultResolution' ], iconPath=currPath): state = createPresets(presetName, presetOrginal) if (state): mel.eval('unifiedRenderGlobalsRevertToDefault') renderConn = cmds.listConnections('defaultRenderGlobals.resolution') # bmp == 20, jpg == 8 # imgFormat = 20 cmds.setAttr('defaultRenderGlobals.imageFormat', imgFormat) cmds.setAttr('%s.width' % renderConn[0], width) cmds.setAttr('%s.height' % renderConn[0], height) cmds.setAttr('defaultRenderGlobals.imageFilePrefix', iconName, type='string') fileName = cmds.render('camera1') loadRemovePreset(presetName) # From here # dest = r'C:\Documents and Settings\mclavan\My Documents\maya\New_Project\tmp' # dest = os.path.join( dest, fileName ) # To There. # targ = r'C:\Documents and Settings\mclavan\Desktop\scenes' # targ = os.path.join( targ, fileName ) dest = fileName targ = os.path.join(iconPath, os.path.split(fileName)[-1]) print("Dest: %s Targ: %s" % (dest, targ)) shutil.move(dest, targ) else: print("Duplicate presetName... Try Again")
def render_image(fn, camera=None, time=None): """ Do a render """ if time is not None: set_time(time) if camera is None: camera = cmds.camera() tmp_path = cmds.render(camera) #cmds.render( cam[0], x=768, y=576 ) p = os.path.join(IMAGE_DIRECTORY, fn) shutil.move(tmp_path, p) print(p) return p
def render(startFrame = None,endFrame = None,frameStep = 1, render_dir = None, renderLayer = None,camera = None, renderer = 'sw',**kwargs): # 解析输入参数 startFrame = startFrame if startFrame not in ['None'] else None endFrame = endFrame if endFrame not in ['None'] else None render_dir = render_dir if render_dir not in ['None'] else None renderLayer = renderLayer if renderLayer not in ['None'] else None camera = camera if camera not in ['None'] else None renderer = renderer if renderer not in ['None'] else None # 渲染相关设置 scenepath = os.path.abspath(kwargs['scene_path']) print("\nSTEP 0 获取场景路径: {}\n".format(scenepath)) workspace = cmds.workspace(q=True,fullName = True) # /maya/projects/default print("\nSTEP 1 获取工作空间: {}\n".format(workspace)) if not render_dir: render_dir = '/'.join([workspace,'images']) print("\nSTEP 2.1 设置渲染图片路径: {}\n".format(render_dir)) if not os.path.isdir(render_dir): try: os.makedirs(render_dir) print("\nSTEP 2.2 新建图片路径: {}\n".format(render_dir)) except: raise Exception('can not make Folder named: %s ' % render_dir) open_scene(scenepath) refs = list_referenced_files() print("\nSTEP 4 场景相关文件: {} \n".format(refs)) # 设置起始和结束帧 if not startFrame: startFrame = int(cmds.currentTime(query = True)) if (not endFrame) or (endFrame < startFrame): endFrame = startFrame # startFrame,endFrame = playback_selection_range() print("\nSTEP 5 起始帧: {} 结束帧: {}\n".format(startFrame,endFrame)) # 设置渲染层, 不同的渲染器对渲染层有不同的配置参数 if not renderLayer: renderLayer = cmds.editRenderLayerGlobals(q = True,currentRenderLayer = True) print("\nSTEP 6.1 未指定渲染层,获取当前渲染层: {}\n".format(renderLayer)) elif renderLayer not in cmds.ls(type = 'renderLayer'): renderLayer = cmds.editRenderLayerGlobals(q = True,currentRenderLayer = True) print('\nSTEP 6.2 指定的渲染层不在当前maya环境上, 使用默认的渲染层: %s\n' %(renderLayer)) else: if cmds.editRenderLayerGlobals(q = True,currentRenderLayer = True) != renderLayer: cmds.editRenderLayerGlobals(currentRenderLayer = renderLayer) print('\nSTEP 6.3 指定的渲染层在当前maya环境上,但不是当前默认渲染层,设置为默认渲染层: %s\n' %(renderLayer)) # 设置摄像机 render_cam = 'persp' change_render_cam(render_cam) print("\nSTEP 7 设置默认摄像机: {}\n".format(render_cam)) # get camera 获取摄像机 if not camera: _cameras = [i for i in cmds.listCameras(p = True) if cmds.getAttr('%s.renderable' % i)] if _cameras: camera = _cameras[0] else: camera = 'persp' print("\nSTEP 8 当前使用的摄像机: {}\n".format(camera)) #打印当前渲染器设置 # render_glob = "defaultRenderGlobals" # list_Attr = cmds.listAttr(render_glob, r=True, s=True) # print("\n") # for attr in list_Attr: # get_attr_name = "%s.%s"%(render_glob, attr) # print("STEP 9 默认Render的全局配置信息: {} = {}".format(get_attr_name, cmds.getAttr(get_attr_name))) # print("\n") # load renderer 加载渲染器 currenders = cmds.renderer(q=True, namesOfAvailableRenderers=True) print('\nSTEP 9 当前可用的渲染器有: {} \n'.format(currenders)) print("\nSTEP 10 当前插件路径: {} \n".format(os.environ['MAYA_PLUG_IN_PATH'])) cmds.loadPlugin( allPlugins=True ) if renderer: if renderer: if renderer != cmds.getAttr('defaultRenderGlobals.currentRenderer'): renderer_dict = {'vray':'vrayformaya', 'arnold':'mtoa', 'mentalRay':'Mayatomr'} for key in renderer_dict.keys(): if renderer == key: if not cmds.pluginInfo(renderer_dict[key], q=True, l=True): try: cmds.loadPlugin(renderer_dict[key]) break except: raise Exception('can not load vray renderer') try: cmds.setAttr('defaultRenderGlobals.currentRenderer',renderer,type = 'string') except: raise Exception('error: set currentRenderer %s fail' % renderer) else: renderer = cmds.getAttr('defaultRenderGlobals.currentRenderer') print('\nSTEP 12 指定的渲染器位当前默认渲染器: %s\n' %(renderer)) w, h = scene_resolution() print('\nSTEP 13 当前图片分辨率:X={} Y={} .\n'.format(w,h)) # 设置图像输出格式 cmds.getAttr('defaultRenderGlobals.imageFormat',asString = True) _format = getFormatType("PNG") print('\nSTEP 14 设置输出图像的格式: %s\n' %(_format)) print('# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #') print('STEP 15 开始执行渲染任务...\n') cd = int(endFrame) + 1 for i in range(int(startFrame), int(cd)): cmds.currentTime(i, u = True) if renderer == 'sw': cmds.render() elif renderer == 'mr': out = cmds.Mayatomr(preview = True, camera = camera) print("cmds.Mayatomr:",out) else: pass if renderer == 'vray': cmds.setAttr ('defaultRenderGlobals.animation', 1 ) cmds.setAttr ('defaultRenderGlobals.startFrame', startFrame ) cmds.setAttr ('defaultRenderGlobals.endFrame', endFrame ) print(cmds.setAttr ('vraySettings.animBatchOnly', 0)) out = pm.vrend(preview = True,camera = camera) print("pm.vrend:",out) elif renderer == 'arnold': for i in range(startFrame,endFrame+1,1): cmds.currentTime(i) out = cmds.arnoldRender(seq=str(i),camera = camera ) print("cmds.arnoldRender:",out) print('# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #')
import maya.cmds as cmds import time #Select the object you want rotated selected = cmds.ls(sl= True, long= True) s = 0 results = [] while s <= 24 : s = s + 1 ; time.sleep(.25) print "s" cmds.rotate(0, 10, 0, relative=True, componentSpace=True) cmds.setAttr("defaultRenderGlobals.imageFormat", 32) result = cmds.render('persp', x=512, y=512) print results if s == 25 : print "reload"
import maya.cmds as cmds cmds.render() cam = cmds.camera() cmds.render(cam[0], x=768, y=576)
def batch_render(): del_pointcloud() #autoload Mental-Ray, from http://forums.cgsociety.org/archive/index.php/t-1001360.html #cmds.loadPlugin('Mayatomr', quiet=True) #cmds.setAttr('defaultRenderGlobals.ren', 'mentalRay', type='string') cmds.undoInfo(state=False) #imageFormat 32 means PNG, from here: http://www.oputo.com/html/blog/2010/06/12/defaultrenderglobals-imageformat/ cmds.setAttr('defaultRenderGlobals.imageFormat', 32) #hide our TEMPLATE cmds.hide( "template_skin" ) cmds.hide( "template_bone" ) input_bones_list = cmds.getFileList(folder=path_of_files, filespec='bone*.obj') frames_rendered = 0 for curr_bone in input_bones_list: #take off the .obj, then get the last four digits of the name of the file #split_name = curr_bone.split('.') #file_name = split_name[0] #curr_digits = file_name[-4:] #print curr_digits curr_digits, bone_name, frm_name = get_bone_digit(curr_bone) # Assign shader to objects if draw_mesh: cmds.file(path_of_files + bone_name, i=True) cmds.file(path_of_files + frm_name, i=True) cmds.sets("Mesh", edit=True, forceElement="boneShader") frm_mesh_name = "frm" + curr_digits + "_Mesh" cmds.sets(frm_mesh_name, edit=True, forceElement="skinShader") cmds.select('Mesh') cmds.polySoftEdge(a=soften_angle) cmds.select(frm_mesh_name) cmds.polySoftEdge(a=soften_angle) #load the point cloud if draw_points: point_cloud_file = path_of_files + "frm" + curr_digits + ".xyz" load_xyz( point_cloud_file ) path_to_file = cmds.render() if path_to_file[-3:] != "png": print "Render is NOT outputting pngs! Quitting..." break #rename the rendered file output_name = "frame" + curr_digits + ".png" split_path = path_to_file.split('/') split_path[-1] = output_name new_path = "/".join(split_path) #os.rename(path_to_file, new_path) move(path_to_file, new_path) print 'RENDERED TO: ', new_path #delete the meshes if draw_mesh: cmds.select('Mesh') cmds.delete() frm_mesh_name = "frm" + curr_digits + "_Mesh" cmds.select(frm_mesh_name) cmds.delete() #delete the point cloud if draw_points: del_pointcloud() frames_rendered = frames_rendered + 1 if frames_rendered > max_num_frames: break #show our templates cmds.showHidden( "template_skin" ) cmds.showHidden( "template_bone" ) load_xyz( path_of_files + "frm0000.xyz" )
""" # -*- coding: utf-8 -*- """ Created on Thu Dec 8 11:48:14 2011 @author: - """ from maya import mel from maya import cmds startFrame = cmds.getAttr("defaultRenderGlobals.startFrame") endFrame = cmds.getAttr("defaultRenderGlobals.endFrame") gMainProgressBar = maya.mel.eval('$tmp = $gMainProgressBar'); cmds.progressBar( gMainProgressBar, edit=True, beginProgress=True, isInterruptable=True, status="Rendering...", maxValue=endFrame) for i in range(startFrame,endFrame): if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True ) : break cmds.currentTime( i ) cmds.render() cmds.progressBar(gMainProgressBar, edit=True, step=1) cmds.progressBar(gMainProgressBar, edit=True, endProgress=True) print ("Completed rendering of " + str((endFrame - startFrame) + 1) + " frames.\n");
# -*- coding: utf-8 -*- """ Created on Thu Dec 8 11:48:14 2011 @author: - """ from maya import mel from maya import cmds startFrame = cmds.getAttr("defaultRenderGlobals.startFrame") endFrame = cmds.getAttr("defaultRenderGlobals.endFrame") gMainProgressBar = maya.mel.eval('$tmp = $gMainProgressBar'); cmds.progressBar( gMainProgressBar, edit=True, beginProgress=True, isInterruptable=True, status="Rendering...", maxValue=endFrame) for i in range(startFrame,endFrame): if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True ) : break cmds.currentTime( i ) cmds.render() cmds.progressBar(gMainProgressBar, edit=True, step=1) cmds.progressBar(gMainProgressBar, edit=True, endProgress=True) print ("Completed rendering of " + str((endFrame - startFrame) + 1) + " frames.\n");
def iprRender(*args): if currentRender == 'arnold': if cmds.arnoldIpr(q=1, mode='start'): cmds.arnoldIpr(mode='stop') else: cmds.arnoldIpr(cam=camera1, mode='start') cmds.arnoldIpr(mode='refresh') elif currentRender == 'vray': statusRT = mel.eval('vrayIsRunningIpr();') if statusRT == 0: if cmds.camera(camera1, q=1, o=1): cmds.warning('ortographic views not supported by vrayRT') else: preScale = cmds.getAttr(camera0 + '.preScale') preScale = float(1) / float(preScale) ftrh = cmds.getAttr(camera0 + '.filmTranslateH') ftrv = cmds.getAttr(camera0 + '.filmTranslateV') unitfIxed = 0.709 cmds.setAttr(camera0 + '.cameraScale', preScale) cmds.setAttr(camera0 + ".horizontalFilmOffset", ftrh * unitfIxed) cmds.setAttr(camera0 + ".verticalFilmOffset", ftrv * unitfIxed) mel.eval("vrend -ipr true -cam " + camera0 + ";") else: mel.eval("vrend -ipr false;") elif currentRender == 'mentalRay': if cmds.Mayatomr(q=1, imr=True): cmds.Mayatomr(imr=False) cmds.setAttr(camera0 + ".shakeEnabled", 0) for x in jobList[:]: cmds.scriptJob(kill=x, force=True) jobList.remove(x) else: if cmds.camera(camera1, q=1, o=1): jobIprMr = cmds.scriptJob( attributeChange=['Viewport_Render.translate', forceIpr]) jobIprMr2 = cmds.scriptJob(attributeChange=[ 'Viewport_Render.orthographicWidth', forceIpr ]) jobList.append(jobIprMr) jobList.append(jobIprMr2) else: jobIprMr = cmds.scriptJob( attributeChange=['Viewport_Render.translate', forceIpr]) jobList.append(jobIprMr) cmds.Mayatomr(imr=True, cam=camera0) else: cmds.warning( 'Render engine not supported. Rendering using Maya Software renderer.' ) cmds.render(camera1)
def getRegion(rrStart_x, rrStart_y, rrLast_x, rrLast_y): values = [rrStart_x, rrStart_y, rrLast_x, rrLast_y] camOverscan = cmds.camera(camera0, q=1, ovr=1) if LockedAttr() == 'locked': cmds.warning('Unlock you camera\'s main attributtes') return False if cmds.window("vpRenderWindow", exists=1) == False: getRvStatus() getPaneLayoutStatus() if values[3] < 0: values[3] = 0 if values[2] > formX: values[2] = formX if values[2] - values[0] < 20 or values[1] - values[3] < 20: cmds.warning('Region is too small') else: leftW = marLeft + values[0] topW = marTop + (formY - values[1]) resoX = values[2] - values[0] resoY = values[1] - values[3] main(values) if "Viewport_RenderShape" not in cmds.ls(ca=1): setToolBegin() else: cmds.setAttr('defaultResolution.width', resoX) cmds.setAttr('defaultResolution.height', resoY) aspRatio = float(cmds.getAttr('defaultResolution.width')) / float( cmds.getAttr('defaultResolution.height')) cmds.setAttr('defaultResolution.deviceAspectRatio', aspRatio) ScaleToCrop = float(formX) / resoX ScaleToCrop2 = float(formY) / resoY cmds.setAttr(camera0 + '.preScale', float(ScaleToCrop) / camOverscan) if 'OverScanExpression' not in cmds.ls(et='expression'): cmds.expression(name='OverScanExpression', s=camera0 + '.overscan = Viewport_RenderShape.overscan', o=camera0, ae=1) # Pixel Offset pixoffX = (float(formX) / 2) - (values[0] + float(resoX) / 2) pixoffY = (float(formY) / 2) - (formY - values[1]) - (float(resoY) / 2) # Film Translate FxOff = float(pixoffX) / (formX / 2) FxOff = FxOff * ScaleToCrop if FxOff > 0: FxOff = FxOff * -1 else: FxOff = -FxOff cmds.setAttr(camera0 + '.filmTranslateH', FxOff) unitY = float(formY) / 2 * float(formX) / formY FyOff = float(pixoffY) / unitY FyOff = FyOff * ScaleToCrop cmds.setAttr(camera0 + '.filmTranslateV', FyOff) cmds.setAttr('defaultResolution.width', resoX) cmds.setAttr('defaultResolution.height', resoY) aspRatio = float(cmds.getAttr('defaultResolution.width')) / float( cmds.getAttr('defaultResolution.height')) cmds.setAttr('defaultResolution.deviceAspectRatio', aspRatio) cmds.layout('scrollBarForm', e=1, vis=0) cmds.renderWindowEditor(renderViews, e=True, snp=(currentPanel, resoX, resoY)) cmds.renderWindowEditor(renderViews, e=True, rs=True, cap=0, pca=0) cmds.renderWindowEditor(renderViews, e=1, cl=(resoX, resoY, 0, 0, 0)) if currentRender == 'arnold': cmds.arnoldRender(cam=camera1) elif currentRender == 'vray': if cmds.getAttr("vraySettings.vfbOn") == 1: cmds.setAttr("vraySettings.vfbOn", 0) cmds.setAttr('vraySettings.width', resoX) cmds.setAttr('vraySettings.height', resoY) mel.eval('vraySetPixelDeviceAspect();') vrendCommand = 'vrend -camera %s' % (camera0) mel.eval(vrendCommand) elif currentRender == 'mentalRay': cmds.Mayatomr(pv=True, cam=camera0) else: cmds.warning( 'Render engine not supported. Rendering using Maya Software renderer.' ) cmds.render(camera1, x=resoX, y=resoY) reRenderVals.append(resoX) reRenderVals.append(resoY)
def batch_Render(self): self.get_Information() cmds.render(self.renderable_camera, x=self.image_Width, y=self.image_Height)
def render(self): self._renderPath = cmds.render( self._cam, x= self._width, y= self._height )
def render(self): self._renderPath = cmds.render(self._cam, x=self._width, y=self._height)
def rend(): cmds.setAttr('defaultRenderQuality.enableRaytracing', 1) cmds.render()