-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
688 lines (529 loc) · 20.3 KB
/
__init__.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
import math
import bpy
import os
bl_info = {
'name': 'Blender Skunk',
'description': 'Collection of tools for processing models for CHARK games',
'author': 'CHARK',
'tracker_url': 'https://github.com/chark/blender-skunk',
'doc_url': 'https://github.com/chark/blender-skunk',
'support': 'COMMUNITY',
'version': (0, 0, 14),
'blender': (4, 3, 0),
'category': 'Object',
}
class OpDistributeObjects(bpy.types.Operator):
bl_idname = 'object.skunk_distribute_objects'
bl_label = 'Distribute Objects'
bl_description = 'Distributes selected objects evenly for easy viewing and processing'
bl_options = {'REGISTER', 'UNDO'}
distance: bpy.props.IntProperty(
name='Distance',
description='Distance between objects on selected Axis',
default=10,
min=-1000,
max=1000
)
axis: bpy.props.EnumProperty(
name='Axis',
description='Axis to distribute objects along',
items=[
('X', 'X Axis', 'Distribute along the X axis'),
('Y', 'Y Axis', 'Distribute along the Y axis'),
('Z', 'Z Axis', 'Distribute along the Z axis'),
],
default='X'
)
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def execute(self, context):
objects = sorted(
context.selected_objects[:],
key=lambda object: object.name
)
self.distribute_objects(
objects=objects,
distance=self.distance
)
self.report(
{'INFO'},
f'Distributed {len(objects)} objects on X axis'
)
return {'FINISHED'}
def distribute_objects(self, objects, distance=10):
offset = 0
for object in objects:
if object.parent:
continue
loc = object.location.copy()
if self.axis == 'X':
object.location = (offset, loc.y, loc.z)
elif self.axis == 'Y':
object.location = (loc.x, offset, loc.z)
elif self.axis == 'Z':
object.location = (loc.x, loc.y, offset)
offset += distance
class OpCreateEmptyParents(bpy.types.Operator):
bl_idname = 'object.skunk_create_empty_parents'
bl_label = 'Create Empty Parents'
bl_description = 'Creates empty parent for each selected object'
bl_options = {'REGISTER', 'UNDO'}
child_name_suffix: bpy.props.StringProperty(
name='Child Name Suffix',
description='Suffix appended to child names',
default='LOD0'
)
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def execute(self, context):
objects = context.selected_objects[:]
self.create_empty_parents(
objects=objects,
child_name_suffix=self.child_name_suffix
)
self.report(
{'INFO'},
f'Created empty parents for {len(objects)} objects'
)
return {'FINISHED'}
@staticmethod
def create_empty_parents(objects, child_name_suffix='Child'):
for object in objects:
object_name = object.name
parent_object = OpCreateEmptyParents.create_empty_parent(object)
object.name = f"{object_name}_{child_name_suffix}"
parent_object.name = object_name
@staticmethod
def create_empty_parent(object):
# Create parent
bpy.ops.object.add(type='EMPTY')
parent_object = bpy.context.object
# Clear parent object collections
for collection in parent_object.users_collection:
collection.objects.unlink(parent_object)
# Move parent to the same collections as child
for collection in object.users_collection:
collection.objects.link(parent_object)
# Move parent
object_location = object.location.copy()
parent_object.location = object_location
# Parent child
object.parent = parent_object
object.location = (0, 0, 0)
return parent_object
class OpMatchMeshNames(bpy.types.Operator):
bl_idname = 'object.skunk_match_mesh_names'
bl_label = 'Match Mesh Names'
bl_description = 'Matches names of selected object mesh data to object names'
bl_options = {'REGISTER', 'UNDO'}
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def execute(self, context):
objects = context.selected_objects[:]
updated_objects = self.match_mesh_name_to_object(objects)
self.report(
{'INFO'},
f'Matched mesh names of {len(updated_objects)} objects'
)
return {'FINISHED'}
@staticmethod
def match_mesh_name_to_object(objects, updated_objects=None):
if updated_objects is None:
updated_objects = []
for object in objects:
object_data = object.data
if object_data and object_data.users == 1:
object_data.name = object.name
updated_objects.append(object)
else:
OpMatchMeshNames.match_mesh_name_to_object(object.children, updated_objects)
return updated_objects
class OpSortMeshByMaterial(bpy.types.Operator):
bl_idname = 'object.skunk_sort_mesh_by_material'
bl_label = 'Sort Mesh By Material'
bl_description = (
'Sorts mesh data by material information, this ensures same material '
'order on each selected object'
)
bl_options = {'REGISTER', 'UNDO'}
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def execute(self, context):
objects = context.selected_objects[:]
valid_objects = self.get_valid_objects(objects)
self.sort_mesh_data(valid_objects)
self.report(
{'INFO'},
f'Sorted mesh data of {len(valid_objects)} objects'
)
return {'FINISHED'}
@staticmethod
def get_valid_objects(objects):
valid_objects = []
for object in objects:
if object.type == 'MESH':
valid_objects.append(object)
else:
for child_object in object.children_recursive:
if child_object.type == 'MESH':
valid_objects.append(child_object)
return valid_objects
@staticmethod
def sort_mesh_data(objects):
for object in objects:
bpy.context.view_layer.objects.active = object
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.sort_elements(
type='MATERIAL',
elements={'FACE'}
)
bpy.ops.object.mode_set(mode='OBJECT')
class OpCreateUVs(bpy.types.Operator):
bl_idname = 'object.skunk_create_uvs'
bl_label = 'Create UVs'
bl_description = 'Creates UV0 & UV1, UV1 being a light-map UV'
bl_options = {'REGISTER', 'UNDO'}
angle_limit: bpy.props.FloatProperty(
name='Angle Limit',
description='Angle limit of Smart UV Project',
default=math.radians(89.0),
min=0.0,
max=math.radians(89.0),
subtype='ANGLE'
)
island_margin: bpy.props.FloatProperty(
name='Island Margin',
description='Island Margin of Smart UV Project',
default=0.1,
min=0.0,
max=1.0
)
# Old approach using lightmap pack - results in iffy UVs which cause leaks
# pack_quality: bpy.props.IntProperty(
# name='Light-map UV Quality',
# description='Pack Quality of lightmap UV (aka UV1)',
# default=48,
# min=1,
# max=48
# )
# Old approach using lightmap pack - results in iffy UVs which cause leaks
# margin: bpy.props.FloatProperty(
# name='Light-map UV Margin',
# description='Margin of lightmap UV (aka UV1)',
# default=0.5,
# min=0.0,
# max=1.0
# )
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def execute(self, context):
objects = self.get_valid_objects(context.selected_objects[:])
self.normalize_uv_layers(objects)
self.create_lightmap_uvs_smart(
objects=objects,
angle_limit=self.angle_limit,
island_margin=self.island_margin
)
self.report(
{'INFO'},
f'Created UVs for {len(objects)} objects'
)
return {'FINISHED'}
@staticmethod
def get_valid_objects(objects):
valid_objects = []
for object in objects:
if object.type == 'MESH':
valid_objects.append(object)
else:
for child_object in object.children_recursive:
if child_object.type == 'MESH':
valid_objects.append(child_object)
return valid_objects
@staticmethod
def normalize_uv_layers(objects):
for object in objects:
uv_layers = object.data.uv_layers
uv_index = 0
for uv_layer in uv_layers:
uv_layer.name = f'UV{uv_index}'
uv_index = uv_index + 1
uv_index = len(uv_layers)
while len(uv_layers) < 2:
uv_layers.new(name=f'UV{uv_index}')
uv_index = uv_index + 1
@staticmethod
def create_lightmap_uvs_smart(objects, angle_limit, island_margin):
for object in objects:
bpy.context.view_layer.objects.active = object
# Set the current UV map to UV1
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
object.data.uv_layers.active = object.data.uv_layers.get('UV1')
# Perform lightmap unpacking on UV1
bpy.ops.uv.smart_project(
angle_limit=angle_limit,
island_margin=island_margin,
area_weight=1.0,
scale_to_bounds=True,
correct_aspect=True,
)
bpy.ops.object.mode_set(mode='OBJECT')
# Old approach using lightmap pack - results in iffy UVs which cause leaks
@staticmethod
def create_lightmap_uvs_simple(objects, pack_quality, margin):
for object in objects:
bpy.context.view_layer.objects.active = object
# Set the current UV map to UV1
bpy.ops.object.mode_set(mode='EDIT')
object.data.uv_layers.active = object.data.uv_layers.get('UV1')
# Perform lightmap unpacking on UV1
bpy.ops.uv.lightmap_pack(
PREF_CONTEXT='ALL_FACES',
PREF_BOX_DIV=pack_quality,
PREF_MARGIN_DIV=margin
)
bpy.ops.object.mode_set(mode='OBJECT')
class OpDeleteLODs(bpy.types.Operator):
bl_idname = 'object.skunk_delete_lods'
bl_label = 'Delete LODs'
bl_description = 'Deletes LODs for selected objects'
bl_options = {'REGISTER', 'UNDO'}
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def execute(self, context):
objects = context.selected_objects[:]
valid_objects = self.get_valid_objects(objects)
self.delete_lods(valid_objects)
self.delete_unused_data_blocks()
self.report(
{'INFO'},
f'Deleted LODs for {len(valid_objects)} objects'
)
return {'FINISHED'}
@staticmethod
def get_valid_objects(objects):
valid_objects = []
for object in objects:
if object.type == 'MESH':
valid_objects.append(object)
else:
for object_child in object.children_recursive:
if object_child.type == 'MESH':
valid_objects.append(object_child)
return valid_objects
@staticmethod
def delete_lods(objects):
for object in objects:
object_name = object.name
if object_name.endswith('_LOD0'):
continue
else:
bpy.data.objects.remove(object, do_unlink=True)
@staticmethod
def delete_unused_data_blocks():
for block in bpy.data.meshes:
if block.users == 0:
bpy.data.meshes.remove(block)
for block in bpy.data.materials:
if block.users == 0:
bpy.data.materials.remove(block)
for block in bpy.data.textures:
if block.users == 0:
bpy.data.textures.remove(block)
for block in bpy.data.images:
if block.users == 0:
bpy.data.images.remove(block)
@staticmethod
def create_lods(objects, lod_count, decimate_ratio):
for object in objects:
for lod_index in range(1, lod_count + 1):
OpCreateLODs.create_lod(object, lod_index, pow(decimate_ratio, lod_index))
class OpCreateLODs(bpy.types.Operator):
bl_idname = 'object.skunk_create_lods'
bl_label = 'Create LODs'
bl_description = 'Creates LODs for selected objects'
bl_options = {'REGISTER', 'UNDO'}
lod_count: bpy.props.IntProperty(
name='LODs',
description='LOD count',
default=2,
min=0,
max=5
)
decimate_ratio: bpy.props.FloatProperty(
name='Decimate ratio',
description='Decimate ratio applied to LODs, first LOD will receive this value as is, '
'following LODs will stack this value',
default=0.5,
min=0.0,
max=1.0
)
is_delete_old_lods: bpy.props.BoolProperty(
name='Delete Old LODs',
description='Should old LODs be deleted/overwritten?',
default=True,
)
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def execute(self, context):
objects = context.selected_objects[:]
if self.is_delete_old_lods:
self.delete_lods(self.get_valid_objects(objects))
self.delete_unused_data_blocks()
self.create_lods(self.get_valid_objects(objects), self.lod_count, self.decimate_ratio)
self.report(
{'INFO'},
f'Created {self.lod_count} LODs for {len(objects)} objects'
)
return {'FINISHED'}
@staticmethod
def get_valid_objects(objects):
valid_objects = []
for object in objects:
if object.type == 'MESH':
valid_objects.append(object)
else:
for object_child in object.children_recursive:
if object_child.type == 'MESH':
valid_objects.append(object_child)
return valid_objects
@staticmethod
def delete_lods(objects):
for object in objects:
object_name = object.name
if object_name.endswith('_LOD0'):
continue
else:
bpy.data.objects.remove(object, do_unlink=True)
@staticmethod
def delete_unused_data_blocks():
for block in bpy.data.meshes:
if block.users == 0:
bpy.data.meshes.remove(block)
for block in bpy.data.materials:
if block.users == 0:
bpy.data.materials.remove(block)
for block in bpy.data.textures:
if block.users == 0:
bpy.data.textures.remove(block)
for block in bpy.data.images:
if block.users == 0:
bpy.data.images.remove(block)
@staticmethod
def create_lods(objects, lod_count, decimate_ratio):
for object in objects:
for lod_index in range(1, lod_count + 1):
OpCreateLODs.create_lod(object, lod_index, pow(decimate_ratio, lod_index))
@staticmethod
def create_lod(object, lod_index, decimate_ratio):
# Copy data
object_copy = object.copy()
object_copy.data = object.data.copy()
object_copy.location = object.location
for collection in object.users_collection:
collection.objects.link(object_copy)
# Naming
if object.name.endswith('_LOD0'):
object_name = object.name.replace('_LOD0', f'_LOD{lod_index}')
else:
object_name = f'{object.name}_LOD{lod_index}'
object_copy.data.name = object_name
object_copy.name = object_name
# Decimate
decimate_modifier = object_copy.modifiers.new(name='Decimate', type='DECIMATE')
decimate_modifier.ratio = decimate_ratio
bpy.context.view_layer.objects.active = object_copy
bpy.ops.object.modifier_apply(modifier=decimate_modifier.name)
class OpBulkExport(bpy.types.Operator):
bl_idname = 'object.skunk_bulk_export'
bl_label = 'Bulk Export'
bl_description = 'Exports selected objects as FBX to desktop'
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def execute(self, context):
objects = context.selected_objects[:]
self.export_fbx(objects)
self.report(
{'INFO'},
f'Exported {len(objects)} objects to Desktop'
)
return {'FINISHED'}
@staticmethod
def export_fbx(objects):
# Create a temp scene where exporting will take place
temp_scene = bpy.data.scenes.new('TempFBXExportScene')
bpy.context.window.scene = temp_scene
for object in objects:
temp_scene.collection.objects.link(object)
for child_object in object.children_recursive:
temp_scene.collection.objects.link(child_object)
for object in objects:
path = os.path.join(os.path.expanduser('~'), 'Desktop', f'{object.name}.fbx')
bpy.ops.object.select_all(action='DESELECT')
# Select a target object with children (needed to export only the selection)
object.select_set(True)
for child_object in object.children_recursive:
child_object.select_set(True)
original_location = object.location.copy()
object.location = (0, 0, 0)
bpy.ops.export_scene.fbx(
filepath=path,
use_selection=True,
object_types={'MESH', 'ARMATURE', 'EMPTY'},
apply_scale_options='FBX_SCALE_ALL',
axis_forward='-Y',
axis_up='Z',
use_space_transform=False,
apply_unit_scale=True,
primary_bone_axis='-Y',
secondary_bone_axis='-X',
use_armature_deform_only=True,
add_leaf_bones=False
)
object.location = original_location
# Remove temp scene
bpy.data.scenes.remove(temp_scene)
class SkunkPanel(bpy.types.Panel):
bl_idname = 'skunk_panel'
bl_label = 'Skunk'
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Skunk'
def draw(self, context):
layout = self.layout
layout.label(text='Structure')
layout.operator(OpDistributeObjects.bl_idname)
layout.operator(OpCreateEmptyParents.bl_idname)
layout.label(text='Mesh Data')
layout.operator(OpMatchMeshNames.bl_idname)
layout.operator(OpSortMeshByMaterial.bl_idname)
layout.operator(OpCreateUVs.bl_idname)
layout.label(text='LODs')
layout.operator(OpDeleteLODs.bl_idname)
layout.operator(OpCreateLODs.bl_idname)
layout.label(text='Exporting')
layout.operator(OpBulkExport.bl_idname)
def register():
bpy.utils.register_class(OpDistributeObjects)
bpy.utils.register_class(OpCreateEmptyParents)
bpy.utils.register_class(OpMatchMeshNames)
bpy.utils.register_class(OpSortMeshByMaterial)
bpy.utils.register_class(OpCreateUVs)
bpy.utils.register_class(OpDeleteLODs)
bpy.utils.register_class(OpCreateLODs)
bpy.utils.register_class(OpBulkExport)
bpy.utils.register_class(SkunkPanel)
def unregister():
bpy.utils.unregister_class(OpDistributeObjects)
bpy.utils.unregister_class(OpCreateEmptyParents)
bpy.utils.unregister_class(OpMatchMeshNames)
bpy.utils.unregister_class(OpSortMeshByMaterial)
bpy.utils.unregister_class(OpCreateUVs)
bpy.utils.unregister_class(OpDeleteLODs)
bpy.utils.unregister_class(OpCreateLODs)
bpy.utils.unregister_class(OpBulkExport)
bpy.utils.unregister_class(SkunkPanel)
if __name__ == '__main__':
register()