@babylonjs-toolkit/agent 1.2.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/package.json +1 -1
- package/skills/bt-atlas/SKILL.md +22 -5
- package/skills/bt-design/references/3d-hero-docs.md +10 -3
- package/skills/bt-design/references/3d-hero-scroll.md +30 -5
- package/skills/bt-gauntlet/SKILL.md +4 -4
- package/skills/bt-gauntlet/references/spec-composition.md +4 -2
- package/skills/bt-gauntlet/references/target-images.md +28 -4
- package/skills/bt-gauntlet/references/unity-pipeline.md +30 -8
- package/skills/bt-hero/SKILL.md +3 -3
- package/skills/bt-landing/SKILL.md +1 -1
- package/skills/bt-prototype/SKILL.md +3 -3
- package/skills/bt-unwrap/SKILL.md +396 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/bt_unwrap.py +678 -0
- package/skills/bt-unwrap/scripts/blender/image_utils.py +264 -0
- package/skills/bt-unwrap/scripts/blender/mesh_tools.py +508 -0
- package/skills/bt-unwrap/scripts/blender/model_io.py +135 -0
- package/skills/bt-unwrap/scripts/blender/previews.py +205 -0
- package/skills/bt-unwrap/scripts/blender/rasterizer.py +217 -0
- package/skills/bt-unwrap/scripts/blender/reference_views.py +945 -0
- package/skills/bt-unwrap/scripts/blender/reference_warp.py +571 -0
- package/skills/bt-unwrap/scripts/blender/texture_bake.py +390 -0
- package/skills/bt-unwrap/scripts/blender/texture_compose.py +596 -0
- package/skills/bt-unwrap/scripts/blender/uv_layout.py +605 -0
- package/skills/bt-unwrap/scripts/bt-unwrap.mjs +165 -0
|
@@ -0,0 +1,678 @@
|
|
|
1
|
+
"""
|
|
2
|
+
bt-unwrap — clean up an AI-generated (or any) 3D model and give it a production texture:
|
|
3
|
+
|
|
4
|
+
import -> orient / scale / origin -> repair geometry -> decimate to a face budget -> new UV layout ->
|
|
5
|
+
bake the source textures onto it -> paint sharp reference views onto it -> one PBR material ->
|
|
6
|
+
export (+ LODs) -> before / after previews, UV maps, alignment overlays and a JSON report.
|
|
7
|
+
|
|
8
|
+
Run inside Blender (the bt-unwrap.mjs launcher does this for you):
|
|
9
|
+
|
|
10
|
+
blender --background --factory-startup --python-exit-code 1 --python bt_unwrap.py -- <input> [options]
|
|
11
|
+
"""
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
import traceback
|
|
18
|
+
|
|
19
|
+
SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
|
|
20
|
+
if SCRIPT_DIRECTORY not in sys.path:
|
|
21
|
+
sys.path.insert(0, SCRIPT_DIRECTORY)
|
|
22
|
+
|
|
23
|
+
import bpy # noqa: E402
|
|
24
|
+
import numpy as np # noqa: E402
|
|
25
|
+
|
|
26
|
+
import image_utils # noqa: E402
|
|
27
|
+
import mesh_tools # noqa: E402
|
|
28
|
+
import model_io # noqa: E402
|
|
29
|
+
import previews # noqa: E402
|
|
30
|
+
import reference_views # noqa: E402
|
|
31
|
+
import texture_bake # noqa: E402
|
|
32
|
+
import reference_warp # noqa: E402
|
|
33
|
+
import texture_compose # noqa: E402
|
|
34
|
+
import uv_layout # noqa: E402
|
|
35
|
+
|
|
36
|
+
AUTO_MERGE_DISTANCE_FRACTION = 1e-5
|
|
37
|
+
DEFAULT_OUTPUT_FORMAT = "glb"
|
|
38
|
+
# Island padding scales with the texture: 8 px at 4096 keeps mip levels clean, 2 px is plenty at 1024.
|
|
39
|
+
PADDING_TEXTURE_DIVISOR = 512
|
|
40
|
+
MINIMUM_PADDING = 2
|
|
41
|
+
# Textures are built at twice the output size (up to this) and filtered down, for crisper edges and text.
|
|
42
|
+
SUPERSAMPLE_FACTOR = 2
|
|
43
|
+
MAXIMUM_AUTO_WORK_SIZE = 4096
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
47
|
+
"""Every bt-unwrap option, grouped the way SKILL.md documents them."""
|
|
48
|
+
parser = argparse.ArgumentParser(prog="bt-unwrap", description=__doc__,
|
|
49
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
50
|
+
parser.add_argument("input", help="model to process: .glb .gltf .fbx .obj .usd/.usda/.usdc/.usdz .ply .stl .abc .blend")
|
|
51
|
+
|
|
52
|
+
output = parser.add_argument_group("output")
|
|
53
|
+
output.add_argument("--output", help="output model file; its extension picks the format (.glb .gltf .fbx .obj .usd* .blend)")
|
|
54
|
+
output.add_argument("--out-dir", help="folder for every output (default: <input folder>/<input name>_unwrap)")
|
|
55
|
+
output.add_argument("--format", choices=["glb", "gltf", "fbx", "obj", "usd", "usdz", "blend"], default=None,
|
|
56
|
+
help="output format when --output is not given (default glb)")
|
|
57
|
+
output.add_argument("--lods", default="", help="extra LOD files as triangle ratios, e.g. 0.5,0.25")
|
|
58
|
+
output.add_argument("--no-preview", action="store_true", help="skip before/after renders and overlays")
|
|
59
|
+
output.add_argument("--preview-size", type=int, default=1024, help="preview render size in pixels")
|
|
60
|
+
output.add_argument("--analyze", action="store_true",
|
|
61
|
+
help="only check orientation and reference alignment; write overlays and the report, no model")
|
|
62
|
+
|
|
63
|
+
cleanup = parser.add_argument_group("geometry cleanup")
|
|
64
|
+
cleanup.add_argument("--merge-distance", type=float, default=None,
|
|
65
|
+
help="merge vertices closer than this, in meters (default: 0.001%% of the model diagonal)")
|
|
66
|
+
cleanup.add_argument("--debris-faces", type=int, default=8,
|
|
67
|
+
help="delete loose parts with fewer faces than this (0 keeps all)")
|
|
68
|
+
cleanup.add_argument("--fill-holes", type=int, default=0, help="fill open holes with up to N edges (0 = off)")
|
|
69
|
+
cleanup.add_argument("--no-fix-normals", action="store_true", help="keep the original face winding")
|
|
70
|
+
cleanup.add_argument("--faces", type=int, default=0, help="decimate to about this many triangles (0 = keep)")
|
|
71
|
+
cleanup.add_argument("--shading", choices=["auto", "smooth", "flat", "keep"], default="auto",
|
|
72
|
+
help="auto = smooth with hard edges above --smooth-angle")
|
|
73
|
+
cleanup.add_argument("--smooth-angle", type=float, default=30.0, help="hard-edge angle for --shading auto, degrees")
|
|
74
|
+
cleanup.add_argument("--keep-objects", action="store_true",
|
|
75
|
+
help="keep separate objects and their pivots instead of joining into one mesh")
|
|
76
|
+
|
|
77
|
+
placement = parser.add_argument_group("orientation and size")
|
|
78
|
+
placement.add_argument("--forward", choices=["auto", "keep", "+x", "-x", "+y", "-y"], default="auto",
|
|
79
|
+
help="which Blender axis the model's front faces after import; auto detects it from the references")
|
|
80
|
+
placement.add_argument("--rotate", default=None, help="extra rotation applied first, 'x,y,z' degrees")
|
|
81
|
+
placement.add_argument("--length", type=float, default=0.0, help="scale so front-to-back size is this many meters")
|
|
82
|
+
placement.add_argument("--width", type=float, default=0.0, help="scale so side-to-side size is this many meters")
|
|
83
|
+
placement.add_argument("--height", type=float, default=0.0, help="scale so the height is this many meters")
|
|
84
|
+
placement.add_argument("--origin", choices=["bottom", "center", "keep"], default="bottom",
|
|
85
|
+
help="bottom = center of the footprint at floor level")
|
|
86
|
+
|
|
87
|
+
layout = parser.add_argument_group("UV layout")
|
|
88
|
+
layout.add_argument("--unwrap", choices=["views", "smart", "keep"], default="views",
|
|
89
|
+
help="views = lay faces out from the front/rear/left/right/top/bottom they face; "
|
|
90
|
+
"smart = Blender Smart UV Project (organic shapes); keep = keep the existing UVs")
|
|
91
|
+
layout.add_argument("--projections", type=int, choices=[6, 10, 14], default=6,
|
|
92
|
+
help="views used by --unwrap views: 6 box, 10 + horizontal diagonals, 14 + corners")
|
|
93
|
+
layout.add_argument("--label-smoothing", type=int, default=6, help="passes that merge noisy face groups")
|
|
94
|
+
layout.add_argument("--min-island-faces", type=int, default=24, help="islands smaller than this join a neighbour")
|
|
95
|
+
layout.add_argument("--max-facing-angle", type=float, default=65.0,
|
|
96
|
+
help="a face may join a view only within this angle of facing it, degrees")
|
|
97
|
+
layout.add_argument("--view-density", default="",
|
|
98
|
+
help="texture-space boost per view, e.g. left=1.5,right=1.5 for livery panels")
|
|
99
|
+
layout.add_argument("--smart-angle", type=float, default=66.0, help="angle limit for --unwrap smart, degrees")
|
|
100
|
+
layout.add_argument("--pack-rotate", choices=["none", "cardinal", "any"], default="any",
|
|
101
|
+
help="island rotation while packing: any = tightest (default), cardinal = 90-degree steps, "
|
|
102
|
+
"none = every island upright, for painting by hand")
|
|
103
|
+
layout.add_argument("--padding", type=int, default=None,
|
|
104
|
+
help="pixels between islands and of edge padding (default: texture size / 512, at least 2)")
|
|
105
|
+
layout.add_argument("--no-fix-overlaps", action="store_true", help="do not re-unwrap folded islands")
|
|
106
|
+
layout.add_argument("--hidden-density", type=float, default=0.4,
|
|
107
|
+
help="texel density of surfaces no outside view can see, relative to visible ones; the "
|
|
108
|
+
"texture space saved goes to visible surfaces (1 = uniform density)")
|
|
109
|
+
|
|
110
|
+
texture = parser.add_argument_group("texture")
|
|
111
|
+
texture.add_argument("--texture-size", type=int, default=2048,
|
|
112
|
+
help="square output texture size in pixels (2048 suits game assets; 4096 for hero close-ups)")
|
|
113
|
+
texture.add_argument("--work-size", type=int, default=0,
|
|
114
|
+
help="size the textures are built at before filtering down to --texture-size "
|
|
115
|
+
"(default: twice the output, up to 4096)")
|
|
116
|
+
texture.add_argument("--refs", default=None,
|
|
117
|
+
help="folder of reference images (views found by file name; three-quarter views included)")
|
|
118
|
+
texture.add_argument("--ref", action="append", default=[], metavar="VIEW=PATH",
|
|
119
|
+
help="one reference image: front, rear, left, right, top, bottom, an angled view such as "
|
|
120
|
+
"front_left or top_rear, or oblique for an angle to be found (repeatable)")
|
|
121
|
+
texture.add_argument("--no-oblique", action="store_true",
|
|
122
|
+
help="use straight views only; skip three-quarter / angled reference images")
|
|
123
|
+
texture.add_argument("--ref-rotate", action="append", default=[], metavar="VIEW=DEGREES",
|
|
124
|
+
help="fixed in-plane rotation of a reference (multiples of 90); top/bottom are detected otherwise")
|
|
125
|
+
texture.add_argument("--ref-bg-tolerance", type=float, default=0.08,
|
|
126
|
+
help="how far a pixel may differ from the background color and still be background, 0..1")
|
|
127
|
+
texture.add_argument("--ref-min-iou", type=float, default=0.80,
|
|
128
|
+
help="skip references whose silhouette matches the model worse than this, 0..1")
|
|
129
|
+
texture.add_argument("--ref-align", choices=["fit", "refine"], default="refine",
|
|
130
|
+
help="refine = also search small scale/offset corrections for each reference")
|
|
131
|
+
texture.add_argument("--ref-max-angle", type=float, default=70.0,
|
|
132
|
+
help="surfaces turned further than this from a view get nothing from it, degrees")
|
|
133
|
+
texture.add_argument("--ref-source-score", type=float, default=0.35,
|
|
134
|
+
help="score (0..1: how head-on x how much of the face it sees x how well it agrees) a view "
|
|
135
|
+
"must beat to replace the model's own texture on a face; higher keeps more of it")
|
|
136
|
+
texture.add_argument("--ref-seam-smoothness", type=float, default=0.12,
|
|
137
|
+
help="how strongly neighbouring faces join the same view; higher = larger patches, "
|
|
138
|
+
"fewer seams; 0 = every face for itself")
|
|
139
|
+
texture.add_argument("--no-exposure-match", action="store_true",
|
|
140
|
+
help="do not even out the lighting baked into each reference (per-view gains from overlaps)")
|
|
141
|
+
texture.add_argument("--no-ref-warp", action="store_true",
|
|
142
|
+
help="skip local alignment of references to the source texture (global fit only)")
|
|
143
|
+
texture.add_argument("--ref-warp-max", type=float, default=0.04,
|
|
144
|
+
help="largest local shift a reference may get, as a fraction of its subject size")
|
|
145
|
+
texture.add_argument("--ref-consistency", type=float, default=0.5,
|
|
146
|
+
help="0..1 how closely a reference's features must line up with the model's own texture "
|
|
147
|
+
"where that texture shows any; higher = stricter, 0 = trust references everywhere")
|
|
148
|
+
texture.add_argument("--ref-normal-smoothing", type=int, default=8,
|
|
149
|
+
help="edge rings of normal smoothing used to weigh views, so lumpy panels paint evenly")
|
|
150
|
+
texture.add_argument("--ref-strength", type=float, default=1.0, help="0..1 overall reference opacity")
|
|
151
|
+
texture.add_argument("--ref-edge-inset", type=int, default=3, help="ignore this many pixels at the subject's edge")
|
|
152
|
+
texture.add_argument("--depth-tolerance", type=float, default=0.01,
|
|
153
|
+
help="visibility test slack as a fraction of the model diagonal")
|
|
154
|
+
texture.add_argument("--no-color-match", action="store_true",
|
|
155
|
+
help="do not match the source texture's colors to the references")
|
|
156
|
+
texture.add_argument("--maps", default="auto", help="maps to produce: auto, or a list of color,metallic_roughness,normal")
|
|
157
|
+
texture.add_argument("--roughness", type=float, default=None, help="constant roughness instead of a map")
|
|
158
|
+
texture.add_argument("--metallic", type=float, default=None, help="constant metallic instead of a map")
|
|
159
|
+
texture.add_argument("--no-normal-map", action="store_true", help="never produce a normal map")
|
|
160
|
+
texture.add_argument("--keep-source-normal-map", action="store_true",
|
|
161
|
+
help="carry the source's own normal map over (off: generated normal maps are mostly relief "
|
|
162
|
+
"guessed from their texture, e.g. embossed logos, and fight the repainted texture)")
|
|
163
|
+
texture.add_argument("--bake-distance", type=float, default=0.004,
|
|
164
|
+
help="bake ray search distance as a fraction of the model diagonal")
|
|
165
|
+
texture.add_argument("--bake-samples", type=int, default=4, help="Cycles anti-aliasing samples per texel")
|
|
166
|
+
texture.add_argument("--device", choices=["auto", "cpu", "gpu"], default="auto", help="Cycles bake device")
|
|
167
|
+
texture.add_argument("--image-format", choices=["png", "jpeg", "webp"], default="webp",
|
|
168
|
+
help="how glTF / GLB stores its textures (webp = small downloads via EXT_texture_webp; "
|
|
169
|
+
"png = lossless); the files in textures/ are always lossless PNG masters")
|
|
170
|
+
texture.add_argument("--image-quality", type=int, default=90, help="JPEG / WebP quality 0..100")
|
|
171
|
+
texture.add_argument("--double-sided", action="store_true",
|
|
172
|
+
help="render both sides of every face (only for open, single-sheet surfaces; costs fill rate)")
|
|
173
|
+
texture.add_argument("--draco", action="store_true",
|
|
174
|
+
help="Draco-compress the glTF / GLB geometry (smaller download; needs the Draco decoder "
|
|
175
|
+
"at load time)")
|
|
176
|
+
return parser
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def parse_options(argv: list) -> argparse.Namespace:
|
|
180
|
+
"""
|
|
181
|
+
Parses and normalises the options after Blender's `--` separator.
|
|
182
|
+
|
|
183
|
+
:param argv: Arguments for bt-unwrap only.
|
|
184
|
+
:returns: The options namespace, with derived fields (view_density dict, ref_pairs, lod_ratios, paths).
|
|
185
|
+
:raises SystemExit: on invalid input (argparse prints the reason).
|
|
186
|
+
"""
|
|
187
|
+
parser = build_parser()
|
|
188
|
+
options = parser.parse_args(argv)
|
|
189
|
+
options.input = os.path.abspath(options.input)
|
|
190
|
+
stem = os.path.splitext(os.path.basename(options.input))[0]
|
|
191
|
+
options.stem = stem
|
|
192
|
+
if options.output:
|
|
193
|
+
options.output = os.path.abspath(options.output)
|
|
194
|
+
options.out_dir = os.path.abspath(options.out_dir or os.path.dirname(options.output))
|
|
195
|
+
else:
|
|
196
|
+
options.out_dir = os.path.abspath(options.out_dir or os.path.join(os.path.dirname(options.input), f"{stem}_unwrap"))
|
|
197
|
+
options.output = os.path.join(options.out_dir, f"{stem}.{options.format or DEFAULT_OUTPUT_FORMAT}")
|
|
198
|
+
if _same_path(options.output, options.input):
|
|
199
|
+
parser.error("the output would overwrite the input model; choose another --output or --out-dir "
|
|
200
|
+
"(bt-unwrap never replaces its source)")
|
|
201
|
+
options.view_density = _parse_pairs(parser, options.view_density, "--view-density", float)
|
|
202
|
+
options.ref_pairs = [_parse_reference_entry(parser, entry) for entry in options.ref]
|
|
203
|
+
rotations = _parse_pairs(parser, ",".join(options.ref_rotate), "--ref-rotate", float)
|
|
204
|
+
options.ref_quarter_turns = {view: int(round(degrees / 90.0)) % 4 for view, degrees in rotations.items()}
|
|
205
|
+
options.refs = os.path.abspath(options.refs) if options.refs else None
|
|
206
|
+
options.lod_ratios = [float(value) for value in options.lods.split(",") if value.strip()]
|
|
207
|
+
if any(not 0.0 < ratio < 1.0 for ratio in options.lod_ratios):
|
|
208
|
+
parser.error("--lods ratios must be between 0 and 1, e.g. 0.5,0.25")
|
|
209
|
+
options.fix_normals = not options.no_fix_normals
|
|
210
|
+
options.fix_overlaps = not options.no_fix_overlaps
|
|
211
|
+
options.color_match = not options.no_color_match
|
|
212
|
+
options.exposure_match = not options.no_exposure_match
|
|
213
|
+
if options.texture_size < 64:
|
|
214
|
+
parser.error("--texture-size must be at least 64")
|
|
215
|
+
if options.padding is None:
|
|
216
|
+
options.padding = max(MINIMUM_PADDING, options.texture_size // PADDING_TEXTURE_DIVISOR)
|
|
217
|
+
if options.work_size <= 0:
|
|
218
|
+
options.work_size = max(options.texture_size,
|
|
219
|
+
min(options.texture_size * SUPERSAMPLE_FACTOR, MAXIMUM_AUTO_WORK_SIZE))
|
|
220
|
+
if options.work_size < options.texture_size:
|
|
221
|
+
parser.error("--work-size cannot be smaller than --texture-size")
|
|
222
|
+
options.work_padding = int(round(options.padding * options.work_size / options.texture_size))
|
|
223
|
+
return options
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _parse_reference_entry(parser, entry: str) -> tuple:
|
|
227
|
+
"""Parses one --ref VIEW=PATH entry (the path may itself contain '=' or ',')."""
|
|
228
|
+
if "=" not in entry:
|
|
229
|
+
parser.error(f"--ref expects VIEW=PATH, got '{entry}'")
|
|
230
|
+
view, path = entry.split("=", 1)
|
|
231
|
+
return view.strip().lower(), os.path.abspath(path.strip())
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _same_path(first: str, second: str) -> bool:
|
|
235
|
+
"""True when two paths name the same file (case-insensitive file systems and symlinks included)."""
|
|
236
|
+
return os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second))
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _parse_pairs(parser, text: str, flag: str, convert) -> dict:
|
|
240
|
+
"""Parses 'name=value,name=value' option text."""
|
|
241
|
+
pairs = {}
|
|
242
|
+
for item in [part.strip() for part in text.split(",") if part.strip()]:
|
|
243
|
+
if "=" not in item:
|
|
244
|
+
parser.error(f"{flag} expects name=value, got '{item}'")
|
|
245
|
+
name, value = item.split("=", 1)
|
|
246
|
+
try:
|
|
247
|
+
pairs[name.strip().lower()] = convert(value.strip())
|
|
248
|
+
except ValueError:
|
|
249
|
+
parser.error(f"{flag}: '{value}' is not a valid value for {name}")
|
|
250
|
+
return pairs
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class Run:
|
|
254
|
+
"""One bt-unwrap run: the options, the scene objects being worked on, and the report being built."""
|
|
255
|
+
|
|
256
|
+
def __init__(self, options: argparse.Namespace):
|
|
257
|
+
self.options = options
|
|
258
|
+
self.report = {"input": options.input, "options": _serializable_options(options), "steps": {},
|
|
259
|
+
"warnings": [], "outputs": {}, "timings_seconds": {}}
|
|
260
|
+
self.objects = []
|
|
261
|
+
self.targets = []
|
|
262
|
+
self.sources = []
|
|
263
|
+
self.references = []
|
|
264
|
+
self.before_renders = {}
|
|
265
|
+
self.diagnostic_map_paths = {}
|
|
266
|
+
self.decimated = False
|
|
267
|
+
self.started = time.time()
|
|
268
|
+
|
|
269
|
+
def step(self, name: str, function, *arguments):
|
|
270
|
+
"""Runs one pipeline step, timing it and printing progress."""
|
|
271
|
+
print(f"bt-unwrap: {name} ...", flush=True)
|
|
272
|
+
step_started = time.time()
|
|
273
|
+
result = function(*arguments)
|
|
274
|
+
self.report["timings_seconds"][name] = round(time.time() - step_started, 2)
|
|
275
|
+
return result
|
|
276
|
+
|
|
277
|
+
def warn(self, message: str) -> None:
|
|
278
|
+
"""Records a warning in the report and prints it."""
|
|
279
|
+
self.report["warnings"].append(message)
|
|
280
|
+
print(f"bt-unwrap: WARNING {message}", flush=True)
|
|
281
|
+
|
|
282
|
+
# ----- pipeline -------------------------------------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
def execute(self) -> dict:
|
|
285
|
+
"""Runs the whole pipeline and returns the report."""
|
|
286
|
+
options = self.options
|
|
287
|
+
os.makedirs(options.out_dir, exist_ok=True)
|
|
288
|
+
self.step("import", self.import_model)
|
|
289
|
+
self.step("references", self.load_references)
|
|
290
|
+
self.step("orientation", self.orient_and_scale)
|
|
291
|
+
if not options.no_preview:
|
|
292
|
+
self.step("preview before", self.render_before)
|
|
293
|
+
if options.analyze:
|
|
294
|
+
self.step("reference alignment", self.align_references)
|
|
295
|
+
return self.finish()
|
|
296
|
+
self.step("cleanup", self.cleanup)
|
|
297
|
+
self.step("decimate", self.decimate)
|
|
298
|
+
self.step("unwrap", self.unwrap)
|
|
299
|
+
self.step("reference alignment", self.align_references)
|
|
300
|
+
self.step("textures", self.build_textures)
|
|
301
|
+
self.step("export", self.export)
|
|
302
|
+
if not options.no_preview:
|
|
303
|
+
self.step("preview after", self.render_after)
|
|
304
|
+
return self.finish()
|
|
305
|
+
|
|
306
|
+
def import_model(self) -> None:
|
|
307
|
+
"""Loads the input and records what it contains."""
|
|
308
|
+
self.objects = model_io.import_model(self.options.input)
|
|
309
|
+
meshes = mesh_tools.mesh_objects(self.objects)
|
|
310
|
+
materials = {slot.material.name for obj in meshes for slot in obj.material_slots if slot.material}
|
|
311
|
+
self.report["steps"]["import"] = {
|
|
312
|
+
"objects": len(self.objects), "meshes": len(meshes),
|
|
313
|
+
"triangles": mesh_tools.count_triangles(meshes), "materials": len(materials),
|
|
314
|
+
"images": len([image for image in bpy.data.images if image.size[0] > 0]),
|
|
315
|
+
"has_armature": any(obj.type == "ARMATURE" for obj in self.objects),
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
def load_references(self) -> None:
|
|
319
|
+
"""Finds and loads the reference views (none is fine: the source texture is used alone)."""
|
|
320
|
+
sources, notes = reference_views.discover_references(self.options.refs, self.options.ref_pairs,
|
|
321
|
+
not self.options.no_oblique)
|
|
322
|
+
for source in sources:
|
|
323
|
+
reference = reference_views.load_reference(source, self.options.ref_bg_tolerance,
|
|
324
|
+
self.options.ref_quarter_turns.get(source.view))
|
|
325
|
+
self.references.append(reference)
|
|
326
|
+
self.report["steps"]["references"] = {"found": {source.view: source.path for source in sources},
|
|
327
|
+
"notes": notes}
|
|
328
|
+
|
|
329
|
+
def orient_and_scale(self) -> None:
|
|
330
|
+
"""Turns the model to face glTF +Z (Blender -Y), scales it to size and places its origin."""
|
|
331
|
+
options = self.options
|
|
332
|
+
meshes = mesh_tools.mesh_objects(self.objects)
|
|
333
|
+
mesh_tools.transform_model(self.objects, mesh_tools.rotation_from_euler_degrees(options.rotate))
|
|
334
|
+
|
|
335
|
+
forward = options.forward
|
|
336
|
+
scores = None
|
|
337
|
+
if forward == "auto":
|
|
338
|
+
if any(not reference.oblique for reference in self.references):
|
|
339
|
+
triangles = mesh_tools.collect_triangles(meshes)
|
|
340
|
+
forward, scores = reference_views.detect_forward(self.references, triangles.positions)
|
|
341
|
+
else:
|
|
342
|
+
forward = "keep"
|
|
343
|
+
print("bt-unwrap: no straight reference view to detect the heading from; keeping the imported "
|
|
344
|
+
"one (--forward +x/-x/+y/-y turns it)", flush=True)
|
|
345
|
+
if forward != "keep":
|
|
346
|
+
mesh_tools.transform_model(self.objects, mesh_tools.forward_rotation(forward))
|
|
347
|
+
|
|
348
|
+
matrix, scale_factor = mesh_tools.scale_and_origin_matrix(meshes, options.length, options.width,
|
|
349
|
+
options.height, options.origin)
|
|
350
|
+
mesh_tools.transform_model(self.objects, matrix)
|
|
351
|
+
bpy.context.view_layer.update()
|
|
352
|
+
minimum, maximum = mesh_tools.model_bounds(meshes)
|
|
353
|
+
self.report["steps"]["orientation"] = {
|
|
354
|
+
"forward_axis_detected": forward, "heading_scores": scores, "scale_factor": round(scale_factor, 6),
|
|
355
|
+
"size_meters": np.round(maximum - minimum, 4).tolist(), "origin": options.origin,
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
def render_before(self) -> None:
|
|
359
|
+
"""Renders the model as imported (already turned to the common heading)."""
|
|
360
|
+
preview_dir = os.path.join(self.options.out_dir, "preview")
|
|
361
|
+
self.before_renders = previews.render_views(self.objects, preview_dir, "before", self.options.preview_size)
|
|
362
|
+
|
|
363
|
+
def cleanup(self) -> None:
|
|
364
|
+
"""
|
|
365
|
+
Keeps an untouched copy of the model for baking, then joins (unless --keep-objects), repairs geometry
|
|
366
|
+
and sets shading. The copy keeps the imported shading normals and materials exactly as authored, so the
|
|
367
|
+
bake carries the original look onto the cleaned mesh.
|
|
368
|
+
"""
|
|
369
|
+
options = self.options
|
|
370
|
+
self.sources = [mesh_tools.detached_copy(obj, f"{obj.name}_BakeSource")
|
|
371
|
+
for obj in mesh_tools.mesh_objects(self.objects)]
|
|
372
|
+
if not options.keep_objects:
|
|
373
|
+
if self.report["steps"]["import"]["has_armature"]:
|
|
374
|
+
self.warn("rigged model: objects are kept separate so the skinning survives (--keep-objects)")
|
|
375
|
+
options.keep_objects = True
|
|
376
|
+
else:
|
|
377
|
+
self.objects = [mesh_tools.join_meshes(self.objects)]
|
|
378
|
+
self.targets = mesh_tools.mesh_objects(self.objects)
|
|
379
|
+
diagonal = self.model_diagonal()
|
|
380
|
+
merge_distance = options.merge_distance if options.merge_distance is not None \
|
|
381
|
+
else diagonal * AUTO_MERGE_DISTANCE_FRACTION
|
|
382
|
+
results = [mesh_tools.cleanup_mesh(obj, merge_distance, options.debris_faces, options.fix_normals,
|
|
383
|
+
options.fill_holes) for obj in self.targets]
|
|
384
|
+
mesh_tools.apply_shading(self.targets, options.shading, options.smooth_angle)
|
|
385
|
+
self.report["steps"]["cleanup"] = {"merge_distance": merge_distance, "per_object": results,
|
|
386
|
+
"triangles": mesh_tools.count_triangles(self.targets)}
|
|
387
|
+
|
|
388
|
+
def decimate(self) -> None:
|
|
389
|
+
"""Reduces the model to the face budget (the bake copy keeps the full detail)."""
|
|
390
|
+
options = self.options
|
|
391
|
+
before = mesh_tools.count_triangles(self.targets)
|
|
392
|
+
if options.faces > 0 and before > options.faces:
|
|
393
|
+
budget_share = options.faces / before
|
|
394
|
+
for obj in self.targets:
|
|
395
|
+
mesh_tools.decimate_to_triangles(obj, int(mesh_tools.count_triangles([obj]) * budget_share))
|
|
396
|
+
self.decimated = True
|
|
397
|
+
after = mesh_tools.count_triangles(self.targets)
|
|
398
|
+
self.report["steps"]["decimate"] = {"triangles_before": before, "triangles_after": after,
|
|
399
|
+
"decimated": self.decimated}
|
|
400
|
+
|
|
401
|
+
def unwrap(self) -> None:
|
|
402
|
+
"""Creates the new UV layout."""
|
|
403
|
+
method = self.options.unwrap
|
|
404
|
+
if method == "views":
|
|
405
|
+
statistics = uv_layout.unwrap_by_views(self.targets, self.options)
|
|
406
|
+
elif method == "smart":
|
|
407
|
+
statistics = uv_layout.unwrap_smart(self.targets, self.options)
|
|
408
|
+
else:
|
|
409
|
+
statistics = uv_layout.keep_existing_layout(self.targets)
|
|
410
|
+
if statistics.get("overlap_percent", 0) > 0.5:
|
|
411
|
+
self.warn(f"{statistics['overlap_percent']}% of the layout overlaps; try --projections 14 or --unwrap smart")
|
|
412
|
+
self.report["steps"]["unwrap"] = statistics
|
|
413
|
+
|
|
414
|
+
def align_references(self) -> None:
|
|
415
|
+
"""Fits every reference's camera to the final geometry and builds its visibility depth buffer."""
|
|
416
|
+
meshes = self.targets or mesh_tools.mesh_objects(self.objects)
|
|
417
|
+
triangles = mesh_tools.collect_triangles(meshes)
|
|
418
|
+
proxies = reference_views.build_silhouette_proxies(triangles.positions)
|
|
419
|
+
preview_dir = os.path.join(self.options.out_dir, "preview")
|
|
420
|
+
for reference in self.references:
|
|
421
|
+
reference_views.align_reference(reference, triangles.positions, self.options.ref_align == "refine",
|
|
422
|
+
self.options.ref_min_iou, proxies)
|
|
423
|
+
self.report["steps"]["references"]["notes"].extend(reference_views.settle_oblique_views(self.references))
|
|
424
|
+
for reference in self.references:
|
|
425
|
+
reference_views.build_depth_buffer(reference, triangles.positions)
|
|
426
|
+
if not reference.used:
|
|
427
|
+
self.warn(f"{reference.view} reference not used: {reference.note}")
|
|
428
|
+
if not self.options.no_preview:
|
|
429
|
+
reference.overlay = previews.alignment_overlay(reference, preview_dir)
|
|
430
|
+
self.report["steps"]["references"]["alignment"] = [reference.report() for reference in self.references]
|
|
431
|
+
|
|
432
|
+
def build_textures(self) -> None:
|
|
433
|
+
"""Bakes the source maps onto the new layout, paints the references on, and saves the textures."""
|
|
434
|
+
options = self.options
|
|
435
|
+
texture_bake.ensure_source_materials(self.sources)
|
|
436
|
+
source_summary = texture_bake.describe_source_materials(self.sources)
|
|
437
|
+
constant_color = texture_bake.source_base_color(self.sources)
|
|
438
|
+
maps = self.choose_maps(source_summary)
|
|
439
|
+
size = options.work_size
|
|
440
|
+
diagonal = self.model_diagonal()
|
|
441
|
+
device = "none"
|
|
442
|
+
baked = {}
|
|
443
|
+
if maps:
|
|
444
|
+
device = texture_bake.configure_cycles(options.bake_samples, options.device != "cpu")
|
|
445
|
+
print(f"bt-unwrap: baking {', '.join(maps)} at {size}px on {device}", flush=True)
|
|
446
|
+
baked = texture_bake.bake_source_maps(self.targets, self.sources, size, diagonal * options.bake_distance,
|
|
447
|
+
options.work_padding, tuple(maps), options.keep_source_normal_map)
|
|
448
|
+
else:
|
|
449
|
+
print("bt-unwrap: the source has no color data and there are no references: the material keeps its "
|
|
450
|
+
"constant color; the new layout is ready for painting", flush=True)
|
|
451
|
+
for source in self.sources:
|
|
452
|
+
bpy.data.objects.remove(source, do_unlink=True)
|
|
453
|
+
self.sources = []
|
|
454
|
+
|
|
455
|
+
triangles = mesh_tools.collect_triangles(self.targets, (uv_layout.NEW_UV_LAYER,))
|
|
456
|
+
vertex_normals = mesh_tools.smoothed_vertex_normals(self.targets, options.ref_normal_smoothing)
|
|
457
|
+
surface = texture_compose.build_texel_surface(triangles, size, vertex_normals)
|
|
458
|
+
texture_dir = os.path.join(options.out_dir, "textures")
|
|
459
|
+
texture_paths = {}
|
|
460
|
+
compose_statistics = {}
|
|
461
|
+
output_size = options.texture_size
|
|
462
|
+
color = baked.get("color")
|
|
463
|
+
if color is not None:
|
|
464
|
+
self.match_references(triangles, color)
|
|
465
|
+
color, compose_statistics, diagnostic_maps = texture_compose.compose_color(
|
|
466
|
+
color, surface, triangles, self.references, options, diagonal, options.work_padding)
|
|
467
|
+
color = image_utils.downsample_map(color, output_size)
|
|
468
|
+
if not options.no_preview:
|
|
469
|
+
for name, diagnostic_map in diagnostic_maps.items():
|
|
470
|
+
self.diagnostic_map_paths[name] = image_utils.save_image_array(
|
|
471
|
+
image_utils.downsample_map(diagnostic_map, output_size),
|
|
472
|
+
os.path.join(options.out_dir, "preview", f"{name}_texture.png"))
|
|
473
|
+
# The texture files are lossless masters; the model file encodes them once, in --image-format.
|
|
474
|
+
texture_paths["color"] = image_utils.save_image_array(
|
|
475
|
+
color, os.path.join(texture_dir, f"{options.stem}_basecolor.png"))
|
|
476
|
+
if "metallic_roughness" in baked:
|
|
477
|
+
texture_paths["metallic_roughness"] = image_utils.save_image_array(
|
|
478
|
+
image_utils.downsample_map(baked["metallic_roughness"], output_size),
|
|
479
|
+
os.path.join(texture_dir, f"{options.stem}_metallic_roughness.png"))
|
|
480
|
+
if "normal" in baked:
|
|
481
|
+
texture_paths["normal"] = image_utils.save_image_array(
|
|
482
|
+
image_utils.downsample_map(baked["normal"], output_size, is_normal_map=True),
|
|
483
|
+
os.path.join(texture_dir, f"{options.stem}_normal.png"))
|
|
484
|
+
|
|
485
|
+
uv_layout.finalize_uv_layers(self.targets)
|
|
486
|
+
texture_bake.build_final_material(self.targets, f"{options.stem}_Material", texture_paths,
|
|
487
|
+
options.roughness, options.metallic, constant_color, options.double_sided)
|
|
488
|
+
layout_images = {}
|
|
489
|
+
if not options.no_preview:
|
|
490
|
+
layout_background = color if color is not None else \
|
|
491
|
+
np.broadcast_to(np.array(constant_color, dtype=np.float32), (output_size, output_size, 4)).copy()
|
|
492
|
+
covered = image_utils.downsample_map(surface.covered_mask().astype(np.float32), output_size) > 0.0
|
|
493
|
+
layout_images = previews.uv_layout_images(layout_background, covered, texture_dir, options.stem)
|
|
494
|
+
self.report["steps"]["textures"] = {"bake_device": device, "maps": maps, "source": source_summary,
|
|
495
|
+
"output_size": output_size, "work_size": size,
|
|
496
|
+
"compose": compose_statistics, "files": texture_paths,
|
|
497
|
+
"uv_images": layout_images}
|
|
498
|
+
|
|
499
|
+
def match_references(self, triangles, baked_color) -> None:
|
|
500
|
+
"""
|
|
501
|
+
Locally aligns every used reference to the mesh by matching it against the baked source texture
|
|
502
|
+
rendered from the same camera, then maps where each reference agrees with that texture (and so may
|
|
503
|
+
paint). Writes a check image per view for both.
|
|
504
|
+
"""
|
|
505
|
+
options = self.options
|
|
506
|
+
preview_dir = os.path.join(options.out_dir, "preview")
|
|
507
|
+
for reference in [reference for reference in self.references if reference.used]:
|
|
508
|
+
if not options.no_ref_warp:
|
|
509
|
+
reference.warp = reference_warp.estimate_warp(reference, triangles, baked_color, options.ref_warp_max)
|
|
510
|
+
if reference.warp is None:
|
|
511
|
+
self.warn(f"{reference.view} reference: no detail to align locally; using the global fit only")
|
|
512
|
+
if not options.no_preview:
|
|
513
|
+
check_image = reference_warp.warp_preview(reference, triangles, baked_color)
|
|
514
|
+
image_utils.save_image_array(check_image, os.path.join(preview_dir, f"warp_{reference.view}.png"))
|
|
515
|
+
if options.ref_consistency > 0.0:
|
|
516
|
+
reference.agreement = reference_warp.consistency_map(reference, triangles, baked_color,
|
|
517
|
+
options.ref_consistency)
|
|
518
|
+
if reference.agreement is not None and not options.no_preview:
|
|
519
|
+
image_utils.save_image_array(reference_warp.consistency_preview(reference.agreement),
|
|
520
|
+
os.path.join(preview_dir, f"consistency_{reference.view}.png"))
|
|
521
|
+
self.report["steps"]["references"]["alignment"] = [reference.report() for reference in self.references]
|
|
522
|
+
|
|
523
|
+
def choose_maps(self, source_summary: dict) -> list:
|
|
524
|
+
"""Decides which texture maps to bake from what the source has and what was asked for."""
|
|
525
|
+
options = self.options
|
|
526
|
+
if options.maps != "auto":
|
|
527
|
+
maps = [name.strip() for name in options.maps.split(",") if name.strip()]
|
|
528
|
+
unknown = set(maps) - {"color", "metallic_roughness", "normal"}
|
|
529
|
+
if unknown:
|
|
530
|
+
raise ValueError(f"--maps: unknown map(s) {', '.join(sorted(unknown))}")
|
|
531
|
+
else:
|
|
532
|
+
maps = []
|
|
533
|
+
has_color_data = source_summary["has_color_texture"] or source_summary["has_vertex_colors"] or \
|
|
534
|
+
any(reference.used for reference in self.references)
|
|
535
|
+
if has_color_data:
|
|
536
|
+
maps.append("color")
|
|
537
|
+
if source_summary["has_metallic_roughness_texture"] and (options.roughness is None or options.metallic is None):
|
|
538
|
+
maps.append("metallic_roughness")
|
|
539
|
+
# A normal map earns its texture when it carries shape the mesh lost in decimation, or when the
|
|
540
|
+
# source's own normal map is wanted; a generated one is otherwise guessed relief that fights the
|
|
541
|
+
# repainted texture.
|
|
542
|
+
if self.decimated or (source_summary["has_normal_map"] and options.keep_source_normal_map):
|
|
543
|
+
maps.append("normal")
|
|
544
|
+
if options.no_normal_map and "normal" in maps:
|
|
545
|
+
maps.remove("normal")
|
|
546
|
+
return maps
|
|
547
|
+
|
|
548
|
+
def export(self) -> None:
|
|
549
|
+
"""Writes the model and its LODs."""
|
|
550
|
+
options = self.options
|
|
551
|
+
export_objects = [obj for obj in bpy.context.scene.objects if obj.type in ("MESH", "ARMATURE", "EMPTY")]
|
|
552
|
+
main_path = model_io.export_model(options.output, export_objects, options.image_format, options.image_quality,
|
|
553
|
+
options.draco, self.has_normal_map())
|
|
554
|
+
outputs = {"model": main_path, "lods": []}
|
|
555
|
+
for level, ratio in enumerate(options.lod_ratios, start=1):
|
|
556
|
+
outputs["lods"].append(self.export_lod(level, ratio, export_objects))
|
|
557
|
+
self.report["outputs"].update(outputs)
|
|
558
|
+
self.report["steps"]["export"] = {"triangles": mesh_tools.count_triangles(self.targets),
|
|
559
|
+
"file_megabytes": round(os.path.getsize(main_path) / 1e6, 2)}
|
|
560
|
+
|
|
561
|
+
def export_lod(self, level: int, ratio: float, export_objects: list) -> dict:
|
|
562
|
+
"""Exports one decimated copy that shares the main model's UVs and textures."""
|
|
563
|
+
base, extension = os.path.splitext(self.options.output)
|
|
564
|
+
copies = [mesh_tools.duplicate_object(obj, f"{obj.name}_LOD{level}") for obj in self.targets]
|
|
565
|
+
for copy in copies:
|
|
566
|
+
mesh_tools.decimate_to_triangles(copy, int(mesh_tools.count_triangles([copy]) * ratio))
|
|
567
|
+
others = [obj for obj in export_objects if obj.type != "MESH"]
|
|
568
|
+
path = model_io.export_model(f"{base}_lod{level}{extension}", copies + others, self.options.image_format,
|
|
569
|
+
self.options.image_quality, self.options.draco, self.has_normal_map())
|
|
570
|
+
triangles = mesh_tools.count_triangles(copies)
|
|
571
|
+
for copy in copies:
|
|
572
|
+
bpy.data.objects.remove(copy, do_unlink=True)
|
|
573
|
+
return {"path": path, "ratio": ratio, "triangles": triangles}
|
|
574
|
+
|
|
575
|
+
def render_after(self) -> None:
|
|
576
|
+
"""Renders the result and writes the before/after comparison sheet."""
|
|
577
|
+
preview_dir = os.path.join(self.options.out_dir, "preview")
|
|
578
|
+
after = previews.render_views(self.targets, preview_dir, "after", self.options.preview_size)
|
|
579
|
+
for name, texture_path in self.diagnostic_map_paths.items():
|
|
580
|
+
self.report["outputs"][f"{name}_renders"] = previews.render_with_texture(
|
|
581
|
+
self.targets, texture_path, preview_dir, name, self.options.preview_size)
|
|
582
|
+
sheet = previews.comparison_sheet(self.before_renders, after, os.path.join(preview_dir, "comparison.png"))
|
|
583
|
+
self.report["outputs"]["previews"] = {"before": self.before_renders, "after": after, "comparison": sheet}
|
|
584
|
+
|
|
585
|
+
# ----- helpers --------------------------------------------------------------------------------------
|
|
586
|
+
|
|
587
|
+
def has_normal_map(self) -> bool:
|
|
588
|
+
"""True when the final material carries a baked normal map."""
|
|
589
|
+
return "normal" in self.report["steps"].get("textures", {}).get("files", {})
|
|
590
|
+
|
|
591
|
+
def model_diagonal(self) -> float:
|
|
592
|
+
"""Length of the model's bounding-box diagonal in meters."""
|
|
593
|
+
meshes = self.targets or mesh_tools.mesh_objects(self.objects)
|
|
594
|
+
minimum, maximum = mesh_tools.model_bounds(meshes)
|
|
595
|
+
return float(np.linalg.norm(maximum - minimum))
|
|
596
|
+
|
|
597
|
+
def finish(self) -> dict:
|
|
598
|
+
"""Writes the JSON report and returns it."""
|
|
599
|
+
self.report["timings_seconds"]["total"] = round(time.time() - self.started, 2)
|
|
600
|
+
overlays = [reference.overlay for reference in self.references if reference.overlay]
|
|
601
|
+
if overlays:
|
|
602
|
+
self.report["outputs"]["alignment_overlays"] = overlays
|
|
603
|
+
report_path = os.path.join(self.options.out_dir, f"{self.options.stem}_report.json")
|
|
604
|
+
self.report["outputs"]["report"] = report_path
|
|
605
|
+
with open(report_path, "w", encoding="utf-8") as report_file:
|
|
606
|
+
json.dump(self.report, report_file, indent=2, default=_json_default)
|
|
607
|
+
return self.report
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _serializable_options(options: argparse.Namespace) -> dict:
|
|
611
|
+
"""The options as plain JSON values."""
|
|
612
|
+
return {name: value for name, value in vars(options).items() if isinstance(value, (str, int, float, bool, list, dict, type(None)))}
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _json_default(value):
|
|
616
|
+
"""Converts numpy scalars for json.dump."""
|
|
617
|
+
if isinstance(value, np.generic):
|
|
618
|
+
return value.item()
|
|
619
|
+
if isinstance(value, np.ndarray):
|
|
620
|
+
return value.tolist()
|
|
621
|
+
return str(value)
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def print_summary(report: dict) -> None:
|
|
625
|
+
"""Prints the headline numbers a person (or agent) needs after a run."""
|
|
626
|
+
steps = report["steps"]
|
|
627
|
+
lines = [f"input {report['input']}"]
|
|
628
|
+
if "import" in steps:
|
|
629
|
+
lines.append(f"triangles {steps['import']['triangles']:,} in -> "
|
|
630
|
+
f"{steps.get('export', {}).get('triangles', steps['import']['triangles']):,} out")
|
|
631
|
+
if "orientation" in steps:
|
|
632
|
+
lines.append(f"forward {steps['orientation']['forward_axis_detected']} size {steps['orientation']['size_meters']} m")
|
|
633
|
+
if "unwrap" in steps:
|
|
634
|
+
unwrap = steps["unwrap"]
|
|
635
|
+
lines.append(f"layout {unwrap['method']}: {unwrap['islands']} islands, {unwrap['uv_coverage_percent']}% of the "
|
|
636
|
+
f"texture used, {unwrap['overlap_percent']}% overlap")
|
|
637
|
+
for alignment in steps.get("references", {}).get("alignment", []):
|
|
638
|
+
state = "used" if alignment["used"] else "SKIPPED"
|
|
639
|
+
lines.append(f"reference {alignment['view']:<6} iou {alignment['silhouette_iou']:.3f} {state} {alignment['path']}")
|
|
640
|
+
if "textures" in steps:
|
|
641
|
+
compose = steps["textures"]["compose"]
|
|
642
|
+
lines.append(f"textures {', '.join(steps['textures']['maps']) or 'none (constant color)'}; "
|
|
643
|
+
f"{compose.get('reference_painted_percent', 0.0)}% of the "
|
|
644
|
+
f"surface painted from references")
|
|
645
|
+
for name, path in report["outputs"].items():
|
|
646
|
+
if isinstance(path, str):
|
|
647
|
+
lines.append(f"{name:<10} {path}")
|
|
648
|
+
for lod in report["outputs"].get("lods", []):
|
|
649
|
+
lines.append(f"lod {lod['triangles']:,} triangles {lod['path']}")
|
|
650
|
+
if report["outputs"].get("previews", {}).get("comparison"):
|
|
651
|
+
lines.append(f"compare {report['outputs']['previews']['comparison']}")
|
|
652
|
+
for warning in report["warnings"]:
|
|
653
|
+
lines.append(f"warning {warning}")
|
|
654
|
+
print("\n".join(f"bt-unwrap: {line}" for line in lines), flush=True)
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def main() -> int:
|
|
658
|
+
"""Entry point: parse options after `--`, run, print the summary. Returns the process exit code."""
|
|
659
|
+
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
|
|
660
|
+
options = parse_options(argv)
|
|
661
|
+
try:
|
|
662
|
+
report = Run(options).execute()
|
|
663
|
+
except (RuntimeError, ValueError) as error:
|
|
664
|
+
# Expected failures (bad input, a model the chosen options cannot handle) get a one-line reason;
|
|
665
|
+
# anything else is a bug and keeps Blender's full traceback.
|
|
666
|
+
if os.environ.get("BT_UNWRAP_TRACEBACK"):
|
|
667
|
+
traceback.print_exc()
|
|
668
|
+
print(f"bt-unwrap: FAILED {error}", flush=True)
|
|
669
|
+
return 1
|
|
670
|
+
print_summary(report)
|
|
671
|
+
print("bt-unwrap: DONE", flush=True)
|
|
672
|
+
return 0
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
if __name__ == "__main__":
|
|
676
|
+
exit_code = main()
|
|
677
|
+
if exit_code:
|
|
678
|
+
sys.exit(exit_code)
|