def execute(self, context): node_textures = [] for nt in bpy.data.node_groups: debug.PrintInfo("Checking tree: %s..." % nt.name) for n in nt.nodes: if not hasattr(n, 'texture'): continue if n.texture: debug.PrintInfo("Texture found: %s [\"%s\"]" % (n.texture.name, n.name)) if not n.texture_name: debug.PrintInfo("Restoring texture name: %s [\"%s\"]" % (n.texture.name, n.name)) n.texture_name = n.texture.name node_textures.append(n.texture) textures_to_remove = [] for tex in bpy.data.textures: if not tex.name.startswith( (".Ramp@", ".Bitmap@", ".VRayFakeTexture@")): continue if tex not in node_textures: tex.use_fake_user = False textures_to_remove.append(tex) for tex in textures_to_remove: debug.PrintInfo("Removing: %s..." % tex.name) bpy.data.textures.remove(tex) return {'FINISHED'}
def ImportSettings(context, filePath, pluginFilter=None): debug.PrintInfo('Importing settings from "%s"' % filePath) vrsceneDict = ParseVrscene(filePath) for pluginDesc in vrsceneDict: pluginID = pluginDesc['ID'] pluginName = pluginDesc['Name'] pluginAttrs = pluginDesc['Attributes'] if pluginID not in PLUGINS['SETTINGS']: continue pluginModule = PLUGINS_ID.get(pluginID) if pluginModule is None: continue if not hasattr(context.scene.vray, pluginID): continue propGroup = getattr(context.scene.vray, pluginID) for attrName in pluginAttrs: attrDesc = NodesImport.getParamDesc(pluginModule.PluginParams, attrName) if attrDesc is None: continue attrValue = pluginAttrs[attrName] if attrDesc['type'] == 'ENUM': attrValue = str(attrValue) setattr(propGroup, attrName, attrValue) return {'FINISHED'}
def ConvertNodeMaterial(scene, ob, ma): debug.PrintInfo("Converting node material: %s" % ma.name) materialNode = None maNtree = ma.node_tree nt = _createVRayTree(ma.name, 'Material') ntOutput = _createVRayNode(nt, 'OutputMaterial') ntMaterial = _createVRayNode(nt, 'MtlSingleBRDF') _connectNodes(nt, ntMaterial, 'Material', ntOutput, 'Material') maNtreeOutput = NodesUtils.GetNodeByType(maNtree, 'ShaderNodeOutputMaterial') maShader = NodesUtils.GetConnectedNode(maNtree, maNtreeOutput.inputs['Surface']) vrayNode = ConvertNode(maNtree, maShader, nt) if vrayNode: _connectNodes(nt, vrayNode, 'BRDF', ntMaterial, 'BRDF') NodesTools.rearrangeTree(nt, ntOutput) NodesTools.deselectNodes(nt) ma.vray.ntree = nt return ntMaterial
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 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): for nt in bpy.data.node_groups: debug.PrintInfo("Checking tree: %s..." % nt.name) for n in nt.nodes: if not hasattr(n, 'texture'): continue if n.texture: debug.PrintInfo("Texture presents: %s [\"%s\"]" % (n.texture.name, n.name)) continue if not n.texture_name: debug.PrintError("Outdated node version: %s" % n.name) continue texName = n.texture_name if texName not in bpy.data.textures: debug.PrintInfo("Texture not found: %s" % texName) continue n.texture = bpy.data.textures[texName] debug.PrintInfo("Texture restored: %s [\"%s\"]" % (texName, n.name)) return {'FINISHED'}
def PreprocessTextures(ma, influence): textures = {} for ts in ma.texture_slots: if not (ts and ts.texture): continue tex = ts.texture if tex.type not in TexTypes: continue VRayTexture = tex.vray VRaySlot = tex.vray_slot # Convert mapping here if needed # This will support both vb25's 'master' and 'dev/animation' if not VRaySlot.uv_layer: VRaySlot.uv_layer = ts.uv_layer debug.PrintInfo(' Texture "%s" {%s:%s}' % (tex.name, tex.type, VRayTexture.type)) for inf in influence: slotUse = "map_%s" % inf slotMult = "%s_mult" % inf slotInvert = "%s_invert" % slotUse if not getattr(VRaySlot, slotUse): continue # NOTE: Adding default color value to blend over if not inf in textures: textures[inf] = [ SingleTexture( output=influence[inf]['type'], texture=influence[inf]['value'], ) ] textures[inf].append( SingleTexture( texture=tex, slot=ts, output=influence[inf]['type'], blend_mode=VRaySlot.blend_mode, mult=getattr(VRaySlot, slotMult, 1.0), invert=getattr(VRaySlot, slotInvert, False), stencil=ts.use_stencil, )) return textures
def execute(self, context): VRayExporter = context.scene.vray.Exporter selectedNodeTree = VRayExporter.ntreeListIndex if selectedNodeTree == -1: return {'CANCELLED'} ntree = bpy.data.node_groups[selectedNodeTree] outputNode = NodesExport.GetOutputNode(ntree) if not outputNode: return {'CANCELLED'} exportPath = BlenderUtils.GetFullFilepath( VRayExporter.ntreeExportDirectory) exportPath = PathUtils.CreateDirectory(exportPath) fileName = "%s.vrscene" % LibUtils.CleanString(ntree.name) outputFilepath = os.path.normpath(os.path.join(exportPath, fileName)) debug.PrintInfo('Exporting "%s" to: "%s"' % (ntree.name, outputFilepath)) 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="", ) for sock in outputNode.inputs: conNode = NodesExport.GetConnectedNode(ntree, sock) if conNode: _vray_for_blender.exportNode(ntree.as_pointer(), conNode.as_pointer(), sock.as_pointer()) _vray_for_blender.exit(exporter) 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 execute(self, context): filepath = self.filepath # Сhange the menu title to the most recently chosen option preset_class = getattr(bpy.types, self.menu_idname) preset_class.bl_label = bpy.path.display_name(os.path.basename(filepath)) # Apply preset # debug.PrintInfo('Applying preset from "%s"' % filepath) vrsceneDict = ParseVrscene(filepath) return self._execute(context, vrsceneDict)
def execute(self, context): debug.PrintInfo('Executing operator: "%s"' % self.bl_label) VRayScene = context.scene.vray VRayConverter = VRayScene.VRayConverter try: if VRayConverter.convert_from == 'INTERNAL': convert.convert_bi() convert.ConvertScene(context.scene) except Exception as e: debug.ExceptionInfo(e) self.report({'ERROR'}, "%s" % e) return {'CANCELLED'} return {'FINISHED'}
def CreateTextureNodes(ntree, node, textures): pluginID = node.vray_plugin pluginDesc = PLUGINS_ID[pluginID] for attrDesc in pluginDesc.PluginParams: attrName = attrDesc['attr'] attrSockName = AttributeUtils.GetNameFromAttr(attrName) inputSocket = _findSocketCaseInsensitive(node, attrSockName) if attrDesc['type'] not in AttributeUtils.InputTypes: continue if attrName in textures: tex = textures[attrName] debug.PrintInfo('Found texture "%s" for attr "%s"' % (tex, attrName)) texNode = tex.createNode(ntree) _connectNodes(ntree, texNode, OutputToSocket[tex.output], node, inputSocket.name)
def execute(self, context): VRayScene = context.scene.vray BatchBake = VRayScene.BatchBake VRayBake = VRayScene.BakeView # Copy selection selection = [ob for ob in context.selected_objects] formatDict = LibUtils.GetDefFormatDict() obList = None if BatchBake.work_mode == 'SELECTION': obList = selection elif BatchBake.work_mode == 'LIST': obList = [ item.ob for item in BatchBake.list_items if item.use and item.ob ] numObjects = len(obList) # Backup some settings ValueBackup(VRayScene.SettingsOutput, 'img_dir') ValueBackup(VRayScene.SettingsOutput, 'img_file') ValueBackup(VRayScene.Exporter, 'autoclose') ValueBackup(VRayScene.Exporter, 'auto_save_render') if numObjects: VRayScene.Exporter.auto_save_render = True # We have to wait for render end # only if baking multiple objects if numObjects > 1: VRayScene.Exporter.wait = True VRayScene.Exporter.autoclose = True try: for ob in obList: debug.PrintInfo("Baking: %s..." % ob.name) VRayScene.Exporter.currentBakeObject = ob # UV channel to use for baking uv_channel = None # Find UV map index if BatchBake.uv_map == 'UV_DEFAULT': if len(ob.data.uv_layers): uv_channel = 0 elif BatchBake.uv_map == 'UV_VRAYBAKE': uv_channel = GetUVChannelIndex(ob, "VRayBake") # Add projection if need elif BatchBake.uv_map.startswith('UV_NEW_'): uvName = None if BatchBake.uv_map == 'UV_NEW_SMART': uvName = "VRayBakeSmart" elif BatchBake.uv_map == 'UV_NEW_LM': uvName = "VRayBakeLightmap" uv_channel = GetUVChannelIndex(ob, uvName) if uv_channel is None: if ob.mode in {'EDIT'}: bpy.ops.object.mode_set(mode='OBJECT') bpy.ops.object.select_all(action='DESELECT') ob.select = True context.scene.objects.active = ob if BatchBake.uv_map == 'UV_NEW_SMART': bpy.ops.object.mode_set(mode='EDIT') bpy.ops.mesh.select_all(action='SELECT') layer = ob.data.uv_textures.new(name=uvName) layer.active = True bpy.ops.uv.smart_project( angle_limit=BatchBake.smart_uv.angle_limit, island_margin=BatchBake.smart_uv. island_margin, user_area_weight=BatchBake.smart_uv. user_area_weight, ) bpy.ops.mesh.select_all(action='DESELECT') bpy.ops.object.mode_set(mode='OBJECT') elif BatchBake.uv_map == 'UV_NEW_LM': bpy.ops.uv.lightmap_pack( PREF_CONTEXT='ALL_FACES', PREF_NEW_UVLAYER=True, PREF_BOX_DIV=BatchBake.lightmap_uv. PREF_BOX_DIV, PREF_MARGIN_DIV=BatchBake.lightmap_uv. PREF_MARGIN_DIV, ) ob.data.uv_textures[-1].name = uvName uv_channel = len(ob.data.uv_textures) - 1 if uv_channel is None: debug.PrintError("UV Map is not found!") continue # Bake settings VRayScene.BakeView.bake_node = ob.name VRayScene.BakeView.uv_channel = uv_channel # Setup vars formatDict['$O'] = ("Object Name", LibUtils.CleanString(ob.name, stripSigns=False)) # Render VRayScene.SettingsOutput.img_file = LibUtils.FormatName( BatchBake.output_filename, formatDict) VRayScene.SettingsOutput.img_dir = LibUtils.FormatName( BatchBake.output_dirpath, formatDict) bpy.ops.render.render() except Exception as e: debug.PrintError("Erorr baking objects!") debug.ExceptionInfo(e) # Restore selection for ob in selection: ob.select = True RestoreSettings(context.scene) return {'FINISHED'}
def ImportMaterialWithDisplacement(context, filePath, use_fake_user=True): debug.PrintInfo('Importing materials from "%s"' % filePath) vrsceneDict = {} if filePath.endswith(".vrscene"): vrsceneDict = ParseVrscene(filePath) else: vrsceneDict = ParseVrmat(filePath) nodeNames = [] for pluginDesc in vrsceneDict: pluginID = pluginDesc['ID'] pluginName = pluginDesc['Name'] if pluginID == 'Node': nodeNames.append(pluginName) for nodeName in nodeNames: debug.PrintInfo("Importing material from Node: %s" % nodeName) nodePluginDesc = NodesImport.getPluginByName(vrsceneDict, nodeName) # Import material # maName = nodePluginDesc['Attributes']['material'] if maName in bpy.data.node_groups: continue maPluginDesc = NodesImport.getPluginByName(vrsceneDict, maName) if not maPluginDesc: continue maNtree = bpy.data.node_groups.new(maName, type='VRayNodeTreeMaterial') maNtree.use_fake_user = True maOutputNode = maNtree.nodes.new('VRayNodeOutputMaterial') maNode = NodesImport.createNode(maNtree, maOutputNode, vrsceneDict, maPluginDesc) maNtree.links.new(maNode.outputs['Material'], maOutputNode.inputs['Material']) NodesTools.rearrangeTree(maNtree, maOutputNode) # Check geometry for displacement # geomName = nodePluginDesc['Attributes']['geometry'] geomPluginDesc = NodesImport.getPluginByName(vrsceneDict, geomName) if geomPluginDesc and geomPluginDesc['ID'] == 'GeomDisplacedMesh': colorTexName = geomPluginDesc['Attributes'].get( "displacement_tex_color") floatTexName = geomPluginDesc['Attributes'].get( "displacement_tex_float") if colorTexName or floatTexName: # Create node tree with displace name dispNtree = bpy.data.node_groups.new( geomPluginDesc['Name'], type='VRayNodeTreeMaterial') dispNtree.use_fake_user = True # Add group output to displace tree dispGroupOutput = dispNtree.nodes.new('NodeGroupOutput') # Import texture nodes colorTexNode = NodesImport.FindAndCreateNode( vrsceneDict, colorTexName, dispNtree, dispGroupOutput) floatTexNode = NodesImport.FindAndCreateNode( vrsceneDict, floatTexName, dispNtree, dispGroupOutput) # Add/connect output sockets if colorTexName: dispNtree.outputs.new('VRaySocketColor', 'Color') dispNtree.links.new(colorTexNode.outputs['Output'], dispGroupOutput.inputs['Color']) if floatTexName: dispNtree.outputs.new('VRaySocketFloat', 'Float') dispNtree.links.new(floatTexNode.outputs['Output'], dispGroupOutput.inputs['Float']) NodesTools.rearrangeTree(dispNtree, dispGroupOutput) NodesTools.deselectNodes(dispNtree) # Create a group node in current material tree # to show user that we have displacement dispGroupNode = maNtree.nodes.new('ShaderNodeGroup') dispGroupNode.node_tree = dispNtree dispGroupNode.location.x = 0 dispGroupNode.location.y = 100 # Finally create a material CreateMaterial(maName, maNtree, use_fake_user) NodesTools.deselectNodes(maNtree) return {'FINISHED'}
def ConvertMaterial(scene, ob, ma, textures): VRayMaterial = ma.vray VRayConverter = scene.vray.VRayConverter # This is the last node of the material # NOT the output, but the last Mtl node materialNode = None if VRayMaterial.ntree: outputNode = NodesUtils.GetNodeByType(VRayMaterial.ntree, 'VRayNodeOutputMaterial') materialNode = NodesUtils.GetConnectedNode( VRayMaterial.ntree, outputNode.inputs['Material']) else: if ma.node_tree: if VRayConverter.convert_from == 'CYCLES': return ConvertNodeMaterial(scene, ob, ma) return None debug.PrintInfo("Converting material: %s" % ma.name) nt = _createVRayTree(ma.name, 'Material') outputNode = _createVRayNode(nt, 'OutputMaterial') materialTop = _createVRayNode(nt, 'MtlSingleBRDF') brdfTo = materialTop mainBRDF = None if VRayMaterial.round_edges: mtlRoundEdges = _createVRayNode(nt, 'MtlRoundEdges') mtlRoundEdges.inputs['Radius'].value = VRayMaterial.radius _connectNodes(nt, materialTop, 'Material', mtlRoundEdges, 'Base Mtl') materialTop = mtlRoundEdges if VRayMaterial.material_id_number: mtlMaterialID = _createVRayNode(nt, 'MtlMaterialID') mtlMaterialID.MtlMaterialID.material_id_number = VRayMaterial.material_id_number mtlMaterialID.inputs[ 'Material Id Color'].value = VRayMaterial.material_id_color _connectNodes(nt, materialTop, 'Material', mtlMaterialID, 'Base Mtl') materialTop = mtlMaterialID if VRayMaterial.Mtl2Sided.use: mtl2Sided = _createVRayNode(nt, 'Mtl2Sided') mtl2Sided.Mtl2Sided.force_1sided = VRayMaterial.Mtl2Sided.force_1sided mtl2Sided.inputs['Translucency'].value = [ VRayMaterial.Mtl2Sided.translucency_slider ] * 3 backMat = None if VRayMaterial.Mtl2Sided.back: backMaName = VRayMaterial.Mtl2Sided.back if backMaName in bpy.data.materials: backMa = bpy.data.materials[backMaName] backTex = ProcessTextures(backMa) ConvertMaterial(scene, ob, backMa, backTex) backMat = _createGroupMaterial(nt, backMa) _connectNodes(nt, materialTop, 'Material', mtl2Sided, 'Front') if backMat: _connectNodes(nt, backMat, 'Material', mtl2Sided, 'Back') else: _connectNodes(nt, materialTop, 'Material', mtl2Sided, 'Back') materialTop = mtl2Sided if VRayMaterial.MtlOverride.use: pass for ovrName in {'MtlWrapper', 'MtlRenderStats'}: ovrPropGroup = getattr(VRayMaterial, ovrName) ovrUse = getattr(ovrPropGroup, 'use') if not ovrUse: continue debug.PrintInfo(" Found override: %s" % ovrName) ovrNode = _createVRayNode(nt, ovrName) _connectNodes(nt, materialTop, 'Material', ovrNode, OverrideInputSocket[ovrName]) materialTop = ovrNode # Connect last material to the output materialNode = materialTop _connectNodes(nt, materialTop, 'Material', outputNode, 'Material') # BRDFs # if 'normal' in textures: norTex = _getTextureFromTextures(textures, 'normal') mainBRDF = _createVRayNode(nt, 'BRDFBump') mainBRDF.inputs['Bump Amount Texture'].value = _getBumpAmount(ma) bumpTexNode = norTex.createNode(nt) _connectNodes(nt, bumpTexNode, 'Color', mainBRDF, 'Color Texture') _connectNodes(nt, bumpTexNode, 'Out Intensity', mainBRDF, 'Float Texture') # Finally generate main BRDF node and connect top brdf # if needed brdfType = VRayMaterial.type baseBRDF = _createVRayNode(nt, brdfType) oldPropGroup = getattr(VRayMaterial, brdfType) TransferProperties(baseBRDF, brdfType, oldPropGroup) CreateTextureNodes(nt, baseBRDF, textures) # Manual tweaks if brdfType == 'BRDFVRayMtl': if 'reflect' not in textures: baseBRDF.inputs['Reflect'].value = oldPropGroup.reflect_color if 'refract' not in textures: baseBRDF.inputs['Refract'].value = oldPropGroup.refract_color baseBRDF.inputs['Fog Color Tex'].value = oldPropGroup.fog_color if not mainBRDF: mainBRDF = baseBRDF else: _connectNodes(nt, baseBRDF, 'BRDF', mainBRDF, 'Base Brdf') # Connect last BRDF to the last material _connectNodes(nt, mainBRDF, 'BRDF', brdfTo, 'BRDF') NodesTools.rearrangeTree(nt, outputNode) NodesTools.deselectNodes(nt) VRayMaterial.ntree = nt return materialNode
def ImportMaterials(context, filePath, baseMaterial, use_fake_user=True): debug.PrintInfo('Importing materials from "%s"' % filePath) vrsceneDict = {} if filePath.endswith(".vrscene"): vrsceneDict = ParseVrscene(filePath) else: vrsceneDict = ParseVrmat(filePath) MaterialTypeFilter = { 'STANDARD': { 'MtlSingleBRDF', 'MtlVRmat', 'MtlDoubleSided', 'MtlGLSL', 'MtlLayeredBRDF', 'MtlDiffuse', 'MtlBump', 'Mtl2Sided', }, 'MULTI': {'MtlMulti'}, 'WRAPPED': { 'MtlWrapper', 'MtlWrapperMaya', 'MayaMtlMatte', 'MtlMaterialID', 'MtlMayaRamp', 'MtlObjBBox', 'MtlOverride', 'MtlRenderStats', 'MtlRoundEdges', 'MtlStreakFade', }, } # Collect material names based on selected # base material type # materialNames = [] for pluginDesc in vrsceneDict: pluginID = pluginDesc['ID'] pluginName = pluginDesc['Name'] if pluginID in MaterialTypeFilter[baseMaterial]: materialNames.append(pluginName) for maName in materialNames: debug.PrintInfo("Importing material: %s" % maName) pluginDesc = NodesImport.getPluginByName(vrsceneDict, maName) ntree = bpy.data.node_groups.new(maName, type='VRayNodeTreeMaterial') ntree.use_fake_user = True outputNode = ntree.nodes.new('VRayNodeOutputMaterial') maNode = NodesImport.createNode(ntree, outputNode, vrsceneDict, pluginDesc) ntree.links.new(maNode.outputs['Material'], outputNode.inputs['Material']) NodesTools.rearrangeTree(ntree, outputNode) NodesTools.deselectNodes(ntree) # Finally create a material CreateMaterial(maName, ntree, use_fake_user) return {'FINISHED'}
def run(self): cmd = self.getCommandLine() errCode = 0 if not self.isPreview: commandLine = " ".join(cmd) debug.PrintInfo("Command Line: %s" % commandLine) if self.gen_run_file: baseFile = self.sceneFile if bpy.data.filepath: baseFile = bpy.data.filepath sceneFileName = bpy.path.display_name_from_filepath(baseFile) runExt = "bat" if sys.platform == 'win32' else "sh" cmdSep = "^" if sys.platform == 'win32' else "\\" allTheRest = "%%*" if sys.platform == 'win32' else "$*" runFilename = "render_%s.%s" % (sceneFileName, runExt) runFilepath = os.path.join(os.path.dirname(baseFile), runFilename) debug.PrintInfo("Generating %s..." % runFilename) cmdJoin = " %s\n" % cmdSep fileCmdLine = "%s %s\n" % (PathUtils.Quotes( cmd[0], force=True), cmdSep) fileCmdLine += cmdJoin.join(cmd[1:]) with open(runFilepath, 'w') as f: f.write(fileCmdLine) f.write(" %s\n%s" % (cmdSep, allTheRest)) f.write("\n") if sys.platform not in {'win32'}: os.chmod(runFilepath, 0o744) VRayExporter = bpy.context.scene.vray.Exporter if not VRayExporter.vfb_global_preset_file_use: vray_vfb_global_preset_vars = { 'VRAY_VFB_GLOBAL_PRESET_FILE_USE', 'VRAY_VFB_GLOBAL_PRESET_FILE' } for var in vray_vfb_global_preset_vars: if var in os.environ: del os.environ[var] else: os.environ[ 'VRAY_VFB_GLOBAL_PRESET_FILE_USE'] = "%i" % VRayExporter.vfb_global_preset_file_use os.environ[ 'VRAY_VFB_GLOBAL_PRESET_FILE'] = BlenderUtils.GetFullFilepath( VRayExporter.vfb_global_preset_file) os.environ[ 'VRAY_VFB_ALWAYS_ON_TOP'] = "%i" % VRayExporter.display_vfb_on_top os.environ['VRAY_NO_CTRL_C_HANDLER'] = '1' vfbThemeFilepath = os.path.join(SysUtils.GetUserConfigDir(), "vfb.theme") BlenderUtils.generateVfbTheme(vfbThemeFilepath) os.environ['VRAY_VFB_THEME_FILE'] = vfbThemeFilepath if self.autorun: self.process = subprocess.Popen(cmd) if self.waitExit: errCode = self.process.wait() return errCode
def GetVRayStandalonePath(): VRayPreferences = bpy.context.user_preferences.addons['vb30'].preferences vray_bin = "vray" if sys.platform == 'win32': vray_bin += ".exe" def get_env_paths(var): split_char = ';' if sys.platform == 'win32' else ":" env_var = os.getenv(var) if env_var: return env_var.replace('\"', '').split(split_char) return [] def find_vray_std_osx_official(): vrayPath = "/Applications/ChaosGroup/V-Ray/Standalone_for_snow_leopard_x86/bin/snow_leopard_x86/gcc-4.2/vray" if os.path.exists(vrayPath): return vrayPath return None def find_vray_std_osx(): import glob instLogFilepath = "/var/log/chaos_installs" if not os.path.exists(instLogFilepath): return None instLog = open(instLogFilepath, 'r').readlines() for l in instLog: # Example path: # /Applications/ChaosGroup/V-Ray/Standalone_for_snow_leopard_x86/uninstall/linuxinstaller.app/Contents # if 'V-Ray Standalone' in l and '[UN]' not in l: _tmp_, path = l.strip().split('=') # Going up to /Applications/ChaosGroup/V-Ray/Standalone_for_snow_leopard_x86/bin path = os.path.normpath( os.path.join(path.strip(), '..', '..', '..', "bin")) possiblePaths = glob.glob('%s/*/*/vray' % path) if len(possiblePaths): return possiblePaths[0] return None return None def find_vray_binary(paths): if paths: for p in paths: if p: vray_path = os.path.join(p, vray_bin) if os.path.exists(vray_path): return vray_path return None if not VRayPreferences.detect_vray and VRayPreferences.vray_binary: manualVRayPath = bpy.path.abspath(VRayPreferences.vray_binary) if os.path.exists(manualVRayPath): return manualVRayPath # Check 'VRAY_PATH' environment variable # vray_standalone_paths = get_env_paths('VRAY_PATH') if vray_standalone_paths: vray_standalone = find_vray_binary(vray_standalone_paths) if vray_standalone: return vray_standalone # On OS X check default path and install log # if sys.platform in {'darwin'}: path = find_vray_std_osx_official() if path is not None: return path path = find_vray_std_osx() if path is not None: return path # Try to find Standalone in V-Ray For Maya # for var in reversed(sorted(os.environ.keys())): if var.startswith('VRAY_FOR_MAYA'): if var.find('MAIN') != -1: debug.PrintInfo("Searching in: %s" % var) vray_maya = find_vray_binary( [os.path.join(path, 'bin') for path in get_env_paths(var)]) if vray_maya: debug.PrintInfo("V-Ray found in: %s" % vray_maya) return vray_maya # Try to find vray binary in %PATH% debug.PrintError( "V-Ray not found! Trying to start \"%s\" command from $PATH..." % vray_bin) return shutil.which(vray_bin)
def ConvertObject(scene, ob): debug.PrintInfo("Converting object: %s" % ob.name) VRayConverter = scene.vray.VRayConverter VRayObject = ob.vray VRayData = ob.data.vray needNodeTree = False hasDisplacement = None for ms in ob.material_slots: if not (ms and ms.material): continue ma = ms.material textures = ProcessTextures(ma) if VRayConverter.convert_materials: ConvertMaterial(scene, ob, ma, textures) if 'displacement' in textures: debug.PrintInfo(" Found displacement") hasDisplacement = textures['displacement'] if not VRayConverter.convert_objects: return # Check if we need node tree from override materials for ovrName in ObjectMaterialOverrides: ovrPropGroup = getattr(VRayObject, ovrName) ovrUse = getattr(ovrPropGroup, 'use') if ovrUse: debug.PrintInfo(" Found override: %s" % ovrName) needNodeTree = True break needNodeTree = needNodeTree or hasDisplacement or VRayData.override if not VRayObject.ntree and needNodeTree: nt = _createVRayTree(ob.name, 'Object') outputNode = _createVRayNode(nt, 'ObjectOutput') # MATERIAL # blenderMaterial = _createVRayNode(nt, 'BlenderOutputMaterial') for ovrName in ObjectMaterialOverrides: ovrPropGroup = getattr(VRayObject, ovrName) ovrUse = getattr(ovrPropGroup, 'use') # NOTE: MtlWrapper and MtlOverride could be left on node # as is if not ovrUse: continue pass _connectNodes(nt, blenderMaterial, 'Material', outputNode, 'Material') # GEOMETRY # # Infinite plane or VRayProxy if VRayData.override: debug.PrintInfo(" Found geometry override '%s'" % VRayData.override_type) if VRayData.override_type == 'VRAYPLANE': blenderGeometry = _createVRayNode(nt, 'GeomPlane') else: blenderGeometry = _createVRayNode(nt, 'GeomMeshFile') blenderGeometry.GeomMeshFile.file = VRayData.GeomMeshFile.file # Displacemnt and / or subdivision else: blenderGeometry = _createVRayNode(nt, 'BlenderOutputGeometry') if hasDisplacement: displaceNodeType = 'GeomDisplacedMesh' if VRayObject.GeomStaticSmoothedMesh.use: displaceNodeType = 'GeomStaticSmoothedMesh' dispTex = hasDisplacement dispAmount = _getDisplacementAmount(ob) displaceNode = _createVRayNode(nt, displaceNodeType) displacePropGroup = getattr(displaceNode, displaceNodeType) setattr(displacePropGroup, 'displacement_amount', dispAmount) dispTexNode = dispTex.createNode(nt) # Connect textures _connectNodes(nt, dispTexNode, 'Color', displaceNode, 'Color') _connectNodes(nt, dispTexNode, 'Out Intensity', displaceNode, 'Float') # Connect geometry _connectNodes(nt, blenderGeometry, 'Geometry', displaceNode, 'Mesh') # Set displace as last geometry node blenderGeometry = displaceNode else: if VRayObject.GeomStaticSmoothedMesh.use: pass if blenderGeometry: _connectNodes(nt, blenderGeometry, 'Geometry', outputNode, 'Geometry') NodesTools.rearrangeTree(nt, outputNode) VRayObject.ntree = nt
def convert_bi(): CONVERT_BLEND_TYPE = { 'MIX': 'OVER', 'SCREEN': 'OVER', 'DIVIDE': 'OVER', 'HUE': 'OVER', 'VALUE': 'OVER', 'COLOR': 'OVER', 'SOFT LIGHT': 'OVER', 'LINEAR LIGHT': 'OVER', 'OVERLAY': 'OVER', 'ADD': 'ADD', 'SUBTRACT': 'SUBTRACT', 'MULTIPLY': 'MULTIPLY', 'DIFFERENCE': 'DIFFERENCE', 'DARKEN': 'DARKEN', 'LIGHTEN': 'LIGHTEN', 'SATURATION': 'SATURATE', } for ma in bpy.data.materials: debug.PrintInfo("Converting from Blender Internal: %s" % ma.name) rm = ma.raytrace_mirror rt = ma.raytrace_transparency VRayMaterial = ma.vray BRDFVRayMtl = VRayMaterial.BRDFVRayMtl BRDFVRayMtl.diffuse = ma.diffuse_color if ma.emit > 0.0: VRayMaterial.type = 'BRDFLight' if rm.use: BRDFVRayMtl.reflect_color = tuple([rm.reflect_factor] * 3) BRDFVRayMtl.reflect_glossiness = rm.gloss_factor BRDFVRayMtl.reflect_subdivs = rm.gloss_samples BRDFVRayMtl.reflect_depth = rm.depth BRDFVRayMtl.option_cutoff = rm.gloss_threshold BRDFVRayMtl.anisotropy = 1.0 - rm.gloss_anisotropic if rm.fresnel > 0.0: BRDFVRayMtl.fresnel = True BRDFVRayMtl.fresnel_ior = rm.fresnel for slot in ma.texture_slots: if slot and slot.texture and slot.texture.type in TexTypes: VRaySlot = slot.texture.vray_slot VRayTexture = slot.texture.vray VRaySlot.blend_mode = CONVERT_BLEND_TYPE[slot.blend_type] if slot.use_map_emit: VRayMaterial.type = 'BRDFLight' VRaySlot.map_diffuse = True if slot.use_map_normal: VRaySlot.map_normal = True VRaySlot.BRDFBump.bump_tex_mult = slot.normal_factor if slot.use_map_color_diffuse: VRaySlot.map_diffuse = True VRaySlot.diffuse_mult = slot.diffuse_color_factor if slot.use_map_raymir: VRaySlot.map_reflect = True VRaySlot.reflect_mult = slot.raymir_factor if slot.use_map_alpha: VRaySlot.map_opacity = True VRaySlot.opacity_mult = slot.alpha_factor
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'