forked from prman-pixar/RenderManForBlender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nodes_sg.py
2783 lines (2307 loc) · 113 KB
/
nodes_sg.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 _cycles
from bpy.app.handlers import persistent
import xml.etree.ElementTree as ET
import tempfile
import nodeitems_utils
import shutil
from bpy.props import *
from nodeitems_utils import NodeCategory, NodeItem
from .shader_parameters import class_generate_properties
from .shader_parameters import node_add_inputs
from .shader_parameters import node_add_outputs
from .shader_parameters import socket_map
from .shader_parameters import txmake_options, update_conditional_visops
from .util import args_files_in_path
from .util import get_path_list
from .util import rib
from .util import debug
from .util import user_path
from .util import get_real_path
from .util import readOSO
from .cycles_convert import *
from operator import attrgetter, itemgetter
import os.path
from time import sleep
import traceback
NODE_LAYOUT_SPLIT = 0.5
group_nodes = ['ShaderNodeGroup', 'NodeGroupInput', 'NodeGroupOutput']
# Default Types
# update node during ipr for a socket default_value
def update_func(self, context):
# check if this prop is set on an input
node = self.node if hasattr(self, 'node') else self
from . import engine
if engine.is_ipr_running():
engine.ipr.issue_shader_edits(node=node)
# socket name corresponds to the param on the node
class RendermanSocket:
ui_open = BoolProperty(name='UI Open', default=True)
def get_pretty_name(self, node):
if node.bl_idname in group_nodes:
return self.name
else:
return self.identifier
def get_value(self, node):
if node.bl_idname in group_nodes or not hasattr(node, self.name):
return self.default_value
else:
return getattr(node, self.name)
def draw_color(self, context, node):
return (0.25, 1.0, 0.25, 1.0)
def draw_value(self, context, layout, node):
layout.prop(node, self.identifier)
def draw(self, context, layout, node, text):
if self.is_linked or self.is_output or self.hide_value or not hasattr(self, 'default_value'):
layout.label(self.get_pretty_name(node))
elif node.bl_idname in group_nodes or node.bl_idname == "PxrOSLPatternNode":
layout.prop(self, 'default_value',
text=self.get_pretty_name(node), slider=True)
else:
layout.prop(node, self.name,
text=self.get_pretty_name(node), slider=True)
class RendermanSocketInterface:
def draw_color(self, context):
return (0.25, 1.0, 0.25, 1.0)
def draw(self, context, layout):
layout.label(self.name)
def from_socket(self, node, socket):
if hasattr(self, 'default_value'):
self.default_value = socket.get_value(node)
self.name = socket.name
def init_socket(self, node, socket, data_path):
sleep(.01)
socket.name = self.name
if hasattr(self, 'default_value'):
socket.default_value = self.default_value
# socket types (need this just for the ui_open)
class RendermanNodeSocketFloat(bpy.types.NodeSocketFloat, RendermanSocket):
'''RenderMan float input/output'''
bl_idname = 'RendermanNodeSocketFloat'
bl_label = 'RenderMan Float Socket'
default_value = FloatProperty(update=update_func)
renderman_type = StringProperty(default='float')
def draw_color(self, context, node):
return (0.5, 0.5, 0.5, 1.0)
class RendermanNodeSocketInterfaceFloat(bpy.types.NodeSocketInterfaceFloat, RendermanSocketInterface):
'''RenderMan float input/output'''
bl_idname = 'RendermanNodeSocketInterfaceFloat'
bl_label = 'RenderMan Float Socket'
bl_socket_idname = 'RendermanNodeSocketFloat'
default_value = FloatProperty()
def draw_color(self, context):
return (0.5, 0.5, 0.5, 1.0)
class RendermanNodeSocketInt(bpy.types.NodeSocketInt, RendermanSocket):
'''RenderMan int input/output'''
bl_idname = 'RendermanNodeSocketInt'
bl_label = 'RenderMan Int Socket'
default_value = IntProperty(update=update_func)
renderman_type = StringProperty(default='int')
def draw_color(self, context, node):
return (1.0, 1.0, 1.0, 1.0)
class RendermanNodeSocketInterfaceInt(bpy.types.NodeSocketInterfaceInt, RendermanSocketInterface):
'''RenderMan float input/output'''
bl_idname = 'RendermanNodeSocketInterfaceInt'
bl_label = 'RenderMan Int Socket'
bl_socket_idname = 'RendermanNodeSocketInt'
default_value = IntProperty()
def draw_color(self, context):
return (1.0, 1.0, 1.0, 1.0)
class RendermanNodeSocketString(bpy.types.NodeSocketString, RendermanSocket):
'''RenderMan string input/output'''
bl_idname = 'RendermanNodeSocketString'
bl_label = 'RenderMan String Socket'
default_value = StringProperty(update=update_func)
is_texture = BoolProperty(default=False)
renderman_type = StringProperty(default='string')
class RendermanNodeSocketStruct(bpy.types.NodeSocketString, RendermanSocket):
'''RenderMan struct input/output'''
bl_idname = 'RendermanNodeSocketStruct'
bl_label = 'RenderMan Struct Socket'
hide_value = True
renderman_type = 'string'
default_value = ''
class RendermanNodeSocketInterfaceStruct(bpy.types.NodeSocketInterfaceString, RendermanSocketInterface):
'''RenderMan struct input/output'''
bl_idname = 'RendermanNodeSocketInterfaceStruct'
bl_label = 'RenderMan Struct Socket'
bl_socket_idname = 'RendermanNodeSocketStruct'
hide_value = True
class RendermanNodeSocketColor(bpy.types.NodeSocketColor, RendermanSocket):
'''RenderMan color input/output'''
bl_idname = 'RendermanNodeSocketColor'
bl_label = 'RenderMan Color Socket'
default_value = FloatVectorProperty(size=3,
subtype="COLOR", update=update_func)
renderman_type = StringProperty(default='color')
def draw_color(self, context, node):
return (1.0, 1.0, .5, 1.0)
class RendermanNodeSocketInterfaceColor(bpy.types.NodeSocketInterfaceColor, RendermanSocketInterface):
'''RenderMan color input/output'''
bl_idname = 'RendermanNodeSocketInterfaceColor'
bl_label = 'RenderMan Color Socket'
bl_socket_idname = 'RendermanNodeSocketColor'
default_value = FloatVectorProperty(size=3,
subtype="COLOR")
def draw_color(self, context):
return (1.0, 1.0, .5, 1.0)
class RendermanNodeSocketVector(RendermanSocket, bpy.types.NodeSocketVector):
'''RenderMan vector input/output'''
bl_idname = 'RendermanNodeSocketVector'
bl_label = 'RenderMan Vector Socket'
hide_value = True
default_value = FloatVectorProperty(size=3,
subtype="EULER", update=update_func)
renderman_type = StringProperty(default='vector')
def draw_color(self, context, node):
return (.25, .25, .75, 1.0)
class RendermanNodeSocketInterfaceVector(bpy.types.NodeSocketInterfaceVector, RendermanSocketInterface):
'''RenderMan color input/output'''
bl_idname = 'RendermanNodeSocketInterfaceVector'
bl_label = 'RenderMan Vector Socket'
bl_socket_idname = 'RendermanNodeSocketVector'
hide_value = True
default_value = FloatVectorProperty(size=3,
subtype="EULER")
def draw_color(self, context):
return (.25, .25, .75, 1.0)
# Custom socket type for connecting shaders
class RendermanShaderSocket(bpy.types.NodeSocketShader, RendermanSocket):
'''RenderMan shader input/output'''
bl_idname = 'RendermanShaderSocket'
bl_label = 'RenderMan Shader Socket'
hide_value = True
# Custom socket type for connecting shaders
class RendermanShaderSocketInterface(bpy.types.NodeSocketInterfaceShader, RendermanSocketInterface):
'''RenderMan shader input/output'''
bl_idname = 'RendermanShaderInterfaceSocket'
bl_label = 'RenderMan Shader Socket'
bl_socket_idname = 'RendermanShaderSocket'
hide_value = True
# Base class for all custom nodes in this tree type.
# Defines a poll function to enable instantiation.
class RendermanShadingNode(bpy.types.ShaderNode):
bl_label = 'Output'
def update_mat(self, mat):
if self.renderman_node_type == 'bxdf' and self.outputs['Bxdf'].is_linked:
mat.specular_color = [1, 1, 1]
mat.diffuse_color = [1, 1, 1]
mat.use_transparency = False
mat.specular_intensity = 0
mat.diffuse_intensity = 1
if hasattr(self, "baseColor"):
mat.diffuse_color = self.baseColor
elif hasattr(self, "emitColor"):
mat.diffuse_color = self.emitColor
elif hasattr(self, "diffuseColor"):
mat.diffuse_color = self.diffuseColor
elif hasattr(self, "midColor"):
mat.diffuse_color = self.midColor
elif hasattr(self, "transmissionColor"):
mat.diffuse_color = self.transmissionColor
elif hasattr(self, "frontColor"):
mat.diffuse_color = self.frontColor
# specular intensity
if hasattr(self, "specular"):
mat.specular_intensity = self.specular
elif hasattr(self, "SpecularGainR"):
mat.specular_intensity = self.specularGainR
elif hasattr(self, "reflectionGain"):
mat.specular_intensity = self.reflectionGain
# specular color
if hasattr(self, "specularColor"):
mat.specular_color = self.specularColor
elif hasattr(self, "reflectionColor"):
mat.specular_color = self.reflectionColor
if self.bl_idname in ["PxrGlassBxdfNode", "PxrLMGlassBxdfNode"]:
mat.use_transparency = True
mat.alpha = .5
if self.bl_idname == "PxrLMMetalBxdfNode":
mat.diffuse_color = [0, 0, 0]
mat.specular_intensity = 1
mat.specular_color = self.specularColor
mat.mirror_color = [1, 1, 1]
elif self.bl_idname == "PxrLMPlasticBxdfNode":
mat.specular_intensity = 1
# all the properties of a shader will go here, also inputs/outputs
# on connectable props will have the same name
# node_props = None
def draw_buttons(self, context, layout):
self.draw_nonconnectable_props(context, layout, self.prop_names)
if self.bl_idname == "PxrOSLPatternNode":
layout.operator("node.refresh_osl_shader")
def draw_buttons_ext(self, context, layout):
self.draw_nonconnectable_props(context, layout, self.prop_names)
def draw_nonconnectable_props(self, context, layout, prop_names):
if self.bl_idname in ['PxrLayerPatternNode', 'PxrSurfaceBxdfNode']:
col = layout.column(align=True)
for prop_name in prop_names:
if prop_name not in self.inputs:
for name in getattr(self, prop_name):
if name.startswith('enable'):
col.prop(self, name, text=prop_name.split('.')[-1])
break
return
if self.bl_idname == "PxrOSLPatternNode" or self.bl_idname == "PxrSeExprPatternNode":
prop = getattr(self, "codetypeswitch")
layout.prop(self, "codetypeswitch")
if getattr(self, "codetypeswitch") == 'INT':
prop = getattr(self, "internalSearch")
layout.prop_search(
self, "internalSearch", bpy.data, "texts", text="")
elif getattr(self, "codetypeswitch") == 'EXT':
prop = getattr(self, "shadercode")
layout.prop(self, "shadercode")
elif getattr(self, "codetypeswitch") == 'NODE':
layout.prop(self, "expression")
else:
# temp until we can create ramps natively
if self.plugin_name == 'PxrRamp':
nt = bpy.data.node_groups[self.node_group]
if nt:
layout.template_color_ramp(
nt.nodes["ColorRamp"], 'color_ramp')
for prop_name in prop_names:
prop_meta = self.prop_meta[prop_name]
if 'widget' in prop_meta and prop_meta['widget'] == 'null' or \
'hidden' in prop_meta and prop_meta['hidden']:
continue
if prop_name not in self.inputs:
if prop_meta['renderman_type'] == 'page':
ui_prop = prop_name + "_uio"
ui_open = getattr(self, ui_prop)
icon = 'DISCLOSURE_TRI_DOWN' if ui_open \
else 'DISCLOSURE_TRI_RIGHT'
split = layout.split(NODE_LAYOUT_SPLIT)
row = split.row()
row.prop(self, ui_prop, icon=icon, text='',
icon_only=True, emboss=False, slider=True)
row.label(prop_name.split('.')[-1] + ':')
if ui_open:
prop = getattr(self, prop_name)
self.draw_nonconnectable_props(
context, layout, prop)
elif "Subset" in prop_name and prop_meta['type'] == 'string':
layout.prop_search(self, prop_name, bpy.data.scenes[0].renderman,
"object_groups")
else:
layout.prop(self, prop_name, slider=True)
def copy(self, node):
pass
# self.inputs.clear()
# self.outputs.clear()
def RefreshNodes(self, context, nodeOR=None, materialOverride=None):
# Compile shader. If the call was from socket draw get the node
# information anther way.
if hasattr(context, "node"):
node = context.node
else:
node = nodeOR
prefs = bpy.context.user_preferences.addons[__package__].preferences
out_path = user_path(prefs.env_vars.out)
compile_path = os.path.join(user_path(prefs.env_vars.out), "shaders")
if os.path.exists(out_path):
pass
else:
os.mkdir(out_path)
if os.path.exists(os.path.join(out_path, "shaders")):
pass
else:
os.mkdir(os.path.join(out_path, "shaders"))
if getattr(node, "codetypeswitch") == "EXT":
osl_path = user_path(getattr(node, 'shadercode'))
FileName = os.path.basename(osl_path)
FileNameNoEXT = os.path.splitext(FileName)[0]
FileNameOSO = FileNameNoEXT
FileNameOSO += ".oso"
export_path = os.path.join(
user_path(prefs.env_vars.out), "shaders", FileNameOSO)
if os.path.splitext(FileName)[1] == ".oso":
out_file = os.path.join(user_path(prefs.env_vars.out), "shaders", FileNameOSO)
if not os.path.exists(out_file) or not os.path.samefile(osl_path, out_file):
shutil.copy(osl_path, out_file)
# Assume that the user knows what they were doing when they
# compiled the osl file.
ok = True
else:
ok = node.compile_osl(osl_path, compile_path)
elif getattr(node, "codetypeswitch") == "INT" and node.internalSearch:
script = bpy.data.texts[node.internalSearch]
osl_path = bpy.path.abspath(
script.filepath, library=script.library)
if script.is_in_memory or script.is_dirty or \
script.is_modified or not os.path.exists(osl_path):
osl_file = tempfile.NamedTemporaryFile(
mode='w', suffix=".osl", delete=False)
osl_file.write(script.as_string())
osl_file.close()
FileNameNoEXT = os.path.splitext(script.name)[0]
FileNameOSO = FileNameNoEXT
FileNameOSO += ".oso"
node.plugin_name = FileNameNoEXT
ok = node.compile_osl(osl_file.name, compile_path, script.name)
export_path = os.path.join(
user_path(prefs.env_vars.out), "shaders", FileNameOSO)
os.remove(osl_file.name)
else:
ok = node.compile_osl(osl_path, compile_path)
FileName = os.path.basename(osl_path)
FileNameNoEXT = os.path.splitext(FileName)[0]
node.plugin_name = FileNameNoEXT
FileNameOSO = FileNameNoEXT
FileNameOSO += ".oso"
export_path = os.path.join(
user_path(prefs.env_vars.out), "shaders", FileNameOSO)
else:
ok = False
debug("osl", "Shader cannot be compiled. Shader name not specified")
# If Shader compiled successfully then update node.
if ok:
debug('osl', "Shader Compiled Successfully!")
# Reset the inputs and outputs
node.outputs.clear()
node.inputs.clear()
# Read in new properties
prop_names, shader_meta = readOSO(export_path)
debug('osl', prop_names, "MetaInfo: ", shader_meta)
# Set node name to shader name
node.label = shader_meta["shader"]
node.plugin_name = shader_meta["shader"]
# Generate new inputs and outputs
setattr(node, 'shader_meta', shader_meta)
node.setOslProps(prop_names, shader_meta)
else:
debug("osl", "NODE COMPILATION FAILED")
def compile_osl(self, inFile, outPath, nameOverride=""):
if not nameOverride:
FileName = os.path.basename(inFile)
FileNameNoEXT = os.path.splitext(FileName)[0]
out_file = os.path.join(outPath, FileNameNoEXT)
out_file += ".oso"
else:
FileNameNoEXT = os.path.splitext(nameOverride)[0]
out_file = os.path.join(outPath, FileNameNoEXT)
out_file += ".oso"
ok = _cycles.osl_compile(inFile, out_file)
return ok
def update(self):
debug("info", "UPDATING: ", self.name)
@classmethod
def poll(cls, ntree):
if hasattr(ntree, 'bl_idname'):
return ntree.bl_idname == 'ShaderNodeTree'
else:
return True
def setOslProps(self, prop_names, shader_meta):
for prop_name in prop_names:
prop_type = shader_meta[prop_name]["type"]
if shader_meta[prop_name]["IO"] == "out":
self.outputs.new(
socket_map[prop_type], prop_name)
else:
prop_default = shader_meta[prop_name]["default"]
if prop_type == "float":
prop_default = float(prop_default)
elif prop_type == "int":
prop_default = int(float(prop_default))
if prop_type == "matrix":
self.inputs.new(socket_map["struct"], prop_name, prop_name)
elif prop_type == "void":
pass
elif 'lockgeom' in shader_meta[prop_name] and shader_meta[prop_name]['lockgeom'] == 0:
pass
else:
input = self.inputs.new(socket_map[shader_meta[prop_name]["type"]],
prop_name, prop_name)
input.default_value = prop_default
if prop_type == 'struct' or prop_type == 'point':
input.hide_value = True
input.renderman_type = prop_type
debug('osl', "Shader: ", shader_meta["shader"], "Properties: ",
prop_names, "Shader meta data: ", shader_meta)
compileLocation = self.name + "Compile"
class RendermanOutputNode(RendermanShadingNode):
bl_label = 'RenderMan Material'
renderman_node_type = 'output'
bl_icon = 'MATERIAL'
node_tree = None
def init(self, context):
input = self.inputs.new('RendermanShaderSocket', 'Bxdf')
input.type = 'SHADER'
input.hide_value = True
input = self.inputs.new('RendermanShaderSocket', 'Light')
input.hide_value = True
input = self.inputs.new('RendermanShaderSocket', 'Displacement')
input.hide_value = True
def draw_buttons(self, context, layout):
return
def draw_buttons_ext(self, context, layout):
return
# when a connection is made or removed see if we're in IPR mode and issue
# updates
def update(self):
from . import engine
if engine.is_ipr_running():
engine.ipr.last_edit_mat = None
engine.ipr.issue_shader_edits(nt=self.id_data)
# Final output node, used as a dummy to find top level shaders
class RendermanBxdfNode(RendermanShadingNode):
bl_label = 'Bxdf'
renderman_node_type = 'bxdf'
shading_compatibility = {'NEW_SHADING'}
class RendermanDisplacementNode(RendermanShadingNode):
bl_label = 'Displacement'
renderman_node_type = 'displacement'
# Final output node, used as a dummy to find top level shaders
class RendermanPatternNode(RendermanShadingNode):
bl_label = 'Texture'
renderman_node_type = 'pattern'
bl_type = 'TEX_IMAGE'
bl_static_type = 'TEX_IMAGE'
class RendermanLightNode(RendermanShadingNode):
bl_label = 'Output'
renderman_node_type = 'light'
# Generate dynamic types
class RmanSgShadingExporter:
def __init__(self, **kwargs):
self.sgmngr = kwargs['sgmngr']
self.rman = kwargs['rman']
self.sg_scene = kwargs['sg_scene']
self.sg_root = kwargs['sg_root']
# blender scene and rpass
self.scene = kwargs['scene']
self.rpass = kwargs['rpass']
self.rm = self.scene.renderman
# for an input node output all "nodes"
def export_shader_nodetree(self, id, sg_node=None, mat_sg_handle=None, handle=None, iterate_instance=False):
if id and id.node_tree:
if is_renderman_nodetree(id):
portal = type(
id).__name__ == 'AreaLamp' and id.renderman.renderman_type == 'PORTAL'
# if id.renderman.nodetree not in bpy.data.node_groups:
# load_tree_from_lib(id)
nt = id.node_tree
if not handle:
handle = id.name
if type(id) == bpy.types.Material:
handle = get_mat_name(handle)
out = next((n for n in nt.nodes if hasattr(n, 'renderman_node_type') and
n.renderman_node_type == 'output'),
None)
if out is None:
return
#nodes_to_export = gather_nodes(out)
sg_material = None
bxdfList = []
dispList = []
if sg_node:
sg_material = sg_node
else:
sg_material = self.sg_scene.CreateMaterial(mat_sg_handle)
# bxdf
socket = out.inputs[0]
if socket.is_linked:
for sub_node in gather_nodes(socket.links[0].from_node):
shader_sg_nodes = shader_node_sg(self.sg_scene, self.rman, sub_node, mat_name=handle,
portal=portal)
for s in shader_sg_nodes:
bxdfList.append(s)
if bxdfList:
sg_material.SetBxdf(bxdfList)
# light
if len(out.inputs) > 1:
socket = out.inputs[1]
if socket.is_linked:
for sub_node in gather_nodes(socket.links[0].from_node):
shader_sg_nodes = shader_node_sg(self.sg_scene, self.rman, sub_node, mat_name=handle,
portal=portal)
shader_sg_node = shader_sg_nodes[0]
if shader_sg_node.GetName().CStr() == "PxrMeshLight":
sg_material.SetLight(shader_sg_node)
break
# displacement
if len(out.inputs) > 2:
socket = out.inputs[2]
if socket.is_linked:
for sub_node in gather_nodes(socket.links[0].from_node):
shader_sg_nodes = shader_node_sg(self.sg_scene, self.rman, sub_node, mat_name=handle,
portal=portal)
for s in shader_sg_nodes:
dispList.append(s)
if dispList:
sg_material.SetDisplace(dispList)
return (sg_material, bxdfList)
elif find_node(id, 'ShaderNodeOutputMaterial'):
#print("Error Material %s needs a RenderMan BXDF" % id.name)
return (None, None)
def export_simple_shader(self, mat, sg_node=None, mat_handle=''):
rm = mat.renderman
# if rm.surface_shaders.active == '' or not rpass.surface_shaders: return
name = mat_handle
if name == '':
name = 'material.%s' % get_mat_name(mat.name)
sg_material = None
if sg_node:
sg_material = sg_node
else:
sg_material = self.sg_scene.CreateMaterial(name)
bxdf_name = '%s.PxrDisney' % name
sg_node = self.sg_scene.CreateNode("BxdfFactory", "PxrDisney", bxdf_name)
rix_params = sg_node.EditParameterBegin()
rix_params.SetColor('baseColor', rib(mat.diffuse_color))
rix_params.SetFloat('specular', mat.specular_intensity )
if mat.emit:
rix_params.SetColor("emitColor", rib(mat.diffuse_color))
if mat.subsurface_scattering:
rix_params.SetFloat("subsurface", mat.subsurface_scattering.scale)
rix_params.SetColor("subsurfaceColor", rib(mat.subsurface_scattering.color))
sg_node.EditParameterEnd(rix_params)
sg_material.SetBxdf([sg_node])
return sg_material
def set_rix_param(params, param_type, param_name, val, is_reference=False):
if is_reference:
if param_type == "float":
params.ReferenceFloat(param_name, val)
elif param_type == "int":
params.ReferenceInteger(param_name, val)
elif param_type == "color":
params.ReferenceColor(param_name, val)
elif param_type == "point":
params.ReferencePoint(param_name, val)
elif param_type == "vector":
params.ReferenceVector(param_name, val)
elif param_type == "normal":
params.ReferenceNormal(param_name, val)
else:
if param_type == "float":
params.SetFloat(param_name, val)
elif param_type == "int":
params.SetInteger(param_name, val)
elif param_type == "color":
params.SetColor(param_name, val)
elif param_type == "string":
params.SetString(param_name, val)
elif param_type == "point":
params.SetPoint(param_name, val)
elif param_type == "vector":
params.SetVector(param_name, val)
elif param_type == "normal":
params.SetNormal(param_name, val)
def generate_node_type(prefs, name, args):
''' Dynamically generate a node type from pattern '''
nodeType = args.find("shaderType/tag").attrib['value']
typename = '%s%sNode' % (name, nodeType.capitalize())
nodeDict = {'bxdf': RendermanBxdfNode,
'pattern': RendermanPatternNode,
'displacement': RendermanDisplacementNode,
'light': RendermanLightNode}
if nodeType not in nodeDict.keys():
return
ntype = type(typename, (nodeDict[nodeType],), {})
ntype.bl_label = name
ntype.typename = typename
inputs = [p for p in args.findall('./param')] + \
[p for p in args.findall('./page')]
outputs = [p for p in args.findall('.//output')]
def init(self, context):
if self.renderman_node_type == 'bxdf':
self.outputs.new('RendermanShaderSocket', "Bxdf").type = 'SHADER'
#socket_template = self.socket_templates.new(identifier='Bxdf', name='Bxdf', type='SHADER')
node_add_inputs(self, name, self.prop_names)
node_add_outputs(self)
# if this is PxrLayerSurface set the diffusegain to 0. The default
# of 1 is unintuitive
if self.plugin_name == 'PxrLayerSurface':
self.diffuseGain = 0
elif self.renderman_node_type == 'light':
# only make a few sockets connectable
node_add_inputs(self, name, self.prop_names)
self.outputs.new('RendermanShaderSocket', "Light")
elif self.renderman_node_type == 'displacement':
# only make the color connectable
self.outputs.new('RendermanShaderSocket', "Displacement")
node_add_inputs(self, name, self.prop_names)
# else pattern
elif name == "PxrOSL":
self.outputs.clear()
else:
node_add_inputs(self, name, self.prop_names)
node_add_outputs(self)
if name == "PxrRamp":
node_group = bpy.data.node_groups.new(
'PxrRamp_nodegroup', 'ShaderNodeTree')
node_group.nodes.new('ShaderNodeValToRGB')
node_group.use_fake_user = True
self.node_group = node_group.name
update_conditional_visops(self)
def free(self):
if name == "PxrRamp":
bpy.data.node_groups.remove(bpy.data.node_groups[self.node_group])
ntype.init = init
ntype.free = free
if name == 'PxrRamp':
ntype.node_group = StringProperty('color_ramp', default='')
ntype.plugin_name = StringProperty(name='Plugin Name',
default=name, options={'HIDDEN'})
# lights cant connect to a node tree in 20.0
class_generate_properties(ntype, name, inputs + outputs)
if nodeType == 'light':
ntype.light_shading_rate = FloatProperty(
name="Light Shading Rate",
description="Shading Rate for this light. \
Leave this high unless detail is missing",
default=100.0)
ntype.light_primary_visibility = BoolProperty(
name="Light Primary Visibility",
description="Camera visibility for this light",
default=True)
bpy.utils.register_class(ntype)
return typename, ntype
# UI
def find_node_input(node, name):
for input in node.inputs:
if input.name == name:
return input
return None
def find_node(material, nodetype):
if material and material.node_tree:
ntree = material.node_tree
active_output_node = None
for node in ntree.nodes:
if getattr(node, "bl_idname", None) == nodetype:
if getattr(node, "is_active_output", True):
return node
if not active_output_node:
active_output_node = node
return active_output_node
return None
def find_node_input(node, name):
for input in node.inputs:
if input.name == name:
return input
return None
def panel_node_draw(layout, context, id_data, output_type, input_name):
ntree = id_data.node_tree
node = find_node(id_data, output_type)
if not node:
layout.label(text="No output node")
else:
input = find_node_input(node, input_name)
#layout.template_node_view(ntree, node, input)
draw_nodes_properties_ui(layout, context, ntree)
return True
def is_renderman_nodetree(material):
return find_node(material, 'RendermanOutputNode')
def draw_nodes_properties_ui(layout, context, nt, input_name='Bxdf',
output_node_type="output"):
output_node = next((n for n in nt.nodes
if hasattr(n, 'renderman_node_type') and n.renderman_node_type == output_node_type), None)
if output_node is None:
return
socket = output_node.inputs[input_name]
node = socket_node_input(nt, socket)
layout.context_pointer_set("nodetree", nt)
layout.context_pointer_set("node", output_node)
layout.context_pointer_set("socket", socket)
split = layout.split(0.35)
split.label(socket.name + ':')
if socket.is_linked:
# for lights draw the shading rate ui.
split.operator_menu_enum("node.add_%s" % input_name.lower(),
"node_type", text=node.bl_label)
else:
split.operator_menu_enum("node.add_%s" % input_name.lower(),
"node_type", text='None')
if node is not None:
draw_node_properties_recursive(layout, context, nt, node)
def socket_node_input(nt, socket):
return next((l.from_node for l in nt.links if l.to_socket == socket), None)
def socket_socket_input(nt, socket):
return next((l.from_socket for l in nt.links if l.to_socket == socket and socket.is_linked),
None)
def linked_sockets(sockets):
if sockets is None:
return []
return [i for i in sockets if i.is_linked]
def draw_node_properties_recursive(layout, context, nt, node, level=0):
def indented_label(layout, label, level):
for i in range(level):
layout.label('', icon='BLANK1')
if label:
layout.label(label)
layout.context_pointer_set("node", node)
layout.context_pointer_set("nodetree", nt)
def draw_props(prop_names, layout, level):
for prop_name in prop_names:
# skip showing the shape for PxrStdAreaLight
if prop_name in ["lightGroup", "rman__Shape", "coneAngle", "penumbraAngle"]:
continue
if prop_name == "codetypeswitch":
row = layout.row()
if node.codetypeswitch == 'INT':
row.prop_search(node, "internalSearch",
bpy.data, "texts", text="")
elif node.codetypeswitch == 'EXT':
row.prop(node, "shadercode")
elif prop_name == "internalSearch" or prop_name == "shadercode" or prop_name == "expression":
pass
else:
prop_meta = node.prop_meta[prop_name]
prop = getattr(node, prop_name)
if 'widget' in prop_meta and prop_meta['widget'] == 'null' or \
'hidden' in prop_meta and prop_meta['hidden']:
continue
# else check if the socket with this name is connected
socket = node.inputs[prop_name] if prop_name in node.inputs \
else None
layout.context_pointer_set("socket", socket)
if socket and socket.is_linked:
input_node = socket_node_input(nt, socket)
icon = 'DISCLOSURE_TRI_DOWN' if socket.ui_open \
else 'DISCLOSURE_TRI_RIGHT'
split = layout.split(NODE_LAYOUT_SPLIT)
row = split.row()
indented_label(row, None, level)
row.prop(socket, "ui_open", icon=icon, text='',
icon_only=True, emboss=False)
label = prop_meta.get('label', prop_name)
row.label(label + ':')
if ('type' in prop_meta and prop_meta['type'] == 'vstruct') or prop_name == 'inputMaterial':
split.operator_menu_enum("node.add_layer", "node_type",
text=input_node.bl_label, icon="LAYER_USED")
elif prop_meta['renderman_type'] == 'struct':
split.operator_menu_enum("node.add_manifold", "node_type",
text=input_node.bl_label, icon="LAYER_USED")
elif prop_meta['renderman_type'] == 'normal':
split.operator_menu_enum("node.add_bump", "node_type",
text=input_node.bl_label, icon="LAYER_USED")
else:
split.operator_menu_enum("node.add_pattern", "node_type",
text=input_node.bl_label, icon="LAYER_USED")
if socket.ui_open:
draw_node_properties_recursive(layout, context, nt,
input_node, level=level + 1)
else:
row = layout.row(align=True)
if prop_meta['renderman_type'] == 'page':