@babylonjs-toolkit/agent 1.2.15 → 1.2.18

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.
Files changed (58) hide show
  1. package/README.md +8 -2
  2. package/lib/diskinfo/cli.js +40 -6
  3. package/lib/diskinfo/report.js +28 -15
  4. package/package.json +1 -1
  5. package/skills/bt-blender/SKILL.md +386 -0
  6. package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
  7. package/skills/bt-blender/references/art-style-and-genre.md +173 -0
  8. package/skills/bt-blender/references/characters-and-creatures.md +644 -0
  9. package/skills/bt-blender/references/environments.md +478 -0
  10. package/skills/bt-blender/references/game-engine-export.md +284 -0
  11. package/skills/bt-blender/references/geometry-nodes.md +447 -0
  12. package/skills/bt-blender/references/hard-surface.md +720 -0
  13. package/skills/bt-blender/references/procedural-generation.md +358 -0
  14. package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
  15. package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
  16. package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
  17. package/skills/bt-blender/references/vehicles.md +632 -0
  18. package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
  19. package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
  20. package/skills/bt-blender/scripts/blender/construction_kit.py +1710 -0
  21. package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
  22. package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
  23. package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
  24. package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
  25. package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
  26. package/skills/bt-blender/scripts/blender/image_measure.py +568 -0
  27. package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
  28. package/skills/bt-blender/scripts/blender/measure_stations.py +486 -0
  29. package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
  30. package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
  31. package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
  32. package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
  33. package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
  34. package/skills/bt-blender/scripts/blender/review_render.py +358 -0
  35. package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
  36. package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
  37. package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
  38. package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
  39. package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
  40. package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
  41. package/skills/bt-blender/scripts/blender/world_gate.py +219 -0
  42. package/skills/bt-blender/scripts/bt-blender.mjs +329 -0
  43. package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
  44. package/skills/bt-gauntlet/SKILL.md +6 -6
  45. package/skills/bt-gauntlet/references/critic-rubrics.md +71 -4
  46. package/skills/bt-gauntlet/references/spec-composition.md +13 -0
  47. package/skills/bt-gauntlet/references/unity-pipeline.md +18 -2
  48. package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
  49. package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
  50. package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
  51. package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
  52. package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
  53. package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
  54. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
  55. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
  56. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
  57. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
  58. package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
