-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathbake_common.py
2587 lines (2070 loc) · 96.6 KB
/
bake_common.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, time, os, numpy, tempfile
from bpy.props import *
from .common import *
from .input_outputs import *
from .node_connections import *
from . import lib, Layer, ImageAtlas, UDIM
BL28_HACK = True
BAKE_PROBLEMATIC_MODIFIERS = {
'MIRROR',
'SOLIDIFY',
'ARRAY',
}
JOIN_PROBLEMATIC_TEXCOORDS = {
'Object',
'Generated',
}
EMPTY_IMG_NODE = '___EMPTY_IMAGE__'
ACTIVE_UV_NODE = '___ACTIVE_UV__'
TEMP_EMIT_WHITE = '__EMIT_WHITE__'
TEMP_MATERIAL = '__TEMP_MATERIAL_'
def get_problematic_modifiers(obj):
pms = []
for m in obj.modifiers:
if m.type in BAKE_PROBLEMATIC_MODIFIERS:
# Mirror modifier is not problematic if mirror uv is used
if m.type == 'MIRROR':
if not m.use_mirror_u and not m.use_mirror_v:
if is_bl_newer_than(2, 80):
if m.offset_u == 0.0 and m.offset_v == 0.0:
pms.append(m)
else: pms.append(m)
else: pms.append(m)
return pms
''' Search for texcoord node that output join problematic texcoords outside yp '''
def search_join_problematic_texcoord(tree, node):
for inp in node.inputs:
for link in inp.links:
from_node = link.from_node
from_socket = link.from_socket
if from_node.type == 'TEX_COORD' and from_socket.name in JOIN_PROBLEMATIC_TEXCOORDS:
return True
elif node.type == 'GROUP' and node.node_tree and not node.node_tree.yp.is_ypaint_node:
output = [n for n in node.node_tree.nodes if n.type == 'GROUP_OUTPUT' and n.is_active_output]
if output:
if search_join_problematic_texcoord(node.node_tree, output[0]):
return True
if search_join_problematic_texcoord(tree, from_node):
return True
return False
def is_there_any_missmatched_attribute_types(objs):
# Get number of attributes founds
attr_counts = {}
for obj in objs:
for attr in obj.data.attributes:
if attr.name not in attr_counts:
attr_counts[attr.name] = 1
else:
attr_counts[attr.name] += 1
# Get the same attribute used in all objects
same_attrs = []
for name, count in attr_counts.items():
if count == len(objs):
same_attrs.append(name)
# Is there any missmatched type data
for name in same_attrs:
data_type = ''
domain = ''
for obj in objs:
attr = obj.data.attributes[name]
if data_type == '':
data_type = attr.data_type
elif data_type != attr.data_type:
return True
if domain == '':
domain = attr.domain
elif domain != attr.domain:
return True
return False
def is_join_objects_problematic(yp, mat=None):
for layer in yp.layers:
for mask in layer.masks:
if mask.type in {'VCOL', 'HEMI', 'COLOR_ID'}:
continue
if mask.texcoord_type in JOIN_PROBLEMATIC_TEXCOORDS or mask.type in {'OBJECT_INDEX'}:
print('INFO: Merged bake is not happening because there\'s object index mask')
return True
if layer.type in {'VCOL', 'COLOR', 'BACKGROUND', 'HEMI', 'GROUP'}:
continue
if layer.texcoord_type in JOIN_PROBLEMATIC_TEXCOORDS:
print('INFO: Merged bake is not happening because there\'s problematic texcoord used')
return True
if mat:
output = get_material_output(mat)
if output:
if search_join_problematic_texcoord(mat.node_tree, output):
print('INFO: Merged bake is not happening because there\'s problematic texcoord used outside node')
return True
# Check for missmatched color attribute data
if is_bl_newer_than(3, 2):
objs = get_all_objects_with_same_materials(mat, True)
if is_there_any_missmatched_attribute_types(objs):
print('INFO: Merged bake is not happening because there\'s missmatched attribute data types')
return True
return False
def bake_object_op():
try:
bpy.ops.object.bake()
except Exception as e:
scene = bpy.context.scene
if scene.cycles.device == 'GPU':
print('EXCEPTIION: GPU baking failed! Trying to use CPU...')
scene.cycles.device = 'CPU'
bpy.ops.object.bake()
else:
print('EXCEPTIION:', e)
def remember_before_bake(yp=None, mat=None):
book = {}
book['scene'] = scene = bpy.context.scene
book['obj'] = obj = bpy.context.object
book['mode'] = obj.mode
uv_layers = get_uv_layers(obj)
ypui = bpy.context.window_manager.ypui
# Remember render settings
book['ori_engine'] = scene.render.engine
book['ori_bake_type'] = scene.cycles.bake_type
book['ori_samples'] = scene.cycles.samples
book['ori_threads_mode'] = scene.render.threads_mode
book['ori_margin'] = scene.render.bake.margin
book['ori_use_clear'] = scene.render.bake.use_clear
book['ori_normal_space'] = scene.render.bake.normal_space
book['ori_simplify'] = scene.render.use_simplify
book['ori_device'] = scene.cycles.device
if hasattr(scene.render.bake, 'use_pass_direct'): book['ori_use_pass_direct'] = scene.render.bake.use_pass_direct
if hasattr(scene.render.bake, 'use_pass_indirect'): book['ori_use_pass_indirect'] = scene.render.bake.use_pass_indirect
if hasattr(scene.render.bake, 'use_pass_diffuse'): book['ori_use_pass_diffuse'] = scene.render.bake.use_pass_diffuse
if hasattr(scene.render.bake, 'use_pass_emit'): book['ori_use_pass_emit'] = scene.render.bake.use_pass_emit
if hasattr(scene.render.bake, 'use_pass_ambient_occlusion'):
book['ori_use_pass_ambient_occlusion'] = scene.render.bake.use_pass_ambient_occlusion
if hasattr(scene.render, 'tile_x'):
book['ori_tile_x'] = scene.render.tile_x
book['ori_tile_y'] = scene.render.tile_y
book['ori_use_selected_to_active'] = scene.render.bake.use_selected_to_active
if hasattr(scene.render.bake, 'max_ray_distance'):
book['ori_max_ray_distance'] = scene.render.bake.max_ray_distance
book['ori_cage_extrusion'] = scene.render.bake.cage_extrusion
book['ori_use_cage'] = scene.render.bake.use_cage
if is_bl_newer_than(2, 80):
book['ori_cage_object_name'] = scene.render.bake.cage_object.name if scene.render.bake.cage_object else ''
else: book['ori_cage_object_name'] = scene.render.bake.cage_object
if hasattr(scene.render.bake, 'margin_type'):
book['ori_margin_type'] = scene.render.bake.margin_type
if hasattr(scene.cycles, 'use_denoising'):
book['ori_use_denoising'] = scene.cycles.use_denoising
if hasattr(scene.cycles, 'use_fast_gi'):
book['ori_use_fast_gi'] = scene.cycles.use_fast_gi
if hasattr(scene.render.bake, 'target'):
book['ori_bake_target'] = scene.render.bake.target
if is_bl_newer_than(2, 80):
book['ori_material_override'] = bpy.context.view_layer.material_override
else: book['ori_material_override'] = scene.render.layers.active.material_override
# Multires related
book['ori_use_bake_multires'] = scene.render.use_bake_multires
book['ori_use_bake_clear'] = scene.render.use_bake_clear
book['ori_render_bake_type'] = scene.render.bake_type
book['ori_bake_margin'] = scene.render.bake_margin
if is_bl_newer_than(2, 81) and not is_bl_newer_than(3) and scene.cycles.device == 'GPU' and 'compute_device_type' in bpy.context.preferences.addons['cycles'].preferences:
book['compute_device_type'] = bpy.context.preferences.addons['cycles'].preferences['compute_device_type']
# Remember uv
book['ori_active_uv'] = uv_layers.active.name
active_render_uvs = [u for u in uv_layers if u.active_render]
if active_render_uvs:
book['ori_active_render_uv'] = active_render_uvs[0].name
# Remember scene objects
if is_bl_newer_than(2, 80):
book['ori_hide_selects'] = [o for o in bpy.context.view_layer.objects if o.hide_select]
book['ori_active_selected_objs'] = [o for o in bpy.context.view_layer.objects if o.select_get()]
book['ori_hide_renders'] = [o for o in bpy.context.view_layer.objects if o.hide_render]
book['ori_hide_viewports'] = [o for o in bpy.context.view_layer.objects if o.hide_viewport]
book['ori_hide_objs'] = [o for o in bpy.context.view_layer.objects if o.hide_get()]
layer_cols = get_all_layer_collections([], bpy.context.view_layer.layer_collection)
book['ori_layer_col_hide_viewport'] = [lc for lc in layer_cols if lc.hide_viewport]
book['ori_layer_col_exclude'] = [lc for lc in layer_cols if lc.exclude]
book['ori_col_hide_viewport'] = [c for c in bpy.data.collections if c.hide_viewport]
book['ori_col_hide_render'] = [c for c in bpy.data.collections if c.hide_render]
else:
book['ori_hide_selects'] = [o for o in scene.objects if o.hide_select]
book['ori_active_selected_objs'] = [o for o in scene.objects if o.select]
book['ori_hide_renders'] = [o for o in scene.objects if o.hide_render]
book['ori_hide_objs'] = [o for o in scene.objects if o.hide]
book['ori_scene_layers'] = [i for i in range(20) if scene.layers[i]]
# Remember image editor images
book['editor_images'] = [a.spaces[0].image for a in bpy.context.screen.areas if a.type == 'IMAGE_EDITOR']
book['editor_pins'] = [a.spaces[0].use_image_pin for a in bpy.context.screen.areas if a.type == 'IMAGE_EDITOR']
# Remember world settings
if scene.world:
book['ori_distance'] = scene.world.light_settings.distance
# Remember ypui
#book['ori_disable_temp_uv'] = ypui.disable_auto_temp_uv_update
# Remember yp
if yp:
book['parallax_ch'] = get_root_parallax_channel(yp)
else: book['parallax_ch'] = None
# Remember material props
if mat:
book['ori_bsdf'] = mat.yp.ori_bsdf
# Remember all objects using the same material
objs = get_all_objects_with_same_materials(obj.active_material, True)
book['ori_mat_objs'] = [o.name for o in objs]
book['ori_mat_objs_active_nodes'] = []
# Remember other material active nodes
for o in objs:
active_node_names = []
for m in o.data.materials:
if m and m.use_nodes and m.node_tree.nodes.active:
active_node_names.append(m.node_tree.nodes.active.name)
continue
active_node_names.append('')
book['ori_mat_objs_active_nodes'].append(active_node_names)
return book
def get_active_render_uv_node(tree, active_render_uv_name):
act_uv = tree.nodes.get(ACTIVE_UV_NODE)
if not act_uv:
act_uv = tree.nodes.new('ShaderNodeUVMap')
act_uv.name = ACTIVE_UV_NODE
act_uv.uv_map = active_render_uv_name
return act_uv
def add_active_render_uv_node(tree, active_render_uv_name):
for n in tree.nodes:
# Check for vector input
if n.bl_idname.startswith('ShaderNodeTex'):
vec = n.inputs.get('Vector')
if vec and len(vec.links) == 0:
act_uv = get_active_render_uv_node(tree, active_render_uv_name)
tree.links.new(act_uv.outputs[0], vec)
# Check for texcoord node
if n.type == 'TEX_COORD':
for l in n.outputs['UV'].links:
act_uv = get_active_render_uv_node(tree, active_render_uv_name)
tree.links.new(act_uv.outputs[0], l.to_socket)
# Check for normal map
if n.type == 'NORMAL_MAP':
n.uv_map = active_render_uv_name
if n.type == 'GROUP' and n.node_tree and not n.node_tree.yp.is_ypaint_node:
add_active_render_uv_node(n.node_tree, active_render_uv_name)
def prepare_other_objs_channels(yp, other_objs):
ch_other_objects = []
ch_other_mats = []
ch_other_sockets = []
ch_other_defaults = []
ch_other_alpha_sockets = []
ch_other_alpha_defaults = []
ori_mat_no_nodes = []
valid_bsdf_types = ['BSDF_PRINCIPLED', 'BSDF_DIFFUSE', 'EMISSION']
for ch in yp.channels:
objs = []
mats = []
sockets = []
defaults = []
alpha_sockets = []
alpha_defaults = []
for o in other_objs:
# Normal channel will always use any objects
if ch.type == 'NORMAL':
objs.append(o)
continue
# Set new material if there's no material
if len(o.data.materials) == 0:
temp_mat = get_temp_default_material()
o.data.materials.append(temp_mat)
else:
for i, m in enumerate(o.data.materials):
if m == None:
temp_mat = get_temp_default_material()
o.data.materials[i] = temp_mat
elif not m.use_nodes:
if m not in ori_mat_no_nodes:
ori_mat_no_nodes.append(m)
m.use_nodes = True
for mat in o.data.materials:
if mat == None: continue
if mat in mats: continue
if not mat.use_nodes: continue
# Get material output
output = get_material_output(mat)
if not output: continue
socket = None
default = None
alpha_socket = None
alpha_default = 1.0
# If material originally aren't using nodes
if mat in ori_mat_no_nodes:
if ch.name == 'Color' and hasattr(mat, 'diffuse_color'):
default = mat.diffuse_color
elif hasattr(mat, ch.name):
default = getattr(mat, ch.name)
elif hasattr(mat, ch.name.lower()):
default = getattr(mat, ch.name.lower())
# Search material nodes for yp node
yp_node = get_closest_yp_node_backward(output)
if yp_node:
oyp = yp_node.node_tree.yp
if ch.name in oyp.channels:
socket = yp_node.outputs[ch.name]
# Check for alpha channel
for och in oyp.channels:
if och.enable_alpha: # and och.name == ch.name:
alpha_socket = yp_node.outputs.get(och.name + io_suffix['ALPHA'])
# Check for possible sockets available on the bsdf node
if not socket:
# Search for main bsdf
bsdf_node = get_closest_bsdf_backward(output, valid_bsdf_types)
if ch.name == 'Color' and bsdf_node.type == 'BSDF_PRINCIPLED':
socket = bsdf_node.inputs['Base Color']
elif ch.name in bsdf_node.inputs:
socket = bsdf_node.inputs[ch.name]
if socket:
if len(socket.links) == 0:
if default == None:
default = socket.default_value
else:
socket = socket.links[0].from_socket
# Get alpha socket
alpha_socket = bsdf_node.inputs.get('Alpha')
if alpha_socket:
if len(alpha_socket.links) == 0:
alpha_default = alpha_socket.default_value
alpha_socket = None
else:
alpha_socket = alpha_socket.links[0].from_socket
# Append objects and materials if socket is found
if socket or default:
mats.append(mat)
sockets.append(socket)
defaults.append(default)
alpha_sockets.append(alpha_socket)
alpha_defaults.append(alpha_default)
if o not in objs:
objs.append(o)
ch_other_objects.append(objs)
ch_other_mats.append(mats)
ch_other_sockets.append(sockets)
ch_other_defaults.append(defaults)
ch_other_alpha_sockets.append(alpha_sockets)
ch_other_alpha_defaults.append(alpha_defaults)
return ch_other_objects, ch_other_mats, ch_other_sockets, ch_other_defaults, ch_other_alpha_sockets, ch_other_alpha_defaults, ori_mat_no_nodes
def recover_other_objs_channels(other_objs, ori_mat_no_nodes):
for o in other_objs:
if len(o.data.materials) == 1 and o.data.materials[0].name == TEMP_MATERIAL:
o.data.materials.clear()
else:
for i, m in reversed(list(enumerate(o.data.materials))):
if m.name == TEMP_MATERIAL:
o.data.materials.pop(index=i)
for m in ori_mat_no_nodes:
m.use_nodes = False
remove_temp_default_material()
def prepare_bake_settings(
book, objs, yp=None, samples=1, margin=5, uv_map='', bake_type='EMIT',
disable_problematic_modifiers=False, hide_other_objs=True, bake_from_multires=False,
tile_x=64, tile_y=64, use_selected_to_active=False, max_ray_distance=0.0, cage_extrusion=0.0,
bake_target = 'IMAGE_TEXTURES',
source_objs=[], bake_device='CPU', use_denoising=False, margin_type='ADJACENT_FACES', cage_object_name='',
normal_space='TANGENT',
):
scene = bpy.context.scene
ypui = bpy.context.window_manager.ypui
scene.render.engine = 'CYCLES'
scene.cycles.samples = samples
scene.render.threads_mode = 'AUTO'
scene.render.bake.margin = margin
#scene.render.bake.use_clear = True
scene.render.bake.use_clear = False
scene.render.bake.use_selected_to_active = use_selected_to_active
if hasattr(scene.render.bake, 'max_ray_distance'):
scene.render.bake.max_ray_distance = max_ray_distance
scene.render.bake.cage_extrusion = cage_extrusion
cage_object = bpy.data.objects.get(cage_object_name) if cage_object_name != '' else None
scene.render.bake.use_cage = True if cage_object else False
if cage_object:
if is_bl_newer_than(2, 80): scene.render.bake.cage_object = cage_object
else: scene.render.bake.cage_object = cage_object.name
scene.render.use_simplify = False
if hasattr(scene.render.bake, 'use_pass_direct'): scene.render.bake.use_pass_direct = True
if hasattr(scene.render.bake, 'use_pass_indirect'): scene.render.bake.use_pass_indirect = True
if hasattr(scene.render.bake, 'use_pass_diffuse'): scene.render.bake.use_pass_diffuse = True
if hasattr(scene.render.bake, 'use_pass_emit'): scene.render.bake.use_pass_emit = True
if hasattr(scene.render.bake, 'use_pass_ambient_occlusion'): scene.render.bake.use_pass_ambient_occlusion = True
if hasattr(scene.render, 'tile_x'):
scene.render.tile_x = tile_x
scene.render.tile_y = tile_y
if hasattr(scene.cycles, 'use_denoising'):
scene.cycles.use_denoising = use_denoising
if hasattr(scene.render.bake, 'target'):
scene.render.bake.target = bake_target
if hasattr(scene.render.bake, 'margin_type'):
scene.render.bake.margin_type = margin_type
if is_bl_newer_than(2, 80):
bpy.context.view_layer.material_override = None
else: scene.render.layers.active.material_override = None
if bake_from_multires:
scene.render.use_bake_multires = True
scene.render.bake_type = bake_type
scene.render.bake_margin = margin
scene.render.use_bake_clear = False
else:
scene.render.use_bake_multires = False
scene.cycles.bake_type = bake_type
# Old blender will always use CPU
if not is_bl_newer_than(2, 80):
scene.cycles.device = 'CPU'
else: scene.cycles.device = bake_device
# Use CUDA bake if Optix is selected
if (is_bl_newer_than(2, 81) and not is_bl_newer_than(3) and 'compute_device_type' in bpy.context.preferences.addons['cycles'].preferences and
bpy.context.preferences.addons['cycles'].preferences['compute_device_type'] == 3):
#scene.cycles.device = 'CPU'
bpy.context.preferences.addons['cycles'].preferences['compute_device_type'] = 1
if bake_type == 'NORMAL':
scene.render.bake.normal_space = normal_space
# Disable other object selections and select only active object
if is_bl_newer_than(2, 80):
# Disable exclude only works on source objects
for o in source_objs:
layer_cols = get_object_parent_layer_collections([], bpy.context.view_layer.layer_collection, o)
for lc in layer_cols:
lc.exclude = False
# Show viewport and render of object layer collection
for o in objs:
o.hide_select = False
o.hide_viewport = False
o.hide_render = False
layer_cols = get_object_parent_layer_collections([], bpy.context.view_layer.layer_collection, o)
for lc in layer_cols:
lc.hide_viewport = False
lc.collection.hide_viewport = False
lc.collection.hide_render = False
if hide_other_objs:
for o in bpy.context.view_layer.objects:
if o not in objs:
o.hide_render = True
#for o in scene.objects:
for o in bpy.context.view_layer.objects:
o.select_set(False)
for obj in objs:
obj.hide_set(False)
if bake_from_multires:
# Do not select object without multires modifier
mod = get_multires_modifier(obj)
if not mod:
obj.select_set(False)
else: obj.select_set(True)
else:
obj.select_set(True)
#print(obj.name, obj.hide_render, obj.select_get())
# Disable material override
book['material_override'] = bpy.context.view_layer.material_override
bpy.context.view_layer.material_override = None
else:
for obj in objs:
obj.hide_select = False
obj.hide_render = False
if hide_other_objs:
for o in scene.objects:
if o not in objs:
o.hide_render = True
for o in scene.objects:
o.select = False
for obj in objs:
obj.hide = False
obj.select = True
# Unhide layer objects
if not in_active_279_layer(obj):
for i in range(20):
if obj.layers[i] and not scene.layers[i]:
scene.layers[i] = True
break
# Blender 2.76 needs all objects to be UV unwrapped
if not is_bl_newer_than(2, 77):
ori_active_object = scene.objects.active
uv_layers = get_uv_layers(obj)
if len(uv_layers) == 0:
scene.objects.active = obj
bpy.ops.node.y_add_simple_uvs()
if scene.objects.active != ori_active_object:
scene.objects.active = ori_active_object
book['obj_mods_lib'] = {}
if disable_problematic_modifiers:
for obj in objs:
book['obj_mods_lib'][obj.name] = {}
book['obj_mods_lib'][obj.name]['disabled_mods'] = []
book['obj_mods_lib'][obj.name]['disabled_viewport_mods'] = []
for mod in get_problematic_modifiers(obj):
if mod.show_render:
mod.show_render = False
book['obj_mods_lib'][obj.name]['disabled_mods'].append(mod.name)
if mod.show_viewport:
mod.show_viewport = False
book['obj_mods_lib'][obj.name]['disabled_viewport_mods'].append(mod.name)
# Disable auto temp uv update
#ypui.disable_auto_temp_uv_update = True
# Set to object mode
try: bpy.ops.object.mode_set(mode = 'OBJECT')
except: pass
# Disable parallax channel
if book['parallax_ch']:
book['parallax_ch'].enable_parallax = False
for o in objs:
mat = o.active_material
if not mat: continue
# Add extra uv nodes for non connected texture nodes outside yp node
if uv_map != '':
uv_layers = get_uv_layers(o)
active_render_uvs = [u for u in uv_layers if u.active_render]
if active_render_uvs:
active_render_uv = active_render_uvs[0]
# Only add new uv node if target uv map is different than active render uv
if active_render_uv.name != uv_map:
add_active_render_uv_node(mat.node_tree, active_render_uv.name)
for m in o.data.materials:
if not m or not m.use_nodes: continue
# Create temporary image texture node to make sure
# other materials inside single object did not bake to their active image
if m != mat:
temp = m.node_tree.nodes.get(EMPTY_IMG_NODE)
if not temp:
temp = m.node_tree.nodes.new('ShaderNodeTexImage')
temp.name = EMPTY_IMG_NODE
m.node_tree.nodes.active = temp
# Set active uv layers
if uv_map != '':
for obj in objs:
if obj.type != 'MESH': continue
#set_active_uv_layer(obj, uv_map)
uv_layers = get_uv_layers(obj)
uv = uv_layers.get(uv_map)
if uv:
uv_layers.active = uv
uv.active_render = True
def recover_bake_settings(book, yp=None, recover_active_uv=False, mat=None):
scene = book['scene']
obj = book['obj']
uv_layers = get_uv_layers(obj)
ypui = bpy.context.window_manager.ypui
scene.render.engine = book['ori_engine']
scene.cycles.samples = book['ori_samples']
scene.cycles.bake_type = book['ori_bake_type']
scene.render.threads_mode = book['ori_threads_mode']
scene.render.bake.margin = book['ori_margin']
scene.render.bake.use_clear = book['ori_use_clear']
scene.render.bake.normal_space = book['ori_normal_space']
scene.render.use_simplify = book['ori_simplify']
scene.cycles.device = book['ori_device']
if hasattr(scene.render.bake, 'use_pass_direct'): scene.render.bake.use_pass_direct = book['ori_use_pass_direct']
if hasattr(scene.render.bake, 'use_pass_indirect'): scene.render.bake.use_pass_indirect = book['ori_use_pass_indirect']
if hasattr(scene.render.bake, 'use_pass_emit'): scene.render.bake.use_pass_emit = book['ori_use_pass_emit']
if hasattr(scene.render.bake, 'use_pass_diffuse'): scene.render.bake.use_pass_diffuse = book['ori_use_pass_diffuse']
if hasattr(scene.render.bake, 'use_pass_ambient_occlusion'): scene.render.bake.use_pass_ambient_occlusion = book['ori_use_pass_ambient_occlusion']
if hasattr(scene.render, 'tile_x'):
scene.render.tile_x = book['ori_tile_x']
scene.render.tile_y = book['ori_tile_y']
if hasattr(scene.cycles, 'use_denoising'):
scene.cycles.use_denoising = book['ori_use_denoising']
if hasattr(scene.cycles, 'use_fast_gi'):
scene.cycles.use_fast_gi = book['ori_use_fast_gi']
if hasattr(scene.render.bake, 'target'):
scene.render.bake.target = book['ori_bake_target']
if hasattr(scene.render.bake, 'margin_type'):
scene.render.bake.margin_type = book['ori_margin_type']
scene.render.bake.use_selected_to_active = book['ori_use_selected_to_active']
if hasattr(scene.render.bake, 'max_ray_distance'):
scene.render.bake.max_ray_distance = book['ori_max_ray_distance']
scene.render.bake.cage_extrusion = book['ori_cage_extrusion']
scene.render.bake.use_cage = book['ori_use_cage']
if book['ori_cage_object_name'] != '':
cage_object = bpy.data.objects.get(book['ori_cage_object_name'])
if cage_object:
if is_bl_newer_than(2, 80): scene.render.bake.cage_object = cage_object
else: scene.render.bake.cage_object = cage_object.name
if is_bl_newer_than(2, 80):
bpy.context.view_layer.material_override = book['ori_material_override']
else: scene.render.layers.active.material_override = book['ori_material_override']
# Multires related
scene.render.use_bake_multires = book['ori_use_bake_multires']
scene.render.use_bake_clear = book['ori_use_bake_clear']
scene.render.bake_type = book['ori_render_bake_type']
scene.render.bake_margin = book['ori_bake_margin']
if 'compute_device_type' in book:
bpy.context.preferences.addons['cycles'].preferences['compute_device_type'] = book['compute_device_type']
if is_bl_newer_than(2, 80) and 'material_override' in book:
bpy.context.view_layer.material_override = book['material_override']
# Recover world settings
if scene.world:
scene.world.light_settings.distance = book['ori_distance']
# Recover uv
if recover_active_uv:
uvl = uv_layers.get(book['ori_active_uv'])
if uvl: uv_layers.active = uvl
# NOTE: Blender 2.90 or lower need to use active render so the UV in image editor paint mode is updated
if not is_bl_newer_than(2, 91):
if 'ori_active_render_uv' in book:
uvl = uv_layers.get(book['ori_active_render_uv'])
if uvl: uvl.active_render = True
if is_bl_newer_than(2, 91):
if 'ori_active_render_uv' in book:
uvl = uv_layers.get(book['ori_active_render_uv'])
if uvl: uvl.active_render = True
# Recover active object and mode
if is_bl_newer_than(2, 80):
bpy.context.view_layer.objects.active = obj
else: scene.objects.active = obj
bpy.ops.object.mode_set(mode = book['mode'])
# Disable other object selections
if is_bl_newer_than(2, 80):
# Recover collections
layer_cols = get_all_layer_collections([], bpy.context.view_layer.layer_collection)
for lc in layer_cols:
if lc in book['ori_layer_col_hide_viewport']:
lc.hide_viewport = True
else: lc.hide_viewport = False
if lc in book['ori_layer_col_exclude']:
lc.exclude = True
else: lc.exclude = False
for c in bpy.data.collections:
if c in book['ori_col_hide_viewport']:
c.hide_viewport = True
else: c.hide_viewport = False
if c in book['ori_col_hide_render']:
c.hide_render = True
else: c.hide_render = False
objs = [o for o in bpy.context.view_layer.objects]
for o in objs:
if o in book['ori_active_selected_objs']:
o.select_set(True)
else: o.select_set(False)
if o in book['ori_hide_renders']:
o.hide_render = True
else: o.hide_render = False
if o in book['ori_hide_viewports']:
o.hide_viewport = True
else: o.hide_viewport = False
if o in book['ori_hide_objs']:
o.hide_set(True)
else: o.hide_set(False)
if o in book['ori_hide_selects']:
o.hide_select = True
else: o.hide_select = False
else:
for o in scene.objects:
if o in book['ori_active_selected_objs']:
o.select = True
else: o.select = False
if o in book['ori_hide_renders']:
o.hide_render = True
else: o.hide_render = False
if o in book['ori_hide_objs']:
o.hide = True
else: o.hide = False
if o in book['ori_hide_selects']:
o.hide_select = True
else: o.hide_select = False
for i in range(20):
scene.layers[i] = i in book['ori_scene_layers']
# Recover image editors
for i, area in enumerate([a for a in bpy.context.screen.areas if a.type == 'IMAGE_EDITOR']):
# Some image can be deleted after baking process so use try except
try: area.spaces[0].image = book['editor_images'][i]
except: area.spaces[0].image = None
area.spaces[0].use_image_pin = book['editor_pins'][i]
# Recover active object
# Recover ypui
#ypui.disable_auto_temp_uv_update = book['ori_disable_temp_uv']
# Recover parallax
if book['parallax_ch']:
book['parallax_ch'].enable_parallax = True
# Recover modifiers
for obj_name, lib in book['obj_mods_lib'].items():
o = get_scene_objects().get(obj_name)
if o:
for mod_name in lib['disabled_mods']:
mod = o.modifiers.get(mod_name)
if mod: mod.show_render = True
for mod_name in lib['disabled_viewport_mods']:
mod = o.modifiers.get(mod_name)
if mod: mod.show_viewport = True
if mat:
# Recover stored material original bsdf for preview
if 'ori_bsdf' in book:
mat.yp.ori_bsdf = book['ori_bsdf']
# Recover other material active nodes
if 'ori_mat_objs' in book:
for i, o_name in enumerate(book['ori_mat_objs']):
o = bpy.data.objects.get(o_name)
if not o: continue
for j, m in enumerate(o.data.materials):
if not m or not m.use_nodes: continue
active_node = m.node_tree.nodes.get(book['ori_mat_objs_active_nodes'][i][j])
m.node_tree.nodes.active = active_node
# Remove temporary nodes
temp = m.node_tree.nodes.get(EMPTY_IMG_NODE)
if temp: m.node_tree.nodes.remove(temp)
#act_uv = m.node_tree.nodes.get(ACTIVE_UV_NODE)
#if act_uv: m.node_tree.nodes.remove(act_uv)
def prepare_composite_settings(res_x=1024, res_y=1024, use_hdr=False):
book = {}
# Remember original scene
book['ori_scene_name'] = bpy.context.scene.name
# Remember active object and view layer
book['ori_viewlayer'] = bpy.context.window.view_layer.name if bpy.context.window.view_layer and is_bl_newer_than(2, 80) else ''
book['ori_object'] = bpy.context.object.name if bpy.context.object else ''
# Check if original viewport is using camera view
area = bpy.context.area
book['ori_camera_view'] = area.type == 'VIEW_3D' and area.spaces[0].region_3d.view_perspective == 'CAMERA'
# Create new temporary scene
scene = bpy.data.scenes.new(name='TEMP_COMPOSITE_SCENE')
bpy.context.window.scene = scene
# Set up render settings
scene.cycles.samples = 1
if hasattr(scene, 'eevee'):
scene.eevee.taa_render_samples = 1
scene.render.resolution_x = res_x
scene.render.resolution_y = res_y
scene.render.resolution_percentage = 100
scene.render.pixel_aspect_x = 1.0
scene.render.pixel_aspect_y = 1.0
scene.use_nodes = True
scene.view_settings.view_transform = 'Standard' if is_bl_newer_than(2, 80) else 'Default'
# Float/HDR image related
scene.render.image_settings.file_format = 'OPEN_EXR' if use_hdr else 'PNG'
scene.render.image_settings.color_mode = 'RGBA'
scene.render.image_settings.color_depth = '32' if use_hdr else '8'
# Remember temp scene name
book['temp_scene_name'] = scene.name
# Create temporary camera
if not scene.camera:
cam_data = bpy.data.cameras.new('TEMP_CAM')
cam_obj = bpy.data.objects.new('TEMP_CAM', cam_data)
link_object(scene, cam_obj)
scene.camera = cam_obj
book['temp_camera_name'] = cam_obj.name
return book
def recover_composite_settings(book):
scene = bpy.data.scenes.get(book['temp_scene_name'])
# Remove temporary objects
if 'temp_camera_name' in book:
cam_obj = bpy.data.objects.get(book['temp_camera_name'])
if cam_obj:
cam = cam_obj.data
remove_datablock(bpy.data.objects, cam_obj)
remove_datablock(bpy.data.cameras, cam)
# Remove temp scene
remove_datablock(bpy.data.scenes, scene)
# Go back to original scene
scene = bpy.data.scenes.get(book['ori_scene_name'])
bpy.context.window.scene = scene
# Recover camera view
if book['ori_camera_view']:
bpy.context.area.spaces[0].region_3d.view_perspective = 'CAMERA'
# Recover view layer
if is_bl_newer_than(2, 80):
ori_viewlayer = bpy.context.scene.view_layers.get(book['ori_viewlayer'])
if ori_viewlayer and bpy.context.window.view_layer != ori_viewlayer:
bpy.context.window.view_layer = ori_viewlayer
# Recover active object
ori_object = bpy.data.objects.get(book['ori_object'])
if ori_object and bpy.context.object != ori_object:
set_active_object(ori_object)
def denoise_image(image):
if not is_bl_newer_than(2, 81): return image
T = time.time()
print('DENOISE: Doing Denoise pass on', image.name + '...')
# Preparing settings
book = prepare_composite_settings(use_hdr=image.is_float)
scene = bpy.context.scene
# Set up compositor
tree = scene.node_tree
composite = [n for n in tree.nodes if n.type == 'COMPOSITE'][0]
denoise = tree.nodes.new('CompositorNodeDenoise')
denoise.use_hdr = image.is_float
image_node = tree.nodes.new('CompositorNodeImage')
image_node.image = image
gamma = None
if image.colorspace_settings.name != get_srgb_name() and not image.is_float:
gamma = tree.nodes.new('CompositorNodeGamma')
gamma.inputs[1].default_value = 2.2
rgb = image_node.outputs[0]
if gamma:
tree.links.new(rgb, gamma.inputs[0])
rgb = gamma.outputs[0]
tree.links.new(rgb, denoise.inputs['Image'])
rgb = denoise.outputs[0]
tree.links.new(rgb, composite.inputs[0])
if image.source == 'TILED':
tilenums = [tile.number for tile in image.tiles]
else: tilenums = [1001]
# Get temporary filepath
ext = 'exr' if image.is_float else 'png'
filepath = os.path.join(tempfile.gettempdir(), 'TEST_RENDER__.' + ext)
for tilenum in tilenums:
# Swap tile to 1001 to access the data
if tilenum != 1001:
UDIM.swap_tile(image, 1001, tilenum)
# Set render resolution
scene.render.resolution_x = image.size[0]
scene.render.resolution_y = image.size[1]
# Render image!
bpy.ops.render.render()
# Save the image
render_result = next(img for img in bpy.data.images if img.type == "RENDER_RESULT")
render_result.save_render(filepath)
temp_image = bpy.data.images.load(filepath)
# Copy image pixels
copy_image_pixels(temp_image, image)
# Remove temp image
remove_datablock(bpy.data.images, temp_image)
os.remove(filepath)
# Swap back the tile
if tilenum != 1001:
UDIM.swap_tile(image, 1001, tilenum)
# Recover settings