-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathBakeToLayer.py
3068 lines (2451 loc) · 112 KB
/
BakeToLayer.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, re, time, math, bmesh
from bpy.props import *
from mathutils import *
from .common import *
from .bake_common import *
from .subtree import *
from .input_outputs import *
from .node_connections import *
from .node_arrangements import *
from . import lib, Layer, Mask, ImageAtlas, UDIM, vector_displacement_lib, vector_displacement
TEMP_VCOL = '__temp__vcol__'
TEMP_EMISSION = '_TEMP_EMI_'
class YTryToSelectBakedVertexSelect(bpy.types.Operator):
bl_idname = "wm.y_try_to_select_baked_vertex"
bl_label = "Try to reselect baked selected vertex"
bl_description = "Try to reselect baked selected vertex. It might give you wrong results if mesh number of vertex changed"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return get_active_ypaint_node() and context.object.type == 'MESH'
def execute(self, context):
if not hasattr(context, 'bake_info'):
return {'CANCELLED'}
bi = context.bake_info
if len(bi.selected_objects) == 0:
return {'CANCELLED'}
if context.object.mode != 'OBJECT':
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
scene_objs = get_scene_objects()
objs = []
for bso in bi.selected_objects:
if is_bl_newer_than(2, 79):
bsoo = bso.object
else: bsoo = scene_objs.get(bso.object_name)
if bsoo and bsoo not in objs:
objs.append(bsoo)
# Get actual selectable objects
actual_selectable_objs = []
for o in objs:
if is_bl_newer_than(2, 80):
layer_cols = get_object_parent_layer_collections([], bpy.context.view_layer.layer_collection, o)
#for lc in layer_cols:
# print(lc.name)
if layer_cols and not any([lc for lc in layer_cols if lc.exclude or lc.hide_viewport or lc.collection.hide_viewport]):
actual_selectable_objs.append(o)
else:
if not o.hide_select and in_active_279_layer(o):
actual_selectable_objs.append(o)
if len(actual_selectable_objs) == 0:
self.report({'ERROR'}, "Cannot select the object!")
return {'CANCELLED'}
for obj in actual_selectable_objs:
set_object_hide(obj, False)
set_object_select(obj, True)
set_active_object(actual_selectable_objs[0])
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='DESELECT')
for bso in bi.selected_objects:
if is_bl_newer_than(2, 79):
obj = bso.object
else: obj = scene_objs.get(bso.object_name)
if not obj or obj not in actual_selectable_objs: continue
mesh = obj.data
bm = bmesh.from_edit_mesh(mesh)
bm.verts.ensure_lookup_table()
bm.edges.ensure_lookup_table()
bm.faces.ensure_lookup_table()
if bi.selected_face_mode:
context.tool_settings.mesh_select_mode[0] = False
context.tool_settings.mesh_select_mode[1] = False
context.tool_settings.mesh_select_mode[2] = True
for bsv in bso.selected_vertex_indices:
try: bm.faces[bsv.index].select = True
except: pass
else:
context.tool_settings.mesh_select_mode[0] = True
context.tool_settings.mesh_select_mode[1] = False
context.tool_settings.mesh_select_mode[2] = False
for bsv in bso.selected_vertex_indices:
try: bm.verts[bsv.index].select = True
except: pass
return {'FINISHED'}
class YRemoveBakeInfoOtherObject(bpy.types.Operator):
bl_idname = "wm.y_remove_bake_info_other_object"
bl_label = "Remove other object info"
bl_description = "Remove other object bake info, so it won't be automatically baked anymore if you choose to rebake"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return get_active_ypaint_node() and context.object.type == 'MESH'
def execute(self, context):
if not hasattr(context, 'other_object') or not hasattr(context, 'bake_info'):
return {'CANCELLED'}
#if len(context.bake_info.other_objects) == 1:
# self.report({'ERROR'}, "Cannot delete, need at least one object!")
# return {'CANCELLED'}
for i, oo in enumerate(context.bake_info.other_objects):
if oo == context.other_object:
context.bake_info.other_objects.remove(i)
break
return {'FINISHED'}
def update_bake_to_layer_uv_map(self, context):
if not UDIM.is_udim_supported(): return
if get_user_preferences().enable_auto_udim_detection:
mat = get_active_material()
objs = get_all_objects_with_same_materials(mat)
self.use_udim = UDIM.is_uvmap_udim(objs, self.uv_map)
def get_bakeable_objects_and_meshes(mat, cage_object=None):
objs = []
meshes = []
for ob in get_scene_objects():
if ob.type != 'MESH': continue
if hasattr(ob, 'hide_viewport') and ob.hide_viewport: continue
if len(get_uv_layers(ob)) == 0: continue
if len(ob.data.polygons) == 0: continue
if cage_object and cage_object == ob: continue
# Do not bake objects with hide_render on
if ob.hide_render: continue
if not in_renderable_layer_collection(ob): continue
for i, m in enumerate(ob.data.materials):
if m == mat:
ob.active_material_index = i
if ob not in objs and ob.data not in meshes:
objs.append(ob)
meshes.append(ob.data)
return objs, meshes
def bake_to_entity(bprops, overwrite_img=None, segment=None):
T = time.time()
mat = get_active_material()
node = get_active_ypaint_node()
yp = node.node_tree.yp
scene = bpy.context.scene
obj = bpy.context.object
channel_idx = int(bprops.channel_idx) if 'channel_idx' in bprops and len(yp.channels) > 0 else -1
rdict = {}
rdict['message'] = ''
if bprops.type == 'SELECTED_VERTICES' and obj.mode != 'EDIT':
rdict['message'] = "Should be in edit mode!"
return rdict
if bprops.target_type == 'MASK' and len(yp.layers) == 0:
rdict['message'] = "Mask need active layer!"
return rdict
if bprops.type in {'BEVEL_NORMAL', 'BEVEL_MASK'} and not is_bl_newer_than(2, 80):
rdict['message'] = "Blender 2.80+ is needed to use this feature!"
return rdict
if bprops.type in {'MULTIRES_NORMAL', 'MULTIRES_DISPLACEMENT'} and not is_bl_newer_than(2, 80):
rdict['message'] = "Blender 2.80+ is needed to use this feature!"
return rdict
if (hasattr(obj, 'hide_viewport') and obj.hide_viewport) or obj.hide_render:
rdict['message'] = "Please unhide render and viewport of active object!"
return rdict
if bprops.type == 'FLOW' and (bprops.uv_map == '' or bprops.uv_map_1 == '' or bprops.uv_map == bprops.uv_map_1):
rdict['message'] = "UVMap and Straight UVMap cannot be the same or empty!"
return rdict
# Get cage object
cage_object = None
if bprops.type.startswith('OTHER_OBJECT_') and bprops.cage_object_name != '':
cage_object = bpy.data.objects.get(bprops.cage_object_name)
if cage_object:
if any([mod for mod in cage_object.modifiers if mod.type not in {'ARMATURE'}]) or any([mod for mod in obj.modifiers if mod.type not in {'ARMATURE'}]):
rdict['message'] = "Mesh modifiers is not working with cage object for now!"
return rdict
if len(cage_object.data.polygons) != len(obj.data.polygons):
rdict['message'] = "Invalid cage object, the cage mesh must have the same number of faces as the active object!"
return rdict
objs = [obj]
if mat.users > 1:
objs, meshes = get_bakeable_objects_and_meshes(mat, cage_object)
# Count multires objects
multires_count = 0
if bprops.type.startswith('MULTIRES_'):
for ob in objs:
if get_multires_modifier(ob):
multires_count += 1
if not objs or (bprops.type.startswith('MULTIRES_') and multires_count == 0):
rdict['message'] = "No valid objects found to bake!"
return rdict
do_overwrite = False
overwrite_image_name = ''
if overwrite_img:
do_overwrite = True
overwrite_image_name = overwrite_img.name
# Get other objects for other object baking
other_objs = []
if bprops.type.startswith('OTHER_OBJECT_'):
# Get other objects based on selected objects with different material
for o in bpy.context.selected_objects:
if o in objs or not o.data or not hasattr(o.data, 'materials'): continue
if mat.name not in o.data.materials:
other_objs.append(o)
# Try to get other_objects from bake info
if overwrite_img:
bi = segment.bake_info if segment else overwrite_img.y_bake_info
scene_objs = get_scene_objects()
for oo in bi.other_objects:
if is_bl_newer_than(2, 79):
ooo = oo.object
else: ooo = scene_objs.get(oo.object_name)
if ooo:
if is_bl_newer_than(2, 80):
# Check if object is on current view layer
layer_cols = get_object_parent_layer_collections([], bpy.context.view_layer.layer_collection, ooo)
if ooo not in other_objs and any(layer_cols):
other_objs.append(ooo)
else:
o = scene_objs.get(ooo.name)
if o and o not in other_objs:
other_objs.append(o)
if bprops.type == 'OTHER_OBJECT_CHANNELS':
ch_other_objects, ch_other_mats, ch_other_sockets, ch_other_defaults, ch_other_alpha_sockets, ch_other_alpha_defaults, ori_mat_no_nodes = prepare_other_objs_channels(yp, other_objs)
if not other_objs:
if overwrite_img:
rdict['message'] = "No source objects found! They're probably deleted!"
return rdict
else:
rdict['message'] = "Source objects must be selected and it should have different material!"
return rdict
# Get tile numbers
tilenums = [1001]
if bprops.use_udim:
tilenums = UDIM.get_tile_numbers(objs, bprops.uv_map)
# Remember things
book = remember_before_bake(yp, mat=mat)
# FXAA doesn't work with hdr image
# FXAA also does not works well with baked image with alpha, so other object bake will use SSAA instead
use_fxaa = not bprops.hdr and bprops.fxaa and not bprops.type.startswith('OTHER_OBJECT_')
# For now SSAA only works with other object baking
use_ssaa = bprops.ssaa and bprops.type.startswith('OTHER_OBJECT_')
# Denoising only available for AO bake for now
use_denoise = bprops.denoise and bprops.type in {'AO', 'BEVEL_MASK'} and is_bl_newer_than(2, 81)
# SSAA will multiply size by 2 then resize it back
if use_ssaa:
width = bprops.width * 2
height = bprops.height * 2
else:
width = bprops.width
height = bprops.height
# If use baked disp, need to bake normal and height map first
subdiv_setup_changes = False
height_root_ch = get_root_height_channel(yp)
if height_root_ch and bprops.use_baked_disp and not bprops.type.startswith('MULTIRES_'):
if not height_root_ch.enable_subdiv_setup:
height_root_ch.enable_subdiv_setup = True
subdiv_setup_changes = True
# To hold temporary objects
temp_objs = []
# Sometimes Cavity bake will create temporary objects
if (bprops.type == 'CAVITY' and (bprops.subsurf_influence or bprops.use_baked_disp)):
# NOTE: Baking cavity with subdiv setup can only happen if there's only one object and no UDIM
if is_bl_newer_than(4, 2) and len(objs) == 1 and not bprops.use_udim and height_root_ch and height_root_ch.enable_subdiv_setup:
# Check if there's VDM layer
vdm_layer = get_first_vdm_layer(yp)
vdm_uv_name = vdm_layer.uv_name if vdm_layer else bprops.uv_map
# Get baked combined vdm image
combined_vdm_image = vector_displacement.get_combined_vdm_image(objs[0], vdm_uv_name, width=bprops.width, height=bprops.height)
# Bake tangent and bitangent
# NOTE: Only bake the first object tangent since baking combined mesh can cause memory leak at the moment
tanimage, bitimage = vector_displacement.get_tangent_bitangent_images(objs[0], bprops.uv_map)
# Duplicate object
objs = temp_objs = [get_merged_mesh_objects(scene, objs, True, disable_problematic_modifiers=False)]
# Use VDM loader geometry nodes
# NOTE: Geometry nodes currently does not support UDIM, so using UDIM will cause wrong bake result
set_active_object(objs[0])
vdm_loader = vector_displacement_lib.get_vdm_loader_geotree(bprops.uv_map, combined_vdm_image, tanimage, bitimage, 1.0)
bpy.ops.object.modifier_add(type='NODES')
geomod = objs[0].modifiers[-1]
geomod.node_group = vdm_loader
bpy.ops.object.modifier_apply(modifier=geomod.name)
# Remove temporary datas
remove_datablock(bpy.data.node_groups, vdm_loader)
remove_datablock(bpy.data.images, combined_vdm_image)
else:
objs = temp_objs = get_duplicated_mesh_objects(scene, objs, True)
# Join objects then extend with other objects
elif bprops.type.startswith('OTHER_OBJECT_'):
if len(objs) > 1:
objs = [get_merged_mesh_objects(scene, objs)]
temp_objs = objs.copy()
objs.extend(other_objs)
# Join objects if the number of objects is higher than one
elif not bprops.type.startswith('MULTIRES_') and len(objs) > 1 and not is_join_objects_problematic(yp):
objs = temp_objs = [get_merged_mesh_objects(scene, objs, True)]
fill_mode = 'FACE'
obj_vertex_indices = {}
if bprops.type == 'SELECTED_VERTICES':
if bpy.context.tool_settings.mesh_select_mode[0] or bpy.context.tool_settings.mesh_select_mode[1]:
fill_mode = 'VERTEX'
if is_bl_newer_than(2, 80):
edit_objs = [o for o in objs if o.mode == 'EDIT']
else: edit_objs = [obj]
for ob in edit_objs:
mesh = ob.data
bm = bmesh.from_edit_mesh(mesh)
bm.verts.ensure_lookup_table()
#bm.edges.ensure_lookup_table()
bm.faces.ensure_lookup_table()
v_indices = []
if fill_mode == 'FACE':
for face in bm.faces:
if face.select:
v_indices.append(face.index)
#for loop in face.loops:
# v_indices.append(loop.index)
else:
for vert in bm.verts:
if vert.select:
v_indices.append(vert.index)
obj_vertex_indices[ob.name] = v_indices
bpy.ops.object.mode_set(mode = 'OBJECT')
for ob in objs:
try:
vcol = new_vertex_color(ob, TEMP_VCOL)
set_obj_vertex_colors(ob, vcol.name, (0.0, 0.0, 0.0, 1.0))
set_active_vertex_color(ob, vcol)
except: pass
bpy.ops.object.mode_set(mode = 'EDIT')
bpy.ops.mesh.y_vcol_fill(color_option ='WHITE')
bpy.ops.object.mode_set(mode = 'OBJECT')
# Check if there's channel using alpha
alpha_outp = None
for c in yp.channels:
if c.enable_alpha:
alpha_outp = node.outputs.get(c.name + io_suffix['ALPHA'])
if alpha_outp: break
# Prepare bake settings
if bprops.type == 'AO':
if alpha_outp:
# If there's alpha channel use standard AO bake, which has lesser quality denoising
bake_type = 'AO'
else:
# When there is no alpha channel use combined render bake, which has better denoising
bake_type = 'COMBINED'
elif bprops.type == 'MULTIRES_NORMAL':
bake_type = 'NORMALS'
elif bprops.type == 'MULTIRES_DISPLACEMENT':
bake_type = 'DISPLACEMENT'
elif bprops.type in {'OTHER_OBJECT_NORMAL', 'OBJECT_SPACE_NORMAL'}:
bake_type = 'NORMAL'
else:
bake_type = 'EMIT'
# If use only local, hide other objects
hide_other_objs = bprops.type != 'AO' or bprops.only_local
# Fit tilesize to bake resolution if samples is equal 1
if bprops.samples <= 1:
tile_x = width
tile_y = height
else:
tile_x = 256
tile_y = 256
# Cage object only used for other object baking
cage_object_name = bprops.cage_object_name if bprops.type.startswith('OTHER_OBJECT_') else ''
prepare_bake_settings(
book, objs, yp, samples=bprops.samples, margin=bprops.margin,
uv_map=bprops.uv_map, bake_type=bake_type, #disable_problematic_modifiers=True,
bake_device=bprops.bake_device, hide_other_objs=hide_other_objs,
bake_from_multires=bprops.type.startswith('MULTIRES_'), tile_x = tile_x, tile_y = tile_y,
use_selected_to_active=bprops.type.startswith('OTHER_OBJECT_'),
max_ray_distance=bprops.max_ray_distance, cage_extrusion=bprops.cage_extrusion,
source_objs=other_objs, use_denoising=False, margin_type=bprops.margin_type,
cage_object_name = cage_object_name,
normal_space = 'OBJECT' if bprops.type == 'OBJECT_SPACE_NORMAL' else 'TANGENT'
)
# Set multires level
#ori_multires_levels = {}
if bprops.type.startswith('MULTIRES_'): #or bprops.type == 'AO':
for ob in objs:
mod = get_multires_modifier(ob)
#mod.render_levels = mod.total_levels
if mod and bprops.type.startswith('MULTIRES_'):
mod.render_levels = bprops.multires_base
mod.levels = bprops.multires_base
#ori_multires_levels[ob.name] = mod.render_levels
# Setup for cavity
if bprops.type == 'CAVITY':
tt = time.time()
print('BAKE TO LAYER: Applying subsurf/multires for Cavity bake...')
# Set vertex color for cavity
for ob in objs:
set_active_object(ob)
if bprops.subsurf_influence or bprops.use_baked_disp:
need_to_be_applied_modifiers = []
for m in ob.modifiers:
if m.type in {'SUBSURF', 'MULTIRES'} and m.levels > 0 and m.show_viewport:
# Set multires to the highest level
if m.type == 'MULTIRES':
m.levels = m.total_levels
need_to_be_applied_modifiers.append(m)
# Also apply displace
if m.type == 'DISPLACE' and m.show_viewport:
need_to_be_applied_modifiers.append(m)
# Apply shape keys and modifiers
if any(need_to_be_applied_modifiers):
if ob.data.shape_keys:
if is_bl_newer_than(3, 3):
bpy.ops.object.shape_key_remove(all=True, apply_mix=True)
else: bpy.ops.object.shape_key_remove(all=True)
for m in need_to_be_applied_modifiers:
bpy.ops.object.modifier_apply(modifier=m.name)
# Create new vertex color for dirt
try:
vcol = new_vertex_color(ob, TEMP_VCOL)
set_obj_vertex_colors(ob, vcol.name, (1.0, 1.0, 1.0, 1.0))
set_active_vertex_color(ob, vcol)
except: pass
bpy.ops.paint.vertex_color_dirt(dirt_angle=math.pi / 2)
print('BAKE TO LAYER: Applying subsurf/multires is done in', '{:0.2f}'.format(time.time() - tt), 'seconds!')
# Setup for flow
if bprops.type == 'FLOW':
bpy.ops.object.mode_set(mode = 'OBJECT')
for ob in objs:
uv_layers = get_uv_layers(ob)
main_uv = uv_layers.get(bprops.uv_map)
straight_uv = uv_layers.get(bprops.uv_map_1)
if main_uv and straight_uv:
flow_vcol = get_flow_vcol(ob, main_uv, straight_uv)
# Flip normals setup
if bprops.flip_normals:
#ori_mode[obj.name] = obj.mode
if is_bl_newer_than(2, 80):
# Deselect other objects first
for o in other_objs:
o.select_set(False)
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.flip_normals()
bpy.ops.object.mode_set(mode='OBJECT')
# Reselect other objects
for o in other_objs:
o.select_set(True)
else:
for ob in objs:
if ob in other_objs: continue
scene.objects.active = ob
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.flip_normals()
bpy.ops.object.mode_set(mode='OBJECT')
# More setup
ori_mods = {}
ori_viewport_mods = {}
ori_mat_ids = {}
ori_loop_locs = {}
ori_multires_levels = {}
# Do not disable modifiers for surface based bake types
disable_problematic_modifiers = bprops.type not in {'CAVITY', 'POINTINESS', 'BEVEL_NORMAL', 'BEVEL_MASK'}
for ob in objs:
# Disable few modifiers
ori_mods[ob.name] = [m.show_render for m in ob.modifiers]
ori_viewport_mods[ob.name] = [m.show_viewport for m in ob.modifiers]
if bprops.type.startswith('MULTIRES_'):
mul = get_multires_modifier(ob)
multires_index = 99
if mul:
for i, m in enumerate(ob.modifiers):
if m == mul: multires_index = i
if i > multires_index:
m.show_render = False
m.show_viewport = False
elif disable_problematic_modifiers and ob not in other_objs:
for m in get_problematic_modifiers(ob):
m.show_render = False
ori_mat_ids[ob.name] = []
ori_loop_locs[ob.name] = []
if bprops.subsurf_influence and not bprops.use_baked_disp and not bprops.type.startswith('MULTIRES_'):
for m in ob.modifiers:
if m.type == 'MULTIRES':
ori_multires_levels[ob.name] = m.render_levels
m.render_levels = m.total_levels
break
if len(ob.data.materials) > 1:
active_mat_id = [i for i, m in enumerate(ob.data.materials) if m == mat]
if active_mat_id: active_mat_id = active_mat_id[0]
else: continue
uv_layers = get_uv_layers(ob)
uvl = uv_layers.get(bprops.uv_map)
for p in ob.data.polygons:
# Set uv location to (0,0) if not using current material
if uvl and not bprops.force_bake_all_polygons:
uv_locs = []
for li in p.loop_indices:
uv_locs.append(uvl.data[li].uv.copy())
if p.material_index != active_mat_id:
uvl.data[li].uv = Vector((0.0, 0.0))
ori_loop_locs[ob.name].append(uv_locs)
# Need to assign all polygon to active material if there are multiple materials
ori_mat_ids[ob.name].append(p.material_index)
p.material_index = active_mat_id
# Create bake nodes
tex = mat.node_tree.nodes.new('ShaderNodeTexImage')
bsdf = mat.node_tree.nodes.new('ShaderNodeEmission')
normal_bake = None
geometry = None
vector_math = None
vector_math_1 = None
if bprops.type == 'BEVEL_NORMAL':
#bsdf = mat.node_tree.nodes.new('ShaderNodeBsdfDiffuse')
normal_bake = mat.node_tree.nodes.new('ShaderNodeGroup')
normal_bake.node_tree = get_node_tree_lib(lib.BAKE_NORMAL_ACTIVE_UV)
elif bprops.type == 'BEVEL_MASK':
geometry = mat.node_tree.nodes.new('ShaderNodeNewGeometry')
vector_math = mat.node_tree.nodes.new('ShaderNodeVectorMath')
vector_math.operation = 'CROSS_PRODUCT'
if is_bl_newer_than(2, 81):
vector_math_1 = mat.node_tree.nodes.new('ShaderNodeVectorMath')
vector_math_1.operation = 'LENGTH'
# Get output node and remember original bsdf input
output = get_active_mat_output_node(mat.node_tree)
ori_bsdf = output.inputs[0].links[0].from_socket
if bprops.type == 'AO':
# If there's alpha channel use standard AO bake, which has lesser quality denoising
if alpha_outp:
src = None
if hasattr(scene.cycles, 'use_fast_gi'):
scene.cycles.use_fast_gi = True
if scene.world:
scene.world.light_settings.distance = bprops.ao_distance
# When there is no alpha channel use combined render bake, which has better denoising
else:
src = mat.node_tree.nodes.new('ShaderNodeAmbientOcclusion')
if 'Distance' in src.inputs:
src.inputs['Distance'].default_value = bprops.ao_distance
# Links
if not is_bl_newer_than(2, 80):
mat.node_tree.links.new(src.outputs[0], output.inputs[0])
else:
mat.node_tree.links.new(src.outputs['AO'], bsdf.inputs[0])
mat.node_tree.links.new(bsdf.outputs[0], output.inputs[0])
elif bprops.type == 'POINTINESS':
src = mat.node_tree.nodes.new('ShaderNodeNewGeometry')
# Links
mat.node_tree.links.new(src.outputs['Pointiness'], bsdf.inputs[0])
mat.node_tree.links.new(bsdf.outputs[0], output.inputs[0])
elif bprops.type == 'CAVITY':
src = mat.node_tree.nodes.new('ShaderNodeGroup')
src.node_tree = get_node_tree_lib(lib.CAVITY)
# Set vcol
vcol_node = src.node_tree.nodes.get('vcol')
vcol_node.attribute_name = TEMP_VCOL
mat.node_tree.links.new(src.outputs[0], bsdf.inputs[0])
mat.node_tree.links.new(bsdf.outputs[0], output.inputs[0])
elif bprops.type == 'DUST':
src = mat.node_tree.nodes.new('ShaderNodeGroup')
src.node_tree = get_node_tree_lib(lib.DUST)
mat.node_tree.links.new(src.outputs[0], bsdf.inputs[0])
mat.node_tree.links.new(bsdf.outputs[0], output.inputs[0])
elif bprops.type == 'PAINT_BASE':
src = mat.node_tree.nodes.new('ShaderNodeGroup')
src.node_tree = get_node_tree_lib(lib.PAINT_BASE)
mat.node_tree.links.new(src.outputs[0], bsdf.inputs[0])
mat.node_tree.links.new(bsdf.outputs[0], output.inputs[0])
elif bprops.type == 'BEVEL_NORMAL':
src = mat.node_tree.nodes.new('ShaderNodeBevel')
src.samples = bprops.bevel_samples
src.inputs[0].default_value = bprops.bevel_radius
#mat.node_tree.links.new(src.outputs[0], bsdf.inputs['Normal'])
mat.node_tree.links.new(src.outputs[0], normal_bake.inputs[0])
mat.node_tree.links.new(normal_bake.outputs[0], bsdf.inputs[0])
mat.node_tree.links.new(bsdf.outputs[0], output.inputs[0])
elif bprops.type == 'BEVEL_MASK':
src = mat.node_tree.nodes.new('ShaderNodeBevel')
src.samples = bprops.bevel_samples
src.inputs[0].default_value = bprops.bevel_radius
mat.node_tree.links.new(geometry.outputs['Normal'], vector_math.inputs[0])
mat.node_tree.links.new(src.outputs[0], vector_math.inputs[1])
#mat.node_tree.links.new(src.outputs[0], bsdf.inputs['Normal'])
if is_bl_newer_than(2, 81):
mat.node_tree.links.new(vector_math.outputs[0], vector_math_1.inputs[0])
mat.node_tree.links.new(vector_math_1.outputs[1], bsdf.inputs[0])
else:
mat.node_tree.links.new(vector_math.outputs[1], bsdf.inputs[0])
mat.node_tree.links.new(bsdf.outputs[0], output.inputs[0])
elif bprops.type == 'SELECTED_VERTICES':
if is_bl_newer_than(2, 80):
src = mat.node_tree.nodes.new('ShaderNodeVertexColor')
src.layer_name = TEMP_VCOL
else:
src = mat.node_tree.nodes.new('ShaderNodeAttribute')
src.attribute_name = TEMP_VCOL
mat.node_tree.links.new(src.outputs[0], bsdf.inputs[0])
mat.node_tree.links.new(bsdf.outputs[0], output.inputs[0])
elif bprops.type == 'FLOW':
# Set vcol
src = mat.node_tree.nodes.new('ShaderNodeAttribute')
src.attribute_name = FLOW_VCOL
mat.node_tree.links.new(src.outputs[0], bsdf.inputs[0])
mat.node_tree.links.new(bsdf.outputs[0], output.inputs[0])
else:
src = None
mat.node_tree.links.new(bsdf.outputs[0], output.inputs[0])
# Get number of target images
ch_ids = [0]
# Other object channels related
all_other_mats = []
ori_from_nodes = {}
ori_from_sockets = {}
if bprops.type == 'OTHER_OBJECT_CHANNELS':
ch_ids = [i for i, coo in enumerate(ch_other_objects) if len(coo) > 0]
# Get all other materials
for oo in other_objs:
for m in oo.data.materials:
if m == None or not m.use_nodes: continue
if m not in all_other_mats:
all_other_mats.append(m)
# Remember original socket connected to outputs
for m in all_other_mats:
soc = None
from_node = ''
from_socket = ''
mout = get_material_output(m)
if mout:
for l in mout.inputs[0].links:
soc = l.from_socket
from_node = l.from_node.name
from_socket = l.from_socket.name
# Create temporary emission
temp_emi = m.node_tree.nodes.get(TEMP_EMISSION)
if not temp_emi:
temp_emi = m.node_tree.nodes.new('ShaderNodeEmission')
temp_emi.name = TEMP_EMISSION
m.node_tree.links.new(temp_emi.outputs[0], mout.inputs[0])
ori_from_nodes[m.name] = from_node
ori_from_sockets[m.name] = from_socket
# Newly created layer index and image
active_id = None
image = None
for idx in ch_ids:
# Image name and colorspace
image_name = bprops.name
colorspace = get_srgb_name()
if bprops.type == 'OTHER_OBJECT_CHANNELS':
root_ch = yp.channels[idx]
image_name += ' ' + yp.channels[idx].name
# Hide irrelevant objects
for oo in other_objs:
if oo not in ch_other_objects[idx]:
oo.hide_render = True
else: oo.hide_render = False
if root_ch.type == 'NORMAL':
bake_type = 'NORMAL'
# Set back original socket
for m in all_other_mats:
mout = get_material_output(m)
if mout:
nod = m.node_tree.nodes.get(ori_from_nodes[m.name])
if nod:
soc = nod.outputs.get(ori_from_sockets[m.name])
if soc: m.node_tree.links.new(soc, mout.inputs[0])
else:
bake_type = 'EMIT'
# Set emission connection
connected_mats = []
for j, m in enumerate(ch_other_mats[idx]):
if m in connected_mats: continue
default = ch_other_defaults[idx][j]
socket = ch_other_sockets[idx][j]
temp_emi = m.node_tree.nodes.get(TEMP_EMISSION)
if not temp_emi: continue
if default != None:
# Set default
if type(default) == float:
temp_emi.inputs[0].default_value = (default, default, default, 1.0)
else: temp_emi.inputs[0].default_value = (default[0], default[1], default[2], 1.0)
# Break link
for l in temp_emi.inputs[0].links:
m.node_tree.links.remove(l)
elif socket:
m.node_tree.links.new(socket, temp_emi.inputs[0])
connected_mats.append(m)
colorspace = get_noncolor_name() if root_ch.colorspace == 'LINEAR' else get_srgb_name()
elif bprops.type in {'BEVEL_NORMAL', 'MULTIRES_NORMAL', 'OTHER_OBJECT_NORMAL', 'OBJECT_SPACE_NORMAL'}:
colorspace = get_noncolor_name()
# Using float image will always make the image linear/non-color
if bprops.hdr:
colorspace = get_noncolor_name()
# Base color of baked image
if bprops.type == 'AO':
color = [1.0, 1.0, 1.0, 1.0]
elif bprops.type in {'BEVEL_NORMAL', 'MULTIRES_NORMAL', 'OTHER_OBJECT_NORMAL', 'OBJECT_SPACE_NORMAL'}:
if bprops.hdr:
color = [0.7354, 0.7354, 1.0, 1.0]
else:
color = [0.5, 0.5, 1.0, 1.0]
elif bprops.type == 'FLOW':
color = [0.5, 0.5, 0.0, 1.0]
else:
if bprops.hdr:
color = [0.7354, 0.7354, 0.7354, 1.0]
else: color = [0.5, 0.5, 0.5, 1.0]
# Make image transparent if its baked from other objects
if bprops.type.startswith('OTHER_OBJECT_'):
color[3] = 0.0
# New target image
if bprops.use_udim:
image = bpy.data.images.new(
name=image_name, width=width, height=height,
alpha=True, float_buffer=bprops.hdr, tiled=True
)
# Fill tiles
for tilenum in tilenums:
UDIM.fill_tile(image, tilenum, color, width, height)
UDIM.initial_pack_udim(image, color)
# Remember base color
image.yui.base_color = color
else:
image = bpy.data.images.new(
name=image_name, width=width, height=height,
alpha=True, float_buffer=bprops.hdr
)
image.generated_color = color
image.colorspace_settings.name = colorspace
# Set image filepath if overwrite image is found
if do_overwrite:
# Get overwrite image again to avoid pointer error
overwrite_img = bpy.data.images.get(overwrite_image_name)
#if idx == 0:
if idx == min(ch_ids):
if not overwrite_img.packed_file and overwrite_img.filepath != '':
image.filepath = overwrite_img.filepath
else:
layer = yp.layers[yp.active_layer_index]
root_ch = yp.channels[idx]
ch = layer.channels[idx]
if root_ch.type == 'NORMAL':
source = get_channel_source_1(ch, layer)
else: source = get_channel_source(ch, layer)
if source and hasattr(source, 'image') and source.image and not source.image.packed_file and source.image.filepath != '':
image.filepath = source.image.filepath
# Set bake image
tex.image = image
mat.node_tree.nodes.active = tex
# Bake!
try:
if bprops.type.startswith('MULTIRES_'):
bpy.ops.object.bake_image()
else:
if bake_type != 'EMIT':
bpy.ops.object.bake(type=bake_type)
else: bpy.ops.object.bake()
except Exception as e:
# Try to use CPU if GPU baking is failed
if bprops.bake_device == 'GPU':
print('EXCEPTIION: GPU baking failed! Trying to use CPU...')
bprops.bake_device = 'CPU'
scene.cycles.device = 'CPU'
if bprops.type.startswith('MULTIRES_'):
bpy.ops.object.bake_image()
else:
if bake_type != 'EMIT':
bpy.ops.object.bake(type=bake_type)
else: bpy.ops.object.bake()
else:
print('EXCEPTIION:', e)
if use_fxaa: fxaa_image(image, False, bake_device=bprops.bake_device)
# Bake other object alpha
if bprops.type in {'OTHER_OBJECT_NORMAL', 'OTHER_OBJECT_CHANNELS'}:
alpha_found = False
if bprops.type == 'OTHER_OBJECT_CHANNELS':
# Set emission connection
for j, m in enumerate(ch_other_mats[idx]):
alpha_default = ch_other_alpha_defaults[idx][j]
alpha_socket = ch_other_alpha_sockets[idx][j]
temp_emi = m.node_tree.nodes.get(TEMP_EMISSION)
if not temp_emi: continue
if alpha_default != 1.0:
alpha_found = True
# Set alpha_default
if type(alpha_default) == float:
temp_emi.inputs[0].default_value = (alpha_default, alpha_default, alpha_default, 1.0)
else: temp_emi.inputs[0].default_value = (alpha_default[0], alpha_default[1], alpha_default[2], 1.0)
# Break link
for l in temp_emi.inputs[0].links:
m.node_tree.links.remove(l)
elif alpha_socket:
alpha_found = True
m.node_tree.links.new(alpha_socket, temp_emi.inputs[0])
else:
alpha_found = True
if alpha_found:
temp_img = image.copy()
temp_img.colorspace_settings.name = get_noncolor_name()
tex.image = temp_img
# Set temp filepath
if image.source == 'TILED':
temp_img.name = '__TEMP__'
UDIM.initial_pack_udim(temp_img)
# Need to use clear so there's alpha on the baked image
scene.render.bake.use_clear = True
# Bake emit can will create alpha image
bpy.ops.object.bake(type='EMIT')
# Set tile pixels
for tilenum in tilenums:
# Swap tile