Manual merge of soc-2009-kazanbas branch:
[blender.git] / release / io / engine_render_pov.py
1 import bpy
2
3 from math import atan, pi, degrees
4 import subprocess
5 import os
6 import sys
7 import time
8
9 import platform as pltfrm
10
11 if pltfrm.architecture()[0] == '64bit':
12         bitness = 64
13 else:
14         bitness = 32
15
16 def write_pov(filename, scene=None, info_callback = None):
17         file = open(filename, 'w')
18         
19         # Only for testing
20         if not scene:
21                 scene = bpy.data.scenes[0]
22         
23         render = scene.render_data
24         world = scene.world
25         
26         # --- taken from fbx exporter 
27         ## This was used to make V, but faster not to do all that
28         ##valid = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_,.()[]{}'
29         ##v = range(255)
30         ##for c in valid: v.remove(ord(c))
31         v = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,42,43,46,47,58,59,60,61,62,63,64,92,94,96,124,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254]
32         invalid = ''.join([chr(i) for i in v])
33         def cleanName(name):
34                 for ch in invalid:      name = name.replace(ch, '_')
35                 return name
36         del v
37         
38         # --- done with clean name.
39         
40         def uniqueName(name, nameSeq):
41                 
42                 if name not in nameSeq:
43                         return name
44                 
45                 name_orig = name
46                 i = 1
47                 while name in nameSeq:
48                         name = '%s_%.3d' % (name_orig, i)
49                         i+=1
50                 
51                 return name
52                 
53         
54         def writeMatrix(matrix):
55                 file.write('\tmatrix <%.6f, %.6f, %.6f,  %.6f, %.6f, %.6f,  %.6f, %.6f, %.6f,  %.6f, %.6f, %.6f>\n' %\
56                 (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]) )
57         
58         def writeObjectMaterial(material):
59                 if material and material.transparency_method=='RAYTRACE':
60                         file.write('\tinterior { ior %.6f }\n' % material.raytrace_transparency.ior)
61                         
62                         # Other interior args
63                         # fade_distance 2
64                         # fade_power [Value]
65                         # fade_color
66                         
67                         # dispersion
68                         # dispersion_samples
69         
70         materialNames = {}
71         DEF_MAT_NAME = 'Default'
72         def writeMaterial(material):
73                 # Assumes only called once on each material
74                 
75                 if material:
76                         name_orig = material.name
77                 else:
78                         name_orig = DEF_MAT_NAME
79                 
80                 name = materialNames[name_orig] = uniqueName(cleanName(name_orig), materialNames)
81                 
82                 file.write('#declare %s = finish {\n' % name)
83                 
84                 if material:
85                         file.write('\tdiffuse %.3g\n' % material.diffuse_intensity)
86                         file.write('\tspecular %.3g\n' % material.specular_intensity)
87                         
88                         file.write('\tambient %.3g\n' % material.ambient)
89                         #file.write('\tambient rgb <%.3g, %.3g, %.3g>\n' % tuple([c*material.ambient for c in world.ambient_color])) # povray blends the global value
90                         
91                         # map hardness between 0.0 and 1.0
92                         roughness = ((1.0 - ((material.specular_hardness-1.0)/510.0)))
93                         # scale from 0.0 to 0.1
94                         roughness *= 0.1
95                         # add a small value because 0.0 is invalid
96                         roughness += (1/511.0)
97                         
98                         file.write('\troughness %.3g\n' % roughness)
99                         
100                         # 'phong 70.0 '
101                         
102                         if material.raytrace_mirror.enabled:
103                                 raytrace_mirror= material.raytrace_mirror
104                                 if raytrace_mirror.reflect_factor:
105                                         file.write('\treflection {\n')
106                                         file.write('\t\trgb <%.3g, %.3g, %.3g>' % tuple(material.mirror_color))
107                                         file.write('\t\tfresnel 1 falloff %.3g exponent %.3g metallic %.3g} ' % (raytrace_mirror.fresnel, raytrace_mirror.fresnel_factor, raytrace_mirror.reflect_factor))
108                 
109                 else:
110                         file.write('\tdiffuse 0.8\n')
111                         file.write('\tspecular 0.2\n')
112                         
113                         
114                 
115                 # This is written into the object
116                 '''
117                 if material and material.transparency_method=='RAYTRACE':
118                         'interior { ior %.3g} ' % material.raytrace_transparency.ior
119                 '''
120                 
121                 #file.write('\t\t\tcrand 1.0\n') # Sand granyness
122                 #file.write('\t\t\tmetallic %.6f\n' % material.spec)
123                 #file.write('\t\t\tphong %.6f\n' % material.spec)
124                 #file.write('\t\t\tphong_size %.6f\n' % material.spec)
125                 #file.write('\t\t\tbrilliance %.6f ' % (material.specular_hardness/256.0) # Like hardness
126                 
127                 file.write('}\n')
128         
129         def exportCamera():
130                 camera = scene.camera
131                 matrix = camera.matrix
132                 
133                 # compute resolution
134                 Qsize=float(render.resolution_x)/float(render.resolution_y)
135                 
136                 file.write('camera {\n')
137                 file.write('\tlocation  <0, 0, 0>\n')
138                 file.write('\tlook_at  <0, 0, -1>\n')
139                 file.write('\tright <%s, 0, 0>\n' % -Qsize)
140                 file.write('\tup <0, 1, 0>\n')
141                 file.write('\tangle  %f \n' % (360.0*atan(16.0/camera.data.lens)/pi))
142                 
143                 file.write('\trotate  <%.6f, %.6f, %.6f>\n' % tuple([degrees(e) for e in matrix.rotationPart().toEuler()]))
144                 file.write('\ttranslate <%.6f, %.6f, %.6f>\n' % (matrix[3][0], matrix[3][1], matrix[3][2]))
145                 file.write('}\n')
146         
147         
148         
149         def exportLamps(lamps):
150                 # Get all lamps
151                 for ob in lamps:
152                         lamp = ob.data
153                         
154                         matrix = ob.matrix
155                         
156                         color = tuple([c * lamp.energy for c in lamp.color]) # Colour is modified by energy
157                         
158                         file.write('light_source {\n')
159                         file.write('\t< 0,0,0 >\n')
160                         file.write('\tcolor rgb<%.3g, %.3g, %.3g>\n' % color)
161                         
162                         if lamp.type == 'POINT': # Point Lamp 
163                                 pass
164                         elif lamp.type == 'SPOT': # Spot
165                                 file.write('\tspotlight\n')
166                                 
167                                 # Falloff is the main radius from the centre line
168                                 file.write('\tfalloff %.2f\n' % (lamp.spot_size/2.0) ) # 1 TO 179 FOR BOTH
169                                 file.write('\tradius %.6f\n' % ((lamp.spot_size/2.0) * (1-lamp.spot_blend)) ) 
170                                 
171                                 # Blender does not have a tightness equivilent, 0 is most like blender default.
172                                 file.write('\ttightness 0\n') # 0:10f
173                                 
174                                 file.write('\tpoint_at  <0, 0, -1>\n')
175                         elif lamp.type == 'SUN':
176                                 file.write('\tparallel\n')
177                                 file.write('\tpoint_at  <0, 0, -1>\n') # *must* be after 'parallel'
178                                 
179                         elif lamp.type == 'AREA':
180                                 
181                                 size_x = lamp.size
182                                 samples_x = lamp.shadow_ray_samples_x
183                                 if lamp.shape == 'SQUARE':
184                                         size_y = size_x
185                                         samples_y = samples_x
186                                 else:
187                                         size_y = lamp.size_y
188                                         samples_y = lamp.shadow_ray_samples_y
189                                 
190                                 
191                                 
192                                 file.write('\tarea_light <%d,0,0>,<0,0,%d> %d, %d\n' % (size_x, size_y, samples_x, samples_y))
193                                 if lamp.shadow_ray_sampling_method == 'CONSTANT_JITTERED':
194                                         if lamp.jitter:
195                                                 file.write('\tjitter\n')
196                                 else:
197                                         file.write('\tadaptive 1\n')
198                                         file.write('\tjitter\n')
199                         
200                         if lamp.shadow_method == 'NOSHADOW':
201                                 file.write('\tshadowless\n')    
202                         
203                         file.write('\tfade_distance %.6f\n' % lamp.distance)
204                         file.write('\tfade_power %d\n' % 1) # Could use blenders lamp quad?
205                         writeMatrix(matrix)
206                         
207                         file.write('}\n')
208         
209         def exportMeta(metas):
210                 
211                 # TODO - blenders 'motherball' naming is not supported.
212                 
213                 for ob in metas:
214                         meta = ob.data
215                         
216                         file.write('blob {\n')
217                         file.write('\t\tthreshold %.4g\n' % meta.threshold)
218                         
219                         try:
220                                 material= meta.materials[0] # lame! - blender cant do enything else.
221                         except:
222                                 material= None
223                         
224                         for elem in meta.elements:
225                                 
226                                 if elem.type not in ('BALL', 'ELLIPSOID'):
227                                         continue # Not supported
228                                 
229                                 loc = elem.location
230                                 
231                                 stiffness= elem.stiffness
232                                 if elem.negative:
233                                         stiffness = -stiffness
234                                 
235                                 if elem.type == 'BALL':
236                                         
237                                         file.write('\tsphere { <%.6g, %.6g, %.6g>, %.4g, %.4g ' % (loc.x, loc.y, loc.z, elem.radius, stiffness))
238                                         
239                                         # After this wecould do something simple like...
240                                         #       "pigment {Blue} }"
241                                         # except we'll write the color
242                                 
243                                 elif elem.type == 'ELLIPSOID':
244                                         # location is modified by scale
245                                         file.write('\tsphere { <%.6g, %.6g, %.6g>, %.4g, %.4g ' % (loc.x/elem.size_x, loc.y/elem.size_y, loc.z/elem.size_z, elem.radius, stiffness))
246                                         file.write(     'scale <%.6g, %.6g, %.6g> ' % (elem.size_x, elem.size_y, elem.size_z))
247                                 
248                                 if material:
249                                         diffuse_color = material.diffuse_color
250                                         
251                                         if material.transparency and material.transparency_method=='RAYTRACE':  trans = 1-material.raytrace_transparency.filter
252                                         else:                                                                                                                                   trans = 0.0
253                                         
254                                         file.write(
255                                                 'pigment {rgbft<%.3g, %.3g, %.3g, %.3g, %.3g>} finish {%s} }\n' % \
256                                                 (diffuse_color[0], diffuse_color[1], diffuse_color[2], 1-material.alpha, trans, materialNames[material.name])
257                                         )
258                                         
259                                 else:
260                                         file.write('pigment {rgb<1 1 1>} finish {%s} }\n' % DEF_MAT_NAME)               # Write the finish last.
261                         
262                         writeObjectMaterial(material)
263
264                         writeMatrix(ob.matrix)
265                         
266                         file.write('}\n')
267                 
268                 
269         
270         
271         def exportMeshs(sel):
272                 
273                 ob_num = 0
274                 
275                 for ob in sel:
276                         ob_num+= 1
277                         
278                         if ob.type in ('LAMP', 'CAMERA', 'EMPTY', 'META'):
279                                 continue
280                         
281                         me = ob.data
282                         me_materials= me.materials
283                         
284                         me = ob.create_mesh(True, 'RENDER')
285                         
286                         if not me:
287                                 continue
288                         
289                         if info_callback:
290                                 info_callback('Object %2.d of %2.d (%s)' % (ob_num, len(sel), ob.name))
291                         
292                         #if ob.type!='MESH':
293                         #       continue
294                         # me = ob.data
295                         
296                         matrix = ob.matrix
297                         try:    uv_layer = me.active_uv_texture.data
298                         except:uv_layer = None
299                                 
300                         try:    vcol_layer = me.active_vertex_color.data
301                         except:vcol_layer = None
302                         
303                         faces_verts = [f.verts for f in me.faces]
304                         faces_normals = [tuple(f.normal) for f in me.faces]
305                         verts_normals = [tuple(v.normal) for v in me.verts]
306                         
307                         # quads incur an extra face
308                         quadCount = len([f for f in faces_verts if len(f)==4])
309                         
310                         file.write('mesh2 {\n')
311                         file.write('\tvertex_vectors {\n')
312                         file.write('\t\t%s' % (len(me.verts))) # vert count
313                         for v in me.verts:
314                                 file.write(',\n\t\t<%.6f, %.6f, %.6f>' % tuple(v.co)) # vert count
315                         file.write('\n  }\n')
316                         
317                         
318                         # Build unique Normal list
319                         uniqueNormals = {}
320                         for fi, f in enumerate(me.faces):
321                                 fv = faces_verts[fi]
322                                 # [-1] is a dummy index, use a list so we can modify in place
323                                 if f.smooth: # Use vertex normals
324                                         for v in fv:
325                                                 key = verts_normals[v]
326                                                 uniqueNormals[key] = [-1]
327                                 else: # Use face normal
328                                         key = faces_normals[fi]
329                                         uniqueNormals[key] = [-1]
330                         
331                         file.write('\tnormal_vectors {\n')
332                         file.write('\t\t%d' % len(uniqueNormals)) # vert count
333                         idx = 0
334                         for no, index in uniqueNormals.items():
335                                 file.write(',\n\t\t<%.6f, %.6f, %.6f>' % no) # vert count
336                                 index[0] = idx
337                                 idx +=1
338                         file.write('\n  }\n')
339                         
340                         
341                         # Vertex colours
342                         vertCols = {} # Use for material colours also.
343                         
344                         if uv_layer:
345                                 # Generate unique UV's
346                                 uniqueUVs = {}
347                                 
348                                 for fi, uv in enumerate(uv_layer):
349                                         
350                                         if len(faces_verts[fi])==4:
351                                                 uvs = uv.uv1, uv.uv2, uv.uv3, uv.uv4
352                                         else:
353                                                 uvs = uv.uv1, uv.uv2, uv.uv3
354                                         
355                                         for uv in uvs:
356                                                 uniqueUVs[tuple(uv)] = [-1]
357                                 
358                                 file.write('\tuv_vectors {\n')
359                                 #print unique_uvs
360                                 file.write('\t\t%s' % (len(uniqueUVs))) # vert count
361                                 idx = 0
362                                 for uv, index in uniqueUVs.items():
363                                         file.write(',\n\t\t<%.6f, %.6f>' % uv)
364                                         index[0] = idx
365                                         idx +=1
366                                 '''
367                                 else:
368                                         # Just add 1 dummy vector, no real UV's
369                                         file.write('\t\t1') # vert count
370                                         file.write(',\n\t\t<0.0, 0.0>')
371                                 '''
372                                 file.write('\n  }\n')
373                         
374                         
375                         if me.vertex_colors:
376                                 
377                                 for fi, f in enumerate(me.faces):
378                                         material_index = f.material_index
379                                         material = me_materials[material_index]
380                                         
381                                         if material and material.vertex_color_paint:
382                                                 
383                                                 col = vcol_layer[fi]
384                                                 
385                                                 if len(faces_verts[fi])==4:
386                                                         cols = col.color1, col.color2, col.color3, col.color4
387                                                 else:
388                                                         cols = col.color1, col.color2, col.color3
389                                                 
390                                                 for col in cols:                                        
391                                                         key = col[0], col[1], col[2], material_index # Material index!
392                                                         vertCols[key] = [-1]
393                                                 
394                                         else:
395                                                 if material:
396                                                         diffuse_color = tuple(material.diffuse_color)
397                                                         key = diffuse_color[0], diffuse_color[1], diffuse_color[2], material_index
398                                                         vertCols[key] = [-1]
399                                                 
400                         
401                         else:
402                                 # No vertex colours, so write material colours as vertex colours
403                                 for i, material in enumerate(me_materials):
404                                         
405                                         if material:
406                                                 diffuse_color = tuple(material.diffuse_color)
407                                                 key = diffuse_color[0], diffuse_color[1], diffuse_color[2], i # i == f.mat
408                                                 vertCols[key] = [-1]
409                                 
410                         
411                         # Vert Colours
412                         file.write('\ttexture_list {\n')
413                         file.write('\t\t%s' % (len(vertCols))) # vert count
414                         idx=0
415                         for col, index in vertCols.items():
416                                 
417                                 if me_materials:
418                                         material = me_materials[col[3]]
419                                         material_finish = materialNames[material.name]
420                                         
421                                         if material.transparency and material.transparency_method=='RAYTRACE':  trans = 1-material.raytrace_transparency.filter
422                                         else:                                                                                                                                   trans = 0.0
423                                         
424                                 else:
425                                         material_finish = DEF_MAT_NAME # not working properly,
426                                         trans = 0.0
427                                 
428                                 #print material.apl
429                                 file.write(     ',\n\t\ttexture { pigment {rgbft<%.3g, %.3g, %.3g, %.3g, %.3g>} finish {%s}}' %
430                                                         (col[0], col[1], col[2], 1-material.alpha, trans, material_finish) )
431                                 
432                                 index[0] = idx
433                                 idx+=1
434                         
435                         file.write( '\n  }\n' )
436                         
437                         # Face indicies
438                         file.write('\tface_indices {\n')
439                         file.write('\t\t%d' % (len(me.faces) + quadCount)) # faces count
440                         for fi, f in enumerate(me.faces):
441                                 fv = faces_verts[fi]
442                                 material_index= f.material_index
443                                 if len(fv) == 4:        indicies = (0,1,2), (0,2,3)
444                                 else:                           indicies = ((0,1,2),)
445                                 
446                                 if vcol_layer:
447                                         col = vcol_layer[fi]
448                                         
449                                         if len(fv) == 4:
450                                                 cols = col.color1, col.color2, col.color3, col.color4
451                                         else:
452                                                 cols = col.color1, col.color2, col.color3
453                                 
454                                 
455                                 if not me_materials or me_materials[material_index] == None: # No materials
456                                         for i1, i2, i3 in indicies:
457                                                 file.write(',\n\t\t<%d,%d,%d>' % (fv[i1], fv[i2], fv[i3])) # vert count
458                                 else:
459                                         material = me_materials[material_index]
460                                         for i1, i2, i3 in indicies:
461                                                 if me.vertex_colors and material.vertex_color_paint:
462                                                         # Colour per vertex - vertex colour
463                                                         
464                                                         col1 = cols[i1]
465                                                         col2 = cols[i2]
466                                                         col3 = cols[i3]
467                                                 
468                                                         ci1 = vertCols[col1[0], col1[1], col1[2], material_index][0]
469                                                         ci2 = vertCols[col2[0], col2[1], col2[2], material_index][0]
470                                                         ci3 = vertCols[col3[0], col3[1], col3[2], material_index][0]
471                                                 else:
472                                                         # Colour per material - flat material colour
473                                                         diffuse_color= material.diffuse_color
474                                                         ci1 = ci2 = ci3 = vertCols[diffuse_color[0], diffuse_color[1], diffuse_color[2], f.material_index][0]
475                                                 
476                                                 file.write(',\n\t\t<%d,%d,%d>, %d,%d,%d' % (fv[i1], fv[i2], fv[i3], ci1, ci2, ci3)) # vert count
477                                         
478                                         
479                                         
480                         file.write('\n  }\n')
481                         
482                         # normal_indices indicies
483                         file.write('\tnormal_indices {\n')
484                         file.write('\t\t%d' % (len(me.faces) + quadCount)) # faces count
485                         for fi, fv in enumerate(faces_verts):
486                                 
487                                 if len(fv) == 4:        indicies = (0,1,2), (0,2,3)
488                                 else:                           indicies = ((0,1,2),)
489                                 
490                                 for i1, i2, i3 in indicies:
491                                         if f.smooth:
492                                                 file.write(',\n\t\t<%d,%d,%d>' %\
493                                                 (uniqueNormals[verts_normals[fv[i1]]][0],\
494                                                  uniqueNormals[verts_normals[fv[i2]]][0],\
495                                                  uniqueNormals[verts_normals[fv[i3]]][0])) # vert count
496                                         else:
497                                                 idx = uniqueNormals[faces_normals[fi]][0]
498                                                 file.write(',\n\t\t<%d,%d,%d>' % (idx, idx, idx)) # vert count
499                                                 
500                         file.write('\n  }\n')
501                         
502                         if uv_layer:
503                                 file.write('\tuv_indices {\n')
504                                 file.write('\t\t%d' % (len(me.faces) + quadCount)) # faces count
505                                 for fi, fv in enumerate(faces_verts):
506                                         
507                                         if len(fv) == 4:        indicies = (0,1,2), (0,2,3)
508                                         else:                           indicies = ((0,1,2),)
509                                         
510                                         uv = uv_layer[fi]
511                                         if len(faces_verts[fi])==4:
512                                                 uvs = tuple(uv.uv1), tuple(uv.uv2), tuple(uv.uv3), tuple(uv.uv4)
513                                         else:
514                                                 uvs = tuple(uv.uv1), tuple(uv.uv2), tuple(uv.uv3)
515                                         
516                                         for i1, i2, i3 in indicies:
517                                                 file.write(',\n\t\t<%d,%d,%d>' %\
518                                                 (uniqueUVs[uvs[i1]][0],\
519                                                  uniqueUVs[uvs[i2]][0],\
520                                                  uniqueUVs[uvs[i2]][0])) # vert count
521                                 file.write('\n  }\n')
522                         
523                         if me.materials:
524                                 material = me.materials[0] # dodgy
525                                 writeObjectMaterial(material)
526                         
527                         writeMatrix(matrix)
528                         file.write('}\n')
529                         
530                         bpy.data.remove_mesh(me)
531         
532         def exportWorld(world):
533                 if not world:
534                         return
535                 
536                 mist = world.mist
537                 
538                 if mist.enabled:
539                         file.write('fog {\n')
540                         file.write('\tdistance %.6f\n' % mist.depth)
541                         file.write('\tcolor rgbt<%.3g, %.3g, %.3g, %.3g>\n' % (tuple(world.horizon_color) + (1-mist.intensity,)))
542                         #file.write('\tfog_offset %.6f\n' % mist.start)
543                         #file.write('\tfog_alt 5\n')
544                         #file.write('\tturbulence 0.2\n')
545                         #file.write('\tturb_depth 0.3\n')
546                         file.write('\tfog_type 1\n')
547                         file.write('}\n')
548         
549         def exportGlobalSettings(scene):
550                 
551                 file.write('global_settings {\n')
552
553                 if scene.pov_radio_enable:
554                         file.write('\tradiosity {\n')
555                         file.write("\t\tadc_bailout %.4g\n" % scene.pov_radio_adc_bailout)
556                         file.write("\t\talways_sample %d\n" % scene.pov_radio_always_sample)
557                         file.write("\t\tbrightness %.4g\n" % scene.pov_radio_brightness)
558                         file.write("\t\tcount %d\n" % scene.pov_radio_count)
559                         file.write("\t\terror_bound %.4g\n" % scene.pov_radio_error_bound)
560                         file.write("\t\tgray_threshold %.4g\n" % scene.pov_radio_gray_threshold)
561                         file.write("\t\tlow_error_factor %.4g\n" % scene.pov_radio_low_error_factor)
562                         file.write("\t\tmedia %d\n" % scene.pov_radio_media)
563                         file.write("\t\tminimum_reuse %.4g\n" % scene.pov_radio_minimum_reuse)
564                         file.write("\t\tnearest_count %d\n" % scene.pov_radio_nearest_count)
565                         file.write("\t\tnormal %d\n" % scene.pov_radio_normal)
566                         file.write("\t\trecursion_limit %d\n" % scene.pov_radio_recursion_limit)
567                         file.write('\t}\n')
568                 
569                 if world:
570                         file.write("\tambient_light rgb<%.3g, %.3g, %.3g>\n" % tuple(world.ambient_color))
571                 
572                 file.write('}\n')
573         
574         
575         # Convert all materials to strings we can access directly per vertex.
576         writeMaterial(None) # default material
577         
578         for material in bpy.data.materials:
579                 writeMaterial(material)
580         
581         exportCamera()
582         #exportMaterials()
583         sel = scene.objects
584         exportLamps([l for l in sel if l.type == 'LAMP'])
585         exportMeta([l for l in sel if l.type == 'META'])
586         exportMeshs(sel)
587         exportWorld(scene.world)
588         exportGlobalSettings(scene)
589         
590         file.close()
591
592
593 def write_pov_ini(filename_ini, filename_pov, filename_image):
594         scene = bpy.data.scenes[0]
595         render = scene.render_data
596         
597         x= int(render.resolution_x*render.resolution_percentage*0.01)
598         y= int(render.resolution_y*render.resolution_percentage*0.01)
599         
600         file = open(filename_ini, 'w')
601         
602         file.write('Input_File_Name="%s"\n' % filename_pov)
603         file.write('Output_File_Name="%s"\n' % filename_image)
604         
605         file.write('Width=%d\n' % x)
606         file.write('Height=%d\n' % y)
607         
608         # Needed for border render.
609         '''
610         file.write('Start_Column=%d\n' % part.x)
611         file.write('End_Column=%d\n' % (part.x+part.w))
612         
613         file.write('Start_Row=%d\n' % (part.y))
614         file.write('End_Row=%d\n' % (part.y+part.h))
615         '''
616         
617         file.write('Display=0\n')
618         file.write('Pause_When_Done=0\n')
619         file.write('Output_File_Type=T\n') # TGA, best progressive loading
620         file.write('Output_Alpha=1\n')
621         
622         if render.antialiasing: 
623                 aa_mapping = {'OVERSAMPLE_5':2, 'OVERSAMPLE_8':3, 'OVERSAMPLE_11':4, 'OVERSAMPLE_16':5} # method 1 assumed
624                 file.write('Antialias=1\n')
625                 file.write('Antialias_Depth=%d\n' % aa_mapping[render.antialiasing_samples])
626         else:
627                 file.write('Antialias=0\n')
628         
629         file.close()
630
631 # Radiosity panel, use in the scene for now.
632 FloatProperty= bpy.types.Scene.FloatProperty
633 IntProperty= bpy.types.Scene.IntProperty
634 BoolProperty= bpy.types.Scene.BoolProperty
635
636 # Not a real pov option, just to know if we should write
637 BoolProperty(   attr="pov_radio_enable",
638                                 name="Enable Radiosity",
639                                 description="Enable povrays radiosity calculation.",
640                                 default= False)
641 BoolProperty(   attr="pov_radio_display_advanced",
642                                 name="Advanced Options",
643                                 description="Show advanced options.",
644                                 default= False)
645
646 # Real pov options
647 FloatProperty(  attr="pov_radio_adc_bailout",
648                                 name="ADC Bailout",
649                                 description="The adc_bailout for radiosity rays. Use adc_bailout = 0.01 / brightest_ambient_object for good results.",
650                                 min=0.0, max=1000.0, soft_min=0.0, soft_max=1.0, default= 0.01)
651
652 BoolProperty(   attr="pov_radio_always_sample",
653                                 name="Always Sample",
654                                 description="Only use the data from the pretrace step and not gather any new samples during the final radiosity pass..",
655                                 default= True)
656
657 FloatProperty(  attr="pov_radio_brightness",
658                                 name="Brightness",
659                                 description="Ammount objects are brightened before being returned upwards to the rest of the system.",
660                                 min=0.0, max=1000.0, soft_min=0.0, soft_max=10.0, default= 1.0)
661
662 IntProperty(    attr="pov_radio_count",
663                                 name="Ray Count",
664                                 description="number of rays that are sent out whenever a new radiosity value has to be calculated.",
665                                 min=1, max=1600, default= 35)
666
667 FloatProperty(  attr="pov_radio_error_bound",
668                                 name="Error Bound",
669                                 description="one of the two main speed/quality tuning values, lower values are more accurate.",
670                                 min=0.0, max=1000.0, soft_min=0.1, soft_max=10.0, default= 1.8)
671
672 FloatProperty(  attr="pov_radio_gray_threshold",
673                                 name="Gray Threshold",
674                                 description="one of the two main speed/quality tuning values, lower values are more accurate.",
675                                 min=0.0, max=1.0, soft_min=0, soft_max=1, default= 0.0)
676                                                                 
677 FloatProperty(  attr="pov_radio_low_error_factor",
678                                 name="Low Error Factor",
679                                 description="If you calculate just enough samples, but no more, you will get an image which has slightly blotchy lighting.",
680                                 min=0.0, max=1.0, soft_min=0.0, soft_max=1.0, default= 0.5)
681
682 # max_sample - not available yet
683 BoolProperty(   attr="pov_radio_media", 
684                                 name="Media",
685                                 description="Radiosity estimation can be affected by media.",
686                                 default= False)
687
688 FloatProperty(  attr="pov_radio_minimum_reuse",
689                                 name="Minimum Reuse",
690                                 description="Fraction of the screen width which sets the minimum radius of reuse for each sample point (At values higher than 2% expect errors).",
691                                 min=0.0, max=1.0, soft_min=0.1, soft_max=0.1, default= 0.015)
692                                 
693 IntProperty(    attr="pov_radio_nearest_count",
694                                 name="Nearest Count",
695                                 description="Number of old ambient values blended together to create a new interpolated value.",
696                                 min=1, max=20, default= 5)
697                                 
698 BoolProperty(   attr="pov_radio_normal",
699                                 name="Normals",
700                                 description="Radiosity estimation can be affected by normals.",
701                                 default= False)
702
703 IntProperty(    attr="pov_radio_recursion_limit",
704                                 name="Recursion Limit",
705                                 description="how many recursion levels are used to calculate the diffuse inter-reflection.",
706                                 min=1, max=20, default= 3)
707         
708
709 class PovrayRender(bpy.types.RenderEngine):
710         __idname__ = 'POVRAY_RENDER'
711         __label__ = "Povray"
712         DELAY = 0.02
713         
714         def _export(self, scene):
715                 import tempfile
716                 
717                 self.temp_file_in = tempfile.mktemp(suffix='.pov')
718                 self.temp_file_out = tempfile.mktemp(suffix='.tga')
719                 self.temp_file_ini = tempfile.mktemp(suffix='.ini')
720                 '''
721                 self.temp_file_in = '/test.pov'
722                 self.temp_file_out = '/test.tga'
723                 self.temp_file_ini = '/test.ini'
724                 '''
725                 
726                 def info_callback(txt):
727                         self.update_stats("", "POVRAY: " + txt)
728                         
729                 write_pov(self.temp_file_in, scene, info_callback)
730                 
731         def _render(self):
732                 
733                 try:            os.remove(self.temp_file_out) # so as not to load the old file
734                 except: pass
735                 
736                 write_pov_ini(self.temp_file_ini, self.temp_file_in, self.temp_file_out)
737                 
738                 print ("***-STARTING-***")
739                 
740                 pov_binary = "povray"
741                 
742                 if sys.platform=='win32':
743                         import winreg
744                         regKey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\\POV-Ray\\v3.6\\Windows')
745                         
746                         if bitness == 64:
747                                 pov_binary = winreg.QueryValueEx(regKey, 'Home')[0] + '\\bin\\pvengine64'
748                         else:
749                                 pov_binary = winreg.QueryValueEx(regKey, 'Home')[0] + '\\bin\\pvengine'
750                         
751                 if 1:
752                         self.process = subprocess.Popen([pov_binary, self.temp_file_ini]) # stdout=subprocess.PIPE, stderr=subprocess.PIPE
753                 else:
754                         # This works too but means we have to wait until its done
755                         os.system('%s %s' % (pov_binary, self.temp_file_ini))
756                 
757                 print ("***-DONE-***")
758         
759         def _cleanup(self):
760                 for f in (self.temp_file_in, self.temp_file_ini, self.temp_file_out):
761                         try:            os.remove(f)
762                         except: pass
763                 
764                 self.update_stats("", "")
765         
766         def render(self, scene):
767                 
768                 self.update_stats("", "POVRAY: Exporting data from Blender")
769                 self._export(scene)
770                 self.update_stats("", "POVRAY: Parsing File")
771                 self._render()
772                 
773                 r = scene.render_data
774                 
775                 # compute resolution
776                 x= int(r.resolution_x*r.resolution_percentage*0.01)
777                 y= int(r.resolution_y*r.resolution_percentage*0.01)
778                 
779                 
780                 
781                 # Wait for the file to be created
782                 while not os.path.exists(self.temp_file_out):
783                         if self.test_break():
784                                 try:            self.process.terminate()
785                                 except: pass
786                                 break
787                         
788                         if self.process.poll() != None:
789                                 self.update_stats("", "POVRAY: Failed")
790                                 break
791                         
792                         time.sleep(self.DELAY)
793                 
794                 if os.path.exists(self.temp_file_out):
795                         
796                         self.update_stats("", "POVRAY: Rendering")
797                         
798                         prev_size = -1
799                         
800                         def update_image():
801                                 result = self.begin_result(0, 0, x, y)
802                                 lay = result.layers[0]
803                                 # possible the image wont load early on.
804                                 try:            lay.load_from_file(self.temp_file_out)
805                                 except: pass
806                                 self.end_result(result)
807                         
808                         # Update while povray renders
809                         while True:
810                                 
811                                 # test if povray exists
812                                 if self.process.poll() != None:
813                                         update_image();
814                                         break
815                                 
816                                 # user exit
817                                 if self.test_break():
818                                         try:            self.process.terminate()
819                                         except: pass
820                                         
821                                         break
822                                 
823                                 # Would be nice to redirect the output
824                                 # stdout_value, stderr_value = self.process.communicate() # locks
825                                 
826                                 
827                                 # check if the file updated
828                                 new_size = os.path.getsize(self.temp_file_out)
829                                 
830                                 if new_size != prev_size:
831                                         update_image()
832                                         prev_size = new_size
833                                 
834                                 time.sleep(self.DELAY)
835                 
836                 self._cleanup()
837
838 bpy.types.register(PovrayRender)
839
840 # Use some of the existing buttons.
841 import buttons_scene
842 buttons_scene.SCENE_PT_render.COMPAT_ENGINES.add('POVRAY_RENDER')
843 buttons_scene.SCENE_PT_dimensions.COMPAT_ENGINES.add('POVRAY_RENDER')
844 buttons_scene.SCENE_PT_antialiasing.COMPAT_ENGINES.add('POVRAY_RENDER')
845 buttons_scene.SCENE_PT_output.COMPAT_ENGINES.add('POVRAY_RENDER')
846 del buttons_scene
847
848 # Use only a subset of the world panels
849 import buttons_world
850 buttons_world.WORLD_PT_preview.COMPAT_ENGINES.add('POVRAY_RENDER')
851 buttons_world.WORLD_PT_context_world.COMPAT_ENGINES.add('POVRAY_RENDER')
852 buttons_world.WORLD_PT_world.COMPAT_ENGINES.add('POVRAY_RENDER')
853 buttons_world.WORLD_PT_mist.COMPAT_ENGINES.add('POVRAY_RENDER')
854 del buttons_world
855
856 # Example of wrapping every class 'as is'
857 import buttons_material
858 for member in dir(buttons_material):
859         subclass = getattr(buttons_material, member)
860         try:            subclass.COMPAT_ENGINES.add('POVRAY_RENDER')
861         except: pass
862 del buttons_material
863
864 class RenderButtonsPanel(bpy.types.Panel):
865         __space_type__ = 'PROPERTIES'
866         __region_type__ = 'WINDOW'
867         __context__ = "scene"
868         # COMPAT_ENGINES must be defined in each subclass, external engines can add themselves here
869         
870         def poll(self, context):
871                 rd = context.scene.render_data
872                 return (rd.use_game_engine==False) and (rd.engine in self.COMPAT_ENGINES)
873
874 class SCENE_PT_povray_radiosity(RenderButtonsPanel):
875         __label__ = "Radiosity"
876         COMPAT_ENGINES = set(['POVRAY_RENDER'])
877
878         def draw_header(self, context):
879                 layout = self.layout
880                 scene = context.scene
881                 layout.itemR(scene, "pov_radio_enable", text="")
882
883         def draw(self, context):
884                 layout = self.layout
885                 scene = context.scene
886                 rd = scene.render_data
887                 
888                 layout.active = scene.pov_radio_enable
889                 
890                 split = layout.split()
891                 
892                 col = split.column()
893                 
894                 col.itemR(scene, "pov_radio_count", text="Rays")
895                 col.itemR(scene, "pov_radio_recursion_limit", text="Recursions")
896                 col = split.column()
897                 col.itemR(scene, "pov_radio_error_bound", text="Error")
898                 
899                 layout.itemR(scene, "pov_radio_display_advanced")
900                 
901                 if scene.pov_radio_display_advanced:
902                         split = layout.split()
903                 
904                         col = split.column()
905                         col.itemR(scene, "pov_radio_adc_bailout", slider=True)
906                         col.itemR(scene, "pov_radio_gray_threshold", slider=True)
907                         col.itemR(scene, "pov_radio_low_error_factor", slider=True)
908                         
909                         
910                         
911                         col = split.column()
912                         col.itemR(scene, "pov_radio_brightness")
913                         col.itemR(scene, "pov_radio_minimum_reuse", text="Min Reuse")
914                         col.itemR(scene, "pov_radio_nearest_count")
915                         
916                         
917                         split = layout.split()
918                 
919                         col = split.column()
920                         col.itemL(text="Estimation Influence:")
921                         col.itemR(scene, "pov_radio_media")
922                         col.itemR(scene, "pov_radio_normal")
923                         
924                         col = split.column()
925                         col.itemR(scene, "pov_radio_always_sample")
926                 
927
928 bpy.types.register(SCENE_PT_povray_radiosity)