From 50e45d93a7e89d8f65ede6ac4364b7a13c4e3585 Mon Sep 17 00:00:00 2001 From: Campbell Barton Date: Sat, 22 Jan 2011 05:43:40 +0000 Subject: povray script now passes the pep8 checker. noticed some strange code, added XXX FIXME. --- render_povray/__init__.py | 94 +++--- render_povray/render.py | 767 ++++++++++++++++++++++++---------------------- render_povray/ui.py | 44 ++- 3 files changed, 476 insertions(+), 429 deletions(-) diff --git a/render_povray/__init__.py b/render_povray/__init__.py index 6a4a56d7..4c3f278f 100644 --- a/render_povray/__init__.py +++ b/render_povray/__init__.py @@ -16,6 +16,8 @@ # # ##### END GPL LICENSE BLOCK ##### +# + bl_info = { "name": "POV-Ray 3.7", "author": "Campbell Barton, Silvio Falcinelli, Maurice Raybaud, Constantin Rahn", @@ -43,6 +45,7 @@ else: from render_povray import ui from render_povray import render + def register(): Scene = bpy.types.Scene @@ -80,7 +83,7 @@ def register(): name="Quantity of spaces", description="The number of spaces for indentation", min=1, max=10, default=3) - + Scene.pov_comments_enable = BoolProperty( name="Enable Comments", description="Add comments to pov file", @@ -90,26 +93,26 @@ def register(): Scene.pov_command_line_switches = StringProperty(name="Command Line Switches", description="Command line switches consist of a + (plus) or - (minus) sign, followed by one or more alphabetic characters and possibly a numeric value.", default="", maxlen=500) - + Scene.pov_antialias_enable = BoolProperty( name="Anti-Alias", description="Enable Anti-Aliasing", default=True) - + Scene.pov_antialias_method = EnumProperty( name="Method", description="AA-sampling method. Type 1 is an adaptive, non-recursive, super-sampling method. Type 2 is an adaptive and recursive super-sampling method.", items=(("0", "non-recursive AA", "Type 1 Sampling in POV-Ray"), ("1", "recursive AA", "Type 2 Sampling in POV-Ray")), default="1") - + Scene.pov_antialias_depth = IntProperty( name="Antialias Depth", description="Depth of pixel for sampling", min=1, max=9, default=3) - + Scene.pov_antialias_threshold = FloatProperty( name="Antialias Threshold", description="Tolerance for sub-pixels", min=0.0, max=1.0, soft_min=0.05, soft_max=0.5, default=0.1) - + Scene.pov_jitter_enable = BoolProperty( name="Jitter", description="Enable Jittering. Adds noise into the sampling process (it should be avoided to use jitter in animation).", default=True) @@ -117,15 +120,15 @@ def register(): Scene.pov_jitter_amount = FloatProperty( name="Jitter Amount", description="Amount of jittering.", min=0.0, max=1.0, soft_min=0.01, soft_max=1.0, default=1.0) - + Scene.pov_antialias_gamma = FloatProperty( name="Antialias Gamma", description="POV-Ray compares gamma-adjusted values for super sampling. Antialias Gamma sets the Gamma before comparison.", min=0.0, max=5.0, soft_min=0.01, soft_max=2.5, default=2.5) - + Scene.pov_max_trace_level = IntProperty( name="Max Trace Level", description="Number of reflections/refractions allowed on ray path", min=1, max=256, default=5) - + Scene.pov_radio_adc_bailout = FloatProperty( name="ADC Bailout", description="The adc_bailout for radiosity rays. Use adc_bailout = 0.01 / brightest_ambient_object for good results", min=0.0, max=1000.0, soft_min=0.0, soft_max=1.0, default=0.01, precision=3) @@ -189,7 +192,7 @@ def register(): Mat.pov_irid_enable = BoolProperty( name="Enable Iridescence", description="Newton's thin film interference (like an oil slick on a puddle of water or the rainbow hues of a soap bubble.)", - default=False) + default=False) Mat.pov_mirror_use_IOR = BoolProperty( name="Correct Reflection", @@ -252,17 +255,17 @@ def register(): default=False) Mat.pov_refraction_type = EnumProperty( - items=[("0","None","use only reflective caustics"), - ("1","Fake Caustics","use fake caustics"), - ("2","Photons Caustics","use photons for refractive caustics"), + items=[("0", "None", "use only reflective caustics"), + ("1", "Fake Caustics", "use fake caustics"), + ("2", "Photons Caustics", "use photons for refractive caustics"), ], name="Refractive", description="use fake caustics (fast) or true photons for refractive Caustics", - default="1")#ui.py has to be loaded before render.py with this. - + default="1") # ui.py has to be loaded before render.py with this. + ######################################################################################## #Custom texture gamma - Tex = bpy.types.Texture + Tex = bpy.types.Texture Tex.pov_tex_gamma_enable = BoolProperty( name="Enable custom texture gamma", description="Notify some custom gamma for which texture has been precorrected without the file format carrying it and only if it differs from your OS expected standard (see pov doc)", @@ -278,15 +281,16 @@ def register(): name="Radiosity Importance", description="Priority value relative to other objects for sampling radiosity rays. Increase to get more radiosity rays at comparatively small yet bright objects", min=0.01, max=1.00, default=1.00) - + ######################################EndMR##################################### + def unregister(): import bpy Scene = bpy.types.Scene - Mat = bpy.types.Material # MR - Tex = bpy.types.Texture # MR - Obj = bpy.types.Object # MR + Mat = bpy.types.Material # MR + Tex = bpy.types.Texture # MR + Obj = bpy.types.Object # MR del Scene.pov_radio_enable del Scene.pov_radio_display_advanced del Scene.pov_radio_adc_bailout @@ -301,15 +305,15 @@ def unregister(): del Scene.pov_radio_nearest_count del Scene.pov_radio_normal del Scene.pov_radio_recursion_limit - del Scene.pov_radio_pretrace_start # MR - del Scene.pov_radio_pretrace_end # MR - del Scene.pov_media_enable # MR - del Scene.pov_media_samples # MR - del Scene.pov_media_color # MR - del Scene.pov_baking_enable # MR - del Scene.pov_max_trace_level # MR + del Scene.pov_radio_pretrace_start # MR + del Scene.pov_radio_pretrace_end # MR + del Scene.pov_media_enable # MR + del Scene.pov_media_samples # MR + del Scene.pov_media_color # MR + del Scene.pov_baking_enable # MR + del Scene.pov_max_trace_level # MR del Scene.pov_antialias_enable # CR - del Scene.pov_antialias_method # CR + del Scene.pov_antialias_method # CR del Scene.pov_antialias_depth # CR del Scene.pov_antialias_threshold # CR del Scene.pov_antialias_gamma # CR @@ -319,23 +323,23 @@ def unregister(): del Scene.pov_indentation_character # CR del Scene.pov_indentation_spaces # CR del Scene.pov_comments_enable # CR - del Mat.pov_irid_enable # MR - del Mat.pov_mirror_use_IOR # MR - del Mat.pov_mirror_metallic # MR - del Mat.pov_conserve_energy # MR - del Mat.pov_irid_amount # MR - del Mat.pov_irid_thickness # MR - del Mat.pov_irid_turbulence # MR - del Mat.pov_caustics_enable # MR - del Mat.pov_fake_caustics # MR - del Mat.pov_fake_caustics_power # MR - del Mat.pov_photons_refraction # MR - del Mat.pov_photons_dispersion # MR - del Mat.pov_photons_reflection # MR - del Mat.pov_refraction_type # MR - del Tex.pov_tex_gamma_enable # MR - del Tex.pov_tex_gamma_value # MR - del Obj.pov_importance_value # MR + del Mat.pov_irid_enable # MR + del Mat.pov_mirror_use_IOR # MR + del Mat.pov_mirror_metallic # MR + del Mat.pov_conserve_energy # MR + del Mat.pov_irid_amount # MR + del Mat.pov_irid_thickness # MR + del Mat.pov_irid_turbulence # MR + del Mat.pov_caustics_enable # MR + del Mat.pov_fake_caustics # MR + del Mat.pov_fake_caustics_power # MR + del Mat.pov_photons_refraction # MR + del Mat.pov_photons_dispersion # MR + del Mat.pov_photons_reflection # MR + del Mat.pov_refraction_type # MR + del Tex.pov_tex_gamma_enable # MR + del Tex.pov_tex_gamma_value # MR + del Obj.pov_importance_value # MR if __name__ == "__main__": register() diff --git a/render_povray/render.py b/render_povray/render.py index f432504e..1f95927c 100644 --- a/render_povray/render.py +++ b/render_povray/render.py @@ -16,6 +16,8 @@ # # ##### END GPL LICENSE BLOCK ##### +# + import bpy import subprocess import os @@ -32,64 +34,94 @@ else: ##############################SF########################### -##############find image texture +##############find image texture def splitExt(path): dotidx = path.rfind('.') if dotidx == -1: return path, '' else: - return (path[dotidx:]).upper().replace('.','') + return path[dotidx:].upper().replace(".", "") def imageFormat(imgF): ext = '' ext_orig = splitExt(imgF) - if ext_orig == 'JPG' or ext_orig == 'JPEG': ext='jpeg' - if ext_orig == 'GIF': ext = 'gif' - if ext_orig == 'TGA': ext = 'tga' - if ext_orig == 'IFF': ext = 'iff' - if ext_orig == 'PPM': ext = 'ppm' - if ext_orig == 'PNG': ext = 'png' - if ext_orig == 'SYS': ext = 'sys' - if ext_orig in ('TIFF', 'TIF'): ext = 'tiff' - if ext_orig == 'EXR': ext = 'exr'#POV3.7 Only! - if ext_orig == 'HDR': ext = 'hdr'#POV3.7 Only! --MR + if ext_orig == 'JPG' or ext_orig == 'JPEG': + ext = 'jpeg' + elif ext_orig == 'GIF': + ext = 'gif' + elif ext_orig == 'TGA': + ext = 'tga' + elif ext_orig == 'IFF': + ext = 'iff' + elif ext_orig == 'PPM': + ext = 'ppm' + elif ext_orig == 'PNG': + ext = 'png' + elif ext_orig == 'SYS': + ext = 'sys' + elif ext_orig in ('TIFF', 'TIF'): + ext = 'tiff' + elif ext_orig == 'EXR': + ext = 'exr' # POV3.7 Only! + elif ext_orig == 'HDR': + ext = 'hdr' # POV3.7 Only! --MR + print(imgF) - if not ext: print(' WARNING: texture image format not supported ') # % (imgF , '')) #(ext_orig))) + if not ext: + print(" WARNING: texture image format not supported ") # % (imgF , '')) #(ext_orig))) + return ext + def imgMap(ts): - image_map='' - if ts.mapping=='FLAT':image_map= 'map_type 0 ' - if ts.mapping=='SPHERE':image_map= 'map_type 1 '# map_type 7 in megapov - if ts.mapping=='TUBE':image_map= 'map_type 2 ' + image_map = "" + if ts.mapping == 'FLAT': + image_map = "map_type 0 " + elif ts.mapping == 'SPHERE': + image_map = "map_type 1 " # map_type 7 in megapov + elif ts.mapping == 'TUBE': + image_map = "map_type 2 " #if ts.mapping=='?':image_map= ' map_type 3 '# map_type 3 and 4 in development (?) for POV-Ray, currently they just seem to default back to Flat (type 0) #if ts.mapping=='?':image_map= ' map_type 4 '# map_type 3 and 4 in development (?) for POV-Ray, currently they just seem to default back to Flat (type 0) - if ts.texture.use_interpolation: image_map+= ' interpolate 2 ' - if ts.texture.extension == 'CLIP': image_map+=' once ' - #image_map+='}' - #if ts.mapping=='CUBE':image_map+= 'warp { cubic } rotate <-90,0,180>' #no direct cube type mapping. Though this should work in POV 3.7 it doesn't give that good results(best suited to environment maps?) - #if image_map=='': print(' No texture image found ') + if ts.texture.use_interpolation: + image_map += " interpolate 2 " + if ts.texture.extension == 'CLIP': + image_map += " once " + #image_map += "}" + #if ts.mapping=='CUBE': + # image_map+= 'warp { cubic } rotate <-90,0,180>' #no direct cube type mapping. Though this should work in POV 3.7 it doesn't give that good results(best suited to environment maps?) + #if image_map == "": + # print(' No texture image found ') return image_map + def imgMapBG(wts): - image_mapBG='' - if wts.texture_coords== 'VIEW':image_mapBG= ' map_type 0 ' #texture_coords refers to the mapping of world textures - if wts.texture_coords=='ANGMAP':image_mapBG= ' map_type 1 ' - if wts.texture_coords=='TUBE':image_mapBG= ' map_type 2 ' - if wts.texture.use_interpolation: image_mapBG+= ' interpolate 2 ' - if wts.texture.extension == 'CLIP': image_mapBG+=' once ' + image_mapBG = "" + if wts.texture_coords == 'VIEW': + image_mapBG = " map_type 0 " # texture_coords refers to the mapping of world textures + elif wts.texture_coords == 'ANGMAP': + image_mapBG = " map_type 1 " + elif wts.texture_coords == 'TUBE': + image_mapBG = " map_type 2 " + + if wts.texture.use_interpolation: + image_mapBG += " interpolate 2 " + if wts.texture.extension == 'CLIP': + image_mapBG += " once " #image_mapBG+='}' #if wts.mapping=='CUBE':image_mapBG+= 'warp { cubic } rotate <-90,0,180>' #no direct cube type mapping. Though this should work in POV 3.7 it doesn't give that good results(best suited to environment maps?) - #if image_mapBG=='': print(' No background texture image found ') + #if image_mapBG== "": print(' No background texture image found ') return image_mapBG + def splitFile(path): idx = path.rfind('/') if idx == -1: idx = path.rfind('\\') return path[idx:].replace('/', '').replace('\\', '') + def splitPath(path): idx = path.rfind('/') if idx == -1: @@ -97,8 +129,9 @@ def splitPath(path): else: return path[:idx] -def findInSubDir(filename, subdirectory=''): - pahFile='' + +def findInSubDir(filename, subdirectory=""): + pahFile = "" if subdirectory: path = subdirectory else: @@ -109,45 +142,48 @@ def findInSubDir(filename, subdirectory=''): pahFile = os.path.join(root, filename) return pahFile except OSError: - return '' + return '' + def path_image(image): import os fn = bpy.path.abspath(image) fn_strip = os.path.basename(fn) if not os.path.isfile(fn): - fn=(findInSubDir(splitFile(fn),splitPath(bpy.data.filepath))) - () + fn = findInSubDir(splitFile(fn), splitPath(bpy.data.filepath)) return fn -##############end find image texture +##############end find image texture + def splitHyphen(name): hyphidx = name.find('-') if hyphidx == -1: return name else: - return (name[hyphidx:]).replace('-','') + return name[hyphidx:].replace("-", "") + -##############safety string name material def safety(name, Level): + # safety string name material + # # Level=1 is for texture with No specular nor Mirror reflection # Level=2 is for texture with translation of spec and mir levels for when no map influences them - # Level=3 is for texture with Maximum Spec and Mirror + # Level=3 is for texture with Maximum Spec and Mirror try: if int(name) > 0: - prefix='shader' + prefix = "shader" except: prefix = '' - prefix='shader_' + prefix = "shader_" name = splitHyphen(name) if Level == 2: - return prefix+name + return prefix + name elif Level == 1: - return prefix+name+'0'#used for 0 of specular map + return prefix + name + "0" # used for 0 of specular map elif Level == 3: - return prefix+name+'1'#used for 1 of specular map + return prefix + name + "1" # used for 1 of specular map ##############end safety string name material @@ -155,6 +191,7 @@ def safety(name, Level): TabLevel = 0 + def write_pov(filename, scene=None, info_callback=None): import mathutils #file = filename @@ -172,27 +209,27 @@ def write_pov(filename, scene=None, info_callback=None): TabStr = '' if tabtype == '0': TabStr = '' - elif tabtype == '1': + elif tabtype == '1': TabStr = '\t' elif tabtype == '2': TabStr = spaces * ' ' return TabStr Tab = setTab(scene.pov_indentation_character, scene.pov_indentation_spaces) - + def tabWrite(str_o): global TabLevel - brackets = str_o.count('{') - str_o.count('}') + str_o.count('[') - str_o.count(']') + brackets = str_o.count('{') - str_o.count('}') + str_o.count('[') - str_o.count(']') if brackets < 0: - TabLevel = TabLevel + brackets + TabLevel = TabLevel + brackets if TabLevel < 0: print('Indentation Warning: TabLevel = %s' % TabLevel) TabLevel = 0 - if TabLevel >= 1: + if TabLevel >= 1: file.write('%s' % Tab * TabLevel) file.write(str_o) if brackets > 0: - TabLevel = TabLevel + brackets + TabLevel = TabLevel + brackets def uniqueName(name, nameSeq): @@ -212,45 +249,45 @@ def write_pov(filename, scene=None, info_callback=None): (matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2], matrix[2][0], matrix[2][1], matrix[2][2], matrix[3][0], matrix[3][1], matrix[3][2])) def writeObjectMaterial(material): - + # DH - modified some variables to be function local, avoiding RNA write # this should be checked to see if it is functionally correct - - if material: #and material.transparency_method == 'RAYTRACE':#Commented out: always write IOR to be able to use it for SSS, Fresnel reflections... - #But there can be only one! - if material.subsurface_scattering.use:#SSS IOR get highest priority + + if material: # and material.transparency_method == 'RAYTRACE':#Commented out: always write IOR to be able to use it for SSS, Fresnel reflections... + # But there can be only one! + if material.subsurface_scattering.use: # SSS IOR get highest priority tabWrite('interior {\n') tabWrite('ior %.6f\n' % material.subsurface_scattering.ior) - elif material.pov_mirror_use_IOR:#Then the raytrace IOR taken from raytrace transparency properties and used for reflections if IOR Mirror option is checked + elif material.pov_mirror_use_IOR: # Then the raytrace IOR taken from raytrace transparency properties and used for reflections if IOR Mirror option is checked tabWrite('interior {\n') tabWrite('ior %.6f\n' % material.raytrace_transparency.ior) else: tabWrite('interior {\n') tabWrite('ior %.6f\n' % material.raytrace_transparency.ior) - + pov_fake_caustics = False pov_photons_refraction = False pov_photons_reflection = False - - if material.pov_refraction_type=='0': + + if material.pov_refraction_type == "0": pov_fake_caustics = False pov_photons_refraction = False - pov_photons_reflection = True #should respond only to proper checkerbox - elif material.pov_refraction_type=='1': + pov_photons_reflection = True # should respond only to proper checkerbox + elif material.pov_refraction_type == "1": pov_fake_caustics = True pov_photons_refraction = False - elif material.pov_refraction_type=='2': + elif material.pov_refraction_type == "2": pov_fake_caustics = False pov_photons_refraction = True - #If only Raytrace transparency is set, its IOR will be used for refraction, but user can set up 'un-physical' fresnel reflections in raytrace mirror parameters. - #Last, if none of the above is specified, user can set up 'un-physical' fresnel reflections in raytrace mirror parameters. And pov IOR defaults to 1. + #If only Raytrace transparency is set, its IOR will be used for refraction, but user can set up 'un-physical' fresnel reflections in raytrace mirror parameters. + #Last, if none of the above is specified, user can set up 'un-physical' fresnel reflections in raytrace mirror parameters. And pov IOR defaults to 1. if material.pov_caustics_enable: if pov_fake_caustics: tabWrite('caustics %.3g\n' % material.pov_fake_caustics_power) if pov_photons_refraction: - tabWrite('dispersion %.3g\n' % material.pov_photons_dispersion) #Default of 1 means no dispersion - #TODO + tabWrite('dispersion %.3g\n' % material.pov_photons_dispersion) # Default of 1 means no dispersion + #TODO # Other interior args # if material.use_transparency and material.transparency_method == 'RAYTRACE': # fade_distance 2 @@ -267,7 +304,7 @@ def write_pov(filename, scene=None, info_callback=None): if pov_photons_reflection: tabWrite('reflection on\n') tabWrite('}\n') - + materialNames = {} DEF_MAT_NAME = 'Default' @@ -284,106 +321,104 @@ def write_pov(filename, scene=None, info_callback=None): ##################Several versions of the finish: Level conditions are variations for specular/Mirror texture channel map with alternative finish of 0 specular and no mirror reflection # Level=1 Means No specular nor Mirror reflection # Level=2 Means translation of spec and mir levels for when no map influences them - # Level=3 Means Maximum Spec and Mirror + # Level=3 Means Maximum Spec and Mirror def povHasnoSpecularMaps(Level): if Level == 1: - tabWrite('#declare %s = finish {' % safety(name, Level = 1)) - if comments: file.write(' //No specular nor Mirror reflection\n') - else: tabWrite('\n') + tabWrite('#declare %s = finish {' % safety(name, Level=1)) + if comments: + file.write(' //No specular nor Mirror reflection\n') + else: + tabWrite('\n') elif Level == 2: - tabWrite('#declare %s = finish {' % safety(name, Level = 2)) - if comments: file.write(' //translation of spec and mir levels for when no map influences them\n') - else: tabWrite('\n') + tabWrite('#declare %s = finish {' % safety(name, Level=2)) + if comments: + file.write(' //translation of spec and mir levels for when no map influences them\n') + else: + tabWrite('\n') elif Level == 3: - tabWrite('#declare %s = finish {' % safety(name, Level = 3)) - if comments: file.write(' //Maximum Spec and Mirror\n') - else: tabWrite('\n') - + tabWrite('#declare %s = finish {' % safety(name, Level=3)) + if comments: + file.write(' //Maximum Spec and Mirror\n') + else: + tabWrite('\n') if material: #POV-Ray 3.7 now uses two diffuse values respectively for front and back shading (the back diffuse is like blender translucency) - frontDiffuse=material.diffuse_intensity - backDiffuse=material.translucency - - + frontDiffuse = material.diffuse_intensity + backDiffuse = material.translucency + if material.pov_conserve_energy: #Total should not go above one if (frontDiffuse + backDiffuse) <= 1.0: pass - elif frontDiffuse==backDiffuse: - frontDiffuse = backDiffuse = 0.5 # Try to respect the user's 'intention' by comparing the two values but bringing the total back to one - elif frontDiffuse>backDiffuse: # Let the highest value stay the highest value - backDiffuse = 1-(1-frontDiffuse) + elif frontDiffuse == backDiffuse: + frontDiffuse = backDiffuse = 0.5 # Try to respect the user's 'intention' by comparing the two values but bringing the total back to one + elif frontDiffuse > backDiffuse: # Let the highest value stay the highest value + backDiffuse = 1 - (1 - frontDiffuse) # XXX FIXME! else: - frontDiffuse = 1-(1-backDiffuse) - + frontDiffuse = 1 - (1 - backDiffuse) # XXX FIXME! # map hardness between 0.0 and 1.0 roughness = ((1.0 - ((material.specular_hardness - 1.0) / 510.0))) ## scale from 0.0 to 0.1 - roughness *= 0.1 + roughness *= 0.1 # add a small value because 0.0 is invalid - roughness += (1 / 511.0) + roughness += (1.0 / 511.0) #####################################Diffuse Shader###################################### # Not used for Full spec (Level=3) of the shader if material.diffuse_shader == 'OREN_NAYAR' and Level != 3: - tabWrite('brilliance %.3g\n' % (0.9+material.roughness))#blender roughness is what is generally called oren nayar Sigma, and brilliance in POV-Ray + tabWrite('brilliance %.3g\n' % (0.9 + material.roughness)) # blender roughness is what is generally called oren nayar Sigma, and brilliance in POV-Ray if material.diffuse_shader == 'TOON' and Level != 3: - tabWrite('brilliance %.3g\n' % (0.01+material.diffuse_toon_smooth*0.25)) - frontDiffuse*=0.5 #Lower diffuse and increase specular for toon effect seems to look better in POV-Ray - + tabWrite('brilliance %.3g\n' % (0.01 + material.diffuse_toon_smooth * 0.25)) + frontDiffuse *= 0.5 # Lower diffuse and increase specular for toon effect seems to look better in POV-Ray + if material.diffuse_shader == 'MINNAERT' and Level != 3: #tabWrite('aoi %.3g\n' % material.darkness) - pass #let's keep things simple for now + pass # let's keep things simple for now if material.diffuse_shader == 'FRESNEL' and Level != 3: #tabWrite('aoi %.3g\n' % material.diffuse_fresnel_factor) - pass #let's keep things simple for now + pass # let's keep things simple for now if material.diffuse_shader == 'LAMBERT' and Level != 3: - tabWrite('brilliance 1.8\n') #trying to best match lambert attenuation by that constant brilliance value + tabWrite('brilliance 1.8\n') # trying to best match lambert attenuation by that constant brilliance value - if Level == 2: + if Level == 2: ####################################Specular Shader###################################### - if material.specular_shader == 'COOKTORR' or material.specular_shader == 'PHONG':#No difference between phong and cook torrence in blender HaHa! + if material.specular_shader == 'COOKTORR' or material.specular_shader == 'PHONG': # No difference between phong and cook torrence in blender HaHa! tabWrite('phong %.3g\n' % (material.specular_intensity)) - tabWrite('phong_size %.3g\n'% (material.specular_hardness / 2 + 0.25)) + tabWrite('phong_size %.3g\n' % (material.specular_hardness / 2 + 0.25)) - if material.specular_shader == 'BLINN':#POV-Ray 'specular' keyword corresponds to a Blinn model, without the ior. - tabWrite('specular %.3g\n' % (material.specular_intensity * (material.specular_ior/4))) #Use blender Blinn's IOR just as some factor for spec intensity - tabWrite('roughness %.3g\n' % roughness) + elif material.specular_shader == 'BLINN': # POV-Ray 'specular' keyword corresponds to a Blinn model, without the ior. + tabWrite('specular %.3g\n' % (material.specular_intensity * (material.specular_ior / 4.0))) # Use blender Blinn's IOR just as some factor for spec intensity + tabWrite('roughness %.3g\n' % roughness) #Could use brilliance 2(or varying around 2 depending on ior or factor) too. - - if material.specular_shader == 'TOON': + elif material.specular_shader == 'TOON': tabWrite('phong %.3g\n' % (material.specular_intensity * 2)) - tabWrite('phong_size %.3g\n' % (0.1+material.specular_toon_smooth / 2)) #use extreme phong_size + tabWrite('phong_size %.3g\n' % (0.1 + material.specular_toon_smooth / 2)) # use extreme phong_size + elif material.specular_shader == 'WARDISO': + tabWrite("specular %.3g\n" % (material.specular_intensity / (material.specular_slope + 0.0005))) # find best suited default constant for brilliance Use both phong and specular for some values. + tabWrite("roughness %.4g\n" % (0.0005 + material.specular_slope / 10.0)) # find best suited default constant for brilliance Use both phong and specular for some values. + tabWrite("brilliance %.4g\n" % (1.8 - material.specular_slope * 1.8)) # find best suited default constant for brilliance Use both phong and specular for some values. - if material.specular_shader == 'WARDISO': - tabWrite('specular %.3g\n' % (material.specular_intensity / (material.specular_slope+0.0005))) #find best suited default constant for brilliance Use both phong and specular for some values. - tabWrite('roughness %.4g\n' % (0.0005+material.specular_slope/10)) #find best suited default constant for brilliance Use both phong and specular for some values. - tabWrite('brilliance %.4g\n' % (1.8-material.specular_slope*1.8)) #find best suited default constant for brilliance Use both phong and specular for some values. - - - - ######################################################################################### + ######################################################################################### elif Level == 1: tabWrite('specular 0\n') elif Level == 3: tabWrite('specular 1\n') tabWrite('diffuse %.3g %.3g\n' % (frontDiffuse, backDiffuse)) - tabWrite('ambient %.3g\n' % material.ambient) #tabWrite('ambient rgb <%.3g, %.3g, %.3g>\n' % tuple([c*material.ambient for c in world.ambient_color])) # POV-Ray blends the global value - tabWrite('emission %.3g\n' % material.emit) #New in POV-Ray 3.7 - + tabWrite('emission %.3g\n' % material.emit) # New in POV-Ray 3.7 + #tabWrite('roughness %.3g\n' % roughness) #POV-Ray just ignores roughness if there's no specular keyword - + if material.pov_conserve_energy: - tabWrite('conserve_energy\n')#added for more realistic shading. Needs some checking to see if it really works. --Maurice. + tabWrite('conserve_energy\n') # added for more realistic shading. Needs some checking to see if it really works. --Maurice. # 'phong 70.0 ' if Level != 1: @@ -394,13 +429,21 @@ def write_pov(filename, scene=None, info_callback=None): tabWrite('rgb <%.3g, %.3g, %.3g>' % material.mirror_color[:]) if material.pov_mirror_metallic: tabWrite('metallic %.3g' % (raytrace_mirror.reflect_factor)) - if material.pov_mirror_use_IOR: #WORKING ? - tabWrite('fresnel 1 ')#Removed from the line below: gives a more physically correct material but needs proper IOR. --Maurice + if material.pov_mirror_use_IOR: # WORKING ? + tabWrite('fresnel 1 ') # Removed from the line below: gives a more physically correct material but needs proper IOR. --Maurice tabWrite('falloff %.3g exponent %.3g} ' % (raytrace_mirror.fresnel, raytrace_mirror.fresnel_factor)) if material.subsurface_scattering.use: subsurface_scattering = material.subsurface_scattering - tabWrite('subsurface { <%.3g, %.3g, %.3g>, <%.3g, %.3g, %.3g> }\n' % (sqrt(subsurface_scattering.radius[0])*1.5, sqrt(subsurface_scattering.radius[1])*1.5, sqrt(subsurface_scattering.radius[2])*1.5, 1-subsurface_scattering.color[0], 1-subsurface_scattering.color[1], 1-subsurface_scattering.color[2])) + tabWrite('subsurface { <%.3g, %.3g, %.3g>, <%.3g, %.3g, %.3g> }\n' % ( + sqrt(subsurface_scattering.radius[0]) * 1.5, + sqrt(subsurface_scattering.radius[1]) * 1.5, + sqrt(subsurface_scattering.radius[2]) * 1.5, + 1.0 - subsurface_scattering.color[0], + 1.0 - subsurface_scattering.color[1], + 1.0 - subsurface_scattering.color[2], + ) + ) if material.pov_irid_enable: tabWrite('irid { %.4g thickness %.4g turbulence %.4g }' % (material.pov_irid_amount, material.pov_irid_thickness, material.pov_irid_turbulence)) @@ -408,9 +451,8 @@ def write_pov(filename, scene=None, info_callback=None): else: tabWrite('diffuse 0.8\n') tabWrite('phong 70.0\n') - - #tabWrite('specular 0.2\n') + #tabWrite('specular 0.2\n') # This is written into the object ''' @@ -429,26 +471,25 @@ def write_pov(filename, scene=None, info_callback=None): # Level=2 Means translation of spec and mir levels for when no map influences them povHasnoSpecularMaps(Level=2) - if material: + if material: special_texture_found = False for t in material.texture_slots: - if t and t.texture.type == 'IMAGE' and t.use and t.texture.image and (t.use_map_specular or t.use_map_raymir or t.use_map_normal or t.use_map_alpha): + if t and t.texture.type == 'IMAGE' and t.use and t.texture.image and (t.use_map_specular or t.use_map_raymir or t.use_map_normal or t.use_map_alpha): special_texture_found = True - continue # Some texture found - + continue # Some texture found + if special_texture_found: # Level=1 Means No specular nor Mirror reflection povHasnoSpecularMaps(Level=1) # Level=3 Means Maximum Spec and Mirror povHasnoSpecularMaps(Level=3) - def exportCamera(): camera = scene.camera - + # DH disabled for now, this isn't the correct context - active_object = None #bpy.context.active_object # does not always work MR + active_object = None # bpy.context.active_object # does not always work MR matrix = global_matrix * camera.matrix_world focal_point = camera.data.dof_distance @@ -458,8 +499,8 @@ def write_pov(filename, scene=None, info_callback=None): tabWrite('#declare camLookAt = <%.6f, %.6f, %.6f>;\n' % tuple([degrees(e) for e in matrix.rotation_part().to_euler()])) tabWrite('camera {\n') - if scene.pov_baking_enable and active_object and active_object.type=='MESH': - tabWrite('mesh_camera{ 1 3\n') # distribution 3 is what we want here + if scene.pov_baking_enable and active_object and active_object.type == 'MESH': + tabWrite('mesh_camera{ 1 3\n') # distribution 3 is what we want here tabWrite('mesh{%s}\n' % active_object.name) tabWrite('}\n') tabWrite('location <0,0,.01>') @@ -475,7 +516,7 @@ def write_pov(filename, scene=None, info_callback=None): tabWrite('rotate <%.6f, %.6f, %.6f>\n' % tuple([degrees(e) for e in matrix.rotation_part().to_euler()])) tabWrite('translate <%.6f, %.6f, %.6f>\n' % (matrix[3][0], matrix[3][1], matrix[3][2])) if focal_point != 0: - tabWrite('aperture 0.25\n') # fixed blur amount for now to do, add slider a button? + tabWrite('aperture 0.25\n') # fixed blur amount for now to do, add slider a button? tabWrite('blur_samples 96 128\n') tabWrite('variance 1/10000\n') tabWrite('focal_point <0, 0, %f>\n' % focal_point) @@ -488,32 +529,32 @@ def write_pov(filename, scene=None, info_callback=None): matrix = global_matrix * ob.matrix_world - color = tuple([c * lamp.energy *2 for c in lamp.color]) # Colour is modified by energy #muiltiplie by 2 for a better match --Maurice + color = tuple([c * lamp.energy * 2.0 for c in lamp.color]) # Colour is modified by energy #muiltiplie by 2 for a better match --Maurice tabWrite('light_source {\n') tabWrite('< 0,0,0 >\n') tabWrite('color rgb<%.3g, %.3g, %.3g>\n' % color) - if lamp.type == 'POINT': # Point Lamp + if lamp.type == 'POINT': pass - elif lamp.type == 'SPOT': # Spot + elif lamp.type == 'SPOT': tabWrite('spotlight\n') # Falloff is the main radius from the centre line - tabWrite('falloff %.2f\n' % (degrees(lamp.spot_size) / 2.0)) # 1 TO 179 FOR BOTH + tabWrite('falloff %.2f\n' % (degrees(lamp.spot_size) / 2.0)) # 1 TO 179 FOR BOTH tabWrite('radius %.6f\n' % ((degrees(lamp.spot_size) / 2.0) * (1.0 - lamp.spot_blend))) # Blender does not have a tightness equivilent, 0 is most like blender default. - tabWrite('tightness 0\n') # 0:10f + tabWrite('tightness 0\n') # 0:10f tabWrite('point_at <0, 0, -1>\n') elif lamp.type == 'SUN': tabWrite('parallel\n') - tabWrite('point_at <0, 0, -1>\n') # *must* be after 'parallel' + tabWrite('point_at <0, 0, -1>\n') # *must* be after 'parallel' elif lamp.type == 'AREA': - tabWrite('fade_distance %.6f\n' % (lamp.distance / 5) ) - tabWrite('fade_power %d\n' % 2) # Area lights have no falloff type, so always use blenders lamp quad equivalent for those? + tabWrite('fade_distance %.6f\n' % (lamp.distance / 5.0)) + tabWrite('fade_power %d\n' % 2) # Area lights have no falloff type, so always use blenders lamp quad equivalent for those? size_x = lamp.size samples_x = lamp.shadow_ray_samples_x if lamp.shape == 'SQUARE': @@ -531,20 +572,20 @@ def write_pov(filename, scene=None, info_callback=None): tabWrite('adaptive 1\n') tabWrite('jitter\n') - if lamp.type == 'HEMI':#HEMI never has any shadow attribute + if lamp.type == 'HEMI': # HEMI never has any shadow attribute tabWrite('shadowless\n') elif lamp.shadow_method == 'NOSHADOW': tabWrite('shadowless\n') - if lamp.type != 'SUN' and lamp.type!='AREA' and lamp.type!='HEMI':#Sun shouldn't be attenuated. Hemi and area lights have no falloff attribute so they are put to type 2 attenuation a little higher above. - tabWrite('fade_distance %.6f\n' % (lamp.distance / 5) ) + if lamp.type not in ('SUN', 'AREA', 'HEMI'): # Sun shouldn't be attenuated. Hemi and area lights have no falloff attribute so they are put to type 2 attenuation a little higher above. + tabWrite("fade_distance %.6f\n" % (lamp.distance / 5.0)) if lamp.falloff_type == 'INVERSE_SQUARE': - tabWrite('fade_power %d\n' % 2) # Use blenders lamp quad equivalent + tabWrite('fade_power %d\n' % 2) # Use blenders lamp quad equivalent elif lamp.falloff_type == 'INVERSE_LINEAR': - tabWrite('fade_power %d\n' % 1) # Use blenders lamp linear - elif lamp.falloff_type == 'CONSTANT': #Supposing using no fade power keyword would default to constant, no attenuation. + tabWrite('fade_power %d\n' % 1) # Use blenders lamp linear + elif lamp.falloff_type == 'CONSTANT': # upposing using no fade power keyword would default to constant, no attenuation. pass - elif lamp.falloff_type == 'CUSTOM_CURVE': #Using Custom curve for fade power 3 for now. + elif lamp.falloff_type == 'CUSTOM_CURVE': # Using Custom curve for fade power 3 for now. tabWrite('fade_power %d\n' % 4) writeMatrix(matrix) @@ -579,19 +620,20 @@ def write_pov(filename, scene=None, info_callback=None): ## averageLampLocation[0]=lampLocation[0] / len(lamps)#create an average position for all lamps. ## averageLampLocation[1]=lampLocation[1] / len(lamps)#create an average position for all lamps. ## averageLampLocation[2]=lampLocation[2] / len(lamps)#create an average position for all lamps. -## +## ## averageLampDistance=lampDistance / len(lamps)#create an average distance for all lamps. ## file.write('\n#declare lampTarget= vrotate(<%.4g,%.4g,%.4g>,<%.4g,%.4g,%.4g>);' % (-(averageLampLocation[0]-averageLampDistance), -(averageLampLocation[1]-averageLampDistance), -(averageLampLocation[2]-averageLampDistance), averageLampRotation[0], averageLampRotation[1], averageLampRotation[2])) -## #v(A,B) rotates vector A about origin by vector B. +## #v(A,B) rotates vector A about origin by vector B. ## #################################################################################################################################### def exportMeta(metas): # TODO - blenders 'motherball' naming is not supported. - - if scene.pov_comments_enable and len(metas)>= 1: file.write('//--Blob objects--\n\n') - + + if scene.pov_comments_enable and len(metas) >= 1: + file.write('//--Blob objects--\n\n') + for ob in metas: meta = ob.data @@ -604,7 +646,7 @@ def write_pov(filename, scene=None, info_callback=None): importance = ob.pov_importance_value try: - material = meta.materials[0] # lame! - blender cant do enything else. + material = meta.materials[0] # lame! - blender cant do enything else. except: material = None @@ -638,9 +680,8 @@ def write_pov(filename, scene=None, info_callback=None): material_finish = materialNames[material.name] - tabWrite('pigment {rgbft<%.3g, %.3g, %.3g, %.3g, %.3g>} \n' %(diffuse_color[0], diffuse_color[1], diffuse_color[2], 1.0 - material.alpha, trans, )) + tabWrite('pigment {rgbft<%.3g, %.3g, %.3g, %.3g, %.3g>} \n' % (diffuse_color[0], diffuse_color[1], diffuse_color[2], 1.0 - material.alpha, trans)) tabWrite('finish {%s}\n' % safety(material_finish, Level=2)) - else: tabWrite('pigment {rgb<1 1 1>} \n') @@ -649,17 +690,19 @@ def write_pov(filename, scene=None, info_callback=None): writeObjectMaterial(material) writeMatrix(global_matrix * ob.matrix_world) - #Importance for radiosity sampling added here: + #Importance for radiosity sampling added here: tabWrite('radiosity { \n') tabWrite('importance %3g \n' % importance) tabWrite('}\n') - - tabWrite('}\n') #End of Metaball block - if scene.pov_comments_enable and len(metas)>= 1: file.write('\n') + tabWrite('}\n') # End of Metaball block + + if scene.pov_comments_enable and len(metas) >= 1: + file.write('\n') objectNames = {} DEF_OBJ_NAME = 'Default' + def exportMeshs(scene, sel): ob_num = 0 @@ -683,7 +726,7 @@ def write_pov(filename, scene=None, info_callback=None): # happens when curves cant be made into meshes because of no-data continue - importance = ob.pov_importance_value + importance = ob.pov_importance_value me_materials = me.materials me_faces = me.faces[:] @@ -717,45 +760,43 @@ def write_pov(filename, scene=None, info_callback=None): # Use named declaration to allow reference e.g. for baking. MR file.write('\n') - tabWrite('#declare %s =\n' % name) + tabWrite('#declare %s =\n' % name) tabWrite('mesh2 {\n') tabWrite('vertex_vectors {\n') - tabWrite('%s' % (len(me.vertices))) # vert count - + tabWrite('%s' % (len(me.vertices))) # vert count + for v in me.vertices: file.write(',\n') - tabWrite('<%.6f, %.6f, %.6f>' % v.co[:]) # vert count + tabWrite('<%.6f, %.6f, %.6f>' % v.co[:]) # vert count file.write('\n') tabWrite('}\n') - # Build unique Normal list uniqueNormals = {} for fi, f in enumerate(me_faces): fv = faces_verts[fi] # [-1] is a dummy index, use a list so we can modify in place - if f.use_smooth: # Use vertex normals + if f.use_smooth: # Use vertex normals for v in fv: key = verts_normals[v] uniqueNormals[key] = [-1] - else: # Use face normal + else: # Use face normal key = faces_normals[fi] uniqueNormals[key] = [-1] tabWrite('normal_vectors {\n') - tabWrite('%d' % len(uniqueNormals)) # vert count + tabWrite('%d' % len(uniqueNormals)) # vert count idx = 0 for no, index in uniqueNormals.items(): file.write(',\n') - tabWrite('<%.6f, %.6f, %.6f>' % no) # vert count + tabWrite('<%.6f, %.6f, %.6f>' % no) # vert count index[0] = idx idx += 1 file.write('\n') tabWrite('}\n') - # Vertex colours - vertCols = {} # Use for material colours also. + vertCols = {} # Use for material colours also. if uv_layer: # Generate unique UV's @@ -773,7 +814,7 @@ def write_pov(filename, scene=None, info_callback=None): tabWrite('uv_vectors {\n') #print unique_uvs - tabWrite('%s' % (len(uniqueUVs))) # vert count + tabWrite('%s' % (len(uniqueUVs))) # vert count idx = 0 for uv, index in uniqueUVs.items(): file.write(',\n') @@ -789,7 +830,6 @@ def write_pov(filename, scene=None, info_callback=None): file.write('\n') tabWrite('}\n') - if me.vertex_colors: for fi, f in enumerate(me_faces): @@ -806,7 +846,7 @@ def write_pov(filename, scene=None, info_callback=None): cols = col.color1, col.color2, col.color3 for col in cols: - key = col[0], col[1], col[2], material_index # Material index! + key = col[0], col[1], col[2], material_index # Material index! vertCols[key] = [-1] else: @@ -815,22 +855,20 @@ def write_pov(filename, scene=None, info_callback=None): key = diffuse_color[0], diffuse_color[1], diffuse_color[2], material_index vertCols[key] = [-1] - else: # No vertex colours, so write material colours as vertex colours for i, material in enumerate(me_materials): if material: diffuse_color = material.diffuse_color[:] - key = diffuse_color[0], diffuse_color[1], diffuse_color[2], i # i == f.mat + key = diffuse_color[0], diffuse_color[1], diffuse_color[2], i # i == f.mat vertCols[key] = [-1] - # Vert Colours tabWrite('texture_list {\n') - tabWrite('%s' % (len(vertCols))) # vert count + tabWrite('%s' % (len(vertCols))) # vert count idx = 0 - + for col, index in vertCols.items(): if me_materials: material = me_materials[col[3]] @@ -842,61 +880,57 @@ def write_pov(filename, scene=None, info_callback=None): trans = 0.0 else: - material_finish = DEF_MAT_NAME # not working properly, + material_finish = DEF_MAT_NAME # not working properly, trans = 0.0 ##############SF - texturesDif='' - texturesSpec='' - texturesNorm='' - texturesAlpha='' + texturesDif = "" + texturesSpec = "" + texturesNorm = "" + texturesAlpha = "" for t in material.texture_slots: - if t and t.texture.type == 'IMAGE' and t.use and t.texture.image: + if t and t.texture.type == 'IMAGE' and t.use and t.texture.image: image_filename = path_image(t.texture.image.filepath) imgGamma = '' if image_filename: - if t.use_map_color_diffuse: + if t.use_map_color_diffuse: texturesDif = image_filename colvalue = t.default_value t_dif = t if t_dif.texture.pov_tex_gamma_enable: imgGamma = (' gamma %.3g ' % t_dif.texture.pov_tex_gamma_value) - if t.use_map_specular or t.use_map_raymir: + if t.use_map_specular or t.use_map_raymir: texturesSpec = image_filename colvalue = t.default_value t_spec = t - if t.use_map_normal: + if t.use_map_normal: texturesNorm = image_filename colvalue = t.normal_factor * 10.0 #textNormName=t.texture.image.name + '.normal' #was the above used? --MR t_nor = t - if t.use_map_alpha: + if t.use_map_alpha: texturesAlpha = image_filename colvalue = t.alpha_factor * 10.0 #textDispName=t.texture.image.name + '.displ' #was the above used? --MR t_alpha = t - - - ############################################################################################################## tabWrite('\n') - tabWrite('texture {\n') #THIS AREA NEEDS TO LEAVE THE TEXTURE OPEN UNTIL ALL MAPS ARE WRITTEN DOWN. --MR - + tabWrite('texture {\n') # THIS AREA NEEDS TO LEAVE THE TEXTURE OPEN UNTIL ALL MAPS ARE WRITTEN DOWN. --MR ############################################################################################################## if material.diffuse_shader == 'MINNAERT': tabWrite('\n') tabWrite('aoi\n') tabWrite('texture_map {\n') - tabWrite('[%.3g finish {diffuse %.3g}]\n' % ((material.darkness/2), (2-material.darkness))) - tabWrite('[%.3g' % (1-(material.darkness/2))) + tabWrite('[%.3g finish {diffuse %.3g}]\n' % (material.darkness / 2.0, 2.0 - material.darkness)) + tabWrite("[%.3g" % (1.0 - (material.darkness / 2.0))) ######TO OPTIMIZE? or present a more elegant way? At least make it work!################################################################## #If Fresnel gets removed from 2.5, why bother? if material.diffuse_shader == 'FRESNEL': - + ######END of part TO OPTIMIZE? or present a more elegant way?################################################################## ## #lampLocation=lamp.position @@ -912,52 +946,49 @@ def write_pov(filename, scene=None, info_callback=None): ## degrees(atan((lampLocation - lampLookAt).y/(lampLocation.z))=lamp.rotation[0] ## degrees(atan((lampLocation.z/(lampLocation - lampLookAt).x))=lamp.rotation[1] ## degrees(atan((lampLocation - lampLookAt).x/(lampLocation - lampLookAt).y))=lamp.rotation[2] - - #color = tuple([c * lamp.energy for c in lamp.color]) # Colour is modified by energy - + #color = tuple([c * lamp.energy for c in lamp.color]) # Colour is modified by energy + tabWrite('\n') tabWrite('slope { lampTarget }\n') tabWrite('texture_map {\n') - tabWrite('[%.3g finish {diffuse %.3g}]\n' % ((material.diffuse_fresnel/2), (2-material.diffuse_fresnel_factor))) - tabWrite('[%.3g\n' % (1-(material.diffuse_fresnel/2))) - - + tabWrite('[%.3g finish {diffuse %.3g}]\n' % (material.diffuse_fresnel / 2, 2.0 - material.diffuse_fresnel_factor)) + tabWrite("[%.3g\n" % (1 - (material.diffuse_fresnel / 2.0))) + #if material.diffuse_shader == 'FRESNEL': pigment pattern aoi pigment and texture map above, the rest below as one of its entry - ########################################################################################################################## + ########################################################################################################################## #special_texture_found = False #for t in material.texture_slots: - # if t and t.texture.type == 'IMAGE' and t.use and t.texture.image and (t.use_map_specular or t.use_map_raymir or t.use_map_normal or t.use_map_alpha): + # if t and t.texture.type == 'IMAGE' and t.use and t.texture.image and (t.use_map_specular or t.use_map_raymir or t.use_map_normal or t.use_map_alpha): # special_texture_found = True # continue # Some texture found - #if special_texture_found: - if texturesSpec !='' or texturesAlpha !='' or texturesNorm !='': - if texturesSpec !='': + if texturesSpec != "" or texturesAlpha != "" or texturesNorm != "": + if texturesSpec != "": # tabWrite('\n') tabWrite('pigment_pattern {\n') # POV-Ray "scale" is not a number of repetitions factor, but its inverse, a standard scale factor. # Offset seems needed relatively to scale so probably center of the scale is not the same in blender and POV - mappingSpec = ('translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>\n' % (-t_spec.offset.x ,t_spec.offset.y ,t_spec.offset.z, 1 / t_spec.scale.x, 1 / t_spec.scale.y, 1 / t_spec.scale.z)) - tabWrite('uv_mapping image_map{%s \"%s\" %s}\n' % (imageFormat(texturesSpec) ,texturesSpec ,imgMap(t_spec))) + mappingSpec = "translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>\n" % (-t_spec.offset.x, t_spec.offset.y, t_spec.offset.z, 1.0 / t_spec.scale.x, 1.0 / t_spec.scale.y, 1.0 / t_spec.scale.z) + tabWrite("uv_mapping image_map{%s \"%s\" %s}\n" % (imageFormat(texturesSpec), texturesSpec, imgMap(t_spec))) tabWrite('%s\n' % mappingSpec) tabWrite('}\n') tabWrite('texture_map {\n') tabWrite('[0 \n') if texturesDif == '': - if texturesAlpha !='': + if texturesAlpha != "": tabWrite('\n') # POV-Ray "scale" is not a number of repetitions factor, but its inverse, a standard scale factor. # Offset seems needed relatively to scale so probably center of the scale is not the same in blender and POV - mappingAlpha = (' translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>\n' % (-t_alpha.offset.x,t_alpha.offset.y,t_alpha.offset.z, 1 / t_alpha.scale.x, 1 / t_alpha.scale.y, 1 / t_alpha.scale.z)) - tabWrite('pigment {pigment_pattern {uv_mapping image_map{%s \"%s\" %s}%s' % (imageFormat(texturesAlpha) ,texturesAlpha ,imgMap(t_alpha),mappingAlpha)) + mappingAlpha = " translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>\n" % (-t_alpha.offset.x, t_alpha.offset.y, t_alpha.offset.z, 1.0 / t_alpha.scale.x, 1.0 / t_alpha.scale.y, 1.0 / t_alpha.scale.z) + tabWrite('pigment {pigment_pattern {uv_mapping image_map{%s \"%s\" %s}%s' % (imageFormat(texturesAlpha), texturesAlpha, imgMap(t_alpha), mappingAlpha)) tabWrite('}\n') tabWrite('pigment_map {\n') tabWrite('[0 color rgbft<0,0,0,1,1>]\n') - tabWrite('[1 color rgbft<%.3g, %.3g, %.3g, %.3g, %.3g>]\n' % (col[0], col[1], col[2], 1.0 - material.alpha, trans) ) + tabWrite('[1 color rgbft<%.3g, %.3g, %.3g, %.3g, %.3g>]\n' % (col[0], col[1], col[2], 1.0 - material.alpha, trans)) tabWrite('}\n') tabWrite('}\n') @@ -965,61 +996,61 @@ def write_pov(filename, scene=None, info_callback=None): tabWrite('pigment {rgbft<%.3g, %.3g, %.3g, %.3g, %.3g>}\n' % (col[0], col[1], col[2], 1.0 - material.alpha, trans)) - if texturesSpec !='': - tabWrite('finish {%s}\n' % (safety(material_finish, Level=1)))# Level 1 is no specular - + if texturesSpec != "": + tabWrite('finish {%s}\n' % (safety(material_finish, Level=1))) # Level 1 is no specular + else: - tabWrite('finish {%s}\n' % (safety(material_finish, Level=2)))# Level 2 is translated spec + tabWrite('finish {%s}\n' % (safety(material_finish, Level=2))) # Level 2 is translated spec else: # POV-Ray "scale" is not a number of repetitions factor, but its inverse, a standard scale factor. # Offset seems needed relatively to scale so probably center of the scale is not the same in blender and POV - mappingDif = ('translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>' % (-t_dif.offset.x,t_dif.offset.y,t_dif.offset.z, 1 / t_dif.scale.x, 1 / t_dif.scale.y, 1 / t_dif.scale.z)) - if texturesAlpha !='': + mappingDif = ('translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>' % (-t_dif.offset.x, t_dif.offset.y, t_dif.offset.z, 1.0 / t_dif.scale.x, 1.0 / t_dif.scale.y, 1.0 / t_dif.scale.z)) + if texturesAlpha != "": # POV-Ray "scale" is not a number of repetitions factor, but its inverse, a standard scale factor. # Offset seems needed relatively to scale so probably center of the scale is not the same in blender and POV - mappingAlpha = (' translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>' % (t_alpha.offset.x,t_alpha.offset.y,t_alpha.offset.z,1 / t_alpha.scale.x, 1 / t_alpha.scale.y, 1 / t_alpha.scale.z)) + mappingAlpha = " translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>" % (t_alpha.offset.x, t_alpha.offset.y, t_alpha.offset.z, 1.0 / t_alpha.scale.x, 1.0 / t_alpha.scale.y, 1.0 / t_alpha.scale.z) tabWrite('pigment {\n') tabWrite('pigment_pattern {\n') - tabWrite('uv_mapping image_map{%s \"%s\" %s}%s}\n' % (imageFormat(texturesAlpha),texturesAlpha,imgMap(t_alpha),mappingAlpha)) + tabWrite('uv_mapping image_map{%s \"%s\" %s}%s}\n' % (imageFormat(texturesAlpha), texturesAlpha, imgMap(t_alpha), mappingAlpha)) tabWrite('pigment_map {\n') tabWrite('[0 color rgbft<0,0,0,1,1>]\n') - tabWrite('[1 uv_mapping image_map {%s \"%s\" %s} %s]\n' % (imageFormat(texturesDif),texturesDif,(imgGamma + imgMap(t_dif)),mappingDif)) - tabWrite('}\n' ) - tabWrite('}\n') + tabWrite('[1 uv_mapping image_map {%s \"%s\" %s} %s]\n' % (imageFormat(texturesDif), texturesDif, (imgGamma + imgMap(t_dif)), mappingDif)) + tabWrite("}\n") + tabWrite("}\n") else: - tabWrite('pigment {uv_mapping image_map {%s \"%s\" %s}%s}\n' % (imageFormat(texturesDif),texturesDif,(imgGamma + imgMap(t_dif)),mappingDif)) + tabWrite('pigment {uv_mapping image_map {%s \"%s\" %s}%s}\n' % (imageFormat(texturesDif), texturesDif, (imgGamma + imgMap(t_dif)), mappingDif)) + + if texturesSpec != "": + tabWrite('finish {%s}\n' % (safety(material_finish, Level=1))) # Level 1 is no specular - if texturesSpec !='': - tabWrite('finish {%s}\n' % (safety(material_finish, Level=1)))# Level 1 is no specular - else: - tabWrite('finish {%s}\n' % (safety(material_finish, Level=2)))# Level 2 is translated specular + tabWrite('finish {%s}\n' % (safety(material_finish, Level=2))) # Level 2 is translated specular ## scale 1 rotate y*0 #imageMap = ('{image_map {%s \"%s\" %s }\n' % (imageFormat(textures),textures,imgMap(t_dif))) #tabWrite('uv_mapping pigment %s} %s finish {%s}\n' % (imageMap,mapping,safety(material_finish))) #tabWrite('pigment {uv_mapping image_map {%s \"%s\" %s}%s} finish {%s}\n' % (imageFormat(texturesDif),texturesDif,imgMap(t_dif),mappingDif,safety(material_finish))) - if texturesNorm !='': + if texturesNorm != "": ## scale 1 rotate y*0 # POV-Ray "scale" is not a number of repetitions factor, but its inverse, a standard scale factor. # Offset seems needed relatively to scale so probably center of the scale is not the same in blender and POV - mappingNor = (' translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>' % (-t_nor.offset.x,t_nor.offset.y,t_nor.offset.z, 1 / t_nor.scale.x, 1 / t_nor.scale.y, 1 / t_nor.scale.z)) + mappingNor = " translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>" % (-t_nor.offset.x, t_nor.offset.y, t_nor.offset.z, 1.0 / t_nor.scale.x, 1.0 / t_nor.scale.y, 1.0 / t_nor.scale.z) #imageMapNor = ('{bump_map {%s \"%s\" %s mapping}' % (imageFormat(texturesNorm),texturesNorm,imgMap(t_nor))) #We were not using the above maybe we should? - tabWrite('normal {uv_mapping bump_map {%s \"%s\" %s bump_size %.4g }%s}\n' % (imageFormat(texturesNorm),texturesNorm,imgMap(t_nor),(t_nor.normal_factor * 10),mappingNor)) - if texturesSpec !='': + tabWrite('normal {uv_mapping bump_map {%s \"%s\" %s bump_size %.4g }%s}\n' % (imageFormat(texturesNorm), texturesNorm, imgMap(t_nor), t_nor.normal_factor * 10, mappingNor)) + if texturesSpec != "": tabWrite(']\n') ################################Second index for mapping specular max value################################################################################################## tabWrite('[1 \n') if texturesDif == '': - if texturesAlpha !='': + if texturesAlpha != "": # POV-Ray "scale" is not a number of repetitions factor, but its inverse, a standard scale factor. # Offset seems needed relatively to scale so probably center of the scale is not the same in blender and POV - mappingAlpha = (' translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>\n' % (-t_alpha.offset.x,t_alpha.offset.y,t_alpha.offset.z, 1 / t_alpha.scale.x, 1 / t_alpha.scale.y, 1 / t_alpha.scale.z)) #strange that the translation factor for scale is not the same as for translate. ToDo: verify both matches with blender internal. - tabWrite('pigment {pigment_pattern {uv_mapping image_map{%s \"%s\" %s}%s}\n' % (imageFormat(texturesAlpha) ,texturesAlpha ,imgMap(t_alpha),mappingAlpha)) + mappingAlpha = " translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>\n" % (-t_alpha.offset.x, t_alpha.offset.y, t_alpha.offset.z, 1.0 / t_alpha.scale.x, 1.0 / t_alpha.scale.y, 1.0 / t_alpha.scale.z) # strange that the translation factor for scale is not the same as for translate. ToDo: verify both matches with blender internal. + tabWrite('pigment {pigment_pattern {uv_mapping image_map{%s \"%s\" %s}%s}\n' % (imageFormat(texturesAlpha), texturesAlpha, imgMap(t_alpha), mappingAlpha)) tabWrite('pigment_map {\n') tabWrite('[0 color rgbft<0,0,0,1,1>]\n') tabWrite('[1 color rgbft<%.3g, %.3g, %.3g, %.3g, %.3g>]\n' % (col[0], col[1], col[2], 1.0 - material.alpha, trans)) @@ -1029,22 +1060,22 @@ def write_pov(filename, scene=None, info_callback=None): else: tabWrite('pigment {rgbft<%.3g, %.3g, %.3g, %.3g, %.3g>}\n' % (col[0], col[1], col[2], 1.0 - material.alpha, trans)) - if texturesSpec !='': - tabWrite('finish {%s}\n' % (safety(material_finish, Level=3)))# Level 3 is full specular - + if texturesSpec != "": + tabWrite('finish {%s}\n' % (safety(material_finish, Level=3))) # Level 3 is full specular + else: - tabWrite('finish {%s}\n' % (safety(material_finish, Level=2)))# Level 2 is translated specular + tabWrite('finish {%s}\n' % (safety(material_finish, Level=2))) # Level 2 is translated specular else: # POV-Ray "scale" is not a number of repetitions factor, but its inverse, a standard scale factor. # Offset seems needed relatively to scale so probably center of the scale is not the same in blender and POV - mappingDif = ('translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>' % (-t_dif.offset.x,t_dif.offset.y,t_dif.offset.z, 1 / t_dif.scale.x, 1 / t_dif.scale.y, 1 / t_dif.scale.z)) #strange that the translation factor for scale is not the same as for translate. ToDo: verify both matches with blender internal. - if texturesAlpha !='': - mappingAlpha = ('translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>' % (-t_alpha.offset.x,t_alpha.offset.y,t_alpha.offset.z, 1 / t_alpha.scale.x, 1 / t_alpha.scale.y, 1 / t_alpha.scale.z)) #strange that the translation factor for scale is not the same as for translate. ToDo: verify both matches with blender internal. - tabWrite('pigment {pigment_pattern {uv_mapping image_map{%s \"%s\" %s}%s}\n' % (imageFormat(texturesAlpha),texturesAlpha,imgMap(t_alpha),mappingAlpha)) + mappingDif = ('translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>' % (-t_dif.offset.x, t_dif.offset.y, t_dif.offset.z, 1.0 / t_dif.scale.x, 1.0 / t_dif.scale.y, 1.0 / t_dif.scale.z)) # strange that the translation factor for scale is not the same as for translate. ToDo: verify both matches with blender internal. + if texturesAlpha != "": + mappingAlpha = "translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>" % (-t_alpha.offset.x, t_alpha.offset.y, t_alpha.offset.z, 1.0 / t_alpha.scale.x, 1.0 / t_alpha.scale.y, 1.0 / t_alpha.scale.z) # strange that the translation factor for scale is not the same as for translate. ToDo: verify both matches with blender internal. + tabWrite('pigment {pigment_pattern {uv_mapping image_map{%s \"%s\" %s}%s}\n' % (imageFormat(texturesAlpha), texturesAlpha, imgMap(t_alpha), mappingAlpha)) tabWrite('pigment_map {\n') tabWrite('[0 color rgbft<0,0,0,1,1>]\n') - tabWrite('[1 uv_mapping image_map {%s \"%s\" %s} %s]\n' % (imageFormat(texturesDif),texturesDif,(imgMap(t_dif)+imgGamma),mappingDif)) + tabWrite('[1 uv_mapping image_map {%s \"%s\" %s} %s]\n' % (imageFormat(texturesDif), texturesDif, (imgMap(t_dif) + imgGamma), mappingDif)) tabWrite('}\n') tabWrite('}\n') @@ -1052,42 +1083,40 @@ def write_pov(filename, scene=None, info_callback=None): tabWrite('pigment {\n') tabWrite('uv_mapping image_map {\n') #tabWrite('%s \"%s\" %s}%s\n' % (imageFormat(texturesDif),texturesDif,(imgGamma + imgMap(t_dif)),mappingDif)) - tabWrite('%s \"%s\" \n'%(imageFormat(texturesDif),texturesDif)) - tabWrite('%s\n' % (imgGamma + imgMap(t_dif))) + tabWrite("%s \"%s\" \n" % (imageFormat(texturesDif), texturesDif)) + tabWrite("%s\n" % (imgGamma + imgMap(t_dif))) tabWrite('}\n') tabWrite('%s\n' % mappingDif) tabWrite('}\n') - if texturesSpec !='': - tabWrite('finish {%s}\n' % (safety(material_finish, Level=3)))# Level 3 is full specular + if texturesSpec != "": + tabWrite('finish {%s}\n' % (safety(material_finish, Level=3))) # Level 3 is full specular else: - tabWrite('finish {%s}\n' % (safety(material_finish, Level=2)))# Level 2 is translated specular + tabWrite('finish {%s}\n' % (safety(material_finish, Level=2))) # Level 2 is translated specular ## scale 1 rotate y*0 #imageMap = ('{image_map {%s \"%s\" %s }' % (imageFormat(textures),textures,imgMap(t_dif))) #file.write('\n\t\t\tuv_mapping pigment %s} %s finish {%s}' % (imageMap,mapping,safety(material_finish))) #file.write('\n\t\t\tpigment {uv_mapping image_map {%s \"%s\" %s}%s} finish {%s}' % (imageFormat(texturesDif),texturesDif,imgMap(t_dif),mappingDif,safety(material_finish))) - if texturesNorm !='': + if texturesNorm != "": ## scale 1 rotate y*0 # POV-Ray "scale" is not a number of repetitions factor, but its inverse, a standard scale factor. # Offset seems needed relatively to scale so probably center of the scale is not the same in blender and POV - mappingNor = (' translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>' % (-t_nor.offset.x,t_nor.offset.y,t_nor.offset.z, 1 / t_nor.scale.x, 1 / t_nor.scale.y, 1 / t_nor.scale.z)) + mappingNor = (' translate <%.4g,%.4g,%.4g> scale <%.4g,%.4g,%.4g>' % (-t_nor.offset.x, t_nor.offset.y, t_nor.offset.z, 1.0 / t_nor.scale.x, 1.0 / t_nor.scale.y, 1.0 / t_nor.scale.z)) #imageMapNor = ('{bump_map {%s \"%s\" %s mapping}' % (imageFormat(texturesNorm),texturesNorm,imgMap(t_nor))) #We were not using the above maybe we should? - tabWrite('normal {uv_mapping bump_map {%s \"%s\" %s bump_size %.4g }%s}\n' % (imageFormat(texturesNorm),texturesNorm,imgMap(t_nor),(t_nor.normal_factor * 10),mappingNor)) - if texturesSpec !='': - tabWrite(']\n') + tabWrite('normal {uv_mapping bump_map {%s \"%s\" %s bump_size %.4g }%s}\n' % (imageFormat(texturesNorm), texturesNorm, imgMap(t_nor), t_nor.normal_factor * 10.0, mappingNor)) + if texturesSpec != "": + tabWrite("]\n") - tabWrite('}\n') + tabWrite("}\n") #End of slope/ior texture_map if material.diffuse_shader == 'MINNAERT' or material.diffuse_shader == 'FRESNEL': - tabWrite(']\n') - tabWrite('}\n') - tabWrite('}\n') #THEN IT CAN CLOSE IT --MR - + tabWrite("]\n") + tabWrite("}\n") + tabWrite('}\n') # THEN IT CAN CLOSE IT --MR ############################################################################################################ - index[0] = idx idx += 1 @@ -1095,7 +1124,7 @@ def write_pov(filename, scene=None, info_callback=None): # Face indices tabWrite('face_indices {\n') - tabWrite('%d' % (len(me_faces) + quadCount)) # faces count + tabWrite('%d' % (len(me_faces) + quadCount)) # faces count for fi, f in enumerate(me_faces): fv = faces_verts[fi] material_index = f.material_index @@ -1112,11 +1141,10 @@ def write_pov(filename, scene=None, info_callback=None): else: cols = col.color1, col.color2, col.color3 - - if not me_materials or me_materials[material_index] is None: # No materials + if not me_materials or me_materials[material_index] is None: # No materials for i1, i2, i3 in indices: file.write(',\n') - tabWrite('<%d,%d,%d>' % (fv[i1], fv[i2], fv[i3])) # vert count + tabWrite('<%d,%d,%d>' % (fv[i1], fv[i2], fv[i3])) # vert count else: material = me_materials[material_index] for i1, i2, i3 in indices: @@ -1136,15 +1164,14 @@ def write_pov(filename, scene=None, info_callback=None): ci1 = ci2 = ci3 = vertCols[diffuse_color[0], diffuse_color[1], diffuse_color[2], f.material_index][0] file.write(',\n') - tabWrite('<%d,%d,%d>, %d,%d,%d' % (fv[i1], fv[i2], fv[i3], ci1, ci2, ci3)) # vert count - + tabWrite('<%d,%d,%d>, %d,%d,%d' % (fv[i1], fv[i2], fv[i3], ci1, ci2, ci3)) # vert count file.write('\n') tabWrite('}\n') # normal_indices indices tabWrite('normal_indices {\n') - tabWrite('%d' % (len(me_faces) + quadCount)) # faces count + tabWrite('%d' % (len(me_faces) + quadCount)) # faces count for fi, fv in enumerate(faces_verts): if len(fv) == 4: @@ -1158,18 +1185,18 @@ def write_pov(filename, scene=None, info_callback=None): tabWrite('<%d,%d,%d>' %\ (uniqueNormals[verts_normals[fv[i1]]][0],\ uniqueNormals[verts_normals[fv[i2]]][0],\ - uniqueNormals[verts_normals[fv[i3]]][0])) # vert count + uniqueNormals[verts_normals[fv[i3]]][0])) # vert count else: idx = uniqueNormals[faces_normals[fi]][0] file.write(',\n') - tabWrite('<%d,%d,%d>' % (idx, idx, idx)) # vert count + tabWrite('<%d,%d,%d>' % (idx, idx, idx)) # vert count file.write('\n') tabWrite('}\n') if uv_layer: tabWrite('uv_indices {\n') - tabWrite('%d' % (len(me_faces) + quadCount)) # faces count + tabWrite('%d' % (len(me_faces) + quadCount)) # faces count for fi, fv in enumerate(faces_verts): if len(fv) == 4: @@ -1194,20 +1221,20 @@ def write_pov(filename, scene=None, info_callback=None): if me.materials: try: - material = me.materials[0] # dodgy + material = me.materials[0] # dodgy writeObjectMaterial(material) except IndexError: print(me) writeMatrix(matrix) - - #Importance for radiosity sampling added here: + + #Importance for radiosity sampling added here: tabWrite('radiosity { \n') tabWrite('importance %3g \n' % importance) - tabWrite('}\n') + tabWrite('}\n') - tabWrite('}\n') # End of mesh block - tabWrite('%s\n' % name) # Use named declaration to allow reference e.g. for baking. MR + tabWrite('}\n') # End of mesh block + tabWrite('%s\n' % name) # Use named declaration to allow reference e.g. for baking. MR bpy.data.meshes.remove(me) @@ -1217,13 +1244,13 @@ def write_pov(filename, scene=None, info_callback=None): matrix = global_matrix * camera.matrix_world if not world: return - #############Maurice#################################### + #############Maurice#################################### #These lines added to get sky gradient (visible with PNG output) if world: #For simple flat background: if not world.use_sky_blend: - #Non fully transparent background could premultiply alpha and avoid anti-aliasing display issue: - if render.alpha_mode == 'PREMUL' or render.alpha_mode == 'PREMUL' : + #Non fully transparent background could premultiply alpha and avoid anti-aliasing display issue: + if render.alpha_mode == 'PREMUL' or render.alpha_mode == 'PREMUL': # XXX FIXME! tabWrite('background {rgbt<%.3g, %.3g, %.3g, 0.75>}\n' % (world.horizon_color[:])) #Currently using no alpha with Sky option: elif render.alpha_mode == 'SKY': @@ -1232,51 +1259,55 @@ def write_pov(filename, scene=None, info_callback=None): else: tabWrite('background {rgbt<%.3g, %.3g, %.3g, 1>}\n' % (world.horizon_color[:])) - - worldTexCount=0 + worldTexCount = 0 #For Background image textures - for t in world.texture_slots: #risk to write several sky_spheres but maybe ok. + for t in world.texture_slots: # risk to write several sky_spheres but maybe ok. if t and t.texture.type is not None: - worldTexCount+=1 - if t and t.texture.type == 'IMAGE': #and t.use: #No enable checkbox for world textures yet (report it?) - image_filename = path_image(t.texture.image.filepath) - if t.texture.image.filepath != image_filename: t.texture.image.filepath = image_filename - if image_filename != '' and t.use_map_blend: + worldTexCount += 1 + if t and t.texture.type == 'IMAGE': # and t.use: #No enable checkbox for world textures yet (report it?) + image_filename = path_image(t.texture.image.filepath) + if t.texture.image.filepath != image_filename: + t.texture.image.filepath = image_filename + if image_filename != '' and t.use_map_blend: texturesBlend = image_filename #colvalue = t.default_value t_blend = t #commented below was an idea to make the Background image oriented as camera taken here: http://news.povray.org/povray.newusers/thread/%3Cweb.4a5cddf4e9c9822ba2f93e20@news.povray.org%3E/ #mappingBlend = (' translate <%.4g,%.4g,%.4g> rotate z*degrees(atan((camLocation - camLookAt).x/(camLocation - camLookAt).y)) rotate x*degrees(atan((camLocation - camLookAt).y/(camLocation - camLookAt).z)) rotate y*degrees(atan((camLocation - camLookAt).z/(camLocation - camLookAt).x)) scale <%.4g,%.4g,%.4g>b' % (t_blend.offset.x / 10 ,t_blend.offset.y / 10 ,t_blend.offset.z / 10, t_blend.scale.x ,t_blend.scale.y ,t_blend.scale.z))#replace 4/3 by the ratio of each image found by some custom or existing function #using camera rotation valuesdirectly from blender seems much easier - if t_blend.texture_coords=='ANGMAP': - mappingBlend = ('') + if t_blend.texture_coords == 'ANGMAP': + mappingBlend = "" else: - mappingBlend = (' translate <%.4g-0.5,%.4g-0.5,%.4g-0.5> rotate<0,0,0> scale <%.4g,%.4g,%.4g>' % (t_blend.offset.x / 10 ,t_blend.offset.y / 10 ,t_blend.offset.z / 10, t_blend.scale.x*0.85 , t_blend.scale.y*0.85 , t_blend.scale.z*0.85 )) - #The initial position and rotation of the pov camera is probably creating the rotation offset should look into it someday but at least background won't rotate with the camera now. + mappingBlend = " translate <%.4g-0.5,%.4g-0.5,%.4g-0.5> rotate<0,0,0> scale <%.4g,%.4g,%.4g>" % ( + t_blend.offset.x / 10.0, t_blend.offset.y / 10.0, t_blend.offset.z / 10.0, + t_blend.scale.x * 0.85, t_blend.scale.y * 0.85, t_blend.scale.z * 0.85, + ) + + #The initial position and rotation of the pov camera is probably creating the rotation offset should look into it someday but at least background won't rotate with the camera now. #Putting the map on a plane would not introduce the skysphere distortion and allow for better image scale matching but also some waay to chose depth and size of the plane relative to camera. - tabWrite('sky_sphere {\n') + tabWrite('sky_sphere {\n') tabWrite('pigment {\n') - tabWrite('image_map{%s \"%s\" %s}\n' % (imageFormat(texturesBlend),texturesBlend,imgMapBG(t_blend))) + tabWrite('image_map{%s \"%s\" %s}\n' % (imageFormat(texturesBlend), texturesBlend, imgMapBG(t_blend))) tabWrite('}\n') tabWrite('%s\n' % (mappingBlend)) - tabWrite('}\n') + tabWrite('}\n') #tabWrite('scale 2\n') #tabWrite('translate -1\n') - - #For only Background gradient - - if worldTexCount==0: + + #For only Background gradient + + if worldTexCount == 0: if world.use_sky_blend: - tabWrite('sky_sphere {\n') + tabWrite('sky_sphere {\n') tabWrite('pigment {\n') - tabWrite('gradient y\n')#maybe Should follow the advice of POV doc about replacing gradient for skysphere..5.5 + tabWrite('gradient y\n') # maybe Should follow the advice of POV doc about replacing gradient for skysphere..5.5 tabWrite('color_map {\n') if render.alpha_mode == 'STRAIGHT': tabWrite('[0.0 rgbt<%.3g, %.3g, %.3g, 1>]\n' % (world.horizon_color[:])) tabWrite('[1.0 rgbt<%.3g, %.3g, %.3g, 1>]\n' % (world.zenith_color[:])) elif render.alpha_mode == 'PREMUL': tabWrite('[0.0 rgbt<%.3g, %.3g, %.3g, 0.99>]\n' % (world.horizon_color[:])) - tabWrite('[1.0 rgbt<%.3g, %.3g, %.3g, 0.99>]\n' % (world.zenith_color[:])) #aa premult not solved with transmit 1 + tabWrite('[1.0 rgbt<%.3g, %.3g, %.3g, 0.99>]\n' % (world.zenith_color[:])) # aa premult not solved with transmit 1 else: tabWrite('[0.0 rgbt<%.3g, %.3g, %.3g, 0>]\n' % (world.horizon_color[:])) tabWrite('[1.0 rgbt<%.3g, %.3g, %.3g, 0>]\n' % (world.zenith_color[:])) @@ -1286,10 +1317,10 @@ def write_pov(filename, scene=None, info_callback=None): #sky_sphere alpha (transmit) is not translating into image alpha the same way as 'background' #if world.light_settings.use_indirect_light: - # scene.pov_radio_enable=1 - + # scene.pov_radio_enable=1 + #Maybe change the above to a funtion copyInternalRenderer settings when user pushes a button, then: - #scene.pov_radio_enable = world.light_settings.use_indirect_light + #scene.pov_radio_enable = world.light_settings.use_indirect_light #and other such translations but maybe this would not be allowed either? ############################################################### @@ -1335,13 +1366,13 @@ def write_pov(filename, scene=None, info_callback=None): tabWrite('pretrace_end %.3g\n' % scene.pov_radio_pretrace_end) tabWrite('recursion_limit %d\n' % scene.pov_radio_recursion_limit) tabWrite('}\n') - once=1 + once = 1 for material in bpy.data.materials: if material.subsurface_scattering.use and once: - tabWrite('mm_per_unit %.6f\n' % (material.subsurface_scattering.scale * (-100) + 15))#In pov, the scale has reversed influence compared to blender. these number should correct that - once=0 #In POV-Ray, the scale factor for all subsurface shaders needs to be the same + tabWrite('mm_per_unit %.6f\n' % (material.subsurface_scattering.scale * (-100.0) + 15.0)) # In pov, the scale has reversed influence compared to blender. these number should correct that + once = 0 # In POV-Ray, the scale factor for all subsurface shaders needs to be the same - if world: + if world: tabWrite('ambient_light rgb<%.3g, %.3g, %.3g>\n' % world.ambient_color[:]) if material.pov_photons_refraction or material.pov_photons_reflection: @@ -1354,43 +1385,50 @@ def write_pov(filename, scene=None, info_callback=None): tabWrite('}\n') - sel = scene.objects comments = scene.pov_comments_enable - if comments: file.write('//---------------------------------------------\n//--Exported with POV-Ray exporter for Blender--\n//---------------------------------------------\n\n') - + if comments: + file.write('//---------------------------------------------\n//--Exported with POV-Ray exporter for Blender--\n//---------------------------------------------\n\n') + file.write('#version 3.7;\n') - - if comments: file.write('\n//--Global settings and background--\n\n') - + + if comments: + file.write('\n//--Global settings and background--\n\n') + exportGlobalSettings(scene) - - if comments: file.write('\n') - + + if comments: + file.write('\n') + exportWorld(scene.world) - - if comments: file.write('\n//--Cameras--\n\n') - + + if comments: + file.write('\n//--Cameras--\n\n') + exportCamera() - - if comments: file.write('\n//--Lamps--\n\n') - + + if comments: + file.write('\n//--Lamps--\n\n') + exportLamps([l for l in sel if l.type == 'LAMP']) - - if comments: file.write('\n//--Material Definitions--\n\n') - + + if comments: + file.write('\n//--Material Definitions--\n\n') + # Convert all materials to strings we can access directly per vertex. #exportMaterials() - writeMaterial(None) # default material + writeMaterial(None) # default material for material in bpy.data.materials: - if material.users > 0: + if material.users > 0: writeMaterial(material) - if comments: file.write('\n') + if comments: + file.write('\n') exportMeta([l for l in sel if l.type == 'META']) - if comments: file.write('//--Mesh objects--\n') - + if comments: + file.write('//--Mesh objects--\n') + exportMeshs(scene, sel) #What follow used to happen here: #exportCamera() @@ -1402,13 +1440,12 @@ def write_pov(filename, scene=None, info_callback=None): #print('pov file closed %s' % file.closed) file.close() #print('pov file closed %s' % file.closed) - def write_pov_ini(filename_ini, filename_pov, filename_image): scene = bpy.data.scenes[0] render = scene.render - + x = int(render.resolution_x * render.resolution_percentage * 0.01) y = int(render.resolution_y * render.resolution_percentage * 0.01) @@ -1429,17 +1466,17 @@ def write_pov_ini(filename_ini, filename_pov, filename_image): file.write('End_Row=%d\n' % (part.y+part.h)) ''' - file.write('Bounding_Method=2\n')#The new automatic BSP is faster in most scenes + file.write('Bounding_Method=2\n') # The new automatic BSP is faster in most scenes - file.write('Display=1\n')#Activated (turn this back off when better live exchange is done between the two programs (see next comment) + file.write('Display=1\n') # Activated (turn this back off when better live exchange is done between the two programs (see next comment) file.write('Pause_When_Done=0\n') - file.write('Output_File_Type=N\n') # PNG, with POV-Ray 3.7, can show background color with alpha. In the long run using the POV-Ray interactive preview like bishop 3D could solve the preview for all formats. + file.write('Output_File_Type=N\n') # PNG, with POV-Ray 3.7, can show background color with alpha. In the long run using the POV-Ray interactive preview like bishop 3D could solve the preview for all formats. #file.write('Output_File_Type=T\n') # TGA, best progressive loading file.write('Output_Alpha=1\n') if scene.pov_antialias_enable: # aa_mapping = {'5': 2, '8': 3, '11': 4, '16': 5} # method 2 (recursive) with higher max subdiv forced because no mipmapping in POV-Ray needs higher sampling. - method = {'0':1, '1':2} + method = {'0': 1, '1': 2} file.write('Antialias=on\n') file.write('Sampling_Method=%s\n' % method[scene.pov_antialias_method]) file.write('Antialias_Depth=%d\n' % scene.pov_antialias_depth) @@ -1449,8 +1486,8 @@ def write_pov_ini(filename_ini, filename_pov, filename_image): file.write('Jitter=on\n') file.write('Jitter_Amount=%3g\n' % scene.pov_jitter_amount) else: - file.write('Jitter=off\n')#prevent animation flicker - + file.write('Jitter=off\n') # prevent animation flicker + else: file.write('Antialias=off\n') #print('ini file closed %s' % file.closed) @@ -1462,13 +1499,13 @@ class PovrayRender(bpy.types.RenderEngine): bl_idname = 'POVRAY_RENDER' bl_label = 'POV-Ray 3.7' DELAY = 0.5 - + def _export(self, scene): import tempfile - + # mktemp is Deprecated since version 2.3, replaced with NamedTemporaryFile() #CR self._temp_file_in = tempfile.NamedTemporaryFile(suffix='.pov', delete=False) - self._temp_file_out = tempfile.NamedTemporaryFile(suffix='.png', delete=False)#PNG with POV 3.7, can show the background color with alpha. In the long run using the POV-Ray interactive preview like bishop 3D could solve the preview for all formats. + self._temp_file_out = tempfile.NamedTemporaryFile(suffix='.png', delete=False) # PNG with POV 3.7, can show the background color with alpha. In the long run using the POV-Ray interactive preview like bishop 3D could solve the preview for all formats. #self._temp_file_out = tempfile.NamedTemporaryFile(suffix='.tga', delete=False) self._temp_file_ini = tempfile.NamedTemporaryFile(suffix='.ini', delete=False) ''' @@ -1486,7 +1523,7 @@ class PovrayRender(bpy.types.RenderEngine): def _render(self, scene): try: - os.remove(self._temp_file_out.name) # so as not to load the old file + os.remove(self._temp_file_out.name) # so as not to load the old file except OSError: pass @@ -1495,18 +1532,18 @@ class PovrayRender(bpy.types.RenderEngine): print ('***-STARTING-***') pov_binary = 'povray' - + extra_args = [] - + if scene.pov_command_line_switches != "": for newArg in scene.pov_command_line_switches.split(' '): extra_args.append(newArg) - + if sys.platform == 'win32': import winreg regKey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\\POV-Ray\\v3.7\\Windows') - #64 bits blender + #64 bits blender if bitness == 64: try: pov_binary = winreg.QueryValueEx(regKey, 'Home')[0] + '\\bin\\pvengine64' @@ -1520,13 +1557,12 @@ class PovrayRender(bpy.types.RenderEngine): print("POV-Ray 3.7 64 bits could not execute, running 32 bits instead") else: print("POV-Ray 3.7 64 bits found") - - - #32 bits blender + + #32 bits blender else: try: pov_binary = winreg.QueryValueEx(regKey, 'Home')[0] + '\\bin\\pvengine' - # someone might also run povray 64 bits with a 32 bits build of blender. + # someone might also run povray 64 bits with a 32 bits build of blender. except OSError: try: pov_binary = winreg.QueryValueEx(regKey, 'Home')[0] + '\\bin\\pvengine64' @@ -1536,17 +1572,17 @@ class PovrayRender(bpy.types.RenderEngine): print("Running POV-Ray 3.7 64 bits build with 32 bits Blender, \nYou might want to run Blender 64 bits as well.") else: print("POV-Ray 3.7 32 bits found") - + else: # DH - added -d option to prevent render window popup which leads to segfault on linux extra_args.append('-d') # print('Extra Args: ' + str(extra_args)) - + if 1: # TODO, when POV-Ray isn't found this gives a cryptic error, would be nice to be able to detect if it exists try: - self._process = subprocess.Popen([pov_binary, self._temp_file_ini.name] + extra_args) # stdout=subprocess.PIPE, stderr=subprocess.PIPE + self._process = subprocess.Popen([pov_binary, self._temp_file_ini.name] + extra_args) # stdout=subprocess.PIPE, stderr=subprocess.PIPE except OSError: # TODO, report api print("POV-Ray 3.7: could not execute '%s', possibly POV-Ray isn't installed" % pov_binary) @@ -1566,11 +1602,11 @@ class PovrayRender(bpy.types.RenderEngine): for f in (self._temp_file_in, self._temp_file_ini, self._temp_file_out): #print('Name: %s' % f.name) #print('File closed %s' % f.closed) - f.close() # Why do I have to close them again? Without closeing the pov and ini files are not deletable. PNG is not closable! + f.close() # Why do I have to close them again? Without closeing the pov and ini files are not deletable. PNG is not closable! try: os.unlink(f.name) #os.remove(f.name) - except OSError: #was that the proper error type? + except OSError: # was that the proper error type? #print('Couldn\'t remove/unlink TEMP file %s' % f.name) pass #print('') @@ -1588,13 +1624,13 @@ class PovrayRender(bpy.types.RenderEngine): return r = scene.render -##WIP output format +##WIP output format ## if r.file_format == 'OPENEXR': ## fformat = 'EXR' ## render.color_mode = 'RGBA' ## else: ## fformat = 'TGA' -## r.file_format = 'TARGA' +## r.file_format = 'TARGA' ## r.color_mode = 'RGBA' # compute resolution @@ -1611,7 +1647,7 @@ class PovrayRender(bpy.types.RenderEngine): except OSError: pass break - + poll_result = self._process.poll() if poll_result is not None: print('***POV PROCESS FAILED : %s ***' % poll_result) @@ -1660,7 +1696,6 @@ class PovrayRender(bpy.types.RenderEngine): # Would be nice to redirect the output # stdout_value, stderr_value = self._process.communicate() # locks - # check if the file updated new_size = os.path.getsize(self._temp_file_out.name) @@ -1671,9 +1706,7 @@ class PovrayRender(bpy.types.RenderEngine): time.sleep(self.DELAY) else: print('***POV FILE NOT FOUND***') - + print('***POV FINISHED***') #time.sleep(self.DELAY) self._cleanup() - - diff --git a/render_povray/ui.py b/render_povray/ui.py index 1e14519b..93a21e0c 100644 --- a/render_povray/ui.py +++ b/render_povray/ui.py @@ -16,6 +16,8 @@ # # ##### END GPL LICENSE BLOCK ##### +# + import bpy # Use some of the existing buttons. @@ -82,7 +84,6 @@ for member in dir(properties_data_lamp): del properties_data_lamp - class RenderButtonsPanel(): bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' @@ -94,6 +95,7 @@ class RenderButtonsPanel(): rd = context.scene.render return (rd.use_game_engine == False) and (rd.engine in cls.COMPAT_ENGINES) + class MaterialButtonsPanel(): bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' @@ -106,6 +108,7 @@ class MaterialButtonsPanel(): rd = context.scene.render return mat and (rd.use_game_engine == False) and (rd.engine in cls.COMPAT_ENGINES) + class TextureButtonsPanel(): bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' @@ -118,6 +121,7 @@ class TextureButtonsPanel(): rd = context.scene.render return tex and (rd.use_game_engine == False) and (rd.engine in cls.COMPAT_ENGINES) + class ObjectButtonsPanel(): bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' @@ -129,7 +133,10 @@ class ObjectButtonsPanel(): obj = context.object rd = context.scene.render return obj and (rd.use_game_engine == False) and (rd.engine in cls.COMPAT_ENGINES) + ########################################MR###################################### + + class MATERIAL_PT_povray_mirrorIOR(MaterialButtonsPanel, bpy.types.Panel): bl_label = "IOR Mirror" COMPAT_ENGINES = {'POVRAY_RENDER'} @@ -153,8 +160,8 @@ class MATERIAL_PT_povray_mirrorIOR(MaterialButtonsPanel, bpy.types.Panel): row.label(text="The current Raytrace ") row = col.row() row.alignment = 'CENTER' - row.label(text="Transparency IOR is: "+str(mat.raytrace_transparency.ior)) - + row.label(text="Transparency IOR is: " + str(mat.raytrace_transparency.ior)) + class MATERIAL_PT_povray_metallic(MaterialButtonsPanel, bpy.types.Panel): bl_label = "metallic Mirror" @@ -171,6 +178,7 @@ class MATERIAL_PT_povray_metallic(MaterialButtonsPanel, bpy.types.Panel): mat = context.material layout.active = mat.pov_mirror_metallic + class MATERIAL_PT_povray_conserve_energy(MaterialButtonsPanel, bpy.types.Panel): bl_label = "conserve energy" COMPAT_ENGINES = {'POVRAY_RENDER'} @@ -186,6 +194,7 @@ class MATERIAL_PT_povray_conserve_energy(MaterialButtonsPanel, bpy.types.Panel): mat = context.material layout.active = mat.pov_conserve_energy + class MATERIAL_PT_povray_iridescence(MaterialButtonsPanel, bpy.types.Panel): bl_label = "iridescence" COMPAT_ENGINES = {'POVRAY_RENDER'} @@ -200,7 +209,7 @@ class MATERIAL_PT_povray_iridescence(MaterialButtonsPanel, bpy.types.Panel): mat = context.material layout.active = mat.pov_irid_enable - + if mat.pov_irid_enable: split = layout.split() @@ -214,14 +223,13 @@ class MATERIAL_PT_povray_caustics(MaterialButtonsPanel, bpy.types.Panel): bl_label = "Caustics" COMPAT_ENGINES = {'POVRAY_RENDER'} - def draw_header(self, context): mat = context.material self.layout.prop(mat, "pov_caustics_enable", text="") def draw(self, context): - + layout = self.layout mat = context.material @@ -236,17 +244,15 @@ class MATERIAL_PT_povray_caustics(MaterialButtonsPanel, bpy.types.Panel): ## mat.pov_fake_caustics = False ## mat.pov_photons_refraction = False ## mat.pov_photons_reflection = True - if mat.pov_refraction_type=="1": + if mat.pov_refraction_type == "1": ## mat.pov_fake_caustics = True ## mat.pov_photons_refraction = False col.prop(mat, "pov_fake_caustics_power", slider=True) - elif mat.pov_refraction_type=="2": + elif mat.pov_refraction_type == "2": ## mat.pov_fake_caustics = False ## mat.pov_photons_refraction = True col.prop(mat, "pov_photons_dispersion", slider=True) col.prop(mat, "pov_photons_reflection") - - ## col.prop(mat, "pov_fake_caustics") ## if mat.pov_fake_caustics: @@ -261,6 +267,8 @@ class MATERIAL_PT_povray_caustics(MaterialButtonsPanel, bpy.types.Panel): ## col.prop(mat, "pov_photons_reflection") ####TODO : MAKE THIS A real RADIO BUTTON (using EnumProperty?) ######################################EndMR##################################### + + class RENDER_PT_povray_global_settings(RenderButtonsPanel, bpy.types.Panel): bl_label = "Global Settings" COMPAT_ENGINES = {'POVRAY_RENDER'} @@ -276,12 +284,13 @@ class RENDER_PT_povray_global_settings(RenderButtonsPanel, bpy.types.Panel): col = split.column() col.label(text="Command line switches:") - col.prop(scene, "pov_command_line_switches", text="" ) + col.prop(scene, "pov_command_line_switches", text="") split = layout.split() col = split.column() col.prop(scene, "pov_max_trace_level", text="Ray Depth") col = split.column() + class RENDER_PT_povray_antialias(RenderButtonsPanel, bpy.types.Panel): bl_label = "Anti-Aliasing" COMPAT_ENGINES = {'POVRAY_RENDER'} @@ -304,7 +313,7 @@ class RENDER_PT_povray_antialias(RenderButtonsPanel, bpy.types.Panel): col.prop(scene, "pov_antialias_method", text="") col = split.column() col.prop(scene, "pov_jitter_enable", text="Jitter") - + split = layout.split() col = split.column() col.prop(scene, "pov_antialias_depth", text="AA Depth") @@ -319,9 +328,9 @@ class RENDER_PT_povray_antialias(RenderButtonsPanel, bpy.types.Panel): col = split.column() col.prop(scene, "pov_antialias_threshold", text="AA Threshold") col = split.column() - col.prop(scene, "pov_antialias_gamma", text="AA Gamma") - - + col.prop(scene, "pov_antialias_gamma", text="AA Gamma") + + class RENDER_PT_povray_radiosity(RenderButtonsPanel, bpy.types.Panel): bl_label = "Radiosity" COMPAT_ENGINES = {'POVRAY_RENDER'} @@ -374,6 +383,7 @@ class RENDER_PT_povray_radiosity(RenderButtonsPanel, bpy.types.Panel): col = split.column() col.prop(scene, "pov_radio_always_sample") + class RENDER_PT_povray_media(RenderButtonsPanel, bpy.types.Panel): bl_label = "Atmosphere Media" COMPAT_ENGINES = {'POVRAY_RENDER'} @@ -431,7 +441,7 @@ class RENDER_PT_povray_formatting(RenderButtonsPanel, bpy.types.Panel): col = split.column() col.prop(scene, "pov_indentation_character", text="Indent") col = split.column() - if scene.pov_indentation_character=="2": + if scene.pov_indentation_character == "2": col.prop(scene, "pov_indentation_spaces", text="Spaces") split = layout.split() col = split.column() @@ -458,6 +468,7 @@ class TEXTURE_PT_povray_tex_gamma(TextureButtonsPanel, bpy.types.Panel): col = split.column() col.prop(tex, "pov_tex_gamma_value", text="Gamma Value") + class OBJECT_PT_povray_obj_importance(ObjectButtonsPanel, bpy.types.Panel): bl_label = "POV-Ray" COMPAT_ENGINES = {'POVRAY_RENDER'} @@ -472,4 +483,3 @@ class OBJECT_PT_povray_obj_importance(ObjectButtonsPanel, bpy.types.Panel): col = split.column() col.prop(obj, "pov_importance_value", text="Importance") - -- cgit v1.2.3