@@ -0,0 +1,420 @@
1
+ """
2
+ assembly_check -- is the asset physically put together? Vision critics miss floating parts and gaps;
3
+ this measures them.
4
+
5
+ Every connected mesh island is a part. Parts are linked when they touch or intersect (within a contact
6
+ tolerance); anything not linked to the main body is reported FLOATING with the gap to its nearest part.
7
+ Contacts report how deep two parts sink into each other (0 = flush). An optional spec adds the asset's
8
+ contract: overall size, per-part size, required attachments ("the mirror must touch the door"), and
9
+ intended overlaps that should not be reported.
10
+
11
+ blender --background --factory-startup --python-exit-code 1 --python assembly_check.py -- \
12
+ --model asset.blend [--objects ...] [--spec assembly.json] [--contact-tolerance 0.001] [--root Body] [--out report.json]
13
+
14
+ Spec (all keys optional):
15
+ {
16
+ "units": "m" | "cm" | "mm",
17
+ "contact_tolerance": 0.001,
18
+ "root": "Body", object whose group is the main body
19
+ "overall": {"dims": [x, y, z], "tolerance": 0.01},
20
+ "parts": {"Mirror": {"dims": [x, y, z], "attached_to": ["Door"]}},
21
+ "expect_embedded": [["Bolt*", "Plate"]] fnmatch pairs whose overlap is intended
22
+ }
23
+
24
+ Portions adapted from calebrisc/blender-modeler (scripts/check_geometry.py, commit c8f2459)
25
+ -- Copyright (c) 2026 Cale Briscoe, MIT License:
26
+
27
+ Permission is hereby granted, free of charge, to any person obtaining a copy
28
+ of this software and associated documentation files (the "Software"), to deal
29
+ in the Software without restriction, including without limitation the rights
30
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
31
+ copies of the Software, and to permit persons to whom the Software is
32
+ furnished to do so, subject to the following conditions:
33
+
34
+ The above copyright notice and this permission notice shall be included in all
35
+ copies or substantial portions of the Software.
36
+
37
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
38
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
39
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
40
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
41
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
42
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
43
+ SOFTWARE.
44
+
45
+ Fixed in this port:
46
+ - the main body was the group holding the LOWEST part, so a small part hanging below the body (a
47
+ bolt, an antenna) became the "body" and the real body was reported floating; it is now the group
48
+ holding the largest part (or the spec's root object);
49
+ - the inverted-normals test summed one signed volume over a whole object, so a mirrored object
50
+ (negative scale) read as inverted and two islands could cancel out; it is now per part, corrected
51
+ for mirroring, and taken about the part's own centre;
52
+ - per-part spec sizes used object.dimensions (the local box), which is wrong for rotated objects;
53
+ sizes now come from evaluated world-space vertices;
54
+ - an `attached_to` naming an object that does not exist was silently skipped; it is now an error;
55
+ - the bt-blender result contract and exit codes.
56
+ """
57
+ import fnmatch
58
+ import math
59
+ import os
60
+ import sys
61
+
62
+ sys.dont_write_bytecode = True
63
+ SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
64
+ if SCRIPT_DIRECTORY not in sys.path:
65
+ sys.path.insert(0, SCRIPT_DIRECTORY)
66
+
67
+ import bpy # noqa: E402
68
+ import numpy as np # noqa: E402
69
+ from mathutils import Vector # noqa: E402
70
+ from mathutils.bvhtree import BVHTree # noqa: E402
71
+
72
+ import tool_common # noqa: E402
73
+
74
+ TOOL_NAME = "assembly-check"
75
+
76
+ # Above this many islands an object counts as one part (arrays, text, scattered bolts).
77
+ MAX_ISLANDS_PER_OBJECT = 64
78
+
79
+ # Vertices sampled per part for distance queries.
80
+ MAX_SAMPLES = 3000
81
+
82
+ # Default contact tolerance as a share of the asset's diagonal, with a floor in metres.
83
+ TOLERANCE_FRACTION = 1e-3
84
+ MINIMUM_TOLERANCE = 1e-4
85
+
86
+ # Default size tolerance for spec dimensions: a share of the size, with a floor in metres.
87
+ SIZE_TOLERANCE_FRACTION = 0.05
88
+ MINIMUM_SIZE_TOLERANCE = 0.002
89
+
90
+ # Ray directions for the majority-vote inside test (off-axis on purpose) and the hit limit per ray.
91
+ RAY_DIRECTIONS = [Vector(direction).normalized() for direction in
92
+ ((0.0123, 0.0071, 1.0), (-0.0093, 0.0157, -1.0), (0.577, 0.5953, 0.5587))]
93
+ MAX_RAY_HITS = 256
94
+
95
+ # Ray-cast restart step past a hit: a share of the part's size, with a floor in metres.
96
+ RAY_STEP_FRACTION = 1e-6
97
+ MINIMUM_RAY_STEP = 1e-9
98
+
99
+ # Scale axes differing by more than this count as non-uniform.
100
+ SCALE_UNIFORMITY_TOLERANCE = 1e-4
101
+
102
+ # Main-body parts (nearest by box) searched for each floating part's closest gap.
103
+ GAP_SEARCH_CANDIDATES = 4
104
+
105
+ UNITS = {"m": 1.0, "cm": 100.0, "mm": 1000.0}
106
+
107
+
108
+ def build_parser() -> tool_common.ToolArgumentParser:
109
+ """The tool's command-line options."""
110
+ parser = tool_common.ToolArgumentParser(prog=TOOL_NAME, description=__doc__.strip().splitlines()[0])
111
+ parser.add_argument("--model", help="asset (.blend .glb .gltf .fbx .obj)")
112
+ parser.add_argument("--objects", nargs="*", help="objects of the asset (default every visible mesh)")
113
+ parser.add_argument("--spec", help="assembly spec JSON")
114
+ parser.add_argument("--contact-tolerance", type=float, help="contact tolerance in metres (default 0.1 %% of the diagonal)")
115
+ parser.add_argument("--root", help="object whose group is the main body (default: the largest part's)")
116
+ parser.add_argument("--out", help="also write the report to this JSON file")
117
+ return parser
118
+
119
+
120
+ def _evaluated_arrays(obj) -> dict:
121
+ """The evaluated mesh in world space: vertices, edges, triangles and the polygon of each triangle."""
122
+ depsgraph = bpy.context.evaluated_depsgraph_get()
123
+ evaluated = obj.evaluated_get(depsgraph)
124
+ mesh = evaluated.to_mesh()
125
+ try:
126
+ coordinates = np.empty(len(mesh.vertices) * 3)
127
+ mesh.vertices.foreach_get("co", coordinates)
128
+ edges = np.empty(len(mesh.edges) * 2, dtype=np.int64)
129
+ mesh.edges.foreach_get("vertices", edges)
130
+ mesh.calc_loop_triangles()
131
+ triangles = np.empty(len(mesh.loop_triangles) * 3, dtype=np.int64)
132
+ mesh.loop_triangles.foreach_get("vertices", triangles)
133
+ edge_use = np.zeros(len(mesh.edges), dtype=np.int64)
134
+ loop_edges = np.empty(len(mesh.loops), dtype=np.int64)
135
+ mesh.loops.foreach_get("edge_index", loop_edges)
136
+ np.add.at(edge_use, loop_edges, 1)
137
+ matrix = np.array(evaluated.matrix_world)
138
+ finally:
139
+ evaluated.to_mesh_clear()
140
+ return {"coordinates": coordinates.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3], "edges": edges.reshape(-1, 2),
141
+ "triangles": triangles.reshape(-1, 3), "edge_use": edge_use,
142
+ "mirrored": float(np.linalg.det(matrix[:3, :3])) < 0.0}
143
+
144
+
145
+ def _component_labels(vertex_count: int, edges: np.ndarray) -> np.ndarray:
146
+ """Connected-component label per vertex (union-find)."""
147
+ parent = np.arange(vertex_count)
148
+
149
+ def find(index):
150
+ root = index
151
+ while parent[root] != root:
152
+ root = parent[root]
153
+ while parent[index] != root:
154
+ parent[index], index = root, parent[index]
155
+ return root
156
+
157
+ for first, second in edges:
158
+ first_root, second_root = find(first), find(second)
159
+ if first_root != second_root:
160
+ parent[first_root] = second_root
161
+ roots = np.array([find(index) for index in range(vertex_count)])
162
+ return np.unique(roots, return_inverse=True)[1]
163
+
164
+
165
+ def _signed_volume(points: np.ndarray, triangles: np.ndarray, mirrored: bool) -> float:
166
+ """Signed volume of a closed triangle set about its own centroid (positive = normals outward)."""
167
+ centered = points - points.mean(axis=0)
168
+ first, second, third = centered[triangles[:, 0]], centered[triangles[:, 1]], centered[triangles[:, 2]]
169
+ volume = float(np.einsum("ij,ij->i", first, np.cross(second, third)).sum() / 6.0)
170
+ return -volume if mirrored else volume
171
+
172
+
173
+ def make_parts(obj, arrays: dict, notes: list) -> list:
174
+ """
175
+ Splits one object into parts (its connected islands), each with a BVH tree, samples and health.
176
+
177
+ :param obj: The object.
178
+ :param arrays: Its evaluated world arrays.
179
+ :param notes: Informational notes to append to.
180
+ :returns: List of part dicts.
181
+ """
182
+ coordinates, triangles = arrays["coordinates"], arrays["triangles"]
183
+ labels = _component_labels(len(coordinates), arrays["edges"]) if len(coordinates) else np.zeros(0, dtype=np.int64)
184
+ island_count = int(labels.max()) + 1 if len(labels) else 0
185
+ if island_count > MAX_ISLANDS_PER_OBJECT:
186
+ notes.append(f"{obj.name}: {island_count} islands, treated as one part")
187
+ labels = np.zeros(len(coordinates), dtype=np.int64)
188
+ open_edges = arrays["edges"][arrays["edge_use"] != 2]
189
+ open_vertices = set(open_edges.ravel().tolist())
190
+ triangle_labels = labels[triangles[:, 0]] if len(triangles) else np.zeros(0, dtype=np.int64)
191
+ parts = []
192
+ for label in np.unique(triangle_labels):
193
+ own = triangles[triangle_labels == label]
194
+ vertex_indices = np.unique(own)
195
+ remap = np.full(len(coordinates), -1, dtype=np.int64)
196
+ remap[vertex_indices] = np.arange(len(vertex_indices))
197
+ points = coordinates[vertex_indices]
198
+ local = remap[own]
199
+ closed = not any(index in open_vertices for index in vertex_indices.tolist())
200
+ low, high = points.min(axis=0), points.max(axis=0)
201
+ parts.append({"label": obj.name if len(np.unique(triangle_labels)) == 1 else f"{obj.name}[island {label}]",
202
+ "object": obj.name, "low": low, "high": high,
203
+ "samples": [Vector(point) for point in points[::max(1, len(points) // MAX_SAMPLES)]],
204
+ "tree": BVHTree.FromPolygons(points.tolist(), local.tolist(), epsilon=0.0),
205
+ "epsilon": max(float(np.linalg.norm(high - low)) * RAY_STEP_FRACTION, MINIMUM_RAY_STEP), "closed": closed,
206
+ "volume": _signed_volume(points, local, arrays["mirrored"]) if closed else None})
207
+ return parts
208
+
209
+
210
+ def _box_gap(first: dict, second: dict) -> float:
211
+ """Distance between two parts' world boxes (0 when they overlap)."""
212
+ gaps = np.maximum(np.maximum(second["low"] - first["high"], first["low"] - second["high"]), 0.0)
213
+ return float(np.linalg.norm(gaps))
214
+
215
+
216
+ def minimum_distance(first: dict, second: dict, tolerance: float) -> tuple:
217
+ """
218
+ Smallest vertex-to-surface distance between two parts, both directions.
219
+
220
+ :returns: (distance, intersecting). Stops early once within tolerance.
221
+ """
222
+ if first["tree"].overlap(second["tree"]):
223
+ return 0.0, True
224
+ best = math.inf
225
+ for source, target in ((first, second), (second, first)):
226
+ for point in source["samples"]:
227
+ hit = target["tree"].find_nearest(point)
228
+ if hit[0] is not None and hit[3] < best:
229
+ best = hit[3]
230
+ if best <= tolerance:
231
+ return best, False
232
+ return best, False
233
+
234
+
235
+ def _inside(part: dict, point: Vector) -> bool:
236
+ """Ray-parity inside test against one part, majority of three rays (face normals are not trusted)."""
237
+ votes = 0
238
+ for direction in RAY_DIRECTIONS:
239
+ hits, origin = 0, point
240
+ for _ in range(MAX_RAY_HITS):
241
+ location = part["tree"].ray_cast(origin, direction)[0]
242
+ if location is None:
243
+ break
244
+ hits += 1
245
+ origin = location + direction * part["epsilon"]
246
+ votes += hits % 2
247
+ return votes >= 2
248
+
249
+
250
+ def penetration_depth(first: dict, second: dict) -> float:
251
+ """Approximately how deep two intersecting parts sink into each other (0 = just touching)."""
252
+ depth = 0.0
253
+ for source, target in ((first, second), (second, first)):
254
+ if not target["closed"]:
255
+ continue
256
+ for point in source["samples"]:
257
+ location, _, _, distance = target["tree"].find_nearest(point)
258
+ if location is not None and distance > depth and _inside(target, point):
259
+ depth = distance
260
+ return depth
261
+
262
+
263
+ class _Groups:
264
+ """Union-find over part indices."""
265
+
266
+ def __init__(self, count: int):
267
+ """:param count: Number of parts."""
268
+ self.parent = list(range(count))
269
+
270
+ def find(self, index: int) -> int:
271
+ """Root of a part's group."""
272
+ while self.parent[index] != index:
273
+ self.parent[index] = self.parent[self.parent[index]]
274
+ index = self.parent[index]
275
+ return index
276
+
277
+ def join(self, first: int, second: int) -> None:
278
+ """Merges two parts' groups."""
279
+ self.parent[self.find(first)] = self.find(second)
280
+
281
+
282
+ def _check_size(label: str, actual: np.ndarray, size_spec: dict, scale: float, errors: list) -> None:
283
+ """Compares a world size against a spec's dims (in spec units) and records any axis out of tolerance."""
284
+ wanted = size_spec.get("dims") or size_spec.get("size")
285
+ if not wanted:
286
+ return
287
+ tolerance = size_spec.get("tolerance")
288
+ off = []
289
+ for axis, value, target in zip("XYZ", actual * scale, wanted):
290
+ if target is None:
291
+ continue
292
+ default_allowed = max(MINIMUM_SIZE_TOLERANCE * scale, abs(target) * SIZE_TOLERANCE_FRACTION)
293
+ allowed = tolerance if tolerance is not None else default_allowed
294
+ if abs(value - target) > allowed:
295
+ off.append(f"{axis} {value:.4f} vs {target:.4f}")
296
+ if off:
297
+ errors.append(f"{label} off spec: {'; '.join(off)}")
298
+
299
+
300
+ def _contacts(parts: list, tolerance: float, expected: list) -> tuple:
301
+ """Links touching parts and lists every contact with its penetration depth."""
302
+ groups = _Groups(len(parts))
303
+ contacts = []
304
+
305
+ def is_expected(first_name, second_name):
306
+ return any((fnmatch.fnmatchcase(first_name, first) and fnmatch.fnmatchcase(second_name, second))
307
+ or (fnmatch.fnmatchcase(first_name, second) and fnmatch.fnmatchcase(second_name, first))
308
+ for first, second in expected)
309
+
310
+ for i in range(len(parts)):
311
+ for j in range(i + 1, len(parts)):
312
+ if _box_gap(parts[i], parts[j]) > tolerance:
313
+ continue
314
+ distance, intersecting = minimum_distance(parts[i], parts[j], tolerance)
315
+ if distance > tolerance:
316
+ continue
317
+ groups.join(i, j)
318
+ depth = penetration_depth(parts[i], parts[j]) if intersecting else 0.0
319
+ contacts.append({"a": parts[i]["label"], "b": parts[j]["label"],
320
+ "objects": [parts[i]["object"], parts[j]["object"]],
321
+ "depth_m": round(depth, 5), "expected": is_expected(parts[i]["object"], parts[j]["object"])})
322
+ return groups, contacts
323
+
324
+
325
+ def _floating_groups(parts: list, groups: _Groups, root_index: int) -> list:
326
+ """Every group not joined to the main body, with its closest gap to the main body."""
327
+ root = groups.find(root_index)
328
+ main_parts = [index for index in range(len(parts)) if groups.find(index) == root]
329
+ detached = {}
330
+ for index in range(len(parts)):
331
+ if groups.find(index) != root:
332
+ detached.setdefault(groups.find(index), []).append(index)
333
+ floating = []
334
+ for members in detached.values():
335
+ best, best_part, best_main = math.inf, members[0], main_parts[0]
336
+ for member in members:
337
+ nearest = sorted(main_parts, key=lambda index: _box_gap(parts[member], parts[index]))
338
+ for candidate in nearest[:GAP_SEARCH_CANDIDATES]:
339
+ distance, _ = minimum_distance(parts[member], parts[candidate], 0.0)
340
+ if distance < best:
341
+ best, best_part, best_main = distance, member, candidate
342
+ center = (parts[best_part]["low"] + parts[best_part]["high"]) / 2.0
343
+ floating.append({"parts": [parts[member]["label"] for member in members], "gap_m": round(best, 5),
344
+ "closest": parts[best_part]["label"], "to": parts[best_main]["label"],
345
+ "center": [round(float(value), 4) for value in center]})
346
+ return floating
347
+
348
+
349
+ def run(options) -> dict:
350
+ """
351
+ Builds the part graph and checks it against the spec.
352
+
353
+ :param options: Parsed options.
354
+ :returns: The assembly report.
355
+ """
356
+ spec = tool_common.load_json(options.spec) if options.spec else {}
357
+ units = spec.get("units", "m")
358
+ if units not in UNITS:
359
+ raise ValueError(f"unknown units '{units}'; use one of {sorted(UNITS)}")
360
+ scale = UNITS[units]
361
+ tool_common.load_model(options.model)
362
+ objects = tool_common.resolve_objects(options.objects, types=tuple(tool_common.GEOMETRY_TYPES))
363
+ errors, warnings, notes, parts, health = [], [], [], [], {}
364
+ for obj in objects:
365
+ arrays = _evaluated_arrays(obj)
366
+ object_parts = make_parts(obj, arrays, notes)
367
+ if not object_parts:
368
+ errors.append(f"{obj.name}: no faces after modifiers (an empty boolean result?)")
369
+ continue
370
+ parts.extend(object_parts)
371
+ low = np.min([part["low"] for part in object_parts], axis=0)
372
+ high = np.max([part["high"] for part in object_parts], axis=0)
373
+ health[obj.name] = {"parts": len(object_parts), "world_size": [round(float(value), 5) for value in high - low]}
374
+ inverted = [part["label"] for part in object_parts if part["volume"] is not None and part["volume"] < 0]
375
+ if inverted:
376
+ errors.append(f"{obj.name}: closed part(s) with inverted normals {inverted}")
377
+ if obj.modifiers and max(obj.scale) - min(obj.scale) > SCALE_UNIFORMITY_TOLERANCE and min(obj.scale) > 0:
378
+ warnings.append(f"{obj.name}: non-uniform scale {[round(v, 4) for v in obj.scale]} with modifiers; "
379
+ "bevels and solidify come out uneven - apply the scale")
380
+ if not parts:
381
+ return {"pass": False, "errors": errors or ["no checkable geometry"], "warnings": warnings, "notes": notes}
382
+ low = np.min([part["low"] for part in parts], axis=0)
383
+ high = np.max([part["high"] for part in parts], axis=0)
384
+ diagonal = float(np.linalg.norm(high - low))
385
+ tolerance = options.contact_tolerance or (spec["contact_tolerance"] / scale if "contact_tolerance" in spec
386
+ else max(MINIMUM_TOLERANCE, diagonal * TOLERANCE_FRACTION))
387
+ groups, contacts = _contacts(parts, tolerance, [tuple(pair) for pair in spec.get("expect_embedded", [])])
388
+ root_name = options.root or spec.get("root")
389
+ if root_name and root_name not in {part["object"] for part in parts}:
390
+ raise tool_common.OptionsError(f"root object '{root_name}' is not part of the checked objects")
391
+ root_candidates = [index for index, part in enumerate(parts) if not root_name or part["object"] == root_name]
392
+ root_index = max(root_candidates, key=lambda index: float(np.linalg.norm(parts[index]["high"] - parts[index]["low"])))
393
+ floating = _floating_groups(parts, groups, root_index)
394
+ for group in floating:
395
+ errors.append(f"FLOATING: {group['parts']} is not connected to the main body; closest gap "
396
+ f"{group['gap_m']} m between {group['closest']} and {group['to']}")
397
+ if "overall" in spec:
398
+ _check_size("overall size", high - low, spec["overall"], scale, errors)
399
+ checked = set(health)
400
+ for name, part_spec in (spec.get("parts") or {}).items():
401
+ if name not in checked:
402
+ errors.append(f"missing part from spec: '{name}'")
403
+ continue
404
+ _check_size(f"{name} size", np.array(health[name]["world_size"]), part_spec, scale, errors)
405
+ for other in part_spec.get("attached_to", []):
406
+ if other not in checked:
407
+ errors.append(f"{name}: attached_to names '{other}', which is not part of the asset")
408
+ elif not any(set(contact["objects"]) == {name, other} for contact in contacts):
409
+ errors.append(f"NOT ATTACHED: {name} should touch {other}")
410
+ report = {"pass": not errors, "errors": errors, "warnings": warnings, "notes": notes,
411
+ "contact_tolerance_m": tolerance, "overall_size_m": [round(float(value), 5) for value in high - low],
412
+ "parts": len(parts), "main_body": parts[root_index]["label"], "floating": floating,
413
+ "contacts": contacts, "objects": health}
414
+ if options.out:
415
+ report["report_json"] = tool_common.write_json(options.out, report)
416
+ return report
417
+
418
+
419
+ if __name__ == "__main__":
420
+ tool_common.run_tool(TOOL_NAME, build_parser(), run)