forked from franMarz/TexTools-Blender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utilities_bake.py
568 lines (427 loc) · 15.6 KB
/
utilities_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
import bpy
import bmesh
from mathutils import Vector
from math import pi
from . import utilities_color
from . import settings
keywords_low = ['lowpoly','low','lowp','lp','lo'] #excluded 'l' since TexTools v1.4
keywords_high = ['highpoly','high','highp','hp','hi'] #excluded 'h' since TexTools v1.4
keywords_cage = ['cage'] #excluded 'c' since TexTools v1.4
keywords_float = ['floater','float'] #excluded 'f' since TexTools v1.4
split_chars = [' ','_','.','-']
allMaterials = []
allMaterialsNames = []
elementsCount = 0
class BakeMode:
material = "" #Material name from external blend file
type = 'EMIT'
normal_space = 'TANGENT'
setVColor = None #Set Vertex color method
color = (0.23, 0.23, 0.23, 1) #Background color
engine = 'CYCLES' #render engine, by default CYCLES
composite = None #use composite scene to process end result
use_project = False #Bake projected?
invert = False
relink = {'needed':False}
params = [] #UI Parameters from scene settings
def __init__(self, material="", type='EMIT', normal_space='TANGENT', setVColor=None, color= (0.23, 0.23, 0.23, 1), engine='CYCLES', params = [], composite=None, use_project=False, invert=False, relink = {'needed':False}):
self.material = material
self.type = type
self.normal_space = normal_space
self.setVColor = setVColor
self.color = color
self.engine = engine
self.params = params
self.composite = composite
self.use_project = use_project
self.invert = invert
self.relink = relink
def on_select_bake_mode(mode):
print("Mode changed {}".format(mode))
if len(settings.sets) > 0:
name_texture = "{}_{}".format(settings.sets[0].name, mode)
if name_texture in bpy.data.images:
image = bpy.data.images[name_texture]
# Set background image
for area in bpy.context.screen.areas:
if area.ui_type == 'UV':
area.spaces[0].image = image
def store_bake_settings():
# Render Settings
settings.bake_render_engine = bpy.context.scene.render.engine
settings.bake_cycles_device = bpy.context.scene.cycles.device
settings.bake_cycles_samples = bpy.context.scene.cycles.samples
if settings.bversion >= 2.92:
settings.bake_target_mode = bpy.context.scene.render.bake.target
if settings.bversion < 3:
settings.use_progressive_refine = bpy.context.scene.cycles.use_progressive_refine
if settings.bversion >= 3:
settings.use_denoising = bpy.context.scene.cycles.use_denoising
# Disable Objects that are meant to be hidden
sets = settings.sets
objects_sets = []
for bset in sets:
for obj in bset.objects_low:
if obj not in objects_sets:
objects_sets.append(obj)
for obj in bset.objects_high:
if obj not in objects_sets:
objects_sets.append(obj)
for obj in bset.objects_cage:
if obj not in objects_sets:
objects_sets.append(obj)
settings.bake_objects_hide_render = []
# for obj in bpy.context.view_layer.objects:
# if obj.hide_render == False and obj not in objects_sets:
# Check if layer is active:
# for l in range(0, len(obj.layers)):
# if obj.layers[l] and bpy.context.scene.layers[l]:
# settings.bake_objects_hide_render.append(obj)
# break #sav
for obj in settings.bake_objects_hide_render:
obj.hide_render = True
# obj.cycles_visibility.shadow = False
def restore_bake_settings():
# Render Settings
if settings.bake_render_engine != '':
bpy.context.scene.render.engine = settings.bake_render_engine
bpy.context.scene.cycles.device = settings.bake_cycles_device
bpy.context.scene.cycles.samples = settings.bake_cycles_samples
if settings.bversion >= 2.92:
bpy.context.scene.render.bake.target = settings.bake_target_mode
if settings.bversion < 3:
bpy.context.scene.cycles.use_progressive_refine = settings.use_progressive_refine
if settings.bversion >= 3:
bpy.context.scene.cycles.use_denoising = settings.use_denoising
# Restore Objects that were hidden for baking
for obj in settings.bake_objects_hide_render:
if obj:
obj.hide_render = False
# obj.cycles_visibility.shadow = True
def get_set_name_base(obj):
def remove_digits(name):
# Remove blender naming digits, e.g. cube.001, cube.002,...
if len(name) > 4 and name[-4] == '.' and name[-3:].isdigit():
return name[:-4]
return name
# Reference parent as base name
if obj.parent and obj.parent in bpy.context.selected_objects:
return remove_digits(obj.parent.name).lower()
# Reference group name as base name
elif len(obj.users_collection) == 2:
return remove_digits(obj.users_collection[0].name).lower()
# Use Object name
else:
return remove_digits(obj.name).lower()
def get_set_name(obj):
# Get Basic name
name = get_set_name_base(obj)
# Split by ' ','_','.' etc.
split = name.lower()
for char in split_chars:
split = split.replace(char,' ')
strings = split.split(' ')
# Remove all keys from name
keys = keywords_cage + keywords_high + keywords_low + keywords_float
new_strings = []
for string in strings:
is_found = False
for key in keys:
if string == key:
is_found = True
break
if not is_found:
new_strings.append(string)
elif len(new_strings) > 0:
# No more strings once key is found if we have already something
break
return "_".join(new_strings)
def get_object_type(obj):
name = get_set_name_base(obj)
# Detect by name pattern
split = name.lower()
for char in split_chars:
split = split.replace(char,' ')
strings = split.split(' ')
# Detect float, more rare than low
for string in strings:
for key in keywords_float:
if key == string:
return 'float'
# Detect by modifiers (Only if more than 1 object selected), disabled because I work with subdiv a lot
#if len(bpy.context.selected_objects) > 1:
# if obj.modifiers:
# for modifier in obj.modifiers:
# if modifier.type == 'SUBSURF' and modifier.render_levels > 0:
# return 'high'
# elif modifier.type == 'BEVEL':
# return 'high'
# Detect High first, more rare
for string in strings:
for key in keywords_high:
if key == string:
return 'high'
# Detect cage, more rare than low
for string in strings:
for key in keywords_cage:
if key == string:
return 'cage'
# Detect low
for string in strings:
for key in keywords_low:
if key == string:
return 'low'
# if nothing was detected, assume it is low
return 'low'
def get_baked_images(sets):
images = []
for bset in sets:
name_texture = "{}_".format(bset.name)
for image in bpy.data.images:
if name_texture in image.name:
images.append(image)
return images
def get_bake_sets():
filtered = {}
if len(bpy.context.selected_objects) == 0:
if bpy.context.active_object is not None:
if bpy.context.active_object.mode == 'EDIT' and bpy.context.active_object.type == 'MESH':
filtered[bpy.context.active_object] = get_object_type(bpy.context.active_object)
else:
for obj in bpy.context.selected_objects:
if obj.type == 'MESH':
filtered[obj] = get_object_type(obj)
groups = []
# Group by names
for obj in filtered:
name = get_set_name(obj)
if not groups:
groups.append([obj])
else:
isFound = False
for group in groups:
groupName = get_set_name(group[0])
if name == groupName:
group.append(obj)
isFound = True
break
if not isFound:
groups.append([obj])
# Sort groups alphabetically
keys = [get_set_name(group[0]) for group in groups]
keys.sort()
sorted_groups = []
for key in keys:
for group in groups:
if key == get_set_name(group[0]):
sorted_groups.append(group)
break
groups = sorted_groups
bake_sets = []
for group in groups:
low = []
high = []
cage = []
float = []
for obj in group:
if filtered[obj] == 'low':
low.append(obj)
elif filtered[obj] == 'high':
high.append(obj)
elif filtered[obj] == 'cage':
cage.append(obj)
elif filtered[obj] == 'float':
float.append(obj)
name = get_set_name(group[0])
bake_sets.append(BakeSet(name, low, cage, high, float))
return bake_sets
class BakeSet:
objects_low = [] #low poly geometry
objects_cage = [] #Cage low poly geometry
objects_high = [] #High poly geometry
objects_float = [] #Floating geometry
name = ""
has_issues = False
def __init__(self, name, objects_low, objects_cage, objects_high, objects_float):
self.objects_low = objects_low
self.objects_cage = objects_cage
self.objects_high = objects_high
self.objects_float = objects_float
self.name = name
# Needs low poly objects to bake onto
if len(objects_low) == 0:
self.has_issues = True
# Check Cage Object count to low poly count
if len(objects_cage) > 0 and len(objects_low) != len(objects_cage):
self.has_issues = True
# Check for UV maps
for obj in objects_low:
if len(obj.data.uv_layers) == 0:
self.has_issues = True
break
def assign_vertex_color(obj):
if len(obj.data.vertex_colors) > 0 :
vclsNames = [vcl.name for vcl in obj.data.vertex_colors]
if 'TexTools_temp' in vclsNames:
obj.data.vertex_colors['TexTools_temp'].active = True
else:
obj.data.vertex_colors.new(name='TexTools_temp')
obj.data.vertex_colors['TexTools_temp'].active = True
else:
obj.data.vertex_colors.new(name='TexTools_temp')
def setup_vertex_color_selection(obj):
bpy.ops.object.select_all(action='DESELECT')
obj.select_set( state = True, view_layer = None)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='VERTEX_PAINT')
bpy.context.tool_settings.vertex_paint.brush.color = (0, 0, 0)
bpy.context.object.data.use_paint_mask = False
bpy.ops.paint.vertex_color_set()
bpy.context.tool_settings.vertex_paint.brush.color = (1, 1, 1)
bpy.context.object.data.use_paint_mask = True
bpy.ops.paint.vertex_color_set()
bpy.context.object.data.use_paint_mask = False
# Back to object mode
bpy.ops.object.mode_set(mode='OBJECT')
def setup_vertex_color_dirty(obj):
bpy.ops.object.select_all(action='DESELECT')
obj.select_set( state = True, view_layer = None)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
# Fill white then,
bm = bmesh.from_edit_mesh(obj.data)
colorLayer = bm.loops.layers.color.active
color = utilities_color.safe_color( (1, 1, 1) )
for face in bm.faces:
for loop in face.loops:
loop[colorLayer] = color
obj.data.update()
# Back to object mode
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.paint.vertex_color_dirt(dirt_angle=pi/2)
bpy.ops.paint.vertex_color_dirt()
def setup_vertex_color_id_material(obj, previous_materials):
bpy.ops.object.select_all(action='DESELECT')
obj.select_set( state = True, view_layer = None)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='FACE')
# bm = bmesh.from_edit_mesh(obj.data)
# colorLayer = bm.loops.layers.color.active
for i, mtlname in enumerate(previous_materials[obj]):
if mtlname is not None:
# Select related faces
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bm = bmesh.from_edit_mesh(bpy.context.active_object.data)
for face in bm.faces:
if face.material_index == i:
face.select = True
color = utilities_color.get_color_id(allMaterials.index(bpy.data.materials[mtlname]), 256, jitter=True)
bpy.ops.object.mode_set(mode='VERTEX_PAINT')
bpy.context.tool_settings.vertex_paint.brush.color = color
bpy.context.object.data.use_paint_mask = True
bpy.ops.paint.vertex_color_set()
obj.data.update()
# Back to object mode
bpy.ops.object.mode_set(mode='OBJECT')
def setup_vertex_color_id_element(obj):
bpy.ops.object.select_all(action='DESELECT')
obj.select_set( state = True, view_layer = None)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='FACE')
bm = bmesh.from_edit_mesh(obj.data)
colorLayer = bm.loops.layers.color.active
# Collect elements
processed = set([])
groups = []
for face in bm.faces:
if face not in processed:
bpy.ops.mesh.select_all(action='DESELECT')
face.select = True
bpy.ops.mesh.select_linked(delimit={'NORMAL'})
linked = [face for face in bm.faces if face.select]
for link in linked:
processed.add(link)
groups.append(linked)
global elementsCount
# Color each group
for i in range(0,len(groups)):
color = utilities_color.get_color_id(elementsCount + i, 256, jitter=True)
color = utilities_color.safe_color( color )
for face in groups[i]:
for loop in face.loops:
loop[colorLayer] = color
elementsCount += len(groups)
obj.data.update()
# Back to object mode
bpy.ops.object.mode_set(mode='OBJECT')
def get_image_material(image):
# Clear & Create new material
material = None
if image.name in bpy.data.materials:
# Incorrect existing material, delete first and create new for cycles
material = bpy.data.materials[image.name]
bpy.data.materials.remove(material, do_unlink=True)
material = bpy.data.materials.new(image.name)
else:
material = bpy.data.materials.new(image.name)
# Cycles Material
if bpy.context.scene.render.engine == 'CYCLES' or bpy.context.scene.render.engine == 'BLENDER_EEVEE':
material.use_nodes = True
# Image Node
node_image = None
if "image" in material.node_tree.nodes:
node_image = material.node_tree.nodes["image"]
else:
node_image = material.node_tree.nodes.new("ShaderNodeTexImage")
node_image.name = "image"
node_image.select = True
node_image.image = image
material.node_tree.nodes.active = node_image
#Base Diffuse BSDF
bsdf_node = None
for n in material.node_tree.nodes:
if n.bl_idname == "ShaderNodeBsdfPrincipled":
bsdf_node = n
if "_normal_" in image.name:
# Add Normal Map Nodes
node_normal_map = None
if "normal_map" in material.node_tree.nodes:
node_normal_map = material.node_tree.nodes["normal_map"]
else:
node_normal_map = material.node_tree.nodes.new("ShaderNodeNormalMap")
node_normal_map.name = "normal_map"
# Tangent or World space
if(image.name.endswith("normal_tangent")):
node_normal_map.space = 'TANGENT'
elif(image.name.endswith("normal_object")):
node_normal_map.space = 'WORLD'
# image to normal_map link
material.node_tree.links.new(node_image.outputs[0], node_normal_map.inputs[1])
# normal_map to diffuse_bsdf link
if settings.bversion < 2.91:
material.node_tree.links.new(node_normal_map.outputs[0], bsdf_node.inputs[19])
else:
material.node_tree.links.new(node_normal_map.outputs[0], bsdf_node.inputs[20])
node_normal_map.location = bsdf_node.location - Vector((200, 0))
node_image.location = node_normal_map.location - Vector((200, 0))
else:
# Other images display as Color
# dump(node_image.color_mapping.bl_rna.property_tags)
# image node to diffuse node link
material.node_tree.links.new(node_image.outputs[0], bsdf_node.inputs[0])
return material
elif bpy.context.scene.render.engine == 'BLENDER_EEVEE':
material.use_nodes = True
texture = None
if image.name in bpy.data.textures:
texture = bpy.data.textures[image.name]
else:
texture = bpy.data.textures.new(image.name, 'IMAGE')
texture.image = image
slot = material.texture_slot.add()
slot.texture = texture
slot.mapping = 'FLAT'
# return material