forked from 0xafbf/blender-datasmith-export
-
Notifications
You must be signed in to change notification settings - Fork 1
/
export_datasmith.py
2477 lines (2060 loc) · 76.3 KB
/
export_datasmith.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
# Copyright Andrés Botero 2019
import bpy
import idprop
import bmesh
import math
import os
import time
import hashlib
import shutil
from os import path
from .data_types import UDMesh, Node, sanitize_name
from mathutils import Matrix, Vector, Euler
import logging
log = logging.getLogger("bl_datasmith")
matrix_datasmith = Matrix.Scale(100, 4)
matrix_datasmith[1][1] *= -1.0
matrix_normals = [
[1, 0, 0],
[0, -1, 0],
[0, 0, 1],
]
# used for lights and cameras, whose forward is (0, 0, -1) and its right is (1, 0, 0)
matrix_forward = Matrix((
(0, 1, 0, 0),
(0, 0, -1, 0),
(-1, 0, 0, 0),
(0, 0, 0, 1)
))
def exp_vector(value, exp_list):
# n = Node("Color", {
# nocheckin: may not work
n = Node("Color", {
# "Name": name,
"constant": "(R=%.6f,G=%.6f,B=%.6f,A=1.0)"%tuple(value)
})
return exp_list.push(n)
def exp_color(value, exp_list, name=None):
n = Node("Color", {
"constant": "(R=%.6f,G=%.6f,B=%.6f,A=%.6f)"%tuple(value)
})
if name:
n["Name"] = name
return exp_list.push(n)
def exp_scalar(value, exp_list):
n = Node("Scalar", {
# "Name": "",
"constant": "%f"%value
})
return exp_list.push(n)
def exp_texcoord(exp_list, index=0, u_tiling=1.0, v_tiling=1.0):
n = Node("TextureCoordinate")
n["Index"] = index
n["UTiling"] = u_tiling
n["VTiling"] = v_tiling
pad = Node("AppendVector")
pad.push(Node("0", {"expression": exp_list.push(n) }))
zero = exp_scalar(0, exp_list)
pad.push(Node("1", {"expression": zero }))
return {"expression": exp_list.push(pad) }
def exp_texcoord_node(socket, exp_list):
socket_name = socket.name
if socket_name == "Generated":
n = Node("FunctionCall", { "Function": "/Engine/Functions/Engine_MaterialFunctions02/UVs/BoundingBoxBased_0-1_UVW"})
return { "expression": exp_list.push(n) }
# if socket_name == "Normal":
if socket_name == "UV":
return exp_texcoord(exp_list)
if socket_name == "Object":
n = Node("FunctionCall", { "Function": op_custom_functions["LOCAL_POSITION"]})
return { "expression": exp_list.push(n) }
# if socket_name == "Camera":
# `position from camera in camera space (blue is camera forward, green is camera up`
# if socket_name == "Window":
# seems to be viewport coordinates
# if socket_name == "Reflection":
# direction of reflection in world coordinates
log.warn("Texcoord node doesn't implement %s yet" % socket_name)
def exp_tex_noise(socket, exp_list):
# default if socket.name == "Fac"
function_path = "/DatasmithBlenderContent/MaterialFunctions/TexNoise"
out_socket = 0
if socket.name == "Color":
out_socket = 1
n = Node("FunctionCall", { "Function": function_path})
exp_1 = get_expression(socket.node.inputs['Vector'], exp_list)
exp_2 = get_expression(socket.node.inputs['Scale'], exp_list)
if exp_1:
n.push(Node("0", exp_1))
n.push(Node("1", exp_2))
return { "expression": exp_list.push(n), "OutputIndex":out_socket }
def exp_tex_checker(socket, exp_list):
if socket.node in cached_nodes:
exp = { "expression": cached_nodes[socket.node] }
else:
exp = exp_function_call(
"/DatasmithBlenderContent/MaterialFunctions/TexChecker",
exp_list=exp_list,
inputs=socket.node.inputs,
force_default=True,
)
cached_nodes[socket.node] = exp["expression"]
# could be faster by comparing to constants instead?
exp["OutputIndex"] = socket.node.outputs.find(socket.name)
return exp
def exp_uvmap(node, exp_list):
channel_name = node.uv_map
owner = datasmith_context["material_owner"]
uv_index = 0
m = owner.data
if type(m) is bpy.types.Mesh:
for idx, uv in enumerate(m.uv_layers):
if uv.name == id:
uv_index = idx
return exp_texcoord(exp_list, uv_index)
# instead of setting coordinates here, use coordinates when creating
# the texture expression instead
def exp_texture(path, name=None): # , tex_coord_exp):
n = Node("Texture")
if name:
n["Name"] = name
n["PathName"] = path
#n.push(Node("Coordinates", tex_coord_exp))
return n
def exp_rgb_to_bw(socket, exp_list):
input_exp = get_expression(socket.node.inputs[0], exp_list)
n = Node("DotProduct")
n.push(Node("0", input_exp))
exp_1 = exp_vector( (0.2126, 0.7152, 0.0722), exp_list )
n.push( Node( "1", { "expression": exp_1 } ) )
dot_exp = exp_list.push(n)
return { "expression": dot_exp }
def exp_make_vec3(socket, exp_list):
node = socket.node
output = Node("FunctionCall", { "Function": "/Engine/Functions/Engine_MaterialFunctions02/Utility/MakeFloat3" })
output.push(Node("0", get_expression(node.inputs[0], exp_list)))
output.push(Node("1", get_expression(node.inputs[1], exp_list)))
output.push(Node("2", get_expression(node.inputs[2], exp_list)))
return { "expression": exp_list.push(output) }
def exp_make_hsv(socket, exp_list):
vec3_input = exp_make_vec3(socket, exp_list)
output = Node("FunctionCall", { "Function": "/DatasmithBlenderContent/MaterialFunctions/HSV_To_RGB" })
output.push(Node("0", vec3_input))
return { "expression": exp_list.push(output) }
def exp_break_vec3(socket, exp_list):
expression_idx = -1
if socket.node in cached_nodes:
expression_idx = cached_nodes[socket.node]
else:
output = Node("FunctionCall", { "Function": "/Engine/Functions/Engine_MaterialFunctions02/Utility/BreakOutFloat3Components" })
output.push(Node("0", get_expression(socket.node.inputs[0], exp_list)))
expression_idx = exp_list.push(output)
cached_nodes[socket.node] = expression_idx
output_index = socket.node.outputs.find(socket.name) # could be faster by comparing to constants instead?
return { "expression": expression_idx, "OutputIndex": output_index }
def exp_break_hsv(socket, exp_list):
expression_idx = -1
if socket.node in cached_nodes:
expression_idx = cached_nodes[socket.node]
else:
input = Node("FunctionCall", { "Function": "/DatasmithBlenderContent/MaterialFunctions/RGB_To_HSV" })
hsv_expression_idx = input.push(Node("0", get_expression(socket.node.inputs[0], exp_list)))
output = Node("FunctionCall", { "Function": "/Engine/Functions/Engine_MaterialFunctions02/Utility/BreakOutFloat3Components" })
output.push(Node("0", { "expression": hsv_expression_idx }))
expression_idx = exp_list.push(output)
cached_nodes[socket.node] = expression_idx
output_index = socket.node.outputs.find(socket.name) # could be faster by comparing to constants instead?
return { "expression": expression_idx, "OutputIndex": output_index }
MATH_CUSTOM_FUNCTIONS = {
'INVERSE_SQRT': (1, "/DatasmithBlenderContent/MaterialFunctions/MathInvSqrt"),
'EXPONENT': (1, "/DatasmithBlenderContent/MaterialFunctions/MathExp"),
'SINH': (1, "/DatasmithBlenderContent/MaterialFunctions/MathSinH"),
'COSH': (1, "/DatasmithBlenderContent/MaterialFunctions/MathCosH"),
'TANH': (1, "/DatasmithBlenderContent/MaterialFunctions/MathTanH"),
'MULTIPLY_ADD': (3, "/DatasmithBlenderContent/MaterialFunctions/MathMultiplyAdd"),
'COMPARE': (3, "/DatasmithBlenderContent/MaterialFunctions/MathCompare"),
'SMOOTH_MIN': (3, "/DatasmithBlenderContent/MaterialFunctions/MathSmoothMin"),
'SMOOTH_MAX': (3, "/DatasmithBlenderContent/MaterialFunctions/MathSmoothMax"),
'WRAP': (3, "/DatasmithBlenderContent/MaterialFunctions/MathWrap"),
'SNAP': (2, "/DatasmithBlenderContent/MaterialFunctions/MathSnap"),
'PINGPONG': (2, "/DatasmithBlenderContent/MaterialFunctions/MathPingPong"),
}
# these map 1:1 with UE4 nodes:
MATH_TWO_INPUTS = {
'ADD': "Add",
'SUBTRACT': "Subtract",
'MULTIPLY': "Multiply",
'DIVIDE': "Divide",
'POWER': "Power",
'MINIMUM': "Min",
'MAXIMUM': "Max",
'MODULO': "Fmod",
'ARCTAN2': "Arctangent2",
}
# these use only one input in UE4
MATH_ONE_INPUT = {
'SQRT': "SquareRoot",
'ABSOLUTE': "Abs",
'ROUND': "Round",
'FLOOR': "Floor",
'CEIL': "Ceil",
'FRACT': "Frac",
'SINE': "Sine",
'COSINE': "Cosine",
'TANGENT': "Tangent",
'ARCSINE': "Arcsine",
'ARCCOSINE': "Arccosine",
'ARCTANGENT': "Arctangent",
'SIGN': "Sign",
'TRUNC': "Truncate",
}
# these require specific implementations:
MATH_CUSTOM_IMPL = {
'LOGARITHM', # ue4 only has log2 and log10
'LESS_THAN', # use UE4 If node
'GREATER_THAN', # use UE4 If node
'RADIANS',
'DEGREES',
}
def exp_generic(name, inputs, exp_list, force_default=False):
n = Node(name)
for idx, input in enumerate(inputs):
input_exp = get_expression(input, exp_list, force_default)
n.push(Node(str(idx), input_exp))
return { "expression": exp_list.push(n) }
def exp_function_call(path, inputs, exp_list, force_default=False):
n = Node("FunctionCall", {"Function": path})
for idx, input in enumerate(inputs):
input_exp = get_expression(input, exp_list, force_default)
n.push(Node(str(idx), input_exp))
return { "expression": exp_list.push(n) }
def exp_math(node, exp_list):
op = node.operation
exp = None
if op in MATH_TWO_INPUTS:
exp = exp_generic(
name= MATH_TWO_INPUTS[op],
inputs= node.inputs[:2],
exp_list=exp_list,
force_default=True,
)
elif op in MATH_ONE_INPUT:
exp = exp_generic(
name= MATH_ONE_INPUT[op],
inputs= node.inputs[:1],
exp_list=exp_list,
force_default=True,
)
elif op in MATH_CUSTOM_FUNCTIONS:
size, path = MATH_CUSTOM_FUNCTIONS[op]
exp = exp_function_call(
path,
inputs= node.inputs[:size],
exp_list=exp_list,
)
elif op in MATH_CUSTOM_IMPL:
in_0 = get_expression(node.inputs[0], exp_list)
n = None
if op == 'RADIANS':
n = Node("Multiply")
n.push(Node("0", in_0))
n.push(Node("1", { "expression": exp_scalar(math.tau / 360, exp_list)}))
elif op == 'DEGREES':
n = Node("Multiply")
n.push(Node("0", in_0))
n.push(Node("1", { "expression": exp_scalar(360 / math.tau, exp_list)}))
else:
# these use two inputs
in_1 = get_expression(node.inputs[1], exp_list)
if op == 'LOGARITHM': # take two logarithms and divide
log0 = Node("Logarithm2")
log0.push(Node("0", in_0))
exp_0 = exp_list.push(log0)
log1 = Node("Logarithm2")
log1.push(Node("0", in_1))
exp_1 = exp_list.push(log1)
n = Node("Divide")
n.push(Node("0", {"expression": exp_0}))
n.push(Node("1", {"expression": exp_1}))
elif op == 'LESS_THAN':
n = Node("If")
one = {"expression": exp_scalar(1.0, exp_list)}
zero = {"expression": exp_scalar(0.0, exp_list)}
n.push(Node("0", in_0)) # A
n.push(Node("1", in_1)) # B
n.push(Node("2", zero)) # A > B
n.push(Node("3", one)) # A == B
n.push(Node("4", one)) # A < B
elif op == 'GREATER_THAN':
n = Node("If")
one = {"expression": exp_scalar(1.0, exp_list)}
zero = {"expression": exp_scalar(0.0, exp_list)}
n.push(Node("0", in_0)) # A
n.push(Node("1", in_1)) # B
n.push(Node("2", one)) # A > B
n.push(Node("3", zero)) # A == B
n.push(Node("4", zero)) # A < B
assert n
exp = { "expression": exp_list.push(n) }
assert exp, "unrecognized math operation: %s" % op
if getattr(node, "use_clamp", False):
clamp = Node("Saturate")
clamp.push(Node("0", exp))
exp = { "expression": exp_list.push(clamp) }
return exp
# these nodes should only be built-ins (green nodes)
VECT_MATH_SAME_AS_SCALAR = {
'ADD',
'SUBTRACT',
'MULTIPLY',
'DIVIDE',
'ABSOLUTE',
'MINIMUM',
'MAXIMUM',
'FLOOR',
'CEIL',
'MODULO',
'SINE',
'COSINE',
'TANGENT',
}
VECT_MATH_NODES = {
'CROSS_PRODUCT': (2, "CrossProduct"),
'DOT_PRODUCT': (2, "DotProduct"),
'DISTANCE': (2, "Distance"),
'NORMALIZE': (1, "Normalize"),
'FRACTION': (1, "Frac"),
}
VECT_MATH_FUNCTIONS = { # tuples are (input_count, path)
'WRAP': (3, "/DatasmithBlenderContent/MaterialFunctions/VectWrap"),
'SNAP': (2, "/DatasmithBlenderContent/MaterialFunctions/VectSnap"),
'PROJECT': (2, "/DatasmithBlenderContent/MaterialFunctions/VectProject"),
'REFLECT': (2, "/DatasmithBlenderContent/MaterialFunctions/VectReflect"),
}
def exp_vect_math(node, exp_list):
node_op = node.operation
if node_op in VECT_MATH_SAME_AS_SCALAR:
return exp_math(node, exp_list)
elif node_op in VECT_MATH_NODES:
size, name = VECT_MATH_NODES[node_op]
return exp_generic(
name=name,
inputs=node.inputs[:size],
exp_list=exp_list,
force_default=True,
)
elif node_op in VECT_MATH_FUNCTIONS:
size, path = VECT_MATH_FUNCTIONS[node_op]
return exp_function_call(
path,
inputs= node.inputs[:size],
exp_list=exp_list,
force_default=True,
)
elif node_op == 'SCALE':
return exp_generic(
name= "Multiply",
inputs= (node.inputs[0], node.inputs[3]),
exp_list=exp_list,
force_default=True,
)
elif node_op == 'LENGTH':
n = Node("Distance")
n.push(Node("0", get_expression(node.inputs[0], exp_list) ))
n.push(Node("1", { "expression": exp_vector((0,0,0), exp_list) } ))
return { "expression": exp_list.push(n) }
log.error("VECT_MATH node operation:%s not found" % node_op)
# TODO: make test cases for all math nodes
def exp_gamma(node, exp_list):
n = Node(MATH_TWO_INPUTS['POWER'])
exp_0 = get_expression(node.inputs["Color"], exp_list)
n.push(Node("0", exp_0))
exp_1 = get_expression(node.inputs["Gamma"], exp_list)
n.push(Node("1", exp_1))
return {"expression": exp_list.push(n)}
op_map_color = {
# MIX is handled manually
'DARKEN': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_Darken",
# MULTIPLY is handled in MATH_TWO_INPUTS
'BURN': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_ColorBurn",
# TODO: check for blender implementation of burn, it could mean this:
#'BURN': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_LinearBurn",
'LIGHTEN': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_Lighten",
'SCREEN': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_Screen",
'DODGE': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_ColorDodge",
'OVERLAY': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_Overlay",
# ADD is handled in MATH_TWO_INPUTS
'SOFT_LIGHT': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_SoftLight",
'LINEAR_LIGHT': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_LinearLight",
'DIFFERENCE': "/Engine/Functions/Engine_MaterialFunctions03/Blends/Blend_Difference",
# SUBTRACT is handled in MATH_TWO_INPUTS
# DIVIDE is handled in MATH_TWO_INPUTS
'HUE': "/DatasmithBlenderContent/MaterialFunctions/Blend_Hue",
'SATURATION': "/DatasmithBlenderContent/MaterialFunctions/Blend_Saturation",
'COLOR': "/DatasmithBlenderContent/MaterialFunctions/Blend_Color",
'VALUE': "/DatasmithBlenderContent/MaterialFunctions/Blend_Value",
}
def exp_blend(exp_0, exp_1, blend_type, exp_list):
if blend_type == 'MIX':
return exp_1
n = None
if blend_type in {'ADD', 'SUBTRACT', 'MULTIPLY', 'DIVIDE'}:
n = Node(MATH_TWO_INPUTS[blend_type])
else:
n = Node("FunctionCall", { "Function": op_map_color[blend_type]})
assert n
n.push(Node("0", exp_0))
n.push(Node("1", exp_1))
return {"expression": exp_list.push(n)}
def exp_mixrgb(node, exp_list):
exp_1 = get_expression(node.inputs['Color1'], exp_list)
exp_2 = get_expression(node.inputs['Color2'], exp_list)
# TODO: optimize case fac is disconnected and equals one (or zero)
# TODO: add logic for clamp
exp_result = exp_blend(exp_1, exp_2, node.blend_type, exp_list)
lerp = Node("LinearInterpolate")
lerp.push(Node("0", exp_1))
lerp.push(Node("1", exp_result))
exp_fac = get_expression(node.inputs['Fac'], exp_list)
lerp.push(Node("2", exp_fac))
return exp_list.push(lerp)
op_custom_functions = {
"BRIGHTCONTRAST": "/DatasmithBlenderContent/MaterialFunctions/BrightContrast",
"COLOR_RAMP": "/DatasmithBlenderContent/MaterialFunctions/ColorRamp",
"CURVE_RGB": "/DatasmithBlenderContent/MaterialFunctions/RGBCurveLookup2",
"FRESNEL": "/DatasmithBlenderContent/MaterialFunctions/BlenderFresnel",
"HUE_SAT": "/DatasmithBlenderContent/MaterialFunctions/AdjustHSV",
"LAYER_WEIGHT": "/DatasmithBlenderContent/MaterialFunctions/LayerWeight",
"LOCAL_POSITION": "/DatasmithBlenderContent/MaterialFunctions/BlenderLocalPosition",
"MAPPING_POINT2D": "/DatasmithBlenderContent/MaterialFunctions/MappingPoint2D_2",
"MAPPING_POINT3D": "/DatasmithBlenderContent/MaterialFunctions/MappingPoint3D",
"MAPPING_TEX2D": "/DatasmithBlenderContent/MaterialFunctions/MappingTexture2D_2",
"MAPPING_TEX3D": "/DatasmithBlenderContent/MaterialFunctions/MappingTexture3D",
"MAPPING_NORMAL": "/DatasmithBlenderContent/MaterialFunctions/MappingNormal",
"NORMAL_FROM_HEIGHT": "/Engine/Functions/Engine_MaterialFunctions03/Procedurals/NormalFromHeightmap",
"WORLD_POSITION": "/DatasmithBlenderContent/MaterialFunctions/BlenderWorldPosition",
}
def exp_generic_function(node, exp_list, node_type, socket_names):
n = Node("FunctionCall", { "Function": op_custom_functions[node_type]})
for idx, socket_name in enumerate(socket_names):
input_expression = get_expression(node.inputs[socket_name], exp_list)
n.push(Node(str(idx), input_expression))
return {"expression": exp_list.push(n) }
def exp_bright_contrast(node, exp_list):
return exp_generic_function(node, exp_list, 'BRIGHTCONTRAST', ('Color', 'Bright', 'Contrast'))
def exp_hsv(node, exp_list):
n = Node("FunctionCall", { "Function": op_custom_functions["HUE_SAT"]})
exp_hue = get_expression(node.inputs['Hue'], exp_list)
n.push(Node("0", exp_hue))
exp_sat = get_expression(node.inputs['Saturation'], exp_list)
n.push(Node("1", exp_sat))
exp_value = get_expression(node.inputs['Value'], exp_list)
n.push(Node("2", exp_value))
exp_fac = get_expression(node.inputs['Fac'], exp_list)
n.push(Node("3", exp_fac))
exp_color = get_expression(node.inputs['Color'], exp_list)
n.push(Node("4", exp_color))
return exp_list.push(n)
def exp_invert(node, exp_list):
n = Node("OneMinus")
exp_color = get_expression(node.inputs['Color'], exp_list)
n.push(Node("0", exp_color))
invert_exp = exp_list.push(n)
blend = Node("LinearInterpolate")
exp_fac = get_expression(node.inputs['Fac'], exp_list)
blend.push(Node("0", exp_color))
blend.push(Node("1", {"expression": invert_exp}))
blend.push(Node("2", exp_fac))
return exp_list.push(blend)
def exp_mapping(node, exp_list):
if node.vector_type == 'NORMAL':
mapping_type = 'MAPPING_NORMAL'
else:
node_input_rot = node.inputs["Rotation"]
default_rot = node_input_rot.default_value
uses_3d_rot = default_rot.x != 0 or default_rot.y != 0
use_2d_node = not node_input_rot.links and not uses_3d_rot
if node.vector_type == 'POINT' or node.vector_type == 'VECTOR':
if use_2d_node:
mapping_type = 'MAPPING_POINT2D'
else:
mapping_type = 'MAPPING_POINT3D'
elif node.vector_type == 'TEXTURE':
if use_2d_node:
mapping_type = 'MAPPING_TEX2D'
else:
mapping_type = 'MAPPING_TEX3D'
n = Node("FunctionCall", { "Function": op_custom_functions[mapping_type]})
input_vector = get_expression(node.inputs['Vector'], exp_list)
input_location = get_expression(node.inputs['Location'], exp_list)
input_rotation = get_expression(node.inputs['Rotation'], exp_list)
input_scale = get_expression(node.inputs['Scale'], exp_list)
n.push(Node("0", input_vector))
n.push(Node("1", input_location))
n.push(Node("2", input_rotation))
n.push(Node("3", input_scale))
return {"expression": exp_list.push(n)}
def exp_normal_map(socket, exp_list):
node_input = socket.node.inputs['Color']
# hack: is it safe to assume that everything under here is normal?
# maybe not, because it could be masks to mix normals
# most certainly, these wouldn't be colors (so should be non-srgb)
push_context("NORMAL")
return_exp = get_expression(node_input, exp_list)
pop_context()
strength_input = socket.node.inputs["Strength"]
if strength_input.links or strength_input.default_value != 1.0:
node_strength = Node("FunctionCall", {"Function": "/DatasmithBlenderContent/MaterialFunctions/NormalStrength"})
node_strength.push(Node("0", return_exp))
node_strength.push(Node("1", get_expression(strength_input, exp_list)))
return_exp = { "expression": exp_list.push(node_strength) }
return return_exp
def exp_new_geometry(socket, exp_list):
socket_name = socket.name
if socket_name == "Position":
blend = Node("FunctionCall", { "Function": op_custom_functions["WORLD_POSITION"]})
n = exp_list.push(blend)
return { "expression": n }
if socket_name == "Normal":
blend = Node("PixelNormalWS")
n = exp_list.push(blend)
return { "expression": n }
if socket_name == "Tangent":
blend = Node("VertexTangentWS")
n = exp_list.push(blend)
return { "expression": n }
if socket_name == "True Normal":
blend = Node("VertexNormalWS")
n = exp_list.push(blend)
return { "expression": n }
# if socket_name == "Incoming":
# this would be cameraposition - worldposition
# if socket_name == "Parametric":
# this appears to be per-triangle barycentric coordinates
# if socket_name == "Backfacing":
# exactly what it says, I thought UE4 had this
if socket_name == "Pointiness":
exp = exp_scalar(0, exp_list)
return {"expression": exp}
# if socket_name == "Random Per Island":
log.error("Node NEW_GEOMETRY has unhanded socket:%s" % socket_name)
def exp_texture_coordinates(socket, exp_list):
socket_name = socket.name
if socket_name == "Position":
blend = Node("FunctionCall", { "Function": op_custom_functions["WORLD_POSITION"]})
n = exp_list.push(blend)
return { "expression": n }
if socket_name == "Normal":
blend = Node("PixelNormalWS")
n = exp_list.push(blend)
return { "expression": n }
if socket_name == "Tangent":
blend = Node("VertexTangentWS")
n = exp_list.push(blend)
return { "expression": n }
if socket_name == "True Normal":
blend = Node("VertexNormalWS")
n = exp_list.push(blend)
return { "expression": n }
# if socket_name == "Incoming":
# this would be cameraposition - worldposition
# if socket_name == "Parametric":
# this appears to be per-triangle barycentric coordinates
# if socket_name == "Backfacing":
# exactly what it says, I thought UE4 had this
if socket_name == "Pointiness":
exp = exp_scalar(0, exp_list)
return {"expression": exp}
# if socket_name == "Random Per Island":
log.error("Node NEW_GEOMETRY has unhanded socket:%s" % socket_name)
def exp_layer_weight(socket, exp_list):
expr = None
if socket.node in reverse_expressions:
expr = reverse_expressions[socket.node]
else:
exp_blend = get_expression(socket.node.inputs['Blend'], exp_list)
n = Node("FunctionCall", { "Function": op_custom_functions['LAYER_WEIGHT']})
n.push(Node("0", exp_blend))
expr = exp_list.push(n)
reverse_expressions[socket.node] = expr
log.warn("layer weight missing normal input")
if socket.name == "Fresnel":
return {"expression": expr, "OutputIndex": 0}
elif socket.name == "Facing":
return {"expression": expr, "OutputIndex": 1}
log.error("LAYER_WEIGHT node from unknown socket")
return {"expression": expr, "OutputIndex": 0}
def exp_light_path(socket, exp_list):
log.warn("incomplete node implementation: LIGHT_PATH")
n = exp_scalar(1, exp_list)
return {"expression": n}
def exp_object_info(socket, exp_list):
field = socket.name
if field == "Location":
# TODO: check if we need to transform these to blender space
exp = exp_list.push(Node("ObjectPositionWS"))
elif field == "Random":
exp = exp_list.push(Node("PerInstanceRandom"))
elif field == "Object Index":
log.warning("Node Object Info>Object Index translated to random as it is used to randomize too")
exp = exp_list.push(Node("PerInstanceRandom"))
else:
log.error("Can't write Material node 'Object Info' field:%s" % field)
exp = exp_scalar(0, exp_list)
return {"expression": exp, "OutputIndex": 0}
DATASMITH_TEXTURE_SIZE = 1024
def add_material_curve2(curve):
# do some material curves initialization
material_curves = datasmith_context["material_curves"]
if material_curves is None:
material_curves = np.zeros((DATASMITH_TEXTURE_SIZE, DATASMITH_TEXTURE_SIZE, 4))
datasmith_context["material_curves"] = material_curves
datasmith_context["material_curves_count"] = 0
mat_curve_idx = datasmith_context["material_curves_count"]
datasmith_context["material_curves_count"] = mat_curve_idx + 1
log.info("writing curve:%s" % mat_curve_idx)
# write texture from top
row_idx = DATASMITH_TEXTURE_SIZE - mat_curve_idx - 1
values = material_curves[row_idx]
factor = DATASMITH_TEXTURE_SIZE - 1
# check for curve type, do sampling
curve_type = type(curve)
if curve_type == bpy.types.ColorRamp:
for idx in range(DATASMITH_TEXTURE_SIZE):
values[idx] = curve.evaluate(idx/factor)
elif curve_type == bpy.types.CurveMapping:
curves = curve.curves
position = 0
for idx in range(DATASMITH_TEXTURE_SIZE):
position = idx/factor
values[idx, 0] = curve.evaluate(curves[0], position)
values[idx, 1] = curve.evaluate(curves[1], position)
values[idx, 2] = curve.evaluate(curves[2], position)
values[idx, 3] = curve.evaluate(curves[3], position)
return mat_curve_idx
def exp_blackbody(from_node, exp_list):
n = Node("BlackBody")
exp_0 = get_expression(from_node.inputs[0], exp_list)
n.push(Node("0", exp_0))
exp = exp_list.push(n)
return {"expression": exp}
def exp_color_ramp(from_node, exp_list):
ramp = from_node.color_ramp
idx = add_material_curve2(ramp)
level = get_expression(from_node.inputs['Fac'], exp_list)
curve_idx = exp_scalar(idx, exp_list)
compatibility_mode = datasmith_context["compatibility_mode"]
if compatibility_mode:
pixel_offset = exp_scalar(0.5, exp_list)
vertical_res = exp_scalar(1/DATASMITH_TEXTURE_SIZE, exp_list) # curves texture size
n = Node("Add")
n.push(Node("0", {"expression": curve_idx}))
n.push(Node("1", {"expression": pixel_offset}))
curve_y = exp_list.push(n)
n2 = Node("Multiply")
n2.push(Node("0", {"expression": curve_y}))
n2.push(Node("1", {"expression": vertical_res}))
curve_v = exp_list.push(n2)
n3 = Node("AppendVector")
n3.push(Node("0", level))
n3.push(Node("1", {"expression": curve_v}))
tex_coord = exp_list.push(n3)
texture_exp = exp_texture("datasmith_curves", "datasmith_curves")
texture_exp.push(Node("Coordinates", {"expression":tex_coord}))
return exp_list.push(texture_exp)
else:
vertical_res = exp_scalar(DATASMITH_TEXTURE_SIZE, exp_list) # curves texture size
texture = exp_texture_object("datasmith_curves", exp_list)
lookup = Node("FunctionCall", { "Function": op_custom_functions["COLOR_RAMP"]})
lookup.push(Node("0", level))
lookup.push(Node("1", {"expression": curve_idx } ))
lookup.push(Node("2", {"expression": vertical_res } ))
lookup.push(Node("3", {"expression": texture } ))
result = exp_list.push(lookup)
return result
def exp_curvergb(from_node, exp_list):
mapping = from_node.mapping
mapping.initialize()
idx = add_material_curve2(mapping)
factor = get_expression(from_node.inputs['Fac'], exp_list)
color = get_expression(from_node.inputs['Color'], exp_list)
curve_idx = exp_scalar(idx, exp_list)
vertical_res = exp_scalar(DATASMITH_TEXTURE_SIZE, exp_list) # curves texture size
texture = exp_texture_object("datasmith_curves", exp_list)
lookup = Node("FunctionCall", { "Function": op_custom_functions["CURVE_RGB"]})
lookup.push(Node("0", color))
lookup.push(Node("1", {"expression": curve_idx}))
lookup.push(Node("2", {"expression": vertical_res}))
lookup.push(Node("3", {"expression": texture}))
blend_exp = exp_list.push(lookup)
blend = Node("LinearInterpolate")
blend.push(Node("0", color))
blend.push(Node("1", {"expression": blend_exp}))
blend.push(Node("2", factor))
result = exp_list.push(blend)
return result
def exp_texture_object(name, exp_list):
n = Node("TextureObject")
n.push(Node("0", {
"name": "Texture",
"type": "Texture",
"val": name,
}))
return exp_list.push(n)
def exp_bump(node, exp_list):
height_input = node.inputs['Height']
if height_input.links:
from_node = height_input.links[0].from_node
if from_node.type == 'TEX_IMAGE':
image = from_node.image
name = sanitize_name(image.name)
# ensure that texture is exported
get_or_create_texture(name, image)
image_object = exp_texture_object(name, exp_list)
bump_node = Node("FunctionCall", { "Function": op_custom_functions["NORMAL_FROM_HEIGHT"]})
bump_node.push(Node("0", {"expression": image_object}))
bump_node.push(Node("1", get_expression(node.inputs['Strength'], exp_list)))
bump_node.push(Node("2", get_expression(node.inputs['Distance'], exp_list)))
bump_node.push(Node("3", get_expression(from_node.inputs['Vector'], exp_list)))
exp = exp_list.push(bump_node)
return {"expression": exp}
else:
log.warn("trying to export bump node, but input is not an image")
else:
log.warn("trying to export bump node without connections")
group_context = {}
def exp_group(socket, exp_list):
node = socket.node
global group_context
global reverse_expressions
global cached_nodes
new_context = {}
new_cached_nodes = {}
for input in node.inputs:
new_context[input.name] = get_expression(input, exp_list)
previous_reverse = reverse_expressions
reverse_expressions = {}
previous_context = group_context
previous_cached_nodes = cached_nodes
group_context = new_context
cached_nodes = new_cached_nodes
# now traverse the inner graph
output_name = socket.name
node_tree = node.node_tree
# search for active output node:
output_node = None
for node in node_tree.nodes:
if type(node) == bpy.types.NodeGroupOutput:
if node.is_active_output or output_node is None:
output_node = node
# TODO: handle case when output_node is None
inner_socket = output_node.inputs[output_name]
inner_exp = get_expression(inner_socket, exp_list)
group_context = previous_context
cached_nodes = previous_cached_nodes
reverse_expressions = previous_reverse
return inner_exp
def exp_group_input(socket, exp_list):
outer_expression = group_context[socket.name]
return outer_expression
def exp_attribute(socket, exp_list):
exp = exp_list.push(Node("VertexColor"))
ret = {"expression": exp, "OutputIndex": 0}
# average channels if socket is Fac
if socket.name == "Fac":
#TODO: check if we should do some colorimetric aware convertion to grayscale
n = Node("DotProduct")
n.push(Node("0", ret))
exp_1 = exp_vector((0.333333, 0.333333, 0.333333), exp_list)
n.push(Node("1", {"expression": exp_1}))
dot_exp = exp_list.push(n)
ret = {"expression": dot_exp}
return ret
def exp_vertex_color(socket, exp_list):
exp = exp_list.push(Node("VertexColor"))
if socket.name == "Color":
return {"expression": exp, "OutputIndex": 0}
elif socket.name == "Alpha":
return {"expression": exp, "OutputIndex": 4}
def exp_fresnel(node, exp_list):
n = Node("FunctionCall", { "Function": op_custom_functions["FRESNEL"]})
exp_ior = get_expression(node.inputs['IOR'], exp_list)
n.push(Node("0", exp_ior))
return exp_list.push(n)
context_stack = []
def push_context(context):
context_stack.append(context)
def pop_context():
context_stack.pop()
def get_context():
if context_stack:
return context_stack[-1]
expression_log_prefix = ""
def get_expression(field, exp_list, force_default=False):
# this may return none for fields without default value
# most of the time blender doesn't have default value for vector
# node inputs, but it does for scalars and colors
# TODO: check which cases we should be careful
global expression_log_prefix
field_path = f"{field.node.name}/{field.name}:{field.type}"
log.debug(expression_log_prefix + field_path)
if not field.links:
if field.type == 'VALUE':
exp = exp_scalar(field.default_value, exp_list)
return {"expression": exp, "OutputIndex": 0}
elif field.type == 'RGBA':
exp = exp_color(field.default_value, exp_list)
return {"expression": exp, "OutputIndex": 0}
elif field.type == 'VECTOR':
use_vector_default = force_default or type(field.default_value) in {Vector, Euler}
if use_vector_default:
exp = exp_vector(field.default_value, exp_list)
return {"expression": exp, "OutputIndex": 0}
elif field.type == 'SHADER':
# same as holdout shader
bsdf = {
"BaseColor": {"expression": exp_scalar(0.0, exp_list)},
"Roughness": {"expression": exp_scalar(1.0, exp_list)},
}
return bsdf
log.debug("field has no links, and no default value " + str(field))
return None
prev_prefix = expression_log_prefix
expression_log_prefix += "| "
try:
return_exp = get_expression_inner(field, exp_list)
except:
return_exp = None
expression_log_prefix = prev_prefix
# if a color output is connected to a scalar input, average by using dot product
if field.type == 'VALUE':
other_output = field.links[0].from_socket
if other_output.type == 'RGBA' or other_output.type == 'VECTOR':
#TODO: check if we should do some colorimetric aware convertion to grayscale
n = Node("DotProduct")
exp_0 = return_exp
n.push(Node("0", exp_0))
exp_1 = exp_vector((0.333333, 0.333333, 0.333333), exp_list)
n.push(Node("1", {"expression": exp_1}))
dot_exp = exp_list.push(n)
return_exp = {"expression": dot_exp}
socket = field.links[0].from_socket
reverse_expressions[socket] = return_exp
log.debug("%send field:%s = %s" % (expression_log_prefix, field_path, return_exp))
return return_exp
def get_expression_inner(field, exp_list):
node = field.links[0].from_node
socket = field.links[0].from_socket
log.debug(f"{expression_log_prefix} get_expression_inner {node.name} {socket.name}")
# if this node is already exported, connect to that instead
# I am considering in
if socket in reverse_expressions:
return reverse_expressions[socket]
# The cases are ordered like in blender Add menu, others first, shaders second, then the rest
# these are handled first as these can refer bsdfs
if node.type == 'GROUP':