-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprocgen_assets.py
executable file
·1316 lines (1138 loc) · 47.8 KB
/
procgen_assets.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
#!/usr/bin/env -S blender --factory-startup --background --enable-autoexec --python-exit-code 1 --python
"""
Script for automated procedural asset generation using Blender that revolves around its rich
node-based system for geometry (Geometry Nodes) and materials (Shader Nodes).
Overview:
The requested node trees are constructed via scripts defined by `--autorun_scripts`. A sequence of
Geometry Nodes moodifiers is then applied to a prototype object that is duplicated for each generated
variant. Once the geometry is finalized, a procedural material is applied and baked into PBR textures
before exporting the final model.
Example (manual invocation is not recommended):
blender --python procgen_assets.py -- \
--autorun_scripts path/to/nodes_0.py path/to/nodes_1.py ... \
--geometry_nodes '{"NodeModifierName": {"input_name": input_value, ...}, ...}' \
--material MaterialName \
--texture_resolution 4096 \
--num_assets 10 \
--ext usdz \
--outdir path/to/output/directory
"""
from __future__ import annotations
import argparse
import contextlib
import enum
import io
import json
import math
import os
import re
import sys
import time
from copy import deepcopy
from os import path
from pathlib import Path
from typing import Any, Dict, List, Literal, Optional, TextIO, Tuple, Union
from xml.dom import minidom as xml_dom
from xml.etree import ElementTree as xml_et
import bpy
import mathutils
def main(**kwargs):
print_bpy(f"[INFO]: Starting procedural asset generation with kwargs: {kwargs}")
verify_requirements()
ProceduralGenerator.generate(**kwargs)
class ProceduralGenerator:
"""
Generator of procedural models using Blender.
"""
@classmethod
def generate(
cls,
*,
## Input
autorun_scripts: List[str],
## Output
outdir: str,
name: str,
ext: str,
overwrite_min_age: int,
## Generator
seed: int,
num_assets: int,
## Export
export_kwargs: Dict[str, Any],
render_thumbnail: bool,
thumbnail_resolution: int,
## Geometry
geometry_nodes: Dict[str, Dict[str, Any]],
decimate_angle_limit: Optional[float],
decimate_face_count: Optional[int],
## Material
material: Optional[str],
texture_resolution: int,
render_samples: int,
):
"""
Entrypoint method for generating a set of procedural models.
"""
# Preprocess the input arguments
outdir = Path(outdir).absolute().as_posix()
if not ext.startswith("."):
ext = f".{ext}"
# Create the output directory
os.makedirs(name=outdir, exist_ok=True)
# Reset to factory settings with an empty scene
bpy.ops.wm.read_factory_settings(use_empty=True)
# Autorun all input scripts
for script in autorun_scripts:
print_bpy(f"[INFO]: Running script: {script}")
bpy.ops.script.python_file_run(filepath=script)
# Extract a map of the input socket mapping for all loaded node groups
node_group_input_socket_maps = cls.extract_aliased_input_socket_id_mappings()
# Create an empty mesh object and treat it as a prototype that will be duplicated for each processed seed
bpy.ops.object.add(type="MESH")
proto_obj: bpy.types.Object = bpy.context.active_object
proto_obj.name = name
proto_obj.data.name = name
proto_obj.hide_render = True
# Apply the requested list of geometry nodes to the prototype object
cls.apply_geometry_nodes_modifiers(
obj=proto_obj,
geometry_nodes=geometry_nodes,
node_group_input_socket_maps=node_group_input_socket_maps,
)
should_bake_material = material is not None
if not should_bake_material:
for node_group_inputs in geometry_nodes.values():
for value in node_group_inputs.values():
if isinstance(value, str) and value.startswith("MAT:"):
should_bake_material = True
break
else:
continue
break
# Preheat the oven for baking the material into PBR textures
if should_bake_material:
ProceduralGenerator.Baker.preheat_oven(render_samples=render_samples)
# Prepare the scene for rendering the thumbnail
if render_thumbnail:
ProceduralGenerator.Exporter.prepare_renderer()
# Generate models over the specified range
for current_seed in range(seed, seed + num_assets):
# Form the output filepath
filepath = path.join(outdir, f"{name}{current_seed}")
# Skip generation if the file already exists and is too recent
if path.exists(filepath) and (
overwrite_min_age < 0
or (overwrite_min_age > time.time() - path.getmtime(filepath))
):
print_bpy(
f"[INFO]: Skipping generation of '{filepath}' because it was generated in the last {overwrite_min_age} seconds"
)
continue
# Duplicate the prototype object, rename it, select it and mark it as the active object
obj = cls.duplicate_object(obj=proto_obj, seed=current_seed)
# Update the random seed of all geometry nodes modifiers that have a seed input socket
geometry_nodes_modifiers = [
modifier
for modifier in obj.modifiers.values()
if modifier.type == "NODES"
]
for modifier in geometry_nodes_modifiers:
if seed_id := node_group_input_socket_maps[
modifier.node_group.name
].get("seed"):
modifier[seed_id] = current_seed
# Apply changes via mesh update
obj.data.update()
# Apply all modifiers
for modifier in obj.modifiers:
bpy.ops.object.modifier_apply(modifier=modifier.name)
# If specified, bake the material into PBR textures
if should_bake_material:
obj.hide_render = False
if material:
obj.data.materials.clear()
obj.data.materials.append(bpy.data.materials.get(material))
ProceduralGenerator.Baker.bake_into_pbr_material(
obj=obj, texture_resolution=texture_resolution
)
# Decimate the mesh if necessary
if decimate_angle_limit:
bpy.ops.object.modifier_add(type="DECIMATE")
obj.modifiers["Decimate"].decimate_type = "DISSOLVE"
obj.modifiers["Decimate"].angle_limit = decimate_angle_limit
if decimate_face_count:
# Decimate the mesh
bpy.ops.object.modifier_add(type="DECIMATE")
obj.modifiers["Decimate"].ratio = decimate_face_count / len(
obj.data.polygons
)
bpy.ops.object.modifier_apply(modifier="Decimate")
# Export the model
cls.Exporter.export(
filepath=filepath,
ext=ext,
render_thumbnail=render_thumbnail,
thumbnail_resolution=thumbnail_resolution,
**export_kwargs,
)
print_bpy(
f"[LOG]: Generated asset #{current_seed} ({current_seed-seed+1}/{num_assets}): {filepath}"
)
# Update the viewport to keep track of progress
if not bpy.app.background:
bpy.ops.wm.redraw_timer(type="DRAW_WIN_SWAP", iterations=1)
# Remove the generated object
bpy.data.objects.remove(obj)
print_bpy("[INFO]: Generation completed")
@staticmethod
def extract_aliased_input_socket_id_mappings() -> Dict[str, Dict[str, str]]:
def _extract_input_socket_id_mapping(
node_group: bpy.types.NodeTree,
) -> Dict[str, str]:
return {
canonicalize_str(item.name): item.identifier
for item in node_group.interface.items_tree.values()
if item.item_type == "SOCKET" and item.in_out == "INPUT"
}
# Extract a map of the input socket mapping for all node groups
node_group_input_socket_maps = {
node_group_name: _extract_input_socket_id_mapping(node_group)
for node_group_name, node_group in bpy.data.node_groups.items()
}
# Rename common aliases for convenience
COMMON_ALIASES: Dict[str, List[str]] = {
"seed": [
"pseodorandomseed",
"randomseed",
"rng",
],
"detail": [
"detaillevel",
"detailobject",
"levelofdetail",
"subdivisionlevel",
"subdivisions",
"subdivlevel",
],
}
for node_group_input_socket_map in node_group_input_socket_maps.values():
for target, possible_alias in COMMON_ALIASES.items():
original_alias: Optional[str] = (
target if target in node_group_input_socket_map.keys() else None
)
for key in node_group_input_socket_map.keys():
if key in possible_alias:
if original_alias is not None:
raise ValueError(
"Ambiguous name of the input socket '{target}' (canonicalized): '{original_alias}', '{key}'"
)
original_alias = key
if original_alias is not None and original_alias != target:
node_group_input_socket_map[target] = node_group_input_socket_map[
original_alias
]
return node_group_input_socket_maps
@staticmethod
def apply_geometry_nodes_modifiers(
obj: bpy.types.Object,
*,
geometry_nodes: Dict[str, Dict[str, Any]],
node_group_input_socket_maps: Dict[str, Dict[str, str]],
):
for i, (node_group_name, node_group_inputs) in enumerate(
geometry_nodes.items()
):
# Create a new nodes modifier
modifier: bpy.types.NodesModifier = obj.modifiers.new(
name=f"node{i}", type="NODES"
)
# Assign the requested node group
if node_group := bpy.data.node_groups.get(node_group_name):
modifier.node_group = node_group
else:
raise ValueError(
f"Node group '{node_group_name}' not found in the list of available groups: {bpy.data.node_groups.keys()}"
)
# Set inputs accordingly
for key, value in node_group_inputs.items():
socket_id = node_group_input_socket_maps[node_group_name][
canonicalize_str(key)
]
if isinstance(value, str) and value.startswith("MAT:"):
material_name = value[4:]
material = bpy.data.materials.get(material_name)
if not material:
raise ValueError(
f"Material '{material_name}' not found in the list of available materials: {bpy.data.materials.keys()}"
)
modifier[socket_id] = material
else:
modifier[socket_id] = value
# Apply changes via mesh update
obj.data.update()
@staticmethod
def duplicate_object(obj: bpy.types.Object, seed: int) -> bpy.types.Object:
# Select the object to duplicate
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
# Duplicate the object
bpy.ops.object.duplicate()
# Get the new duplicated object (it will be the active object)
new_obj = bpy.context.active_object
# Rename the new object based on the seed
new_obj.name = f"{obj.name}_{seed}"
new_obj.data.name = f"{obj.data.name}_{seed}"
# Select the new object and make it the active object
bpy.ops.object.select_all(action="DESELECT")
new_obj.select_set(True)
bpy.context.view_layer.objects.active = new_obj
return new_obj
class Recipe(enum.Enum):
ALBEDO = enum.auto()
METALLIC = enum.auto()
SPECULAR = enum.auto()
ROUGHNESS = enum.auto()
NORMAL = enum.auto()
@staticmethod
def enabled_recipes():
return (
ProceduralGenerator.Recipe.ALBEDO,
ProceduralGenerator.Recipe.METALLIC,
# ProceduralGenerator.Recipe.SPECULAR,
ProceduralGenerator.Recipe.ROUGHNESS,
ProceduralGenerator.Recipe.NORMAL,
)
@property
def bake_type(self):
match self:
case self.ALBEDO:
return "DIFFUSE"
case self.METALLIC:
return "EMIT"
case self.SPECULAR:
return "GLOSSY"
case _:
return self.name
@property
def color_space(self):
return "sRGB" if self.ALBEDO == self else "Non-Color"
@property
def shader_socket_name(self):
match self:
case self.ALBEDO:
return "Base Color"
case self.METALLIC:
return "Metallic"
case self.SPECULAR:
return "Specular Tint"
case self.ROUGHNESS:
return "Roughness"
case self.NORMAL:
return "Normal"
def prep(self, material: bpy.types.Material) -> Dict[str, Any]:
match self:
# If the shader node has a "Metallic" input, it needs to be disabled for baking
case self.ALBEDO:
# Get the output material node
output_material_node = [
node
for node in material.node_tree.nodes
if node.type == "OUTPUT_MATERIAL"
][0]
# Get surface shader socket
shader_node_socket = output_material_node.inputs["Surface"]
if not shader_node_socket.is_linked:
return {}
# Get the shader node connected to the socket
shader_node = shader_node_socket.links[0].from_node
# No need to do anything if the shader node does not have a "Metallic" input
if "Metallic" not in shader_node.inputs:
return {}
metallic_socket = shader_node.inputs["Metallic"]
ingredients = {}
# If the metallic input is linked, store the original link source and temporarily disconnect it
if metallic_socket.is_linked:
metallic_socket_links = metallic_socket.links[0]
ingredients["orig_metallic_from_socket"] = (
metallic_socket_links.from_socket
)
material.node_tree.links.remove(metallic_socket_links)
# Always store the original default value and set it to 0.0
ingredients["orig_metallic_default_value"] = (
metallic_socket.default_value
)
metallic_socket.default_value = 0.0
return ingredients
# Render the metallic input as emission originating from the surface shader's metallic input
case self.METALLIC:
# Get the output material node
output_material_node = [
node
for node in material.node_tree.nodes
if node.type == "OUTPUT_MATERIAL"
][0]
# Get surface shader socket
shader_node_socket = output_material_node.inputs["Surface"]
if not shader_node_socket.is_linked:
return {}
# Get the shader link
shader_link = shader_node_socket.links[0]
# Get the shader node connected to the socket
shader_node = shader_link.from_node
# Store the original link source and temporarily disconnect it
ingredients = {
"orig_surface_shader_source": shader_link.from_socket
}
material.node_tree.links.remove(shader_link)
# No need to do anything if the shader node does not have a "Metallic" input
orig_metallic_default_value = 0.0
with_emissive_rgb_node = False
if "Metallic" in shader_node.inputs:
metallic_socket = shader_node.inputs["Metallic"]
# If the metallic input is linked, store the original link source and temporarily disconnect it
if metallic_socket.is_linked:
metallic_socket_links = metallic_socket.links[0]
material.node_tree.links.new(
metallic_socket_links.from_socket,
shader_node_socket,
)
else:
with_emissive_rgb_node = True
orig_metallic_default_value = metallic_socket.default_value
else:
with_emissive_rgb_node = True
if with_emissive_rgb_node:
rgb_node = material.node_tree.nodes.new(type="ShaderNodeRGB")
rgb_node.outputs[0].default_value = (
*((orig_metallic_default_value,) * 3),
1.0,
)
material.node_tree.links.new(
rgb_node.outputs["Color"], shader_node_socket
)
ingredients["emissive_rgb_node"] = rgb_node
return ingredients
case _:
return {}
def cleanup(
self,
material: bpy.types.Material,
*,
orig_metallic_from_socket: Optional[bpy.types.NodeSocket] = None,
orig_metallic_default_value: Optional[float] = None,
orig_surface_shader_source: Optional[bpy.types.NodeSocket] = None,
emissive_rgb_node: Optional[bpy.types.Node] = None,
):
match self:
case self.ALBEDO:
if orig_metallic_default_value or orig_metallic_from_socket:
link = (
[
node
for node in material.node_tree.nodes
if node.type == "OUTPUT_MATERIAL"
][0]
.inputs["Surface"]
.links[0]
)
# TODO: Fix this ugly hack
if hasattr(link, "inputs"):
metallic_socket = link.inputs["Metallic"]
metallic_socket.default_value = orig_metallic_default_value
if orig_metallic_from_socket:
material.node_tree.links.new(
orig_metallic_from_socket,
metallic_socket,
)
case self.METALLIC:
if orig_surface_shader_source:
shader_node_socket = [
node
for node in material.node_tree.nodes
if node.type == "OUTPUT_MATERIAL"
][0].inputs["Surface"]
shader_link = shader_node_socket.links[0]
material.node_tree.links.remove(shader_link)
material.node_tree.links.new(
orig_surface_shader_source,
shader_node_socket,
)
if emissive_rgb_node:
material.node_tree.nodes.remove(emissive_rgb_node)
class Baker:
"""
Simple wrapper around Blender baking capabilities.
"""
@staticmethod
def preheat_oven(render_samples: int):
# Only Cycles supports texture baking
bpy.context.scene.render.engine = "CYCLES"
bpy.data.scenes[0].render.engine = "CYCLES"
# Bake using GPU
bpy.context.preferences.addons["cycles"].preferences.compute_device_type = (
"CUDA"
)
bpy.context.preferences.addons["cycles"].preferences.get_devices()
for device in bpy.context.preferences.addons["cycles"].preferences.devices:
device.use = device.type == "CUDA"
bpy.context.scene.render.engine = "CYCLES"
bpy.context.scene.cycles.device = "GPU"
# Improve performance (only few samples are needed for baking)
bpy.context.scene.cycles.samples = render_samples
# Consider only the color pass (no environment lighting)
bpy.context.scene.render.bake.use_pass_direct = False
bpy.context.scene.render.bake.use_pass_indirect = False
bpy.context.scene.render.bake.use_pass_color = True
@classmethod
def bake_into_pbr_material(
cls,
obj: bpy.types.Object,
*,
texture_resolution: int,
):
# Adjust the recipe according to the object
bpy.context.scene.render.bake.margin = texture_resolution // 64
# Unwrap the object if necessary
if not obj.data.uv_layers:
cls._unwrap_uv_on_active_obj(obj, texture_resolution)
# Get the material
material = obj.data.materials[-1]
# Bake all textures from the recipe
baked_textures = {}
for recipe in ProceduralGenerator.Recipe.enabled_recipes():
ingredients = recipe.prep(material=material)
# Create the image node into which the texture will be baked
image_node = cls._create_image_node(
material=material,
recipe=recipe,
texture_resolution=texture_resolution,
)
# Bake the texture
bpy.ops.object.bake(type=recipe.bake_type)
baked_textures[recipe] = image_node.image
# Remove the image node and cleanup the material
material.node_tree.nodes.remove(image_node)
recipe.cleanup(material=material, **ingredients)
# Create a new PBR material with the baked textures
pbr_material = cls._bake_into_pbr_material(
name=f"PBR_{obj.name}", baked_textures=baked_textures
)
# Replace the original material with the new PBR material
obj.data.materials.clear()
obj.data.materials.append(pbr_material)
@classmethod
def _bake_into_pbr_material(
cls,
name: str,
baked_textures: Dict[ProceduralGenerator.Recipe, bpy.types.Image],
) -> bpy.types.Material:
# Create a new material
pbr_material = bpy.data.materials.new(name=name)
pbr_material.use_nodes = True
# Get handles to the nodes and links
nodes = pbr_material.node_tree.nodes
links = pbr_material.node_tree.links
# Clear the existing nodes
nodes.clear()
# Create Material Output and Principled BSDF nodes
shader_node = nodes.new(type="ShaderNodeBsdfPrincipled")
shader_node.location = (-300, 0)
output_node = nodes.new(type="ShaderNodeOutputMaterial")
output_node.location = (0, 0)
links.new(shader_node.outputs["BSDF"], output_node.inputs["Surface"])
# Create Texture Coordinate and Mapping nodes
texcoord_node = nodes.new(type="ShaderNodeTexCoord")
texcoord_node.location = (-1200, 0)
mapping_node = nodes.new(type="ShaderNodeMapping")
mapping_node.location = (-1000, 0)
links.new(mapping_node.inputs["Vector"], texcoord_node.outputs["UV"])
# Create baked textures
for i, (recipe, texture) in enumerate(baked_textures.items()):
# Create Image Texture node
img_texture = nodes.new(type="ShaderNodeTexImage")
img_texture.image = texture
img_texture.location = (
-800,
375 * (0.5 * len(baked_textures) + 0.5 - i),
)
links.new(img_texture.inputs["Vector"], mapping_node.outputs["Vector"])
match recipe:
# Normal map requires the Normal Map node
case ProceduralGenerator.Recipe.NORMAL:
normal_map_node = nodes.new(type="ShaderNodeNormalMap")
normal_map_node.location = (-500, -127)
links.new(
img_texture.outputs["Color"],
normal_map_node.inputs["Color"],
)
links.new(
normal_map_node.outputs["Normal"],
shader_node.inputs[recipe.shader_socket_name],
)
# Other textures are directly linked to the shader node
case _:
links.new(
img_texture.outputs["Color"],
shader_node.inputs[recipe.shader_socket_name],
)
return pbr_material
@staticmethod
def _unwrap_uv_on_active_obj(obj: bpy.types.Object, texture_resolution: int):
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.select_all(action="SELECT")
# Try with the default unwrap first, but capture the output in case it fails (printed as warning to stdout)
stdout_str = io.StringIO()
with contextlib.redirect_stdout(stdout_str):
bpy.ops.uv.unwrap()
# If the default unwrap failed, try with the Smart UV Project
if "Unwrap failed" in stdout_str.getvalue():
bpy.ops.uv.smart_project(
rotate_method="AXIS_ALIGNED", island_margin=0.5 / texture_resolution
)
bpy.ops.object.mode_set(mode="OBJECT")
@classmethod
def _create_image_node(
cls,
material: bpy.types.Material,
recipe: ProceduralGenerator.Recipe,
texture_resolution: int,
):
node = material.node_tree.nodes.new("ShaderNodeTexImage")
node.image = cls._create_image_texture(
name=recipe.name.lower(),
texture_resolution=texture_resolution,
color_space=recipe.color_space,
)
material.node_tree.nodes.active = node
return node
@staticmethod
def _create_image_texture(
name: str,
*,
texture_resolution: int,
color_space: Literal["Non-Color", "sRGB"],
):
image = bpy.data.images.new(
name,
width=texture_resolution,
height=texture_resolution,
alpha=False,
float_buffer=False,
tiled=False,
)
image.alpha_mode = "NONE"
image.colorspace_settings.name = color_space
return image
class Exporter:
"""
Simple wrapper around Blender export capabilities.
"""
@staticmethod
def prepare_renderer():
bpy.ops.object.light_add(
type="SUN",
rotation=(-0.25 * math.pi, -0.4 * math.pi, 0.0),
)
bpy.context.object.data.energy = 100.0
bpy.context.object.data.angle = 0.0
bpy.ops.object.camera_add(location=(0.0, 0.0, 1.0))
bpy.context.scene.camera = bpy.context.object
bpy.context.scene.camera.data.type = "ORTHO"
bpy.context.scene.camera.data.clip_start = 1e-06
bpy.context.scene.render.film_transparent = True
@classmethod
def export(
cls,
filepath: Union[str, Path],
*,
ext: str,
render_thumbnail: bool,
thumbnail_resolution: int,
**kwargs,
):
# Dispatch the export based on the file extension
match ext:
case ".usdz" | ".usdc" | ".usda" | ".usd":
cls.usd_export(filepath=filepath, ext=ext, **kwargs)
case ".sdf":
cls.sdf_export(
filepath=filepath,
render_thumbnail=render_thumbnail,
thumbnail_resolution=thumbnail_resolution,
**kwargs,
)
case ".abc":
cls.abc_export(filepath=filepath, **kwargs)
case ".fbx":
cls.fbx_export(filepath=filepath, **kwargs)
case ".glb" | ".gltf":
cls.gltf_export(filepath=filepath, ext=ext, **kwargs)
case ".obj":
cls.obj_export(filepath=filepath, **kwargs)
case ".ply":
cls.ply_export(filepath=filepath, **kwargs)
case ".stl":
cls.stl_export(filepath=filepath, **kwargs)
case _:
raise ValueError(f"Unsupported export format: '{ext}'")
@staticmethod
def abc_export(
filepath: Union[str, Path],
**kwargs,
):
"""
Export via `bpy.ops.wm.alembic_export()`
"""
DEFAULT_EXPORT_OVERRIDES = {
"check_existing": False,
"selected": True,
}
# Prepare the output path
if not isinstance(filepath, Path):
filepath = Path(filepath)
filepath = filepath.with_suffix(".abc").absolute()
# Forward export kwargs
export_kwargs = deepcopy(DEFAULT_EXPORT_OVERRIDES)
export_kwargs.update(kwargs)
# Export the Alembic file
bpy.ops.wm.alembic_export(
filepath=filepath.as_posix(),
**export_kwargs,
)
@staticmethod
def fbx_export(
filepath: Union[str, Path],
**kwargs,
):
"""
Export via `bpy.ops.export_scene.fbx()`
"""
DEFAULT_EXPORT_OVERRIDES = {
"check_existing": False,
"use_selection": True,
}
# Prepare the output path
if not isinstance(filepath, Path):
filepath = Path(filepath)
filepath = filepath.with_suffix(".fbx").absolute()
# Forward export kwargs
export_kwargs = deepcopy(DEFAULT_EXPORT_OVERRIDES)
export_kwargs.update(kwargs)
# Export the FBX file
bpy.ops.export_scene.fbx(
filepath=filepath.as_posix(),
**export_kwargs,
)
@staticmethod
def gltf_export(
filepath: Union[str, Path],
*,
ext: str,
**kwargs,
):
"""
Export via `bpy.ops.export_scene.gltf()`
"""
DEFAULT_EXPORT_OVERRIDES = {
"check_existing": False,
"use_selection": True,
}
# Prepare the output path
if not isinstance(filepath, Path):
filepath = Path(filepath)
filepath = filepath.with_suffix(ext).absolute()
# Forward export kwargs
export_kwargs = deepcopy(DEFAULT_EXPORT_OVERRIDES)
export_kwargs.update(kwargs)
# Export the GLTF file
bpy.ops.wm.usd_export(
filepath=filepath.as_posix(),
**export_kwargs,
)
@staticmethod
def obj_export(
filepath: Union[str, Path],
**kwargs,
):
"""
Export via `bpy.ops.wm.obj_export()`
"""
DEFAULT_EXPORT_OVERRIDES = {
"check_existing": False,
"export_selected_objects": True,
}
# Prepare the output path
if not isinstance(filepath, Path):
filepath = Path(filepath)
filepath = filepath.with_suffix(".obj").absolute()
# Forward export kwargs
export_kwargs = deepcopy(DEFAULT_EXPORT_OVERRIDES)
export_kwargs.update(kwargs)
# Export the Wavefront OBJ file
bpy.ops.wm.obj_export(
filepath=filepath.as_posix(),
**export_kwargs,
)
@staticmethod
def ply_export(
filepath: Union[str, Path],
**kwargs,
):
"""
Export via `bpy.ops.wm.ply_export()`
"""
DEFAULT_EXPORT_OVERRIDES = {
"check_existing": False,
"export_selected_objects": True,
}
# Prepare the output path
if not isinstance(filepath, Path):
filepath = Path(filepath)
filepath = filepath.with_suffix(".ply").absolute()
# Forward export kwargs
export_kwargs = deepcopy(DEFAULT_EXPORT_OVERRIDES)
export_kwargs.update(kwargs)
# Export the PLY file
bpy.ops.wm.ply_export(
filepath=filepath.as_posix(),
**export_kwargs,
)
@staticmethod
def sdf_export(
filepath: Union[str, Path],
*,
render_thumbnail: bool,
thumbnail_resolution: int,
**kwargs,
):
"""
Export an SDF model with a corresponding GLTF mesh.
"""
DEFAULT_EXPORT_OVERRIDES = {
"check_existing": False,
"use_selection": True,
}
# Prepare the output path
if not isinstance(filepath, Path):
filepath = Path(filepath)
filepath = filepath.absolute()
model_name = filepath.stem
filepath_model = Path(path.join(filepath, "model.sdf"))
filepath_config = Path(path.join(filepath, "model.config"))
filepath_mesh = Path(path.join(filepath, "meshes", f"{model_name}.glb"))
filepath_thumbnail = Path(path.join(filepath, "thumbnails", "0.png"))
# Create parent directories
os.makedirs(name=filepath, exist_ok=True)
os.makedirs(name=filepath_mesh.parent, exist_ok=True)
os.makedirs(name=filepath_thumbnail.parent, exist_ok=True)
# Forward export kwargs
export_kwargs = deepcopy(DEFAULT_EXPORT_OVERRIDES)
export_kwargs.update(kwargs)
# Export the USD file
bpy.ops.export_scene.gltf(
filepath=filepath_mesh.as_posix(),
**export_kwargs,
)
# Write the SDF model file
sdf = xml_et.Element("sdf", attrib={"version": "1.9"})
model = xml_et.SubElement(sdf, "model", attrib={"name": model_name})
link = xml_et.SubElement(
model, "link", attrib={"name": f"{model_name}_link"}
)
pose = xml_et.SubElement(link, "pose")
pose.text = f"0 0 0 {math.pi/2} 0 0"
visual = xml_et.SubElement(
link, "visual", attrib={"name": f"{model_name}_visual"}
)
visual_geometry = xml_et.SubElement(visual, "geometry")
visual_mesh = xml_et.SubElement(visual_geometry, "mesh")
visual_mesh_uri = xml_et.SubElement(visual_mesh, "uri")
visual_mesh_uri.text = path.relpath(start=filepath, path=filepath_mesh)
collision = xml_et.SubElement(
link, "collision", attrib={"name": f"{model_name}_collision"}
)
collision_geometry = xml_et.SubElement(collision, "geometry")
collision_mesh = xml_et.SubElement(collision_geometry, "mesh")
collision_mesh_uri = xml_et.SubElement(collision_mesh, "uri")
collision_mesh_uri.text = path.relpath(start=filepath, path=filepath_mesh)