@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,219 @@
1
+ """
2
+ world_gate -- silhouette IoU at true world scale. The model is rendered through an orthographic camera
3
+ whose window is exactly the reference image's world window (from its pixels-per-metre and origin pixel),
4
+ so render and reference compare pixel for pixel: a model that is 3 cm too short or sits 2 cm off its axis
5
+ loses IoU instead of being re-centred away. Also reports the size ratio and centre offset of the two
6
+ silhouettes in metres, band widths top to bottom, and a diff image (grey both, red reference only,
7
+ blue model only).
8
+
9
+ IoU is a registration gate, not a shape gate: a part can be 10 % too fat and still score 0.9. Grade
10
+ shape with measure_stations.
11
+
12
+ blender --background --factory-startup --python-exit-code 1 --python world_gate.py -- \
13
+ --model model.blend --image refs/right.png --view right --pixels-per-metre 480 \
14
+ --origin-pixel 512 700 [--crop l t r b] [--min-iou 0.9] [--out evidence/]
15
+ ... --python world_gate.py -- --spec stations_spec.json (every view of a stations spec)
16
+
17
+ Portions adapted from majidmanzarpour/blender-game-skills (mirrored as Godsified/blender-game-skills-for-claude,
18
+ skills/blender-image-to-3d/scripts/world_gate.py) -- Copyright (c) 2026 Majid Manzarpour, MIT License:
19
+
20
+ Permission is hereby granted, free of charge, to any person obtaining a copy
21
+ of this software and associated documentation files (the "Software"), to deal
22
+ in the Software without restriction, including without limitation the rights
23
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
24
+ copies of the Software, and to permit persons to whom the Software is
25
+ furnished to do so, subject to the following conditions:
26
+
27
+ The above copyright notice and this permission notice shall be included in all
28
+ copies or substantial portions of the Software.
29
+
30
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
31
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
32
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
33
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
34
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
35
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
36
+ SOFTWARE.
37
+
38
+ Changes from the original: any named straight view (top and bottom included, not only horizontal
39
+ azimuths); the reference mask uses border-connected background separation instead of a corner-colour
40
+ threshold that also removed light details inside the subject; an empty reference and a one-row subject
41
+ no longer crash the band measurement; a crop box; size ratio and centre offset in metres; the gate's
42
+ pass / fail is the exit code instead of always exiting 0.
43
+ """
44
+ import os
45
+ import sys
46
+
47
+ sys.dont_write_bytecode = True
48
+ SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
49
+ if SCRIPT_DIRECTORY not in sys.path:
50
+ sys.path.insert(0, SCRIPT_DIRECTORY)
51
+
52
+ import numpy as np # noqa: E402
53
+
54
+ import image_measure # noqa: E402
55
+ import ortho_views # noqa: E402
56
+ import tool_common # noqa: E402
57
+
58
+ TOOL_NAME = "world-gate"
59
+
60
+ DEFAULT_MINIMUM_IOU = 0.90
61
+ DEFAULT_BANDS = 10
62
+
63
+ # Diff image colours: neither, both, reference only, model only.
64
+ DIFF_BACKGROUND = (0.16, 0.16, 0.16)
65
+ DIFF_BOTH = (0.59, 0.59, 0.59)
66
+ DIFF_REFERENCE_ONLY = (0.90, 0.24, 0.24)
67
+ DIFF_MODEL_ONLY = (0.24, 0.43, 0.94)
68
+
69
+
70
+ def build_parser() -> tool_common.ToolArgumentParser:
71
+ """The tool's command-line options."""
72
+ parser = tool_common.ToolArgumentParser(prog=TOOL_NAME, description=__doc__.strip().splitlines()[0])
73
+ parser.add_argument("--spec", help="stations spec JSON: gate every view in it")
74
+ parser.add_argument("--model", help="model (.blend .glb .gltf .fbx .obj)")
75
+ parser.add_argument("--objects", nargs="*", help="objects to render (default every visible mesh)")
76
+ parser.add_argument("--image", help="reference image of one straight view")
77
+ parser.add_argument("--view", choices=sorted(ortho_views.VIEW_AXES), help="the view the image shows")
78
+ parser.add_argument("--name", help="evidence name (default: the view)")
79
+ parser.add_argument("--pixels-per-metre", type=float)
80
+ parser.add_argument("--origin-pixel", type=float, nargs=2, metavar=("COLUMN", "ROW"),
81
+ help="pixel where the world origin projects (axis column, ground row)")
82
+ parser.add_argument("--crop", type=float, nargs=4, metavar=("LEFT", "TOP", "RIGHT", "BOTTOM"))
83
+ parser.add_argument("--background-tolerance", type=float, default=image_measure.DEFAULT_BACKGROUND_TOLERANCE)
84
+ parser.add_argument("--min-iou", type=float, default=DEFAULT_MINIMUM_IOU)
85
+ parser.add_argument("--bands", type=int, default=DEFAULT_BANDS)
86
+ parser.add_argument("--supersample", type=int, default=ortho_views.DEFAULT_SUPERSAMPLE)
87
+ parser.add_argument("--out", help="evidence folder (default: <image or spec folder>/world_gate)")
88
+ return parser
89
+
90
+
91
+ def band_width_differences(reference: np.ndarray, model: np.ndarray, bands: int) -> list:
92
+ """
93
+ Width difference (model minus reference, as a fraction of the reference subject's height) at the
94
+ middle row of each of `bands` horizontal bands, top to bottom.
95
+
96
+ :param reference: Reference mask.
97
+ :param model: Model mask.
98
+ :param bands: Number of bands.
99
+ :returns: List of fractions; None for a band row the reference does not cover.
100
+ """
101
+ rows = np.flatnonzero(reference.any(axis=1))
102
+ top, bottom = int(rows[0]), int(rows[-1]) + 1
103
+ subject_height = max(1, bottom - top)
104
+ differences = []
105
+ for band in range(bands):
106
+ row = top + (band + 0.5) * subject_height / bands
107
+ reference_extent = image_measure.extent_along_row(reference, row)
108
+ model_extent = image_measure.extent_along_row(model, row)
109
+ if reference_extent is None:
110
+ differences.append(None)
111
+ continue
112
+ model_width = 0.0 if model_extent is None else model_extent[1] - model_extent[0]
113
+ differences.append(round((model_width - (reference_extent[1] - reference_extent[0])) / subject_height, 4))
114
+ return differences
115
+
116
+
117
+ def _registration(reference: np.ndarray, model: np.ndarray, pixels_per_metre: float) -> dict:
118
+ """Size ratio (model / reference) and centre offset in metres of the two silhouettes' bounding boxes."""
119
+ reference_bounds = image_measure.subject_bounds(reference)
120
+ model_bounds = image_measure.subject_bounds(model)
121
+ if model_bounds is None:
122
+ return {"model_visible": False}
123
+ reference_size = np.array([reference_bounds[2] - reference_bounds[0], reference_bounds[3] - reference_bounds[1]])
124
+ model_size = np.array([model_bounds[2] - model_bounds[0], model_bounds[3] - model_bounds[1]])
125
+ reference_center = np.array([reference_bounds[0] + reference_bounds[2], reference_bounds[1] + reference_bounds[3]]) / 2
126
+ model_center = np.array([model_bounds[0] + model_bounds[2], model_bounds[1] + model_bounds[3]]) / 2
127
+ offset = (model_center - reference_center) / pixels_per_metre
128
+ return {"model_visible": True,
129
+ "width_ratio": round(float(model_size[0] / reference_size[0]), 4),
130
+ "height_ratio": round(float(model_size[1] / reference_size[1]), 4),
131
+ "center_offset_right_m": round(float(offset[0]), 4),
132
+ "center_offset_up_m": round(float(-offset[1]), 4)}
133
+
134
+
135
+ def gate_view(view_spec: dict, objects: list, out_directory: str, options) -> dict:
136
+ """
137
+ Renders and gates one view.
138
+
139
+ :param view_spec: {"name", "view", "image", "pixels_per_metre", "origin_pixel", optional "crop",
140
+ "background_tolerance"} with an absolute image path.
141
+ :param objects: Model objects.
142
+ :param out_directory: Evidence folder.
143
+ :param options: Parsed options (min_iou, bands, supersample).
144
+ :returns: The view's result.
145
+ """
146
+ reference_rgba = tool_common.load_image(view_spec["image"])
147
+ height, width = reference_rgba.shape[:2]
148
+ frame = ortho_views.frame_from_spec(view_spec, width, height)
149
+ crop = view_spec.get("crop")
150
+ reference = image_measure.apply_crop(
151
+ image_measure.subject_mask(reference_rgba, float(view_spec.get("background_tolerance", image_measure.DEFAULT_BACKGROUND_TOLERANCE))), crop)
152
+ if not reference.any():
153
+ raise ValueError(f"view '{view_spec['name']}': no subject found in {view_spec['image']}")
154
+ name = view_spec["name"]
155
+ model = image_measure.apply_crop(ortho_views.silhouette_mask(
156
+ objects, view_spec["view"], frame, os.path.join(out_directory, f"silhouette_{name}.png"), options.supersample), crop)
157
+ intersection, union = float((reference & model).sum()), float((reference | model).sum())
158
+ reference_area = float(reference.sum())
159
+ diff = np.empty((height, width, 3), dtype=np.float32)
160
+ diff[:] = DIFF_BACKGROUND
161
+ diff[reference & model] = DIFF_BOTH
162
+ diff[reference & ~model] = DIFF_REFERENCE_ONLY
163
+ diff[~reference & model] = DIFF_MODEL_ONLY
164
+ iou = round(intersection / max(1.0, union), 4)
165
+ return {"name": name, "view": view_spec["view"], "image": view_spec["image"], "iou": iou,
166
+ "pass": iou >= options.min_iou,
167
+ "reference_only_percent": round(100.0 * float((reference & ~model).sum()) / reference_area, 2),
168
+ "model_only_percent": round(100.0 * float((~reference & model).sum()) / reference_area, 2),
169
+ "band_width_differences": band_width_differences(reference, model, options.bands),
170
+ "registration": _registration(reference, model, frame.pixels_per_metre),
171
+ "diff_image": tool_common.save_image(os.path.join(out_directory, f"diff_{name}.png"), diff)}
172
+
173
+
174
+ def _views_from_options(options) -> tuple:
175
+ """The views to gate and the folder relative paths start from: from a spec, or from single-view flags."""
176
+ if options.spec:
177
+ spec_path = os.path.abspath(options.spec)
178
+ spec_directory = os.path.dirname(spec_path)
179
+ spec = tool_common.load_json(spec_path)
180
+ views = []
181
+ for view in spec.get("views") or []:
182
+ if view.get("frame"):
183
+ continue
184
+ views.append({**view, "image": os.path.normpath(os.path.join(spec_directory, view["image"]))})
185
+ model = spec.get("model")
186
+ return views, spec_directory, None if model is None else os.path.join(spec_directory, model), spec.get("objects")
187
+ missing = [flag for flag, value in (("--image", options.image), ("--view", options.view),
188
+ ("--pixels-per-metre", options.pixels_per_metre),
189
+ ("--origin-pixel", options.origin_pixel)) if value is None]
190
+ if missing:
191
+ raise tool_common.OptionsError(f"give --spec, or all of {', '.join(missing)}")
192
+ image = os.path.abspath(options.image)
193
+ view = {"name": options.name or options.view, "view": options.view, "image": image,
194
+ "pixels_per_metre": options.pixels_per_metre, "origin_pixel": options.origin_pixel,
195
+ "crop": options.crop, "background_tolerance": options.background_tolerance}
196
+ return [view], os.path.dirname(image), None, None
197
+
198
+
199
+ def run(options) -> dict:
200
+ """
201
+ Gates every requested view.
202
+
203
+ :param options: Parsed options.
204
+ :returns: {"pass", "views": [...]}.
205
+ """
206
+ views, base_directory, spec_model, spec_objects = _views_from_options(options)
207
+ if not views:
208
+ raise ValueError("no views to gate")
209
+ tool_common.load_model(options.model or spec_model)
210
+ objects = tool_common.resolve_objects(options.objects or spec_objects)
211
+ out_directory = os.path.abspath(options.out or os.path.join(base_directory, "world_gate"))
212
+ results = [gate_view(view, objects, out_directory, options) for view in views]
213
+ report = {"pass": all(result["pass"] for result in results), "min_iou": options.min_iou, "views": results}
214
+ report["report_json"] = tool_common.write_json(os.path.join(out_directory, "world_gate.json"), report)
215
+ return report
216
+
217
+
218
+ if __name__ == "__main__":
219
+ tool_common.run_tool(TOOL_NAME, build_parser(), run)
@@ -0,0 +1,329 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * bt-blender launcher: finds Blender on macOS, Windows or Linux and runs one bt-blender tool headless.
4
+ *
5
+ * node bt-blender.mjs <tool> [tool options] run a tool; prints its one JSON result line
6
+ * node bt-blender.mjs <tool> --help the tool's options
7
+ * node bt-blender.mjs run <script.py> [args] run your own build script with the construction kit importable
8
+ * node bt-blender.mjs --list list the tools as JSON
9
+ * node bt-blender.mjs --which-blender print the Blender it would use
10
+ *
11
+ * Launcher-only options (anywhere on the line):
12
+ * --blender <path> use this Blender executable (else $BLENDER, then PATH, then the usual install folders)
13
+ * --verbose show Blender's full log and Python tracebacks
14
+ *
15
+ * Exit code: the tool's: 0 passed, 1 gate failed or error, 2 bad options or unknown tool.
16
+ */
17
+ import { spawn, spawnSync } from 'node:child_process';
18
+ import { existsSync, readdirSync } from 'node:fs';
19
+ import { homedir } from 'node:os';
20
+ import path from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+
23
+ /** Folder holding this launcher; the Blender tools live in its `blender/` subfolder. */
24
+ const SCRIPT_DIRECTORY = path.dirname(fileURLToPath(import.meta.url));
25
+
26
+ /** Folder of the Blender-side tools and the construction kit. */
27
+ const BLENDER_DIRECTORY = path.join(SCRIPT_DIRECTORY, 'blender');
28
+
29
+ /** Marks the tool's JSON result line in Blender's output. */
30
+ const RESULT_PREFIX = 'BT_BLENDER_RESULT ';
31
+
32
+ /** Exit codes shared with the tools. */
33
+ const EXIT_PASSED = 0;
34
+ const EXIT_FAILED = 1;
35
+ const EXIT_BAD_OPTIONS = 2;
36
+
37
+ /** Blender stdout lines kept, for the error report, when a tool prints no result. */
38
+ const LOG_TAIL_LINES = 20;
39
+
40
+ /** Lines from Blender worth showing on stderr when not --verbose. */
41
+ const IMPORTANT_LINE = /Traceback|Error|error:|^\s+File "/;
42
+
43
+ /** Blender's own start-up and shut-down lines, hidden from help output and `run`. */
44
+ const BLENDER_BOILERPLATE = /^Blender \d|^Read prefs|^Read blend|^Blender quit|^$/;
45
+
46
+ /** The tools: launcher name, script, and what it is for. */
47
+ const TOOLS = {
48
+ 'measure-stations': { script: 'measure_stations.py', description: 'grade model silhouettes against reference views station by station (MATCH / CLOSE / WRONG), corner radii, shading continuity' },
49
+ 'world-gate': { script: 'world_gate.py', description: 'world-scale silhouette gate: IoU and band differences against registered reference views' },
50
+ 'view-consistency': { script: 'view_consistency.py', description: 'check the reference views agree with each other (and with known dimensions) before fitting' },
51
+ 'review-render': { script: 'review_render.py', description: 'contact sheet (clay, parts, wire) and a render at the in-game pixel height' },
52
+ 'qa-check': { script: 'qa_check.py', description: 'asset QA gate: z-fighting, floating parts, normals, topology, UVs, weights, materials' },
53
+ 'assembly-check': { script: 'assembly_check.py', description: 'part graph: floating gaps, contacts and penetration depth, spec sizes and attachments' },
54
+ 'export': { script: 'export_asset.py', description: 'export glTF / GLB or Unity FBX, re-import size check, glTF summary and Khronos validation' },
55
+ 'validate-gltf': { node: 'validate_gltf.mjs', description: 'Khronos glTF-Validator on a .glb / .gltf (Node only, no Blender)' },
56
+ 'run': { description: 'run your own script in Blender with the construction kit importable: run <script.py> [args]' },
57
+ };
58
+
59
+ /**
60
+ * Lists the places Blender is usually installed on this platform, newest version first.
61
+ * @returns {string[]} Candidate executable paths (may not exist).
62
+ */
63
+ function installedBlenderCandidates() {
64
+ if (process.platform === 'darwin') {
65
+ return ['/Applications/Blender.app/Contents/MacOS/Blender',
66
+ path.join(homedir(), 'Applications/Blender.app/Contents/MacOS/Blender')];
67
+ }
68
+ if (process.platform === 'win32') {
69
+ const roots = [process.env.ProgramFiles, process.env['ProgramFiles(x86)']].filter(Boolean)
70
+ .map((root) => path.join(root, 'Blender Foundation'));
71
+ const candidates = [];
72
+ for (const root of roots) {
73
+ if (!existsSync(root)) continue;
74
+ const versions = readdirSync(root).filter((name) => name.toLowerCase().startsWith('blender'))
75
+ .sort((first, second) => second.localeCompare(first, undefined, { numeric: true }));
76
+ candidates.push(...versions.map((name) => path.join(root, name, 'blender.exe')));
77
+ }
78
+ return candidates;
79
+ }
80
+ const optFolders = existsSync('/opt') ? readdirSync('/opt').filter((name) => name.startsWith('blender'))
81
+ .map((name) => path.join('/opt', name, 'blender')) : [];
82
+ return ['/usr/bin/blender', '/usr/local/bin/blender', '/snap/bin/blender', ...optFolders];
83
+ }
84
+
85
+ /**
86
+ * Checks whether a command resolves on PATH.
87
+ * @param {string} command - Command name.
88
+ * @returns {boolean} True when it runs.
89
+ */
90
+ function isOnPath(command) {
91
+ const probe = spawnSync(command, ['--version'], { stdio: 'ignore' });
92
+ return probe.status === 0;
93
+ }
94
+
95
+ /**
96
+ * Picks the Blender executable to use.
97
+ * @param {string | undefined} explicitPath - Path from --blender.
98
+ * @returns {string} The executable.
99
+ * @throws {Error} When no Blender can be found.
100
+ */
101
+ function findBlender(explicitPath) {
102
+ const configured = explicitPath || process.env.BLENDER;
103
+ if (configured) {
104
+ if (!existsSync(configured)) throw new Error(`Blender not found at ${configured}`);
105
+ return configured;
106
+ }
107
+ if (isOnPath('blender')) return 'blender';
108
+ const installed = installedBlenderCandidates().find((candidate) => existsSync(candidate));
109
+ if (installed) return installed;
110
+ throw new Error('Blender not found. Install Blender (the tools are tested on 5.3), or pass --blender <path> / set BLENDER.');
111
+ }
112
+
113
+ /**
114
+ * Splits launcher-only options from the tool name and the tool's own options.
115
+ * @param {string[]} argv - Command-line arguments after the script name.
116
+ * @returns {{ blenderPath: string | undefined, verbose: boolean, whichBlender: boolean, list: boolean, tool: string | undefined, toolArguments: string[] }}
117
+ */
118
+ function parseLauncherArguments(argv) {
119
+ const remaining = [];
120
+ let blenderPath;
121
+ let verbose = false;
122
+ let whichBlender = false;
123
+ let list = false;
124
+ for (let index = 0; index < argv.length; index += 1) {
125
+ const argument = argv[index];
126
+ if (argument === '--blender') {
127
+ blenderPath = argv[index + 1];
128
+ index += 1;
129
+ } else if (argument === '--verbose') {
130
+ verbose = true;
131
+ } else if (argument === '--which-blender') {
132
+ whichBlender = true;
133
+ } else if (argument === '--list') {
134
+ list = true;
135
+ } else {
136
+ remaining.push(argument);
137
+ }
138
+ }
139
+ return { blenderPath, verbose, whichBlender, list, tool: remaining[0], toolArguments: remaining.slice(1) };
140
+ }
141
+
142
+ /**
143
+ * Prints one JSON result line.
144
+ * @param {object} result - The result.
145
+ */
146
+ function emit(result) {
147
+ process.stdout.write(`${JSON.stringify(result)}\n`);
148
+ }
149
+
150
+ /**
151
+ * Prints the launcher's usage.
152
+ */
153
+ function printUsage() {
154
+ const width = Math.max(...Object.keys(TOOLS).map((name) => name.length));
155
+ const lines = Object.entries(TOOLS).map(([name, tool]) => ` ${name.padEnd(width)} ${tool.description}`);
156
+ process.stdout.write(['usage: node bt-blender.mjs <tool> [options] | run <script.py> [args] | --list | --which-blender',
157
+ ' [--blender <path>] [--verbose]', '', 'tools:', ...lines, '', '<tool> --help lists its options.', ''].join('\n'));
158
+ }
159
+
160
+ /**
161
+ * Collects a child stream into lines, calling back for each complete line.
162
+ * @param {import('node:stream').Readable} stream - Blender's stdout or stderr.
163
+ * @param {(line: string) => void} onLine - Called for every line.
164
+ */
165
+ function readLines(stream, onLine) {
166
+ let pending = '';
167
+ stream.setEncoding('utf8');
168
+ stream.on('data', (chunk) => {
169
+ pending += chunk;
170
+ const lines = pending.split(/\r?\n/);
171
+ pending = lines.pop();
172
+ lines.forEach(onLine);
173
+ });
174
+ stream.on('end', () => {
175
+ if (pending) onLine(pending);
176
+ });
177
+ }
178
+
179
+ /**
180
+ * Runs a child process, relaying its output through the given line handlers.
181
+ * @param {string} command - Executable.
182
+ * @param {string[]} commandArguments - Its arguments.
183
+ * @param {(line: string) => void} onStdout - stdout line handler.
184
+ * @param {(line: string) => void} onStderr - stderr line handler.
185
+ * @param {NodeJS.ProcessEnv} environment - Environment.
186
+ * @returns {Promise<{ code: number, startError: Error | undefined }>} Exit code, or the error that stopped it starting.
187
+ */
188
+ function runChild(command, commandArguments, onStdout, onStderr, environment) {
189
+ const child = spawn(command, commandArguments, { stdio: ['ignore', 'pipe', 'pipe'], env: environment });
190
+ readLines(child.stdout, onStdout);
191
+ readLines(child.stderr, onStderr);
192
+ return new Promise((resolve) => {
193
+ child.on('close', (code) => resolve({ code: code ?? EXIT_FAILED, startError: undefined }));
194
+ child.on('error', (error) => resolve({ code: EXIT_FAILED, startError: error }));
195
+ });
196
+ }
197
+
198
+ /**
199
+ * Blender's arguments for a Python script, with the kit folder importable and no bytecode written.
200
+ * @param {string} script - Python script path.
201
+ * @param {string[]} scriptArguments - Arguments after `--`.
202
+ * @returns {string[]} Blender arguments.
203
+ */
204
+ function blenderArguments(script, scriptArguments) {
205
+ const setup = `import sys; sys.dont_write_bytecode = True; sys.path.insert(0, ${JSON.stringify(BLENDER_DIRECTORY)})`;
206
+ return ['--background', '--factory-startup', '--python-exit-code', '1',
207
+ '--python-expr', setup, '--python', script, '--', ...scriptArguments];
208
+ }
209
+
210
+ /**
211
+ * Runs a Blender tool and prints only its JSON result.
212
+ * @param {string} name - Tool name.
213
+ * @param {string} blender - Blender executable.
214
+ * @param {string[]} toolArguments - The tool's options.
215
+ * @param {boolean} verbose - Show Blender's whole log.
216
+ * @returns {Promise<number>} Exit code.
217
+ */
218
+ async function runTool(name, blender, toolArguments, verbose) {
219
+ const wantsHelp = toolArguments.includes('--help') || toolArguments.includes('-h');
220
+ const environment = { ...process.env, PYTHONDONTWRITEBYTECODE: '1', ...(verbose ? { BT_BLENDER_TRACEBACK: '1' } : {}) };
221
+ let result;
222
+ const logTail = [];
223
+ const onStdout = (line) => {
224
+ if (line.startsWith(RESULT_PREFIX)) {
225
+ result = line.slice(RESULT_PREFIX.length);
226
+ } else if (verbose || (wantsHelp && !BLENDER_BOILERPLATE.test(line))) {
227
+ process.stdout.write(`${line}\n`);
228
+ } else {
229
+ logTail.push(line);
230
+ if (logTail.length > LOG_TAIL_LINES) logTail.shift();
231
+ }
232
+ };
233
+ const onStderr = (line) => {
234
+ if (verbose || IMPORTANT_LINE.test(line)) process.stderr.write(`${line}\n`);
235
+ };
236
+ const script = path.join(BLENDER_DIRECTORY, TOOLS[name].script);
237
+ const { code, startError } = await runChild(blender, blenderArguments(script, toolArguments), onStdout, onStderr, environment);
238
+ if (startError) {
239
+ emit({ ok: false, tool: name, error: `could not start Blender: ${startError.message}` });
240
+ return EXIT_FAILED;
241
+ }
242
+ if (result !== undefined) {
243
+ process.stdout.write(`${result}\n`);
244
+ return code;
245
+ }
246
+ if (wantsHelp) return code;
247
+ emit({ ok: false, tool: name, error: `Blender exited ${code} without a result`, log_tail: logTail });
248
+ return code === EXIT_PASSED ? EXIT_FAILED : code;
249
+ }
250
+
251
+ /**
252
+ * Runs the user's own script in Blender, relaying its output.
253
+ * @param {string} blender - Blender executable.
254
+ * @param {string[]} runArguments - Script path, then its arguments.
255
+ * @param {boolean} verbose - Also show Blender's own start-up lines.
256
+ * @returns {Promise<number>} Exit code.
257
+ */
258
+ async function runScript(blender, runArguments, verbose) {
259
+ const [script, ...scriptArguments] = runArguments;
260
+ if (!script || !existsSync(script)) {
261
+ emit({ ok: false, tool: 'run', error: script ? `script not found: ${path.resolve(script)}` : 'usage: run <script.py> [args]' });
262
+ return EXIT_BAD_OPTIONS;
263
+ }
264
+ const environment = { ...process.env, PYTHONDONTWRITEBYTECODE: '1' };
265
+ const relay = (destination) => (line) => {
266
+ if (verbose || !BLENDER_BOILERPLATE.test(line)) destination.write(`${line}\n`);
267
+ };
268
+ const { code, startError } = await runChild(blender, blenderArguments(path.resolve(script), scriptArguments),
269
+ relay(process.stdout), relay(process.stderr), environment);
270
+ if (startError) {
271
+ emit({ ok: false, tool: 'run', error: `could not start Blender: ${startError.message}` });
272
+ return EXIT_FAILED;
273
+ }
274
+ return code;
275
+ }
276
+
277
+ /**
278
+ * Runs a Node-only tool in this process's Node.
279
+ * @param {string} name - Tool name.
280
+ * @param {string[]} toolArguments - The tool's options.
281
+ * @returns {Promise<number>} Exit code.
282
+ */
283
+ async function runNodeTool(name, toolArguments) {
284
+ const script = path.join(SCRIPT_DIRECTORY, TOOLS[name].node);
285
+ const { code, startError } = await runChild(process.execPath, [script, ...toolArguments],
286
+ (line) => process.stdout.write(`${line}\n`), (line) => process.stderr.write(`${line}\n`), process.env);
287
+ if (startError) {
288
+ emit({ ok: false, tool: name, error: `could not start Node: ${startError.message}` });
289
+ return EXIT_FAILED;
290
+ }
291
+ return code;
292
+ }
293
+
294
+ /**
295
+ * Dispatches the command line.
296
+ * @returns {Promise<number>} Exit code.
297
+ */
298
+ async function main() {
299
+ const { blenderPath, verbose, whichBlender, list, tool, toolArguments } = parseLauncherArguments(process.argv.slice(2));
300
+ if (list) {
301
+ emit({ ok: true, tools: Object.entries(TOOLS).map(([name, entry]) => ({ name, description: entry.description })) });
302
+ return EXIT_PASSED;
303
+ }
304
+ if (!whichBlender && (!tool || tool === '--help' || tool === '-h')) {
305
+ printUsage();
306
+ return tool ? EXIT_PASSED : EXIT_BAD_OPTIONS;
307
+ }
308
+ if (tool && !whichBlender && !Object.hasOwn(TOOLS, tool)) {
309
+ emit({ ok: false, error: `unknown tool '${tool}'`, tools: Object.keys(TOOLS) });
310
+ return EXIT_BAD_OPTIONS;
311
+ }
312
+ if (tool && TOOLS[tool].node) return runNodeTool(tool, toolArguments);
313
+ let blender;
314
+ try {
315
+ blender = findBlender(blenderPath);
316
+ } catch (error) {
317
+ if (whichBlender) process.stderr.write(`bt-blender: ${error.message}\n`);
318
+ else emit({ ok: false, tool, error: error.message });
319
+ return EXIT_FAILED;
320
+ }
321
+ if (whichBlender) {
322
+ process.stdout.write(`${blender}\n`);
323
+ return EXIT_PASSED;
324
+ }
325
+ if (tool === 'run') return runScript(blender, toolArguments, verbose);
326
+ return runTool(tool, blender, toolArguments, verbose);
327
+ }
328
+
329
+ process.exitCode = await main();