-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbake.py
2091 lines (1703 loc) · 81.9 KB
/
bake.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
import bpy
import os
import mathutils
from . import addon_updater_ops
from . import utils
from . import nodeutils
from . import cc3
from . import vars
def make_new_image(name, size, format, ext, dir, data, alpha):
img = bpy.data.images.new(name, size, size, alpha=alpha, is_data=data)
img.pixels[0] = 0
img.file_format = format
dir = os.path.join(bpy.path.abspath("//"), dir)
os.makedirs(dir, exist_ok=True)
img.filepath_raw = os.path.join(dir, name + ext)
img.save()
return img
def get_image_format():
props = bpy.context.scene.CC3BakeProps
format = props.target_format
ext = ".jpg"
if format == "PNG":
ext = ".png"
elif format == "JPEG":
ext = ".jpg"
return format, ext
def get_bake_path():
props = bpy.context.scene.CC3BakeProps
base_dir = os.path.join(bpy.path.abspath("//"))
bake_path = props.bake_path
try:
if os.path.isabs(bake_path):
path = bake_path
else:
path = os.path.join(base_dir, bake_path)
except:
path = os.path.join(base_dir, "Bake")
return path
def make_image_target(nodes, name, size, data = True, alpha = False):
props = bpy.context.scene.CC3BakeProps
format, ext = get_image_format()
depth = 24
if alpha:
format = "PNG"
ext = ".png"
depth = 32
path = get_bake_path()
# find an old image with the same name to reuse:
for img in bpy.data.images:
if img.name.startswith(name) and img.name.endswith(name):
img_path, img_file = os.path.split(img.filepath)
same_path = False
try:
if os.path.samefile(path, img_path):
same_path = True
except:
same_path = False
if img.file_format == format and img.depth == depth and same_path:
utils.log_info("Reusing image: " + name)
try:
if img.size[0] != size or img.size[1] != size:
utils.log_info("Scaling image: " + name + " to: " + str(size))
img.scale(size, size)
return img
except:
utils.log_info("Bad image: " + img.name)
bpy.data.images.remove(img)
else:
utils.log_info("Wrong path or format: " + img.name + ", " + img_path + "==" + path + "?, " + img.file_format + "==" + format + "?, depth: " + str(depth) + "==" + str(img.depth) + "?")
bpy.data.images.remove(img)
# or just make a new one:
utils.log_info("Creating new image: " + name + " size: " + str(size))
img = make_new_image(name, size, format, ext, path, data, alpha)
return img
def copy_image_target(image_node, name, size, data = True, alpha = False):
props = bpy.context.scene.CC3BakeProps
# return None if it's a bad image source
if image_node is None or image_node.image is None:
return None
if image_node.image.size[0] == 0 or image_node.image.size[1] == 0:
return None
format, ext = get_image_format()
depth = 24
if alpha:
format = "PNG"
ext = ".png"
depth = 32
path = get_bake_path()
# find an old image with the same name to reuse:
for img in bpy.data.images:
if img.name.startswith(name) and img.name.endswith(name):
img_path, img_file = os.path.split(img.filepath)
same_path = False
try:
if os.path.samefile(path, img_path):
same_path = True
except:
same_path = False
if same_path:
utils.log_info("Removing existing copy: " + img.name)
bpy.data.images.remove(img)
utils.log_info("Copying existing image: " + image_node.image.name)
img = image_node.image.copy()
img.name = name
if img.size[0] != size or img.size[1] != size:
utils.log_info("Resizing image: " + str(size))
img.scale(size, size)
if img.file_format != format:
if utils.check_blender_version("3.0.0"):
utils.log_info("Changing image format: " + format)
img.file_format = format
else:
utils.log_info("Not changing image format of copy in Blender <= 2.93 (causes crash): " + format)
dir = os.path.join(bpy.path.abspath("//"), path)
os.makedirs(dir, exist_ok=True)
img.filepath_raw = os.path.join(dir, name + ext)
img.save()
return img
def copy_target(source_mat, mat, source_node, source_socket, map_suffix, data):
props = bpy.context.scene.CC3BakeProps
nodes = mat.node_tree.nodes
links = mat.node_tree.links
target_suffix = get_target_map_suffix(map_suffix)
mat_name = utils.strip_name(mat.name)
size = get_target_map_size(source_mat, map_suffix)
utils.log_info("Copying direct image source: " + source_node.name)
image = copy_image_target(source_node, mat_name + "_" + target_suffix, size, data)
# fall back to baking the source if we can't copy the image:
if image is None and source_socket:
utils.log_info("Bad image source, falling back to baking!")
return bake_target(source_mat, mat, source_node, source_socket, map_suffix, data)
if image:
image_node = nodeutils.make_image_node(nodes, image)
image_node.name = vars.BAKE_PREFIX + mat_name + "_" + map_suffix
return image_node
return None
old_samples = 64
old_file_format = "PNG"
old_quality = 90
old_compression = 15
old_view_transform = "Standard"
old_look = "None"
old_gamma = 1
old_exposure = 0
old_colorspace = "Raw"
def prep_bake(width, height):
global old_samples, old_file_format, old_quality, old_compression
global old_view_transform, old_look, old_gamma, old_exposure, old_colorspace
old_samples = bpy.context.scene.cycles.samples
old_file_format = bpy.context.scene.render.image_settings.file_format
old_quality = bpy.context.scene.render.image_settings.quality
old_compression = bpy.context.scene.render.image_settings.compression
old_view_transform = bpy.context.scene.view_settings.view_transform
old_look = bpy.context.scene.view_settings.look
old_gamma = bpy.context.scene.view_settings.gamma
old_exposure = bpy.context.scene.view_settings.exposure
old_colorspace = bpy.context.scene.sequencer_colorspace_settings.name
props = bpy.context.scene.CC3BakeProps
# blender 3.0
if utils.check_blender_version("3.0.0"):
bpy.context.scene.cycles.preview_samples = props.bake_samples
bpy.context.scene.cycles.use_adaptive_sampling = False
bpy.context.scene.cycles.use_preview_adaptive_sampling = False
bpy.context.scene.cycles.use_denoising = False
bpy.context.scene.cycles.use_preview_denoising = False
bpy.context.scene.cycles.use_auto_tile = False
bpy.context.scene.render.use_bake_multires = False
bpy.context.scene.render.bake.use_selected_to_active = False
bpy.context.scene.render.bake.use_pass_direct = False
bpy.context.scene.render.bake.use_pass_indirect = False
try:
bpy.context.scene.cycles.samples = props.bake_samples
bpy.context.scene.render.bake.target = 'IMAGE_TEXTURES'
except:
pass
bpy.context.scene.render.bake.margin = 1
bpy.context.scene.render.bake.use_clear = True
bpy.context.scene.render.image_settings.file_format = get_image_format()[0]
bpy.context.scene.render.image_settings.quality = props.jpeg_quality
bpy.context.scene.render.image_settings.compression = props.png_compression
bpy.context.scene.view_settings.view_transform = 'Standard' #'Raw'
bpy.context.scene.view_settings.look = 'None'
bpy.context.scene.view_settings.gamma = 1
bpy.context.scene.view_settings.exposure = 0
bpy.context.scene.sequencer_colorspace_settings.name = 'Raw'
def post_bake():
global old_samples, old_file_format, old_quality, old_compression
global old_view_transform, old_look, old_gamma, old_exposure, old_colorspace
try:
bpy.context.scene.cycles.samples = old_samples
except:
pass
bpy.context.scene.render.image_settings.file_format = old_file_format
bpy.context.scene.render.image_settings.quality = old_quality
bpy.context.scene.render.image_settings.compression = old_compression
bpy.context.scene.view_settings.view_transform = old_view_transform
bpy.context.scene.view_settings.look = old_look
bpy.context.scene.view_settings.gamma = old_gamma
bpy.context.scene.view_settings.exposure = old_exposure
bpy.context.scene.sequencer_colorspace_settings.name = old_colorspace
def bake_target(source_mat, mat, source_node, source_socket, map_suffix, data):
props = bpy.context.scene.CC3BakeProps
nodes = mat.node_tree.nodes
links = mat.node_tree.links
target_suffix = get_target_map_suffix(map_suffix)
output_node = nodeutils.find_node_by_type(nodes, "OUTPUT_MATERIAL")
mat_name = utils.strip_name(mat.name)
target_size = get_target_map_size(source_mat, map_suffix)
source_size = detect_size_from_suffix(source_mat, map_suffix)
if props.scale_maps and target_size < source_size:
utils.log_info("Baking source size: " + str(source_size))
size = source_size
else:
size = target_size
image = make_image_target(nodes, mat_name + "_" + target_suffix, size, data)
image_node = nodeutils.make_image_node(nodes, image)
image_node.name = vars.BAKE_PREFIX + mat_name + "_" + map_suffix
bpy.context.scene.cycles.samples = props.bake_samples
utils.log_info("Baking: " + source_node.name + " / " + source_socket + " suffix " + target_suffix)
prep_bake(size, size)
nodeutils.link_nodes(links, source_node, source_socket, output_node, "Surface")
image_node.select = True
nodes.active = image_node
bpy.ops.object.bake(type='COMBINED')
if props.scale_maps and target_size < source_size:
utils.log_info("Scaling to target size: " + str(target_size))
image.scale(target_size, target_size)
image.save_render(filepath = image.filepath, scene = bpy.context.scene)
image.reload()
post_bake()
return image_node
def bake_shader_normal(source_mat, mat):
props = bpy.context.scene.CC3BakeProps
nodes = mat.node_tree.nodes
links = mat.node_tree.links
target_suffix = get_target_map_suffix("Normal")
shader_node = nodeutils.get_shader_node(nodes)
bsdf_node = nodeutils.get_bsdf_node(nodes)
output_node = nodeutils.find_node_by_type(nodes, "OUTPUT_MATERIAL")
mat_name = utils.strip_name(mat.name)
target_size = get_target_map_size(source_mat, "Normal")
source_size = detect_size_from_suffix(source_mat, "Normal")
if props.scale_maps and target_size < source_size:
size = source_size
else:
size = target_size
image = make_image_target(nodes, mat_name + "_" + target_suffix, size, True)
image_node = nodeutils.make_image_node(nodes, image)
image_node.name = vars.BAKE_PREFIX + mat_name + "_Normal"
prep_bake(size, size)
nodeutils.link_nodes(links, bsdf_node, "BSDF", output_node, "Surface")
image_node.select = True
nodes.active = image_node
bpy.ops.object.bake(type='NORMAL')
if props.scale_maps and target_size < source_size:
image.scale(target_size, target_size)
image.save_render(filepath = image.filepath, scene = bpy.context.scene)
image.reload()
post_bake()
return image_node
def bake_socket_input(source_mat, mat, to_node, to_socket, suffix, data = True):
from_node = nodeutils.get_node_connected_to_input(to_node, to_socket)
from_socket = nodeutils.get_socket_connected_to_input(to_node, to_socket)
return bake_socket_output(source_mat, mat, from_node, from_socket, suffix, data)
def bake_socket_output(source_mat, mat, from_node, from_socket, suffix, data = True):
if from_node:
# Note: Don't copy Alpha inputs as full textures, just Color inputs:
if from_node.type == "TEX_IMAGE" and from_socket == "Color":
return copy_target(source_mat, mat, from_node, from_socket, suffix, data)
else:
return bake_target(source_mat, mat, from_node, from_socket, suffix, data)
return from_node
def position(node, loc):
if node:
node.location = loc
def prep_diffuse(mat, shader_node):
props = bpy.context.scene.CC3BakeProps
nodes = mat.node_tree.nodes
links = mat.node_tree.links
# turn off depth for cornea parallax
parallax_tiling_node = nodeutils.find_node_by_keywords(nodes, nodeutils.NODE_PREFIX, "(tiling_rl_cornea_shader_DIFFUSE_mapping)")
if parallax_tiling_node:
nodeutils.set_node_input(parallax_tiling_node, "Depth", 0.0)
# for baking separate diffuse and AO, set the amount of AO to bake into the diffuse map
if shader_node:
nodeutils.set_node_input(shader_node, "AO Strength", props.ao_in_diffuse)
def prep_ao(mat, shader_node):
props = bpy.context.scene.CC3BakeProps
ao_strength = 1.0
if shader_node:
# fetch the intended ao strength
ao_strength = nodeutils.get_node_input(shader_node, "AO Strength", 1.0)
# max out the ao strength for baking
nodeutils.set_node_input(shader_node, "AO Strength", 1.0)
return ao_strength
def prep_sss(shader_node, bsdf_node : bpy.types.Node):
props = bpy.context.scene.CC3BakeProps
sss_radius = mathutils.Vector((0.01, 0.01, 0.01))
sss_radius = nodeutils.get_node_input(bsdf_node, "Subsurface Radius", sss_radius)
return sss_radius
def prep_alpha(mat, shader_node):
props = bpy.context.scene.CC3BakeProps
nodes = mat.node_tree.nodes
links = mat.node_tree.links
return
def can_bake_shader_node(shader_node, bsdf_node, bsdf_socket):
props = bpy.context.scene.CC3BakeProps
if shader_node is None:
return False
if nodeutils.is_mixer_connected(bsdf_node, bsdf_socket):
return not props.bake_mixers
return nodeutils.get_node_connected_to_input(bsdf_node, bsdf_socket) == shader_node
def bake_material(obj, mat, source_mat):
props = bpy.context.scene.CC3BakeProps
nodes = mat.node_tree.nodes
links = mat.node_tree.links
shader_node : bpy.types.Node = nodeutils.get_shader_node(nodes)
bsdf_node = nodeutils.get_bsdf_node(nodes)
bake_maps = vars.get_bake_target_maps(props.target_mode)
utils.log_info("Baking for " + props.target_mode + ": " + obj.name + " / " + mat.name)
utils.log_info("")
# Texture Map Baking
#
# Diffuse Maps & AO
diffuse_bake_node = None
ao_bake_node = None
ao_strength = 1.0
if nodeutils.is_connected(bsdf_node, "Base Color"):
if can_bake_shader_node(shader_node, bsdf_node, "Base Color"):
# if the shader_node does not have an "AO" output node, then copy the AO texture directly.
# note: so far, nothing has an "AO" output node.
if "AO" in bake_maps:
ao_strength = prep_ao(mat, shader_node)
if "AO" in shader_node.outputs:
ao_bake_node = bake_socket_output(source_mat, mat, shader_node, "AO", "AO")
else:
ao_node = nodeutils.find_shader_texture(nodes, "AO")
if ao_node:
ao_bake_node = bake_socket_output(source_mat, mat, ao_node, "Color", "AO")
if "Diffuse" in bake_maps:
# if there is a "Diffuse" output node, bake that, otherwise bake the "Base Color" output node.
prep_diffuse(mat, shader_node)
if "Diffuse" in shader_node.outputs:
diffuse_bake_node = bake_socket_output(source_mat, mat, shader_node, "Diffuse", "Diffuse", False)
else:
diffuse_bake_node = bake_socket_output(source_mat, mat, shader_node, "Base Color", "Diffuse", False)
elif bsdf_node:
# bake BSDF base color input
diffuse_bake_node = bake_socket_input(source_mat, mat, bsdf_node, "Base Color", "Diffuse", False)
# Subsurface Scattering Maps
sss_bake_node = None
sss_radius = 1.0
if nodeutils.is_connected(bsdf_node, "Subsurface"):
if "Subsurface" in bake_maps:
sss_radius = prep_sss(mat, shader_node)
if can_bake_shader_node(shader_node, bsdf_node, "Subsurface"):
sss_bake_node = bake_socket_output(source_mat, mat, shader_node, "Subsurface", "Subsurface")
elif bsdf_node:
sss_bake_node = bake_socket_input(source_mat, mat, bsdf_node, "Subsurface", "Subsurface")
# Thickness Maps (Subsurface transmission)
# the transmission map texture is not used, but it is added to the material nodes
thickness_bake_node = None
if "Thickness" in bake_maps:
utils.log_info("Processing Thickness/Transmission")
thickness_node = nodeutils.find_shader_texture(nodes, "TRANSMISSION")
if thickness_node:
utils.log_info("thickness texture found...")
thickness_bake_node = bake_socket_output(source_mat, mat, thickness_node, "Color", "Thickness")
# Metallic Maps
metallic_bake_node = None
if nodeutils.is_connected(bsdf_node, "Metallic"):
if "Metallic" in bake_maps:
utils.log_info("Processing Metallic")
if can_bake_shader_node(shader_node, bsdf_node, "Metallic"):
metallic_bake_node = bake_socket_output(source_mat, mat, shader_node, "Metallic", "Metallic")
elif bsdf_node:
metallic_bake_node = bake_socket_input(source_mat, mat, bsdf_node, "Metallic", "Metallic")
# Specular Maps
specular_bake_node = None
if nodeutils.is_connected(bsdf_node, "Specular"):
if "Specular" in bake_maps:
utils.log_info("Processing Specular")
if can_bake_shader_node(shader_node, bsdf_node, "Specular"):
specular_bake_node = bake_socket_output(source_mat, mat, shader_node, "Specular", "Specular")
elif bsdf_node:
specular_bake_node = bake_socket_input(source_mat, mat, bsdf_node, "Specular", "Specular")
specular_scale = 1.0
if shader_node:
specular_scale = nodeutils.get_node_input(shader_node, "Specular Scale", specular_scale)
specular_scale = nodeutils.get_node_input(shader_node, "Front Specular", specular_scale)
nodeutils.set_node_input(bsdf_node, "Specular", 0.5 * specular_scale)
# Roughness Maps
roughnesss_bake_node = None
if nodeutils.is_connected(bsdf_node, "Roughness"):
if "Roughness" in bake_maps:
utils.log_info("Processing Roughness")
if can_bake_shader_node(shader_node, bsdf_node, "Roughness"):
roughnesss_bake_node = bake_socket_output(source_mat, mat, shader_node, "Roughness", "Roughness")
elif bsdf_node:
roughnesss_bake_node = bake_socket_input(source_mat, mat, bsdf_node, "Roughness", "Roughness")
# Emission Maps
# copy emission maps directly...
emission_bake_node = None
if nodeutils.is_connected(bsdf_node, "Emission"):
if "Emission" in bake_maps:
utils.log_info("Processing Emission")
emission_node = nodeutils.find_shader_texture(nodes, "EMISSION")
if emission_node:
if can_bake_shader_node(shader_node, bsdf_node, "Emission"):
emission_bake_node = bake_socket_output(source_mat, mat, emission_node, "Color", "Emission")
elif bsdf_node:
emission_bake_node = bake_socket_input(source_mat, mat, bsdf_node, "Emission", "Emission")
# Alpha Maps
alpha_bake_node = None
if nodeutils.is_connected(bsdf_node, "Alpha") or (shader_node and "Opacity" in shader_node.outputs):
if ((mat.blend_method != "OPAQUE" and "Alpha" in bake_maps) or
(shader_node and "Opacity" in shader_node.outputs and "Alpha" in bake_maps)):
prep_alpha(mat, shader_node)
if (can_bake_shader_node(shader_node, bsdf_node, "Alpha")
or (shader_node and "Opacity" in shader_node.outputs)):
if "Opacity" in shader_node.outputs:
alpha_bake_node = bake_socket_output(source_mat, mat, shader_node, "Opacity", "Alpha")
mat.blend_method = "BLEND"
mat.shadow_method = "NONE"
else:
alpha_bake_node = bake_socket_output(source_mat, mat, shader_node, "Alpha", "Alpha")
elif bsdf_node:
alpha_bake_node = bake_socket_input(source_mat, mat, bsdf_node, "Alpha", "Alpha")
# Transmission Maps (Refractive Transparency)
transmission_bake_node = None
if nodeutils.is_connected(bsdf_node, "Transmission"):
if "Transmission" in bake_maps:
if can_bake_shader_node(shader_node, bsdf_node, "Transmission"):
transmission_bake_node = bake_socket_output(source_mat, mat, shader_node, "Transmission", "Transmission")
elif bsdf_node:
transmission_bake_node = bake_socket_input(source_mat, mat, bsdf_node, "Transmission", "Transmission")
# Bump Maps
# if shader group node has a "Bump Map" input, then copy the bump map texture directly
bump_bake_node = None
bump_distance = 0.01
if nodeutils.is_connected(bsdf_node, "Normal"):
if "Bump" in bake_maps and props.allow_bump_maps:
if can_bake_shader_node(shader_node, bsdf_node, "Normal"):
bump_node = nodeutils.find_shader_texture(nodes, "BUMP")
bump_distance = nodeutils.get_node_input(shader_node, "Bump Strength", 0.01)
if bump_node:
bump_bake_node = bake_socket_output(source_mat, mat, bump_node, "Color", "Bump")
elif bsdf_node:
input_node = nodeutils.get_node_connected_to_input(bsdf_node, "Normal")
if input_node.type == "BUMP":
height_node = nodeutils.get_node_connected_to_input(input_node, "Height")
if height_node:
bump_bake_node = bake_socket_input(source_mat, mat, input_node, "Height", "Bump")
bump_distance = nodeutils.get_node_input(input_node, "Distance", 1.0)
# Normal Maps
# if the shader group node has a "Blend Normal" color output, bake that,
# otherwise copy the normal map texture directly
# DO NOT BAKE the normal vector output.
normal_bake_node = None
normal_strength = 1.0
bump_to_normal = False
if nodeutils.is_connected(bsdf_node, "Normal"):
if "Normal" in bake_maps:
if "Bump" not in bake_maps or not props.allow_bump_maps:
bump_to_normal = True
if can_bake_shader_node(shader_node, bsdf_node, "Normal"):
normal_strength = nodeutils.get_node_input(shader_node, "Normal Strength", 1.0)
if "Blend Normal" in shader_node.outputs:
normal_strength = 1.0
normal_bake_node = bake_socket_output(source_mat, mat, shader_node, "Blend Normal", "Normal")
else:
normal_node = nodeutils.find_shader_texture(nodes, "NORMAL")
if normal_node:
normal_bake_node = bake_socket_output(source_mat, mat, normal_node, "Color", "Normal")
else:
normal_bake_node = bake_shader_normal(source_mat, mat)
elif bsdf_node:
input_node = nodeutils.get_node_connected_to_input(bsdf_node, "Normal")
if input_node:
if input_node.type == "NORMAL_MAP":
# just a normal mapper, bake the entire normal input
normal_bake_node = bake_shader_normal(source_mat, mat)
normal_strength = nodeutils.get_node_input(input_node, "Strength", 1.0)
elif input_node.type == "BUMP":
# bump node mappers can have heightmap and normal inputs
normal_node = nodeutils.get_node_connected_to_input(input_node, "Normal")
height_node = nodeutils.get_node_connected_to_input(input_node, "Height")
if bump_to_normal:
# bake everything into the normal
normal_bake_node = bake_shader_normal(source_mat, mat)
normal_strength = 1.0
else:
# bake the normal separately
if normal_node:
normal_bake_node = bake_socket_input(source_mat, mat, input_node, "Normal", "Normal")
normal_strength = nodeutils.get_node_input(normal_node, "Strength", 1.0)
else:
# something is plugged into the normals, but can't tell what, so just bake the shader normals
normal_bake_node = bake_shader_normal(source_mat, mat)
# Micro Normals
# always copy the micro normal map texture directly
micro_normal_bake_node = None
micro_normal_strength = 1
micro_normal_tiling = 20
micro_normal_scale = mathutils.Vector((1, 1, 1))
if nodeutils.is_connected(bsdf_node, "Normal"):
if "MicroNormal" in bake_maps:
micro_normal_node = nodeutils.find_shader_texture(nodes, "MICRONORMAL")
if micro_normal_node:
tiling_node = nodeutils.get_node_connected_to_input(micro_normal_node, "Vector")
if tiling_node:
if "Tiling" in tiling_node.inputs:
micro_normal_scale = nodeutils.get_node_input(tiling_node, "Tiling", micro_normal_scale)
micro_normal_tiling = micro_normal_scale[0]
micro_normal_scale = mathutils.Vector((micro_normal_tiling, micro_normal_tiling, 1))
elif "Scale" in tiling_node.inputs:
micro_normal_scale = nodeutils.get_node_input(tiling_node, "Scale", micro_normal_scale)
micro_normal_tiling = micro_normal_scale[0]
micro_normal_scale = mathutils.Vector((micro_normal_tiling, micro_normal_tiling, 1))
utils.log_info(f"Tiling: {micro_normal_scale}")
# disconnect any tiling/mapping nodes before baking the micro normal...
nodeutils.unlink_node(links, micro_normal_node, "Vector")
micro_normal_bake_node = bake_socket_output(source_mat, mat, micro_normal_node, "Color", "MicroNormal")
# Micro Normal Mask
# if the shader group node as a "Normal Mask" float output, bake that,
# otherwise copy the micro normal mask directly
micro_normal_mask_bake_node = None
micro_normal_stength = 1.0
if nodeutils.is_connected(bsdf_node, "Normal"):
if "MicroNormalMask" in bake_maps:
if shader_node:
if "Normal Mask" in shader_node.outputs:
micro_normal_mask_bake_node = bake_socket_output(source_mat, mat, shader_node, "Normal Mask", "MicroNormalMask")
micro_normal_strength = 1.0
else:
micro_normal_mask_node = nodeutils.find_shader_texture(nodes, "MICRONMASK")
micro_normal_strength = nodeutils.get_node_input(shader_node, "Micro Normal Strength", 1.0)
if micro_normal_mask_node:
micro_normal_mask_bake_node = bake_socket_output(source_mat, mat, micro_normal_mask_node, "Color", "MicroNormalMask")
# Post processing
#
utils.log_info("Post Processing Textures...")
utils.log_info("")
if props.target_mode == "BLENDER":
pass
elif props.target_mode == "GODOT":
pass
elif props.target_mode == "SKETCHFAB":
pass
elif props.target_mode == "GLTF":
if props.pack_gltf:
# BaseMap: RGB: diffuse, A: alpha
combine_diffuse_tex(nodes, source_mat, mat,
diffuse_bake_node, alpha_bake_node)
# GLTF pack: R: Ao, G: Roughness, B: Metallic
combine_gltf(nodes, source_mat, mat, ao_bake_node, roughnesss_bake_node, metallic_bake_node)
elif props.target_mode == "UNITY_URP":
# BaseMap: RGB: diffuse, A: alpha
combine_diffuse_tex(nodes, source_mat, mat,
diffuse_bake_node, alpha_bake_node)
# MetallicAlpha: RGB: Metallic, A: Smoothness = f(Rougness)
make_metallic_smoothness_tex(nodes, source_mat, mat, metallic_bake_node, roughnesss_bake_node)
elif props.target_mode == "UNITY_HDRP":
# BaseMap: RGB: diffuse, A: alpha
combine_diffuse_tex(nodes, source_mat, mat,
diffuse_bake_node, alpha_bake_node)
# Mask: R: Metallic, G: AO, B: Micro-Normal Mask, A: Smoothness = f(Roughness)
combine_hdrp_mask_tex(nodes, source_mat, mat,
metallic_bake_node, ao_bake_node, micro_normal_mask_bake_node, roughnesss_bake_node)
# Detail: R: 0.5, G: Micro-Normal.R, B: 0.5, A: Micro-Normal.G
combine_hdrp_detail_tex(nodes, source_mat, mat,
micro_normal_bake_node)
# invert the thickness map
process_hdrp_subsurfaces_tex(sss_bake_node, thickness_bake_node)
# reconnect the materials
utils.log_info("Reconnecting baked material:")
utils.log_info("")
reconnect_material(mat, ao_strength, sss_radius, bump_distance, normal_strength, micro_normal_strength, micro_normal_scale)
def combine_diffuse_tex(nodes, source_mat, mat, diffuse_node, alpha_node):
diffuse_data = None
alpha_data = None
bsdf_node = nodeutils.get_bsdf_node(nodes)
diffuse_value = nodeutils.get_node_input(bsdf_node, "Base Color", (1,1,1,1))
# image.pixels object fetches the entire array anew every call and is extremely slow to use
# directly so, for speed, make a copy of it into a tuple or a list and work on that.
if diffuse_node:
# read-only tuple copy for fastest read speed
diffuse_data = diffuse_node.image.pixels[:]
if alpha_node:
# read-only tuple copy for fastest read speed
alpha_data = alpha_node.image.pixels[:]
if diffuse_node is None and alpha_node is None:
return
utils.log_info("Combining diffuse with alpha...")
map_suffix = "BaseMap"
target_suffix = get_target_map_suffix(map_suffix)
mat_name = utils.strip_name(mat.name)
size = get_target_map_size(source_mat, map_suffix)
image = make_image_target(nodes, mat_name + "_" + target_suffix, size, False, True)
image_node = nodeutils.make_image_node(nodes, image)
image_node.name = vars.BAKE_PREFIX + mat_name + "_" + map_suffix
image_node.select = True
nodes.active = image_node
# writeable list copy for fastest write speed
image_data = list(image.pixels)
l = len(image_data)
for i in range(0, l, 4):
if diffuse_data:
image_data[i+0] = diffuse_data[i+0]
image_data[i+1] = diffuse_data[i+1]
image_data[i+2] = diffuse_data[i+2]
else:
image_data[i+0] = diffuse_value[0]
image_data[i+1] = diffuse_value[1]
image_data[i+2] = diffuse_value[2]
if alpha_data:
image_data[i+3] = alpha_data[i]
else:
image_data[i+3] = 1
# replace in-place in one go.
image.pixels[:] = image_data
image.update()
image.save()
def combine_hdrp_mask_tex(nodes, source_mat, mat, metallic_node, ao_node, mask_node, roughness_node):
props = bpy.context.scene.CC3BakeProps
metallic_data = None
ao_data = None
mask_data = None
roughness_data = None
if metallic_node:
metallic_data = metallic_node.image.pixels[:]
if ao_node:
ao_data = ao_node.image.pixels[:]
if mask_node:
mask_data = mask_node.image.pixels[:]
if roughness_node:
roughness_data = roughness_node.image.pixels[:]
if metallic_node is None and ao_node is None and mask_node is None and roughness_node is None:
return
utils.log_info("Combining Unity HDRP Mask Texture...")
bsdf_node = nodeutils.get_bsdf_node(nodes)
metallic_value = nodeutils.get_node_input(bsdf_node, "Metallic", 0.0)
roughness_value = nodeutils.get_node_input(bsdf_node, "Roughness", 0.0)
ao_value = 1
mask_value = 1
map_suffix = "Mask"
target_suffix = get_target_map_suffix(map_suffix)
mat_name = utils.strip_name(mat.name)
size = get_target_map_size(source_mat, map_suffix)
image = make_image_target(nodes, mat_name + "_" + target_suffix, size, True, True)
image_node = nodeutils.make_image_node(nodes, image)
image_node.name = vars.BAKE_PREFIX + mat_name + "_" + map_suffix
image_node.select = True
nodes.active = image_node
image_data = list(image.pixels)
l = len(image_data)
# Mask: R: Metallic, G: AO, B: Micro-Normal Mask, A: Smoothness = 0.5 + 0.5*(1-Roughess)^2
for i in range(0, l, 4):
# Red
if metallic_data:
image_data[i] = metallic_data[i]
else:
image_data[i] = metallic_value
# Green
if ao_data:
image_data[i+1] = ao_data[i]
else:
image_data[i+1] = ao_value
# Blue
if mask_data:
image_data[i+2] = mask_data[i]
else:
image_data[i+2] = mask_value
# Alpha
if roughness_data:
roughness = roughness_data[i]
else:
roughness = roughness_value
if props.smoothness_mapping == "SIR":
smoothness = pow(1 - roughness, 2)
elif props.smoothness_mapping == "IRS":
smoothness = 1 - pow(roughness, 2)
elif props.smoothness_mapping == "IRSR":
smoothness = 1 - pow(roughness, 0.5)
elif props.smoothness_mapping == "SRIR":
smoothness = pow(1 - roughness, 0.5)
elif props.smoothness_mapping == "SRIRS":
smoothness = pow(1 - pow(roughness, 2), 0.5)
else: # IR
smoothness = 1 - roughness
image_data[i+3] = smoothness
image.pixels[:] = image_data
image.update()
image.save()
def combine_hdrp_detail_tex(nodes, source_mat, mat, detail_normal_node):
detail_data = None
if detail_normal_node:
detail_data = detail_normal_node.image.pixels[:]
else:
return
utils.log_info("Combining Unity HDRP Detail Texture...")
map_suffix = "Detail"
target_suffix = get_target_map_suffix(map_suffix)
mat_name = utils.strip_name(mat.name)
size = get_target_map_size(source_mat, map_suffix)
image = make_image_target(nodes, mat_name + "_" + target_suffix, size, True, True)
image_node = nodeutils.make_image_node(nodes, image)
image_node.name = vars.BAKE_PREFIX + mat_name + "_" + map_suffix
image_node.select = True
nodes.active = image_node
image_data = list(image.pixels)
l = len(image_data)
# Detail: R: 0.5, G: Micro-Normal.R, B: 0.5, A: Micro-Normal.G
for i in range(0, l, 4):
image_data[i+0] = 0.5
image_data[i+2] = 0.5
if detail_data:
image_data[i+1] = detail_data[i+0]
image_data[i+3] = detail_data[i+1]
else:
image_data[i+1] = 0.5
image_data[i+3] = 0.5
image.pixels[:] = image_data
image.update()
image.save()
def process_hdrp_subsurfaces_tex(sss_node, trans_node):
if trans_node and trans_node.image:
image = trans_node.image
trans_data = list(image.pixels)
l = len(trans_data)
for i in range(0, l, 4):
trans_data[i+0] = 1.0 - trans_data[i+0]
trans_data[i+1] = 1.0 - trans_data[i+1]
trans_data[i+2] = 1.0 - trans_data[i+2]
image.pixels[:] = trans_data
image.update()
image.save()
def make_metallic_smoothness_tex(nodes, source_mat, mat, metallic_node, roughness_node):
props = bpy.context.scene.CC3BakeProps
metallic_data = None
roughness_data = None
if metallic_node and metallic_node.image:
metallic_data = metallic_node.image.pixels[:]
if roughness_node and roughness_node.image:
roughness_data = roughness_node.image.pixels[:]
if metallic_node is None and roughness_node is None:
return
utils.log_info("Create Unity URP/3D Metallic Alpha Texture from Metallic and Roughness...")
bsdf_node = nodeutils.get_bsdf_node(nodes)
roughness_value = nodeutils.get_node_input(bsdf_node, "Roughness", 0.5)
metallic_value = nodeutils.get_node_input(bsdf_node, "Metallic", 0)
map_suffix = "MetallicAlpha"
target_suffix = get_target_map_suffix(map_suffix)
mat_name = utils.strip_name(mat.name)
size = get_target_map_size(source_mat, map_suffix)
image = make_image_target(nodes, mat_name + "_" + target_suffix, size, True, True)
image_node = nodeutils.make_image_node(nodes, image)
image_node.name = vars.BAKE_PREFIX + mat_name + "_" + map_suffix
image_node.select = True
nodes.active = image_node
image_data = list(image.pixels)
l = len(image_data)
# Mask: R: Metallic, G: AO, B: Micro-Normal Mask, A: Smoothness = 0.5 + 0.5*(1-Roughess)^2
for i in range(0, l, 4):
if roughness_data:
roughness = roughness_data[i]
else:
roughness = roughness_value
if metallic_data:
metallic = metallic_data[i]
else:
metallic = metallic_value
if props.smoothness_mapping == "SIR":
smoothness = pow(1 - roughness, 2)
elif props.smoothness_mapping == "IRS":
smoothness = 1 - pow(roughness, 2)
elif props.smoothness_mapping == "IRSR":
smoothness = 1 - pow(roughness, 0.5)
elif props.smoothness_mapping == "SRIR":
smoothness = pow(1 - roughness, 0.5)
elif props.smoothness_mapping == "SRIRS":
smoothness = pow(1 - pow(roughness, 2), 0.5)
else: # IR
smoothness = 1 - roughness
image_data[i+0] = metallic
image_data[i+1] = metallic
image_data[i+2] = metallic
image_data[i+3] = smoothness
image.pixels[:] = image_data
image.update()
image.save()
def combine_gltf(nodes, source_mat, mat, ao_node, roughness_node, metallic_node):
props = bpy.context.scene.CC3BakeProps
metallic_data = None
ao_data = None
roughness_data = None
if metallic_node:
metallic_data = metallic_node.image.pixels[:]
if ao_node:
ao_data = ao_node.image.pixels[:]
if roughness_node:
roughness_data = roughness_node.image.pixels[:]
if metallic_node is None and ao_node is None and roughness_node is None:
return
utils.log_info("Combining GLTF texture pack...")
bsdf_node = nodeutils.get_bsdf_node(nodes)
metallic_value = nodeutils.get_node_input(bsdf_node, "Metallic", 0.0)
roughness_value = nodeutils.get_node_input(bsdf_node, "Roughness", 0.0)
ao_value = 1
map_suffix = "GLTF"
target_suffix = get_target_map_suffix(map_suffix)
mat_name = utils.strip_name(mat.name)
size = get_target_map_size(source_mat, map_suffix)
image = make_image_target(nodes, mat_name + "_" + target_suffix, size, True, False)
image_node = nodeutils.make_image_node(nodes, image)
image_node.name = vars.BAKE_PREFIX + mat_name + "_" + map_suffix
image_node.select = True
nodes.active = image_node