forked from prman-pixar/RenderManForBlender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
export.py
4078 lines (3332 loc) · 148 KB
/
export.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ##### BEGIN MIT LICENSE BLOCK #####
#
# Copyright (c) 2015 - 2017 Pixar
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#
# ##### END MIT LICENSE BLOCK #####
import bpy
import math
import mathutils
import os
import sys
import time
import traceback
import platform
from mathutils import Matrix, Vector, Quaternion, Euler
from . import bl_info
from .util import rib, rib_path, rib_ob_bounds
from .util import make_frame_path
from .util import init_env
from .util import get_sequence_path
from .util import user_path
from .util import path_list_convert, get_real_path
from .util import get_properties, check_if_archive_dirty
from .util import locate_openVDB_cache
from .util import debug, get_addon_prefs
from .util import find_it_path
from .nodes import export_shader_nodetree, get_textures, get_textures_for_node, get_tex_file_name
from .nodes import shader_node_rib, get_mat_name
from .nodes import replace_frame_num
addon_version = bl_info['version']
# ------------- Atom's helper functions -------------
GLOBAL_ZERO_PADDING = 5
# Objects that can be exported as a polymesh via Blender to_mesh() method.
# ['MESH','CURVE','FONT']
SUPPORTED_INSTANCE_TYPES = ['MESH', 'CURVE', 'FONT', 'SURFACE']
SUPPORTED_DUPLI_TYPES = ['FACES', 'VERTS', 'GROUP'] # Supported dupli types.
# These object types can have materials.
MATERIAL_TYPES = ['MESH', 'CURVE', 'FONT']
# Objects without to_mesh() conversion capabilities.
EXCLUDED_OBJECT_TYPES = ['LAMP', 'CAMERA', 'ARMATURE']
# Only these light types affect volumes.
VOLUMETRIC_LIGHT_TYPES = ['SPOT', 'AREA', 'POINT']
MATERIAL_PREFIX = "mat_"
TEXTURE_PREFIX = "tex_"
MESH_PREFIX = "me_"
CURVE_PREFIX = "cu_"
GROUP_PREFIX = "group_"
MESHLIGHT_PREFIX = "meshlight_"
PSYS_PREFIX = "psys_"
DUPLI_PREFIX = "dupli_"
DUPLI_SOURCE_PREFIX = "dup_src_"
def get_matrix_for_object(passedOb):
if passedOb.parent:
mtx = Matrix.Identity(4)
else:
mtx = passedOb.matrix_world
return mtx
# check for a singular matrix
def is_singular(mtx):
return mtx[0][0] == 0.0 and mtx[1][1] == 0.0 and mtx[2][2] == 0.0
# export the instance of an object (dupli)
def export_object_instance(ri, mtx=None, instance_handle=None, num=None):
if mtx and not is_singular(mtx):
ri.AttributeBegin()
ri.Attribute("identifier", {"int id": num})
ri.Transform(rib(mtx))
ri.ObjectInstance(instance_handle)
ri.AttributeEnd()
# ------------- Filtering -------------
def is_visible_layer(scene, ob):
for i in range(len(scene.layers)):
if scene.layers[i] and ob.layers[i]:
return True
return False
def is_renderable(scene, ob):
return (is_visible_layer(scene, ob) and not ob.hide_render) or \
(ob.type in ['ARMATURE', 'LATTICE', 'EMPTY'] and ob.dupli_type not in SUPPORTED_DUPLI_TYPES)
# and not ob.type in ('CAMERA', 'ARMATURE', 'LATTICE'))
def is_renderable_or_parent(scene, ob):
if ob.type == 'CAMERA':
return True
if is_renderable(scene, ob):
return True
elif hasattr(ob, 'children') and ob.children:
for child in ob.children:
if is_renderable_or_parent(scene, child):
return True
return False
def is_data_renderable(scene, ob):
return (is_visible_layer(scene, ob) and not ob.hide_render and ob.type not in ('EMPTY', 'ARMATURE', 'LATTICE'))
def renderable_objects(scene):
return [ob for ob in scene.objects if (is_renderable(scene, ob) or is_data_renderable(scene, ob))]
# ------------- Archive Helpers -------------
# Generate an automatic path to write an archive when
# 'Export as Archive' is enabled
def auto_archive_path(paths, objects, create_folder=False):
filename = objects[0].name + ".rib"
if os.getenv("ARCHIVE") is not None:
archive_dir = os.getenv("ARCHIVE")
else:
archive_dir = os.path.join(paths['export_dir'], "archives")
if create_folder and not os.path.exists(archive_dir):
os.mkdir(archive_dir)
return os.path.join(archive_dir, filename)
def archive_objects(scene):
archive_obs = []
for ob in renderable_objects(scene):
# explicitly set
if ob.renderman.export_archive:
archive_obs.append(ob)
# particle instances
for psys in ob.particle_systems:
rm = psys.settings.renderman
if rm.particle_type == 'OBJECT':
try:
ob = bpy.data.objects[rm.particle_instance_object]
archive_obs.append(ob)
except:
pass
# dupli objects (TODO)
return archive_obs
# ------------- Data Access Helpers -------------
def get_subframes(segs, scene):
if segs == 0:
return []
min = -1.0
rm = scene.renderman
shutter_interval = rm.shutter_angle / 360.0
if rm.shutter_timing == 'CENTER':
min = 0 - .5 * shutter_interval
elif rm.shutter_timing == 'PRE':
min = 0 - shutter_interval
elif rm.shutter_timing == 'POST':
min = 0
return [min + i * shutter_interval / (segs - 1) for i in range(segs)]
def is_subd_last(ob):
return ob.modifiers and \
ob.modifiers[len(ob.modifiers) - 1].type == 'SUBSURF'
def is_subd_displace_last(ob):
if len(ob.modifiers) < 2:
return False
return (ob.modifiers[len(ob.modifiers) - 2].type == 'SUBSURF' and
ob.modifiers[len(ob.modifiers) - 1].type == 'DISPLACE')
def is_subdmesh(ob):
return (is_subd_last(ob) or is_subd_displace_last(ob))
# XXX do this better, perhaps by hooking into modifier type data in RNA?
# Currently assumes too much is deforming when it isn't
def is_deforming(ob):
deforming_modifiers = ['ARMATURE', 'MESH_SEQUENCE_CACHE', 'CAST', 'CLOTH', 'CURVE', 'DISPLACE',
'HOOK', 'LATTICE', 'MESH_DEFORM', 'SHRINKWRAP', 'EXPLODE',
'SIMPLE_DEFORM', 'SMOOTH', 'WAVE', 'SOFT_BODY',
'SURFACE', 'MESH_CACHE', 'FLUID_SIMULATION',
'DYNAMIC_PAINT']
if ob.modifiers:
# special cases for auto subd/displace detection
if len(ob.modifiers) == 1 and is_subd_last(ob):
return False
if len(ob.modifiers) == 2 and is_subd_displace_last(ob):
return False
for mod in ob.modifiers:
if mod.type in deforming_modifiers:
return True
if ob.data and hasattr(ob.data, 'shape_keys') and ob.data.shape_keys:
return True
return is_deforming_fluid(ob)
# handle special case of fluid sim a bit differently
def is_deforming_fluid(ob):
if ob.modifiers:
mod = ob.modifiers[len(ob.modifiers) - 1]
return mod.type == 'SMOKE' and mod.smoke_type == 'DOMAIN'
def psys_name(ob, psys):
return "%s.%s-%s" % (ob.name, psys.name, psys.settings.type)
# if we don't replace slashes could end up with them in file names
def fix_name(name):
return name.replace('/', '')
# get a name for the data block. if it's modified by the obj we need it
# specified
def data_name(ob, scene):
if not ob:
return ''
if not ob.data:
return fix_name(ob.name)
# if this is a blob return the family name
if ob.type == 'META':
return fix_name(ob.name.split('.')[0])
if is_smoke(ob) or ob.renderman.primitive == 'RI_VOLUME':
return "%s-VOLUME" % fix_name(ob.name)
if ob.data.users > 1 and (ob.is_modified(scene, "RENDER") or
ob.is_deform_modified(scene, "RENDER") or
ob.renderman.primitive != 'AUTO' or
(ob.renderman.motion_segments_override and
is_deforming(ob))):
return "%s.%s-MESH" % (fix_name(ob.name), fix_name(ob.data.name))
else:
return "%s-MESH" % fix_name(ob.data.name)
def get_name(ob):
return psys_name(ob) if type(ob) == bpy.types.ParticleSystem \
else fix_name(ob.data.name)
# ------------- Geometry Access -------------
def get_strands(scene, ob, psys, objectCorrectionMatrix=False):
# we need this to get st
if(objectCorrectionMatrix):
matrix = ob.matrix_world.inverted_safe()
loc, rot, sca = matrix.decompose()
psys_modifier = None
for mod in ob.modifiers:
if hasattr(mod, 'particle_system') and mod.particle_system == psys:
psys_modifier = mod
break
tip_width = psys.settings.cycles.tip_width * psys.settings.cycles.radius_scale
base_width = psys.settings.cycles.root_width * psys.settings.cycles.radius_scale
conwidth = (tip_width == base_width)
steps = 2 ** psys.settings.render_step
if conwidth:
widthString = "constantwidth"
hair_width = base_width
debug("info", widthString, hair_width)
else:
widthString = "vertex float width"
hair_width = []
psys.set_resolution(scene=scene, object=ob, resolution='RENDER')
num_parents = len(psys.particles)
num_children = len(psys.child_particles)
total_hair_count = num_parents + num_children
export_st = psys.settings.renderman.export_scalp_st and psys_modifier and len(
ob.data.uv_layers) > 0
curve_sets = []
points = []
vertsArray = []
scalpS = []
scalpT = []
nverts = 0
for pindex in range(total_hair_count):
if psys.settings.child_type != 'NONE' and pindex < num_parents:
continue
strand_points = []
# walk through each strand
for step in range(0, steps + 1):
pt = psys.co_hair(object=ob, particle_no=pindex, step=step)
if(objectCorrectionMatrix):
pt = pt + loc
if not pt.length_squared == 0:
strand_points.extend(pt)
else:
# this strand ends prematurely
break
if len(strand_points) > 1:
# double the first and last
strand_points = strand_points[:3] + \
strand_points + strand_points[-3:]
vertsInStrand = len(strand_points) // 3
# for varying width make the width array
if not conwidth:
decr = (base_width - tip_width) / (vertsInStrand - 2)
hair_width.extend([base_width] + [(base_width - decr * i)
for i in range(vertsInStrand - 2)] +
[tip_width])
# add the last point again
points.extend(strand_points)
vertsArray.append(vertsInStrand)
nverts += vertsInStrand
# get the scalp S
if export_st:
if pindex >= num_parents:
particle = psys.particles[
(pindex - num_parents) % num_parents]
else:
particle = psys.particles[pindex]
st = psys.uv_on_emitter(psys_modifier, particle, pindex)
scalpS.append(st[0])
scalpT.append(st[1])
# if we get more than 100000 vertices, export ri.Curve and reset. This
# is to avoid a maxint on the array length
if nverts > 100000:
curve_sets.append(
(vertsArray, points, widthString, hair_width, scalpS, scalpT))
nverts = 0
points = []
vertsArray = []
if not conwidth:
hair_width = []
scalpS = []
scalpT = []
if nverts > 0:
curve_sets.append((vertsArray, points, widthString,
hair_width, scalpS, scalpT))
psys.set_resolution(scene=scene, object=ob, resolution='PREVIEW')
return curve_sets
# only export particles that are alive,
# or have been born since the last frame
def valid_particle(pa, valid_frames):
return pa.die_time >= valid_frames[-1] and pa.birth_time <= valid_frames[0]
def get_particles(scene, ob, psys, valid_frames=None):
P = []
rot = []
width = []
valid_frames = (scene.frame_current,
scene.frame_current) if valid_frames is None else valid_frames
psys.set_resolution(scene, ob, 'RENDER')
for pa in [p for p in psys.particles if valid_particle(p, valid_frames)]:
P.extend(pa.location)
rot.extend(pa.rotation)
if pa.alive_state != 'ALIVE':
width.append(0.0)
else:
width.append(pa.size)
psys.set_resolution(scene, ob, 'PREVIEW')
return (P, rot, width)
def get_mesh(mesh, get_normals=False):
nverts = []
verts = []
P = []
N = []
for v in mesh.vertices:
P.extend(v.co)
for p in mesh.polygons:
nverts.append(p.loop_total)
verts.extend(p.vertices)
if get_normals:
if p.use_smooth:
for vi in p.vertices:
N.extend(mesh.vertices[vi].normal)
else:
N.extend(list(p.normal) * p.loop_total)
if len(verts) > 0:
P = P[:int(max(verts) + 1) * 3]
# return the P's minus any unconnected
return (nverts, verts, P, N)
# requires facevertex interpolation
def get_mesh_uv(mesh, name="", flipvmode='NONE'):
uvs = []
if not name:
uv_loop_layer = mesh.uv_layers.active
else:
# assuming uv loop layers and uv textures share identical indices
idx = mesh.uv_textures.keys().index(name)
uv_loop_layer = mesh.uv_layers[idx]
if uv_loop_layer is None:
return None
for uvloop in uv_loop_layer.data:
uvs.append(uvloop.uv.x)
# renderman expects UVs flipped vertically from blender
# best to do this in pattern, provided here as additional option
if flipvmode == 'UV':
uvs.append(1.0-uvloop.uv.y)
elif flipvmode == 'TILE':
uvs.append(math.ceil(uvloop.uv.y) - uvloop.uv.y + math.floor(uvloop.uv.y))
elif flipvmode == 'NONE':
uvs.append(uvloop.uv.y)
return uvs
# requires facevertex interpolation
def get_mesh_vcol(mesh, name=""):
vcol_layer = mesh.vertex_colors[name] if name != "" \
else mesh.vertex_colors.active
cols = []
if vcol_layer is None:
return None
for vcloop in vcol_layer.data:
cols.extend(vcloop.color)
return cols
# requires per-vertex interpolation
def get_mesh_vgroup(ob, mesh, name=""):
vgroup = ob.vertex_groups[name] if name != "" else ob.vertex_groups.active
weights = []
if vgroup is None:
return None
for v in mesh.vertices:
if len(v.groups) == 0:
weights.append(0.0)
else:
weights.extend([g.weight for g in v.groups
if g.group == vgroup.index])
return weights
# if a mesh has more than one material
def is_multi_material(mesh):
if type(mesh) != bpy.types.Mesh or len(mesh.materials) < 2 \
or len(mesh.polygons) == 0:
return False
first_mat = mesh.polygons[0].material_index
for p in mesh.polygons:
if p.material_index != first_mat:
return True
return False
def get_primvars(ob, geo, interpolation=""):
primvars = {}
if ob.type != 'MESH':
return primvars
rm = ob.data.renderman
interpolation = 'facevarying' if not interpolation else interpolation
# get material id if this is a multi-material mesh
if is_multi_material(geo):
primvars["uniform float material_id"] = rib([p.material_index
for p in geo.polygons])
if rm.export_default_uv:
uvs = get_mesh_uv(geo, flipvmode=rm.export_flipv)
if uvs and len(uvs) > 0:
primvars["%s float[2] st" % interpolation] = uvs
if rm.export_default_vcol:
vcols = get_mesh_vcol(geo)
if vcols and len(vcols) > 0:
primvars["%s color Cs" % interpolation] = rib(vcols)
# custom prim vars
for p in rm.prim_vars:
if p.data_source == 'VERTEX_COLOR':
vcols = get_mesh_vcol(geo, p.data_name)
if vcols and len(vcols) > 0:
primvars["%s color %s" % (interpolation, p.name)] = rib(vcols)
elif p.data_source == 'UV_TEXTURE':
uvs = get_mesh_uv(geo, p.data_name, flipvmode=rm.export_flipv)
if uvs and len(uvs) > 0:
primvars["%s float[2] %s" % (interpolation, p.name)] = uvs
elif p.data_source == 'VERTEX_GROUP':
weights = get_mesh_vgroup(ob, geo, p.data_name)
if weights and len(weights) > 0:
primvars["vertex float %s" % p.name] = weights
return primvars
def get_primvars_particle(scene, psys, subframes):
primvars = {}
rm = psys.settings.renderman
cfra = scene.frame_current
for p in rm.prim_vars:
pvars = []
if p.data_source in ('VELOCITY', 'ANGULAR_VELOCITY'):
if p.data_source == 'VELOCITY':
for pa in \
[p for p in psys.particles if valid_particle(p, subframes)]:
pvars.extend(pa.velocity)
elif p.data_source == 'ANGULAR_VELOCITY':
for pa in \
[p for p in psys.particles if valid_particle(p, subframes)]:
pvars.extend(pa.angular_velocity)
primvars["uniform float[3] %s" % p.name] = pvars
elif p.data_source in \
('SIZE', 'AGE', 'BIRTH_TIME', 'DIE_TIME', 'LIFE_TIME', 'ID'):
if p.data_source == 'SIZE':
for pa in \
[p for p in psys.particles if valid_particle(p, subframes)]:
pvars.append(pa.size)
elif p.data_source == 'AGE':
for pa in \
[p for p in psys.particles if valid_particle(p, subframes)]:
pvars.append((cfra - pa.birth_time) / pa.lifetime)
elif p.data_source == 'BIRTH_TIME':
for pa in \
[p for p in psys.particles if valid_particle(p, subframes)]:
pvars.append(pa.birth_time)
elif p.data_source == 'DIE_TIME':
for pa in \
[p for p in psys.particles if valid_particle(p, subframes)]:
pvars.append(pa.die_time)
elif p.data_source == 'LIFE_TIME':
for pa in \
[p for p in psys.particles if valid_particle(p, subframes)]:
pvars.append(pa.lifetime)
elif p.data_source == 'ID':
pvars = [id for id, p in psys.particles.items(
) if valid_particle(p, subframes)]
primvars["varying float %s" % p.name] = pvars
return primvars
def get_fluid_mesh(scene, ob):
subframe = scene.frame_subframe
fluidmod = [m for m in ob.modifiers if m.type == 'FLUID_SIMULATION'][0]
fluidmeshverts = fluidmod.settings.fluid_mesh_vertices
mesh = create_mesh(ob, scene)
(nverts, verts, P, N) = get_mesh(mesh)
removeMeshFromMemory(mesh.name)
# use fluid vertex velocity vectors to reconstruct moving points
P = [P[i] + fluidmeshverts[int(i / 3)].velocity[i % 3] * subframe * 0.5 for
i in range(len(P))]
return (nverts, verts, P, N)
def get_subd_creases(mesh):
creases = []
# only do creases 1 edge at a time for now,
# detecting chains might be tricky..
for e in mesh.edges:
if e.crease > 0.0:
creases.append((e.vertices[0], e.vertices[1],
e.crease * e.crease * 10))
# squared, to match blender appareance better
#: range 0 - 10 (infinitely sharp)
return creases
def create_mesh(ob, scene):
# 2 special cases to ignore:
# subsurf last or subsurf 2nd last +displace last
reset_subd_mod = False
if is_subd_last(ob) and ob.modifiers[len(ob.modifiers) - 1].show_render:
reset_subd_mod = True
ob.modifiers[len(ob.modifiers) - 1].show_render = False
# elif is_subd_displace_last(ob):
# ob.modifiers[len(ob.modifiers)-2].show_render = False
# ob.modifiers[len(ob.modifiers)-1].show_render = False
mesh = ob.to_mesh(scene, True, 'RENDER', calc_tessface=False,
calc_undeformed=True)
if reset_subd_mod:
ob.modifiers[len(ob.modifiers) - 1].show_render = True
return mesh
def modify_light_matrix(m, ob):
scale = [1.0, 1.0, 1.0]
if ob.data.type in ['AREA', 'SPOT', 'SUN']:
data = ob.data
m2 = Matrix.Rotation(math.radians(180), 4, 'X')
m = m * m2
if ob.data.type == 'AREA':
if data.renderman.area_shape == 'rect':
scale = [data.size, data.size_y, 1.0]
elif data.renderman.area_shape == 'disk':
scale = [data.size, data.size, 1.0]
elif data.renderman.area_shape == 'sphere':
# Force uniform scaling. First rebuild transform w/o scale
loc, rot, sca = m.decompose()
med = m.median_scale
m = (Matrix.Translation(loc) *
Matrix.Rotation(rot.angle, 4, rot.axis))
# Then factor in uniform approximation of old scale
scale = [data.size * med, data.size * med, data.size * med]
elif ob.data.type == 'SPOT':
scale = [0.01, 0.01, 1.0]
elif ob.data.type == 'POINT':
scale = [0.001, 0.001, 0.001]
m *= Matrix.Scale(scale[0], 4, (1.0, 0.0, 0.0))
m *= Matrix.Scale(scale[1], 4, (0.0, 1.0, 0.0))
m *= Matrix.Scale(scale[2], 4, (0.0, 0.0, 1.0))
if ob.data.type in ['HEMI']:
eul = m.to_euler()
eul = Euler([eul[0], eul[1], eul[2]], eul.order)
m = eul.to_matrix().to_4x4()
m = m * Matrix.Rotation(math.pi, 4, 'Z')
elif ob.data.renderman.renderman_type not in ["FILTER"]:
m = m * Matrix.Scale(-1.0, 4, (1, 0, 0))
return m
def export_transform(ri, instance, concat=False, flatten=False):
ob = instance.ob
export_motion_begin(ri, instance.motion_data)
if instance.transforming and len(instance.motion_data) > 0:
samples = [sample[1] for sample in instance.motion_data]
else:
samples = [ob.matrix_local] if ob.parent and ob.parent_type == "object" and ob.type != 'LAMP'\
else [ob.matrix_world]
for m in samples:
if instance.type == 'LAMP':
m = modify_light_matrix(m.copy(), ob)
if concat and ob.parent_type == "object":
ri.ConcatTransform(rib(m))
ri.ScopedCoordinateSystem(instance.ob.name)
else:
ri.Transform(rib(m))
ri.ScopedCoordinateSystem(instance.ob.name)
export_motion_end(ri, instance.motion_data)
def export_object_transform(ri, ob):
m = ob.parent.matrix_world * ob.matrix_local if ob.parent \
else ob.matrix_world
if ob.type == 'LAMP':
m = modify_light_matrix(m.copy(), ob)
ri.Transform(rib(m))
ri.ScopedCoordinateSystem(ob.name)
def export_light_source(ri, lamp):
names = {'POINT': 'PxrSphereLight', 'SUN': 'PxrDistantLight',
'SPOT': 'PxrDiskLight', 'HEMI': 'PxrDomeLight', 'AREA': 'PxrRectLight'}
params = {"float exposure": [lamp.energy * 5.0],
"__instanceid": lamp.name,
"color lightColor": rib(lamp.color)}
if lamp.type not in ['HEMI']:
params['int areaNormalize'] = 1
if lamp.type == 'SUN':
params["float exposure"] = 0
ri.Light(names[lamp.type], lamp.name, params)
def export_light_filters(ri, lamp, do_coordsys=False):
rm = lamp.renderman
for lf in rm.light_filters:
if lf.filter_name in bpy.data.objects:
light_filter = bpy.data.objects[lf.filter_name]
if do_coordsys:
ri.TransformBegin()
export_object_transform(ri, light_filter)
ri.TransformEnd()
filter_plugin = light_filter.data.renderman.get_light_node()
params = property_group_to_params(
filter_plugin, lamp=light_filter.data)
params['__instanceid'] = light_filter.name
params['string coordsys'] = light_filter.name
ri.LightFilter(light_filter.data.renderman.get_light_node_name(
), light_filter.data.name, params)
def export_light_shaders(ri, lamp, group_name='', portal_parent=''):
handle = lamp.name
rm = lamp.renderman
# need this for rerendering
ri.Attribute('identifier', {'string name': handle})
# do the shader
light_shader = rm.get_light_node()
if light_shader:
# make sure the shape is set on PxrStdAreaLightShape
params = property_group_to_params(light_shader)
params['__instanceid'] = handle
params['string lightGroup'] = group_name
if hasattr(light_shader, 'iesProfile'):
params['string iesProfile'] = bpy.path.abspath(
light_shader.iesProfile)
if lamp.type == 'SPOT':
params['float coneAngle'] = math.degrees(lamp.spot_size)
params['float coneSoftness'] = lamp.spot_blend
if lamp.type in ['SPOT', 'POINT']:
params['int areaNormalize'] = 1
if rm.renderman_type == 'PORTAL' and portal_parent and portal_parent.type == 'LAMP' \
and portal_parent.data.renderman.renderman_type == 'ENV':
parent_node = portal_parent.data.renderman.get_light_node()
parent_params = property_group_to_params(parent_node)
params['string domeSpace'] = portal_parent.name
params['string portalName'] = handle
params['string domeColorMap'] = parent_params[
'string lightColorMap']
if 'vector colorMapGamma' in params and params['vector colorMapGamma'] == (1.0, 1.0, 1.0):
params['vector colorMapGamma'] = parent_params[
'vector colorMapGamma']
if 'float colorMapSaturation' in params and params['float colorMapSaturation'] == 1.0:
params['float colorMapSaturation'] = parent_params[
'float colorMapSaturation']
params['float intensity'] = parent_params[
'float intensity'] * params['float intensityMult']
del params['float intensityMult']
params['float exposure'] = parent_params['float exposure']
params['color lightColor'] = [
i * j for i, j in zip(parent_params['color lightColor'], params['color tint'])]
del params['color tint']
if not params['int enableTemperature']:
params['int enableTemperature'] = parent_params[
'int enableTemperature']
params['float temperature'] = parent_params[
'float temperature']
params['float specular'] *= parent_params['float specular']
params['float diffuse'] *= parent_params['float diffuse']
primary_vis = rm.light_primary_visibility
ri.Attribute("visibility", {'int transmission': 0, 'int indirect': 0,
'int camera': int(primary_vis)})
ri.Light(rm.get_light_node_name(), handle, params)
else:
export_light_source(ri, lamp)
def export_world_rib(ri, world):
if world and world.renderman.world_rib_box != '':
export_rib_box(ri, world.renderman.world_rib_box)
def export_world(ri, world, do_geometry=True):
if not world:
return
rm = world.renderman
# if no shader do nothing!
if rm.use_renderman_node and rm.renderman_type == 'NONE':
return
params = []
ri.AttributeBegin()
world_type = rm.renderman_type if rm.use_renderman_node else 'ENV'
if do_geometry:
m = Matrix.Identity(4)
m = m * Matrix.Rotation(math.radians(180), 4, 'Y')
eul = m.to_euler()
eul = Euler([-eul[0], -eul[1], eul[2]], eul.order)
m = eul.to_matrix().to_4x4()
m2 = Matrix.Rotation(math.radians(180), 4, 'X')
m = m * m2
m = m * Matrix.Scale(-1.0, 4, (1, 0, 0))
ri.Transform(rib(m))
# No need to name Coordinate System system for world.
# ri.ShadingRate(rm.shadingrate)
handle = world.name
# need this for rerendering
ri.Attribute('identifier', {'string name': handle})
# do the light only if nodetree
# make sure the shape is set on PxrStdAreaLightShape
light_shader = rm.get_light_node()
if rm.use_renderman_node:
plugin_name = rm.get_light_node_name()
params = property_group_to_params(light_shader)
else:
plugin_name = "PxrDomeLight"
params = {'color lightColor': rib(world.horizon_color)}
ri.Attribute("visibility", {'int transmission': 0, 'int indirect': 0,
'int camera': int(rm.light_primary_visibility)})
ri.Light(plugin_name, handle, params)
ri.AttributeEnd()
ri.Illuminate(handle, rm.illuminates_by_default)
def get_light_group(light_ob):
scene_rm = bpy.context.scene.renderman
for lg in scene_rm.light_groups:
if lg.name != 'All' and light_ob.name in lg.members:
return lg.name
return ''
def export_light(ri, instance, instances):
ob = instance.ob
lamp = ob.data
rm = lamp.renderman
params = []
# if this is a filter just export the coord sys
if rm.renderman_type == 'FILTER':
ri.TransformBegin()
export_transform(ri, instance)
ri.TransformEnd()
else:
ri.AttributeBegin()
ri.Attribute("identifier", {"string name": lamp.name})
if rm.renderman_type == 'PORTAL' and ob.parent and ob.parent.type == 'LAMP' and \
ob.parent.data.renderman.renderman_type == 'ENV':
export_transform(ri, instances[ob.parent.name])
export_transform(ri, instance)
export_light_filters(ri, lamp)
child_portals = []
if rm.renderman_type == 'ENV' and ob.children:
child_portals = [child for child in ob.children if child.type == 'LAMP' and
child.data.renderman.renderman_type == 'PORTAL']
# if this is an env light and there are portals just do those instead
# of shader
if not child_portals:
export_light_shaders(ri, lamp, get_light_group(ob), ob.parent)
ri.AttributeEnd()
if not child_portals:
# illuminate if illumintaes and not muted
do_light = rm.illuminates_by_default and not rm.mute
if bpy.context.scene.renderman.solo_light:
# check if solo
do_light = do_light and rm.solo
ri.Illuminate(lamp.name, do_light)
for lf in rm.light_filters:
if lf.filter_name in bpy.data.objects:
filter = bpy.data.objects[lf.filter_name].data
ri.EnableLightFilter(lamp.name, filter.name,
filter.renderman.illuminates_by_default)
def export_material(ri, mat, handle=None, iterate_instance=False):
if mat is None:
return
rm = mat.renderman
if mat.node_tree:
export_shader_nodetree(
ri, mat, handle, disp_bound=rm.displacementbound,
iterate_instance=iterate_instance)
else:
export_shader(ri, mat)
def export_material_archive(ri, mat):
if mat:
ri.ReadArchive('material.' + get_mat_name(mat.name))
def export_motion_begin(ri, motion_data):
if len(motion_data) > 1:
ri.MotionBegin([sample[0] for sample in motion_data])
def export_motion_end(ri, motion_data):
if len(motion_data) > 1:
ri.MotionEnd()
def export_hair(ri, scene, ob, psys, data, objectCorrectionMatrix=False):
curves = data if data else get_strands(
scene, ob, psys, objectCorrectionMatrix)
for vertsArray, points, widthString, widths, scalpS, scalpT in curves:
params = {"P": rib(points), widthString: widths, 'uniform integer index': range(len(vertsArray))}
if len(scalpS):
params['uniform float scalpS'] = scalpS
params['uniform float scalpT'] = scalpT
ri.Curves("cubic", vertsArray, "nonperiodic", params)
def geometry_source_rib(ri, scene, ob):
rm = ob.renderman
anim = rm.archive_anim_settings
blender_frame = scene.frame_current
if rm.geometry_source == 'ARCHIVE':
archive_path = \
rib_path(get_sequence_path(rm.path_archive, blender_frame, anim))
ri.ReadArchive(archive_path)
else:
if rm.procedural_bounds == 'MANUAL':
min = rm.procedural_bounds_min
max = rm.procedural_bounds_max
bounds = [min[0], max[0], min[1], max[1], min[2], max[2]]
else:
bounds = rib_ob_bounds(ob.bound_box)
if rm.geometry_source == 'DELAYED_LOAD_ARCHIVE':
archive_path = rib_path(get_sequence_path(rm.path_archive,
blender_frame, anim))
ri.Procedural("DelayedReadArchive", archive_path, rib(bounds))
elif rm.geometry_source == 'PROCEDURAL_RUN_PROGRAM':
path_runprogram = rib_path(rm.path_runprogram)
ri.Procedural("RunProgram", [path_runprogram,
rm.path_runprogram_args],
rib(bounds))
elif rm.geometry_source == 'DYNAMIC_LOAD_DSO':
path_dso = rib_path(rm.path_dso)
ri.Procedural("DynamicLoad", [path_dso, rm.path_dso_initial_data],
rib(bounds))