def LaunchPly2Vrmesh(vrsceneFilepath, vrmeshFilepath=None, nodeName=None, frames=None, applyTm=False, useVelocity=False, previewOnly=False, previewFaces=None): ply2vrmeshBin = "ply2vrmesh{arch}{ext}" ply2vrmeshArch = "" if sys.platform == 'win32': ply2vrmeshExt = ".exe" ply2vrmeshArch = "_%s" % SysUtils.GetArch() elif sys.platform == 'linux': ply2vrmeshExt = ".bin" else: ply2vrmeshExt = ".mach" ply2vrmeshBin = ply2vrmeshBin.format(arch=ply2vrmeshArch, ext=ply2vrmeshExt) exporterPath = SysUtils.GetExporterPath() if not exporterPath: return "Exporter path is not found!" ply2vrmesh = os.path.join(exporterPath, "bin", ply2vrmeshBin) if not os.path.exists(ply2vrmesh): return "ply2vrmesh binary not found!" cmd = [ply2vrmesh] cmd.append(vrsceneFilepath) if previewFaces: cmd.append('-previewFaces') cmd.append('%i' % previewFaces) if previewOnly: cmd.append('-vrscenePreview') if nodeName: cmd.append('-vrsceneNodeName') cmd.append(nodeName) if useVelocity: cmd.append('-vrsceneVelocity') if applyTm: cmd.append('-vrsceneApplyTm') if frames is not None: cmd.append('-vrsceneFrames') cmd.append('%i-%i' % (frames[0], frames[1])) if vrmeshFilepath is not None: cmd.append(vrmeshFilepath) debug.PrintInfo("Calling: %s" % " ".join(cmd)) err = subprocess.call(cmd) if err: return "Error generating vrmesh file!" return None
def Export(bus, scene, engine, isPreview=False): o = bus['output'] VRayScene = scene.vray VRayExporter = VRayScene.Exporter ts = time.time() o.write('MAIN', "\n") o.write('MAIN', SysUtils.GetVRsceneTemplate("defaults.vrscene")) if VRayExporter.draft: o.write('MAIN', "\n") o.write('MAIN', SysUtils.GetVRsceneTemplate("draft.vrscene")) exp_channels.ExportRenderElements(bus) if VRayExporter.animation_mode in {'FRAMEBYFRAME', 'NONE'}: err = exp_frame.ExportSingleFrame(bus) elif VRayExporter.animation_mode == 'CAMERA_LOOP': err = exp_anim_camera_loop.ExportCameraLoop(bus) else: err = exp_anim_full.ExportAnimation(bus, scene.frame_start, scene.frame_end, scene.frame_step) if VRayScene.Includer.use: if VRayScene.Includer.use: o.write('MAIN', "\n// Include additional *.vrscene files") for includeFile in VRayScene.Includer.nodes: if not includeFile.use: continue filepath = BlenderUtils.GetFullFilepath(includeFile.scene) o.write('MAIN', '\n#include "%s" // %s' % (filepath, includeFile.name)) o.write('MAIN', '\n') # No need for interpolate() anymore o.setAnimation(False) exp_settings.ExportSettings(bus) te = time.time() - ts td = datetime.timedelta(seconds=te) d = datetime.datetime(1, 1, 1) + td if not bus['preview']: debug.PrintMsg("Export done [%.2i:%.2i:%.2i]" % (d.hour, d.minute, d.second)) return err
def draw(self, context): layout = self.layout layout.label(text="Exporter revision: %s" % version.VERSION) layout.prop(self, "detect_vray") if not self.detect_vray: vrayStds = SysUtils.GetVRayStandalones() if vrayStds: pathBox = layout.box() pathBox.label("V-Ray Standalone is found in:") for vrayStd in vrayStds: vrayExePath = vrayStds[vrayStd] split = pathBox.split(percentage=0.3) col = split.column() col.label(vrayStd) col = split.column() op = col.operator('vray.select_vray_std', text=vrayExePath, icon='FILE_TICK') op.bin_path = vrayExePath vrayBin = "vray.exe" if sys.platform == 'win32' else "vray" layout.label( 'You could manually select "%s" binary, please, note NOT to use relative path here:' % vrayBin) split = layout.split(percentage=0.2, align=True) split.column().label("Filepath:") split.column().prop(self, "vray_binary", text="")
def GetRegClasses(): reg_classes = [] if SysUtils.hasRtExporter(): reg_classes.append(VRayRendererRT) else: reg_classes.append(VRayRenderer) reg_classes.append(VRayRendererPreview) return reg_classes
def GetRegClasses(): reg_classes = [] if SysUtils.hasRtExporter(): reg_classes.append(VRayRendererRT) else: reg_classes.append(VRayRenderer) reg_classes.append(VRayRendererPreview) return reg_classes
def draw(self, context): presetPaths = { os.path.join(SysUtils.GetExporterPath(), "presets", self.preset_subdir), os.path.join(SysUtils.GetUserConfigDir(), "presets", self.preset_subdir), } paths = [] for path in presetPaths: if os.path.exists(path): paths.append(path) if hasattr(self, 'menu_item_save') and self.menu_item_save: op = self.layout.operator('vray.export_asset', text="Save Selected", icon='FILE_TICK') op.asset_type = self.preset_subdir self.layout.separator() self.path_menu(paths)
def writeDatablock(bus, pluginModule, pluginName, propGroup, overrideParams): o = bus['output'] scene, ca = BlenderUtils.GetSceneAndCamera(bus) VRayScene = scene.vray VRayBake = VRayScene.BakeView if VRayBake.use: return VRayCamera = ca.data.vray RenderView = VRayCamera.RenderView SettingsCamera = VRayCamera.SettingsCamera SettingsCameraDof = VRayCamera.SettingsCameraDof CameraStereoscopic = VRayCamera.CameraStereoscopic VRayStereoscopicSettings = VRayScene.VRayStereoscopicSettings fov, orthoWidth = BlenderUtils.GetCameraFOV(scene, ca) overrideParams['use_scene_offset'] = SysUtils.IsGPUEngine(bus) overrideParams['clipping'] = RenderView.clip_near or RenderView.clip_far # if SettingsCamera.type not in {'SPHERIFICAL', 'BOX'}: if RenderView.clip_near: overrideParams['clipping_near'] = ca.data.clip_start if RenderView.clip_far: overrideParams['clipping_far'] = ca.data.clip_end if 'fov' not in overrideParams: overrideParams['fov'] = fov if 'transform' not in overrideParams: overrideParams['transform'] = ca.matrix_world.normalized() if 'orthographic' not in overrideParams: overrideParams['orthographic'] = ca.data.type == 'ORTHO' overrideParams['orthographicWidth'] = orthoWidth overrideParams['focalDistance'] = BlenderUtils.GetCameraDofDistance(ca) overrideParams['aperture'] = SettingsCameraDof.aperture if VRayStereoscopicSettings.use and not CameraStereoscopic.use: overrideParams['stereo_on'] = True overrideParams['stereo_eye_distance'] = VRayStereoscopicSettings.eye_distance overrideParams['stereo_interocular_method'] = VRayStereoscopicSettings.interocular_method overrideParams['stereo_specify_focus'] = VRayStereoscopicSettings.specify_focus overrideParams['stereo_focus_distance'] = VRayStereoscopicSettings.focus_distance overrideParams['stereo_focus_method'] = VRayStereoscopicSettings.focus_method overrideParams['stereo_view'] = VRayStereoscopicSettings.view else: overrideParams['stereo_on'] = None overrideParams['stereo_eye_distance'] = None overrideParams['stereo_interocular_method'] = None overrideParams['stereo_specify_focus'] = None overrideParams['stereo_focus_distance'] = None overrideParams['stereo_focus_method'] = None overrideParams['stereo_view'] = None return ExportUtils.WritePluginCustom(bus, pluginModule, pluginName, propGroup, overrideParams)
def _check_process(self): _, port, log_lvl = self._get_settings() if self._zmq_process is not None: self._zmq_process.poll() debug.Debug("ZMQ: %s -> code[%s]" % (self._zmq_process, self._zmq_process.returncode)) if self._zmq_process is None or self._zmq_process.returncode is not None: executable_path = SysUtils.GetZmqPath() if not executable_path or not os.path.exists(executable_path): debug.PrintError("Can't find V-Ray ZMQ Server!") return envAppSDK = os.environ.copy() def _joinPath(*args): return os.path.normpath(os.path.join(*args)) def _extendEnv(env, name, value): prevValue = env.get(name, None) env[name] = value if prevValue: env[name] += "%s%s" % (os.pathsep, prevValue) appSdkDir = _joinPath(os.path.dirname(executable_path), "appsdk") envAppSDK['VRAY_ZMQSERVER_APPSDK_PATH'] = os.environ.get( 'VRAY_ZMQSERVER_APPSDK_PATH', appSdkDir) envAppSDK['VRAY_PATH'] = appSdkDir envAppSDK['QT_PLUGIN_PATH'] = appSdkDir envAppSDK['QT_QPA_PLATFORM_PLUGIN_PATH'] = _joinPath( appSdkDir, "platforms") if sys.platform == "win32": _extendEnv(envAppSDK, 'PATH', appSdkDir) elif sys.platform == "linux": _extendEnv(envAppSDK, 'LD_LIBRARY_PATH', appSdkDir) elif sys.platform == "darwin": _extendEnv(envAppSDK, 'DYLD_FALLBACK_LIBRARY_PATH', appSdkDir) cmd = [ executable_path, "-p", port, "-log", self.log_lvl_translate[log_lvl], "-vfb" ] debug.Debug(' '.join(cmd)) try: self.start_heartbeat() self._zmq_process = subprocess.Popen(cmd, env=envAppSDK) except Exception as e: debug.PrintError(e)
def execute(self, context): preset_menu_class = getattr(bpy.types, self.preset_menu) preset_type = preset_menu_class.preset_subdir presetSubdir = PathUtils.CreateDirectory(os.path.join(SysUtils.GetUserConfigDir(), "presets")) exportPath = PathUtils.CreateDirectory(os.path.join(presetSubdir, preset_type)) presetName = preset_menu_class.bl_label if self.remove_active else self.name fileName = "%s.vrscene" % LibUtils.CleanString(bpy.path.display_name(presetName)) outputFilepath = os.path.normpath(os.path.join(exportPath, fileName)) if self.remove_active: # NOTE: Remove function is locked to user config directory, # so system settings are safe debug.PrintInfo('Removing preset file: "%s"' % outputFilepath) if not os.path.exists(outputFilepath): return {'CANCELLED'} try: os.remove(outputFilepath) except: debug.PrintError('Error removing preset file: "%s"!' % outputFilepath) # Set default menu name preset_menu_class.bl_label = bpy.path.display_name(preset_type) else: bus = { 'output' : VRayStream.VRaySimplePluginExporter(outputFilepath), 'scene' : context.scene, 'camera' : context.scene.camera, 'preview' : False, } pluginPresetIDs = None if preset_type == 'global': pluginPresetIDs = (pID for pID in sorted(PLUGINS['SETTINGS'])) else: pluginPresetIDs = PresetTypePlugins[preset_type] for pluginID in pluginPresetIDs: pluginModule = PLUGINS_ID.get(pluginID) if pluginModule is None: continue if not hasattr(context.scene.vray, pluginID): continue propGroup = getattr(context.scene.vray, pluginID) ExportUtils.WritePlugin(bus, pluginModule, pluginID.lower(), propGroup, {}) return {'FINISHED'}
def execute(self, context): VRayScene = context.scene.vray VRayDR = VRayScene.VRayDR nodesFilepath = os.path.join(SysUtils.GetUserConfigDir(), "render_nodes.txt") with open(nodesFilepath, 'w') as nodesFile: for item in VRayDR.nodes: item_data = "{item.name}:{item.address}:{item.use:d}:{item.port_override:d}:{item.port:d}".format( item=item) nodesFile.write("%s\n" % item_data) return {'FINISHED'}
def execute(self, context): # Check if target dir is writable exporterDir = SysUtils.GetExporterPath() if not os.access(exporterDir, os.W_OK): self.report({'ERROR'}, "Exporter directory is not writable!") return {'CANCELLED'} git = shutil.which("git") if not git: if sys.platform == 'win32': # Try default paths gitPaths = ( 'C:/Program Files/Git/bin/git.exe', 'C:/Program Files (x86)/Git/bin/git.exe', ) for _git in gitPaths: if os.path.exists(_git): git = _git break if not git: self.report({'ERROR'}, "Git is not found!") return {'CANCELLED'} if sys.platform == 'win32': git = '"%s"' % git cmds = ("%s fetch" % git, "%s reset --hard origin/master" % git, "%s submodule foreach git fetch" % git, "%s submodule foreach git reset --hard origin/master" % git) os.chdir(exporterDir) err = 0 for cmd in cmds: debug.PrintInfo("Executing: %s" % cmd) err += os.system(cmd) if err: self.report( {'WARNING'}, "V-Ray For Blender: Git update warning! Check system console!") return {'CANCELLED'} self.report({ 'INFO' }, "V-Ray For Blender: Exporter is now updated! Please, restart Blender!" ) return {'FINISHED'}
def ExportSettings(bus): scene = bus['scene'] VRayScene = scene.vray VRayExporter = VRayScene.Exporter for pluginType in {'SETTINGS', 'SETTINGS_GLOBAL'}: for pluginName in PLUGINS[pluginType]: # NOTE: We will export them later to be sure # they go after SettingsOutput if pluginName in ImageFormatPlugins: continue if pluginName in { # TODO: These plugins have to be implemented 'SettingsPtexBaker', 'SettingsVertexBaker', 'SettingsImageFilter', # These plugins will be exported manually 'Includer', 'SettingsEnvironment', 'OutputDeepWriter', # These plugins are exported from camera export 'BakeView', 'VRayStereoscopicSettings', # Unused plugins for now 'SettingsCurrentFrame', 'SettingsLightTree', 'SettingsColorMappingModo', 'SettingsDR', # Deprecated 'SettingsPhotonMap', 'RTEngine', }: continue if not SysUtils.IsGPUEngine(bus): if pluginName in {'RTEngine', 'SettingsRTEngine'}: continue if not VRayScene.SettingsVFB.use: if pluginName in {'EffectLens'}: continue ExportSettingsPlugin(bus, pluginType, pluginName) for pluginName in ImageFormatPlugins: ExportSettingsPlugin(bus, pluginType, pluginName)
def get_stdosl_path(): def getPaths(pathStr): if pathStr: return pathStr.strip().replace('\"','').split(os.pathsep) return [] env = os.environ for key in sorted(env.keys()): if key.startswith('VRAY_OSL_PATH_'): for p in getPaths(env[key]): stdPath = os.path.join(p, 'stdosl.h') if os.path.exists(stdPath): return stdPath cyclesPath = SysUtils.GetCyclesShaderPath() if cyclesPath: return os.path.join(cyclesPath, 'stdosl.h') return ''
def execute(self, context): VRayScene = context.scene.vray VRayDR = VRayScene.VRayDR nodesFilepath = os.path.join(SysUtils.GetUserConfigDir(), "render_nodes.txt") if not os.path.exists(nodesFilepath): return {'CANCELLED'} with open(nodesFilepath, 'r') as nodesFile: VRayDR.nodes.clear() for line in nodesFile.readlines(): l = line.strip() if not l: continue item = VRayDR.nodes.add() nodeSetup = l.split(":") # Initial format if len(nodeSetup) == 2: item.name, item.address = nodeSetup # "Use" added elif len(nodeSetup) == 3: item.name = nodeSetup[0] item.address = nodeSetup[1] item.use = int(nodeSetup[2]) # Port override added elif len(nodeSetup) == 5: item.name = nodeSetup[0] item.address = nodeSetup[1] item.use = int(nodeSetup[2]) item.port_override = int(nodeSetup[3]) item.port = int(nodeSetup[4]) VRayDR.nodes_selected = 0 return {'FINISHED'}
def _check_process(self): _, port, log_lvl = self._get_settings() if self._zmq_process is not None: self._zmq_process.poll() debug.Debug("ZMQ: %s -> code[%s]" % (self._zmq_process, self._zmq_process.returncode)) if self._zmq_process is None or self._zmq_process.returncode is not None: executable_path = SysUtils.GetZmqPath() if not executable_path or not os.path.exists(executable_path): debug.PrintError("Can't find V-Ray ZMQ Server!") else: try: env = os.environ.copy() if sys.platform == "win32": if 'VRAY_ZMQSERVER_APPSDK_PATH' not in env: debug.PrintError( 'Environment variable VRAY_ZMQSERVER_APPSDK_PATH is missing!' ) else: appsdk = os.path.dirname( env['VRAY_ZMQSERVER_APPSDK_PATH']) env['PATH'] = env['PATH'] + os.pathsep + appsdk env['VRAY_PATH'] = appsdk old_ld = (os.pathsep + env['LD_LIBRARY_PATH'] ) if 'LD_LIBRARY_PATH' in env else '' env['LD_LIBRARY_PATH'] = appsdk + old_ld cmd = [ executable_path, "-p", port, "-log", self.log_lvl_translate[log_lvl], "-vfb" ] debug.Debug(' '.join(cmd)) self.start_heartbeat() self._zmq_process = subprocess.Popen(cmd, env=env) except Exception as e: debug.PrintError(e)
def init(): jsonDirpath = os.path.join(SysUtils.GetExporterPath(), "plugins_desc") _vray_for_blender.start(jsonDirpath) if HAS_VB35: _vray_for_blender_rt.load(jsonDirpath)
import sys import shutil import bpy import bmesh from bpy.props import * import vb30.proxy from vb30.lib import LibUtils, BlenderUtils, PathUtils, SysUtils from vb30.lib import ColorUtils from vb30.plugins import PLUGINS, PLUGINS_ID from vb30 import debug HAS_VB35 = SysUtils.hasRtExporter() HAS_ZMQ = HAS_VB35 if HAS_VB35: import _vray_for_blender_rt if HAS_ZMQ: from vb30.engine import ZMQ ## ## ######## ######## ### ######## ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ## ## ## ## ## ###### ## ## ## ## ## ######### ## ## ## ## ## ## ## ## ## ## ## ####### ## ######## ## ## ## ########
def writeDatablock(bus, pluginModule, pluginName, propGroup, overrideParams): scene = bus['scene'] o = bus['output'] camera = bus['camera'] VRayScene = scene.vray VRayExporter = VRayScene.Exporter BakeView = VRayScene.BakeView img_width = int(scene.render.resolution_x * scene.render.resolution_percentage * 0.01) img_height = int(scene.render.resolution_y * scene.render.resolution_percentage * 0.01) # NOTE: Camera could be None when saving a preset, for example if camera: VRayCamera = camera.data.vray CameraStereoscopic = VRayCamera.CameraStereoscopic if SysUtils.IsGPUEngine(bus): if VRayScene.SettingsRTEngine.stereo_mode: img_width *= 2 else: if VRayScene.VRayStereoscopicSettings.use and not CameraStereoscopic.use: if VRayScene.VRayStereoscopicSettings.adjust_resolution: img_width *= 2 if BakeView.use: if BakeView.square_resolution: img_height = img_width overrideParams['img_width'] = img_width overrideParams['img_height'] = img_height overrideParams['bmp_width'] = img_width overrideParams['bmp_height'] = img_height overrideParams['rgn_width'] = img_width overrideParams['rgn_height'] = img_height overrideParams['r_width'] = img_width overrideParams['r_height'] = img_height if not (o.isPreviewRender() or VRayExporter.auto_save_render): overrideParams['img_file'] = "" overrideParams['img_dir'] = "" else: # NOTE: Could happen when saving preset if hasattr(o, 'getFileManager'): pm = o.getFileManager().getPathManager() img_file = pm.getImgFilename() img_dir = pm.getImgDirpath() if not img_file: debug.PrintError("Image output filename is not set!") return None if not img_dir: debug.PrintError("Image output directory is not set!") return None # In case filename is setup as some filepath img_file = os.path.basename(bpy.path.abspath(img_file)) overrideParams['img_file'] = img_file overrideParams['img_dir'] = img_dir if o.isPreviewRender(): overrideParams['img_file_needFrameNumber'] = False if propGroup.img_format in {'EXR', 'VRST'}: if not propGroup.relements_separateFiles: overrideParams['img_rawFile'] = True # Animation overrideParams['anim_start'] = o.frameStart overrideParams['anim_end'] = o.frameEnd overrideParams['frame_start'] = o.frameStart # NOTE: When loading preview image for World # image alpha will be replaced with black color. # We don't want this, so simply use JPEG, # that doesn't have alpha channel if o.isPreviewRender(): overrideParams['img_noAlpha'] = True return ExportUtils.WritePluginCustom(bus, pluginModule, pluginName, propGroup, overrideParams)
def Run(bus): debug.Debug("Run()") scene = bus['scene'] engine = bus['engine'] o = bus['output'] VRayScene = scene.vray VRayExporter = VRayScene.Exporter VRayDR = VRayScene.VRayDR vrayCmd = SysUtils.GetVRayStandalonePath() if not vrayCmd: raise Exception("V-Ray not found!") imageToBlender = VRayExporter.animation_mode == 'NONE' and not scene.render.use_border and VRayExporter.auto_save_render and VRayExporter.image_to_blender p = VRayProcess() p.setVRayStandalone(vrayCmd) p.setSceneFile(o.fileManager.getOutputFilepath()) p.setAutorun(VRayExporter.autorun) p.setVerboseLevel(VRayExporter.verboseLevel) p.setShowProgress(VRayExporter.showProgress) p.setDisplaySRGB(scene.display_settings.display_device == 'sRGB') p.setDisplayVFB(VRayExporter.display) p.setAutoclose(VRayExporter.autoclose) if SysUtils.IsGPUEngine(bus): p.setRtEngine(VRayExporter.device_gpu_type, VRayScene.SettingsRTEngine) # TODO: Rewrite into 'SettingsOutput' if scene.render.use_border: resolution_x = int(scene.render.resolution_x * scene.render.resolution_percentage * 0.01) resolution_y = int(scene.render.resolution_y * scene.render.resolution_percentage * 0.01) x0 = resolution_x * scene.render.border_min_x y0 = resolution_y * (1.0 - scene.render.border_max_y) x1 = resolution_x * scene.render.border_max_x y1 = resolution_y * (1.0 - scene.render.border_min_y) p.setRegion(x0, y0, x1, y1, useCrop=scene.render.use_crop_to_border) if imageToBlender: p.setWaitExit(True) p.setAutoclose(True) if engine.is_preview: p.setPreview(True) p.setShowProgress(0) p.setVerboseLevel(0) p.setAutoclose(True) p.setDisplayVFB(False) if VRayDR.on: if len(VRayDR.nodes): transferAssets = VRayDR.assetSharing == 'TRANSFER' if transferAssets: if VRayDR.checkAssets: transferAssets = 2 p.setDistributed(2 if VRayDR.renderOnlyOnNodes else 1) hosts = [] for n in VRayDR.nodes: if n.use: hosts.append("%s:%s" % (n.address, n.port) if n.port_override else n.address) p.setRenderhosts(hosts) p.setPortNumber(VRayDR.port) p.setTransferAssets(transferAssets) p.setLimitHosts(VRayDR.limitHosts) if VRayExporter.animation_mode == 'NONE': p.setFrames(scene.frame_current) elif VRayExporter.animation_mode == 'FRAMEBYFRAME': p.setWaitExit(True) p.setAutoclose(True) p.setFrames(scene.frame_current) else: p.setFrames(o.frameStart, o.frameEnd, o.frameStep) if not scene.render.threads_mode == 'AUTO': p.setThreads(scene.render.threads) if bpy.app.background or VRayExporter.wait: p.setWaitExit(True) if bpy.app.background: if not VRayExporter.display_vfb_in_batch: p.setDisplayVFB(False) # Disable VFB p.setAutoclose(True) # Exit on render end if VRayExporter.gen_run_file: p.setGenRunFile(True) if VRayExporter.submit_to_vray_cloud: p.setAutorun(False) exportExitStatus = p.run() if exportExitStatus == 0 and VRayExporter.submit_to_vray_cloud: job = VCloudJob(bus) cloudExitStatus = job.submitToCloud() if cloudExitStatus == -404: print("Chaos Cloud binary is not detected on your system!") webbrowser.open("https://www.chaosgroup.com/cloud") if imageToBlender or engine.is_preview: exp_load.LoadImage(scene, engine, o, p)
class VRayExporter(bpy.types.PropertyGroup): experimental = bpy.props.BoolProperty( name="Experimental", description="Enable experimental options", default=False) spherical_harmonics = bpy.props.EnumProperty( name="Spherical Harmonics Mode", description="Bake or render spherical harmonics", items=( ('BAKE', "Bake", ""), ('RENDER', "Render", ""), ), default='BAKE') ######## ## ## ######## ####### ######## ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ### ######## ## ## ######## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ## ## ## ####### ## ## ## currentBakeObject = bpy.props.PointerProperty( name="Current Bake object", type=bpy.types.Object, options={'HIDDEN'}, ) ntreeExportDirectory = bpy.props.StringProperty( name="Export Path", subtype='DIR_PATH', description="Export directory", default="//vrscenes/") activeLayers = bpy.props.EnumProperty( name="Active layers", description="Render objects from layers", items=(('ACTIVE', "Active Layers", ""), ('ALL', "All Layers", ""), ('CUSTOM', "Custom Layers", "")), default='ACTIVE') customRenderLayers = bpy.props.BoolVectorProperty(subtype='LAYER', size=20) use_displace = bpy.props.BoolProperty( name="Displace / Subdiv", description="Use displace / subdivisions", default=True) use_still_motion_blur = bpy.props.BoolProperty( name="Still Motion Blur", description="Generate data for motion blur", default=False) use_hair = bpy.props.BoolProperty(name="Export Hair", description="Render hair", default=True) calculate_instancer_velocity = bpy.props.BoolProperty( name="Calculate instancer velocity", description= "Used to calculate particles velocty when using motion blur", default=False) use_smoke = bpy.props.BoolProperty(name="Export Smoke", description="Render smoke", default=True) camera_loop = bpy.props.BoolProperty( name="Camera Loop", description="Render views from all cameras", default=False) auto_meshes = bpy.props.BoolProperty(name="Re-Export Meshes", description="Re-Export meshes", default=True) debug = bpy.props.BoolProperty(name="Debug", description="Enable script\'s debug output", default=False) output = bpy.props.EnumProperty(name="Exporting Directory", description="Exporting directory", items=(('USER', "Custom Directory", ""), ('SCENE', "Scene File Directory", ""), ('TMP', "Global TMP directory", "")), default='TMP') ntreeListIndex = bpy.props.IntProperty( name="Node Trees List Index", description="Node trees list index", min=-1, default=-1, ) materialListIndex = bpy.props.IntProperty( name="Material List Index", description="Material list index", min=-1, default=-1, update=_mtlEditorUpdatePreview, ) materialListIndexPrev = bpy.props.IntProperty( name="Material List Index Previous State", description="Material list index previous state", min=-1, default=-1, ) materialListShowPreview = bpy.props.BoolProperty( name="Show preview", description="Show preview", default=True) useSeparateFiles = bpy.props.BoolProperty( name="Separate Files", description="Export plugins to separate files", default=True) default_mapping = bpy.props.EnumProperty( name="Default Mapping", description= "Defaul mapping type for procedural texture nodes without \"Mapping\" socket linked", items=( ('0', "Object", "Object mapping"), ('1', "Box", "Box projection"), ('2', "Channel", "Default channel"), ), default='0') ######## ######## ## ## ######## ######## ######## ###### ######## ######## ######## #### ## ## ###### ###### ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## #### ## ## ## ######## ###### ## ## ## ## ## ###### ######## ###### ###### ## ## ## ## ## ## ## #### ###### ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ## ######## ## ## ######## ######## ## ## ###### ######## ## ## #### ## ## ###### ###### animation_mode = bpy.props.EnumProperty( name="Animation Mode", description="Animation Type", items=( ('NONE', "None", "Render single frame"), ('FULL', "Full Range", "Export full animation range then render"), ('CAMERA', "Full Range (Camera Only)", "Export full animation of camera motion"), ('NOTMESHES', "Full Range (Except Geometry)", "Export full animation range then render (meshes are not animated)" ), ('CAMERA_LOOP', "Camera Loop", "Render all scene cameras"), ('FRAMEBYFRAME', "Frame By Frame", "Export and render frame by frame"), ), default='NONE') draft = bpy.props.BoolProperty(name="Draft Render", description="Render with low settings", default=False) select_node_preview = bpy.props.BoolProperty( name="Selected node preview", description="Enable material preview of selected node in node editor", default=False) image_to_blender = bpy.props.BoolProperty( name="Image To Blender", description= "Pass image to Blender on render end (EXR file format is used)", default=False) ######## ######## ####### ###### ######## ###### ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ######## ## ## ## ###### ###### ###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ####### ###### ######## ###### ###### autorun = bpy.props.BoolProperty( name="Autorun", description="Start V-Ray automatically after export", default=True) verboseLevel = bpy.props.EnumProperty( name="Log Level", description= "Specifies the verbose level of information printed to the standard output", items=( ('0', "No information", "No information printed"), ('1', "Only errors", "Only errors"), ('2', "Warnings", "Errors and warnings"), ('3', "Progress", "Errors, warnings and informational messages"), ('4', "All", "All output"), ), default='3') showProgress = bpy.props.EnumProperty( name="Show Progress", description= "Specifies whether calculations progress should be printed to the standard output", items=( ('0', "None", ""), ('1', "Verbose > Only Erros", 'Display progress only if "Verbose Level" is > "Only errors"'), ('2', "Always", "Errors and warnings"), ), default='1') autoclose = bpy.props.BoolProperty( name="Auto Close", description="Stop render and close VFB on Esc", default=False) log_window = bpy.props.BoolProperty(name="Show Log Window", description="Show log window (Linux)", default=False) log_window_type = bpy.props.EnumProperty( name="Log Window Type", description="Log window type", items=(('DEFAULT', "Default", ""), ('XTERM', "XTerm", ""), ('GNOME', "Gnome Terminal", ""), ('KDE', "Konsole", ""), ('CUSTOM', "Custom", "")), default='DEFAULT') log_window_term = bpy.props.StringProperty( name="Custom Terminal", description="Custom log window terminal command", default="x-terminal-emulator") display = bpy.props.BoolProperty(name="Display VFB", description="Display VFB", default=True) display_vfb_in_batch = bpy.props.BoolProperty( name="Display VFB In Batch Mode", description="Display VFB in background mode", default=False) display_vfb_on_top = bpy.props.BoolProperty( name="Display Always On Top", description="Display VFB on top of the other windows", default=True) detect_vray = bpy.props.BoolProperty( name="Detect V-Ray", description="Detect V-Ray binary location", default=True) vray_binary = bpy.props.StringProperty( name="Path", subtype='FILE_PATH', description= "Path to V-Ray binary. Don\'t use relative path here - use absolute!") output_dir = bpy.props.StringProperty( name="Directory", subtype='DIR_PATH', description="User-defined output directory") output_unique = bpy.props.BoolProperty(name="Use Unique Filename", description="Use unique file name", default=False) auto_save_render = bpy.props.BoolProperty( name="Save Render", description="Save render automatically", default=False) wait = bpy.props.BoolProperty( name="Wait Proccess Exit", description="Wait for V-Ray to complete rendering", options={'HIDDEN'}, default=False) gen_run_file = bpy.props.BoolProperty( name="Generate Run File", description="Generate script for render", default=False) ui_render_grouping = bpy.props.BoolProperty(name="Group Render Panels", default=True) ui_render_context = bpy.props.EnumProperty( name="Render Context Panels", description="Show render panels group", items=( ('0', "Render", ""), ('1', "Globals", ""), ('2', "GI", ""), ('3', "Sampler", ""), ('4', "System", ""), ), default='0') op_switch_slots_switch_to = bpy.props.EnumProperty(items=( ('OBJECT', "Object", ""), ('DATA', "Data", ""), ), default='OBJECT') subsurf_to_osd = bpy.props.BoolProperty( name="Subsurf To OpenSubdiv", description= "Automatically convert Subsurf modifier (if last in stack) to V-Ray's OpenSubdiv subdivision", default=False) data_format = bpy.props.EnumProperty( name="Export Format", description="Export data format", items=( ('ZIP', "ZIP", "Compress list data"), ('HEX', "HEX", "Export list data in hex format"), ('ASCII', "Plain Text", "Export as plain text"), ), default='ZIP') backend = bpy.props.EnumProperty( name="V-Ray Backend", description="V-Ray backend", items=SysUtils.getExporterBackendList(), ) work_mode = bpy.props.EnumProperty(name="Render Mode", description="Render mode", items=( ('RENDER', "Render", ""), ('RENDER_EXPORT', "Render & Export", ""), ('EXPORT_ONLY', "Export Only", ""), ), default='RENDER') backend_worker = bpy.props.EnumProperty(name="Server Mode", description="Server mode", items=( ('LOCAL', "Local", ""), ('NETWORK', "Remote", ""), ), default='LOCAL') zmq_address = bpy.props.StringProperty(name="Server Address", description="Server address", default="") zmq_port = bpy.props.IntProperty(name="Server Port", description="Server port", min=1000, max=65535, default=5555) zmq_log_level = bpy.props.EnumProperty(name="ZMQ log level", description="ZMQ log level", items=( ('ERROR', 'Error', ''), ('WARNING', 'Warning', ''), ('DEBUG', 'Debug', ''), ('INFO', 'Info', ''), ), default='ERROR') vfb_global_preset_file_use = bpy.props.BoolProperty( name="Use Global Preset File", description="Use VFB global preset file", default=False) vfb_global_preset_file = bpy.props.StringProperty( name="Global Preset File", subtype='FILE_PATH', description="VFB global preset file", ) viewport_image_type = bpy.props.EnumProperty( name="Viewport Image Type", description="Viewport Image Type", items=(("1", "RAW", "Full Color + Alpha"), ("4", "JPEG", "JPEG compressed")), default='1') viewport_jpeg_quality = bpy.props.IntProperty( name="Image quality", description="JPEG image quality", min=10, max=100, subtype='PERCENTAGE', default=60) viewport_resolution = bpy.props.IntProperty( name="Viewport Resolution", description="Viewport resolution", min=10, max=100, subtype='PERCENTAGE', default=100) viewport_alpha = bpy.props.BoolProperty(name="Show Alpha", description="Show Alpha", default=False) submit_to_vray_cloud = bpy.props.BoolProperty( name="Submit to V-Ray Cloud", description="Submits current scene as a render job to the V-Ray Cloud", default=False) vray_cloud_project_name = bpy.props.StringProperty( name="Project", description="V-Ray Cloud Project Name", default="Blender for V-Ray") vray_cloud_job_name = bpy.props.StringProperty( name="Job", description="V-Ray Cloud Job Name", default="$F") device_type = bpy.props.EnumProperty(name="Device Type", description="Rendering device", items=( ('CPU', "CPU", ""), ('GPU', "GPU", ""), ), default='CPU') device_gpu_type = bpy.props.EnumProperty(name="GPU Device Type", description="GPU device type", items=( ('CUDA', "CUDA", ""), ('OPENCL', "OpenCL", ""), ), default='CUDA')
def use_zmq(self): return SysUtils.hasZMQEnabled()
# All Rights Reserved. V-Ray(R) is a registered trademark of Chaos Software. # import bpy import sys import _vray_for_blender import os import json from vb30 import version from vb30.lib import SysUtils from vb30.lib import BlenderUtils HAS_VB35 = SysUtils.hasRtExporter() if HAS_VB35: import _vray_for_blender_rt TYPE = 'SYSTEM' ID = 'VRayExporter' NAME = 'Exporter' DESC = "Exporter configuration" def _mtlEditorUpdatePreview(self, context): if self.materialListIndexPrev != self.materialListIndex: self.materialListIndexPrev = self.materialListIndex _vray_for_blender.updatePreview(bpy.context.as_pointer(), BlenderUtils.NC_MATERIAL)
def execute(self, context): if not self.asset_name: self.report({'ERROR'}, "Asset name is not set!") return {'CANCELLED'} presetsPath = PathUtils.CreateDirectory(os.path.join(SysUtils.GetUserConfigDir(), "presets")) userNodeAssetPath = PathUtils.CreateDirectory(os.path.join(presetsPath, self.asset_type)) fileName = "%s.vrscene" % LibUtils.CleanString(bpy.path.display_name(self.asset_name)) outputFilepath = os.path.normpath(os.path.join(userNodeAssetPath, fileName)) # Create exporter (output) o = VRayStream.VRaySimplePluginExporter(outputFilepath) exporter = _vray_for_blender.init( engine = 0, context = bpy.context.as_pointer(), scene = bpy.context.scene.as_pointer(), data = bpy.data.as_pointer(), mainFile = o.output, objectFile = o.output, envFile = o.output, geometryFile = o.output, lightsFile = o.output, materialFile = o.output, textureFile = o.output, drSharePath = "", ) # Get selected nodes ntree = context.space_data.edit_tree selectedNode = context.selected_nodes[0] if selectedNode.bl_idname == 'VRayNodeRenderChannels': pluginNames = [] for inSock in selectedNode.inputs: pluginNames.append(NodesExport.WriteConnectedNode(None, ntree, inSock)) pluginName = "List(%s)" % ",".join(pluginNames) else: if selectedNode.bl_idname == 'VRayNodeOutputMaterial': selectedNode = NodesExport.GetConnectedNode(ntree, selectedNode.inputs['Material']) pluginName = _vray_for_blender.exportNode( ntree.as_pointer(), selectedNode.as_pointer(), None ) # Write fake Asset node o.set('MAIN', 'Asset', self.asset_type.capitalize()) o.writeHeader() o.writeAttibute(self.asset_type, pluginName) o.writeFooter() o.done() _vray_for_blender.exit(exporter) return {'FINISHED'}
class VRayRendererRT(VRayRendererBase): bl_idname = 'VRAY_RENDER_RT' bl_label = "V-Ray" bl_use_preview = True bl_preview_filepath = SysUtils.GetPreviewBlend() bl_use_shading_nodes = True backgroundRendererInstance = 0 def getExporter(self): # In case of preview "scene" argument will point # to the preview scene, but we need to use settings # from the actual scene # return bpy.context.scene.vray.Exporter def __init__(self): _vray_for_blender_rt.set_preview_dir(PathUtils.GetPreviewDir()) VRayRendererRT.backgroundRendererInstance += 1 self.canRender = True if bpy.app.background: # when in background mode, Blender's animation handler will create # the renderer for each frame, but we will do all the work on the first # call so we ignore all others self.canRender = VRayRendererRT.backgroundRendererInstance == 1 self.parseArguments() debug.Debug("__init__()") self.renderer = None def __del__(self): debug.Debug("__del__()") self._free_renderer() def _free_renderer(self): if hasattr(self, 'renderer') and self.renderer is not None: _vray_for_blender_rt.free(self.renderer) self.renderer = None def _getImageFormats(self): try: items = PLUGINS_ID['SettingsOutput'].PluginParams for param in items: if param['attr'] == 'img_format': return param['items'] except Exception: return [] return [] # We are in background mode, so override UI settings with supported arugmnets def parseArguments(self): frameStart = None frameEnd = None outputDir = '' renderAnim = False imgFormat = None argc = len(sys.argv) for (idx, arg) in enumerate(sys.argv): hasNext = idx < argc if arg in {'-f', '--render-frame'} and hasNext: frameStart = frameEnd = sys.argv[idx + 1] elif arg in {'-s', '--frame-start'} and hasNext: frameStart = sys.argv[idx + 1] elif arg in {'-e', '--frame-end'} and hasNext: frameEnd = sys.argv[idx + 1] elif arg in {'-o', '--render-output'} and hasNext: outputDir = sys.argv[idx + 1] elif arg in {'-F', '--render-format'} and hasNext: imgFormat = sys.argv[idx + 1] elif arg in {'-a', '--render-anim'}: renderAnim = True vrayExporter = self.getExporter() vrayScene = bpy.context.scene.vray debug.PrintInfo('Command line overrides:') if imgFormat: formats = self._getImageFormats() newFormatName = None newFormatIdx = 0 savedFormatName = None for img in formats: if img[1].lower() == imgFormat.lower(): newFormatName = img[1] newFormatIdx = img[0] if img[0].lower() == vrayScene.SettingsOutput.img_format: # get this so we can log it savedFormatName = img[1] if newFormatName and savedFormatName: break if newFormatName: if newFormatName != savedFormatName: debug.PrintInfo( 'Changing image output format from "%s" to "%s"' % (savedFormatName, newFormatName)) vrayScene.SettingsOutput.img_format = newFormatIdx else: debug.PrintError('Format "%s" not found, using "%s"' % (imgFormat, savedFormatName)) if outputDir != '': vrayExporter.auto_save_render = True vrayScene.SettingsOutput.img_dir = outputDir debug.PrintInfo('Changing image output directory to "%s"' % outputDir) vrayExporter.output = 'USER' vrayExporter.output_dir = outputDir debug.PrintInfo('Changing .vrscene output directory to "%s"' % outputDir) if renderAnim and vrayExporter.animation_mode == 'NONE': # if we dont have anim mode set, use Full Range debug.PrintInfo('Changing Animation Mode from "%s" to "FULL"' % vrayExporter.animation_mode) vrayExporter.animation_mode = 'FULL' if frameStart == frameEnd and frameStart != None: # force single frame debug.PrintInfo('Changing Animation Mode from "%s" to "NONE"' % vrayExporter.animation_mode) vrayExporter.animation_mode = 'NONE' # Check if we can actually render def doRender(self): errString = "Animation is supported trough Render Image, with Animation set to not None" if self.is_animation: if bpy.app.background: # We generally dont want to support Blender's animation rendering # because it will re-create the renderer for each frame but in # background we dont really have a choice so we export everything # on the first frame and ignore all other if not self.canRender: debug.PrintError(errString) return False else: self.report({'ERROR'}, errString) return False return True # Production rendering # def update(self, data, scene): if not self.doRender(): return debug.Debug("update()") vrayExporter = self.getExporter() if vrayExporter.backend != 'STD': ZMQ.check_start() # Init ZMQ exporter if not self.renderer: arguments = { 'context': bpy.context.as_pointer(), 'engine': self.as_pointer(), 'data': data.as_pointer(), 'scene': scene.as_pointer(), } self.renderer = _vray_for_blender_rt.init(**arguments) if self.renderer: _vray_for_blender_rt.update(self.renderer) def render(self, scene): if not self.doRender(): return debug.Debug("render()") vrayExporter = self.getExporter() use_std = vrayExporter.backend == 'STD' if use_std: super().render(scene) if bpy.app.background: # free renderer so we close and flush all files self._free_renderer() # in backgorund mode we render only once, so exit here to force # Blender not rendering more frames and not wrinting files sys.exit(0) elif self.renderer: _vray_for_blender_rt.render(self.renderer) # Interactive rendering # def view_update(self, context): if not self.doRender(): return debug.Debug("view_update()") ZMQ.check_start() if not self.renderer: self.renderer = _vray_for_blender_rt.init_rt( context=context.as_pointer(), engine=self.as_pointer(), data=bpy.data.as_pointer(), scene=bpy.context.scene.as_pointer(), ) if self.renderer: _vray_for_blender_rt.view_update(self.renderer) def _view_draw(self, context): if not self.doRender(): return if self.renderer: _vray_for_blender_rt.view_draw(self.renderer) # OSL scripts def update_script_node(self, node): osl.update_script_node(node, self.report)
def use_zmq(self): return SysUtils.hasZMQEnabled()
def GetPluginsDir(): return os.path.join(SysUtils.GetExporterPath(), "plugins")
class VRayRendererRT(VRayRendererBase): bl_idname = 'VRAY_RENDER_RT' bl_label = "V-Ray" bl_use_preview = True bl_preview_filepath = SysUtils.GetPreviewBlend() bl_use_shading_nodes = True def _get_settings(self): # In case of preview "scene" argument will point # to the preview scene, but we need to use settings # from the actual scene # return bpy.context.scene.vray.Exporter def __init__(self): debug.Debug("__init__()") self.renderer = None def __del__(self): debug.Debug("__del__()") if hasattr(self, 'renderer') and self.renderer is not None: _vray_for_blender_rt.free(self.renderer) # Production rendering # def update(self, data, scene): debug.Debug("update()") vrayExporter = self._get_settings() if vrayExporter.backend != 'STD': ZMQ.check_start() # Init ZMQ exporter if not self.renderer: arguments = { 'context': bpy.context.as_pointer(), 'engine': self.as_pointer(), 'data': data.as_pointer(), 'scene': scene.as_pointer(), } self.renderer = _vray_for_blender_rt.init(**arguments) if self.renderer: _vray_for_blender_rt.update(self.renderer) def render(self, scene): debug.Debug("render()") vrayExporter = self._get_settings() use_std = vrayExporter.backend == 'STD' if use_std: super().render(scene) elif self.renderer: _vray_for_blender_rt.render(self.renderer) # Interactive rendering # def view_update(self, context): debug.Debug("view_update()") ZMQ.check_start() if not self.renderer: self.renderer = _vray_for_blender_rt.init_rt( context=context.as_pointer(), engine=self.as_pointer(), data=bpy.data.as_pointer(), scene=bpy.context.scene.as_pointer(), ) if self.renderer: _vray_for_blender_rt.view_update(self.renderer) def _view_draw(self, context): if self.renderer: _vray_for_blender_rt.view_draw(self.renderer)
import os import sys import subprocess import ipaddress import bpy import _vray_for_blender from vb30.lib import SysUtils from vb30 import export, debug from vb30.lib.VRayStream import VRayExportFiles from vb30.lib.VRayStream import VRayFilePaths # Check if current build support new RT exporter HAS_VB35 = SysUtils.hasRtExporter() HAS_ZMQ = SysUtils.hasZMQEnabled() if HAS_VB35: import _vray_for_blender_rt # This will hold handle to subprocess.Popen to the zmq server if # it is started in local mode, and it should be terminated on Shutdown() # class ZMQProcess: log_lvl_translate = { 'ERROR': '4', 'WARNING': '3', 'DEBUG': '2', 'INFO': '1', }
class VRayRendererPreview(VRayRendererBase): bl_idname = 'VRAY_RENDER_PREVIEW' bl_label = "V-Ray (With Material Preview)" bl_use_preview = True bl_preview_filepath = SysUtils.GetPreviewBlend()
import ipaddress import bpy import _vray_for_blender from vb30.lib import SysUtils, PathUtils from vb30 import export, debug from vb30 import osl from vb30.plugins import PLUGINS_ID from vb30.lib.VRayStream import VRayExportFiles from vb30.lib.VRayStream import VRayFilePaths # Check if current build support new RT exporter HAS_VB35 = SysUtils.hasRtExporter() HAS_ZMQ = SysUtils.hasZMQEnabled() if HAS_VB35: import _vray_for_blender_rt # This will hold handle to subprocess.Popen to the zmq server if # it is started in local mode, and it should be terminated on Shutdown() # class ZMQProcess: log_lvl_translate = { 'ERROR': '4', 'WARNING': '3', 'DEBUG': '2', 'INFO': '1',