Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

fix: make a bare clone usable by any of five agent harnesses (#65)

Matthew Kissinger0cc956f8f279
diff --git a/.agents/skills/kiln-setup-workspace/SKILL.md b/.agents/skills/kiln-setup-workspace/SKILL.md
new file mode 100644
index 00000000..53d90ff8
--- /dev/null
+++ b/.agents/skills/kiln-setup-workspace/SKILL.md
@@ -0,0 +1,53 @@
+---
+name: kiln-setup-workspace
+description: Create and verify a Kiln asset workspace for a chosen coding-agent harness. Use before authoring when the current directory is the engine repository, an empty folder, or any project without a working kiln_workspace server.
+license: MIT
+---
+
+# Set up a workspace for asset authoring
+
+This repository is the engine. Asset authoring happens in a separate workspace, and the two are different tasks with different tools. Establish which one is being asked before running anything.
+
+Authoring an asset needs a workspace. Changing the engine's own behaviour does not; read `AGENTS.md` at the repository root instead and stay in the checkout.
+
+Do not author assets inside the engine checkout. The authoring skills assume a workspace, and giving a model the engine implementation and the example collection alongside its task changes what it produces.
+
+## Create the workspace
+
+Choose an absolute path to an empty directory outside the checkout.
+
+```bash
+node scripts/create-workspace.mjs /absolute/empty-workspace --harness claude
+```
+
+From an installed package, the equivalent is `kiln-init /absolute/empty-workspace --harness claude`. Author, refine and QA skills are installed by default; `--skills compose,batch` adds the optional scene-composition and trial-dispatch workflows. Ask the user which harness they use rather than assuming; the choice writes different configuration and cannot be changed afterwards without a fresh workspace.
+
+| `--harness` | Launch from the workspace |
+| --- | --- |
+| `claude` | `claude` |
+| `codex` | `codex` |
+| `opencode` | `opencode` |
+| `agy` | `node agy.mjs` |
+| `hermes` | `node hermes.mjs --ignore-rules` |
+
+Antigravity and Hermes get a generated launcher because each needs arguments or a separate profile that the bare command does not supply. Hermes authenticates in its own profile; setup copies no credentials.
+
+## Verify the loadout before authoring
+
+Accept the project and MCP trust prompts, then confirm the server is actually live rather than assuming it from configuration. Call `kiln_list_primitives` on `kiln_workspace` with `capabilities: true`; it returns the runtime, source, export and camera contract and proves the tools resolved. A server named `kiln` from a global installation is a different thing. Do not substitute it silently; report the setup problem instead.
+
+Confirm the installed skills are readable at `skills/` in the workspace, and read the relevant one from there rather than a global copy. Whether the harness also registers them natively depends on the harness.
+
+## Relocation and repair
+
+Moving the workspace or the engine installation breaks the generated absolute paths, and so does replacing the Node that setup validated.
+
+```bash
+node /current/kiln/scripts/create-workspace.mjs /absolute/empty-workspace --repair
+```
+
+Repair rewrites generated runtime paths only. It preserves copied skills, saved revisions and assets, refuses configuration that was edited by hand, and does not upgrade the skills. To evaluate a different engine version, create a fresh workspace from that version so instructions and tools match.
+
+## What isolation means
+
+A separate workspace limits task context. It is not an operating-system sandbox, and it is not a git repository. User-level instructions, memory, authentication and filesystem permissions still apply. For comparing harnesses or models, read `skills/kiln-batch-dispatch/references/clean-room-evaluation.md` in the engine checkout, which covers recording inherited context and reporting trials.
diff --git a/.claude/skills/kiln-setup-workspace/SKILL.md b/.claude/skills/kiln-setup-workspace/SKILL.md
new file mode 100644
index 00000000..53d90ff8
--- /dev/null
+++ b/.claude/skills/kiln-setup-workspace/SKILL.md
@@ -0,0 +1,53 @@
+---
+name: kiln-setup-workspace
+description: Create and verify a Kiln asset workspace for a chosen coding-agent harness. Use before authoring when the current directory is the engine repository, an empty folder, or any project without a working kiln_workspace server.
+license: MIT
+---
+
+# Set up a workspace for asset authoring
+
+This repository is the engine. Asset authoring happens in a separate workspace, and the two are different tasks with different tools. Establish which one is being asked before running anything.
+
+Authoring an asset needs a workspace. Changing the engine's own behaviour does not; read `AGENTS.md` at the repository root instead and stay in the checkout.
+
+Do not author assets inside the engine checkout. The authoring skills assume a workspace, and giving a model the engine implementation and the example collection alongside its task changes what it produces.
+
+## Create the workspace
+
+Choose an absolute path to an empty directory outside the checkout.
+
+```bash
+node scripts/create-workspace.mjs /absolute/empty-workspace --harness claude
+```
+
+From an installed package, the equivalent is `kiln-init /absolute/empty-workspace --harness claude`. Author, refine and QA skills are installed by default; `--skills compose,batch` adds the optional scene-composition and trial-dispatch workflows. Ask the user which harness they use rather than assuming; the choice writes different configuration and cannot be changed afterwards without a fresh workspace.
+
+| `--harness` | Launch from the workspace |
+| --- | --- |
+| `claude` | `claude` |
+| `codex` | `codex` |
+| `opencode` | `opencode` |
+| `agy` | `node agy.mjs` |
+| `hermes` | `node hermes.mjs --ignore-rules` |
+
+Antigravity and Hermes get a generated launcher because each needs arguments or a separate profile that the bare command does not supply. Hermes authenticates in its own profile; setup copies no credentials.
+
+## Verify the loadout before authoring
+
+Accept the project and MCP trust prompts, then confirm the server is actually live rather than assuming it from configuration. Call `kiln_list_primitives` on `kiln_workspace` with `capabilities: true`; it returns the runtime, source, export and camera contract and proves the tools resolved. A server named `kiln` from a global installation is a different thing. Do not substitute it silently; report the setup problem instead.
+
+Confirm the installed skills are readable at `skills/` in the workspace, and read the relevant one from there rather than a global copy. Whether the harness also registers them natively depends on the harness.
+
+## Relocation and repair
+
+Moving the workspace or the engine installation breaks the generated absolute paths, and so does replacing the Node that setup validated.
+
+```bash
+node /current/kiln/scripts/create-workspace.mjs /absolute/empty-workspace --repair
+```
+
+Repair rewrites generated runtime paths only. It preserves copied skills, saved revisions and assets, refuses configuration that was edited by hand, and does not upgrade the skills. To evaluate a different engine version, create a fresh workspace from that version so instructions and tools match.
+
+## What isolation means
+
+A separate workspace limits task context. It is not an operating-system sandbox, and it is not a git repository. User-level instructions, memory, authentication and filesystem permissions still apply. For comparing harnesses or models, read `skills/kiln-batch-dispatch/references/clean-room-evaluation.md` in the engine checkout, which covers recording inherited context and reporting trials.
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 1a8a03ad..fab1f9e6 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -12,9 +12,26 @@
"longDescription": "Author JavaScript, inspect camera views, and save GLBs with source revisions for later refinement.",
"developerName": "Matthew Kissinger",
"category": "Developer Tools",
- "capabilities": ["Read", "Write"],
- "defaultPrompt": ["Create a game prop and save its editable GLB bundle.", "Browse my collection and refine an existing asset."]
+ "capabilities": [
+ "Read",
+ "Write"
+ ],
+ "defaultPrompt": [
+ "Create a game prop and save its editable GLB bundle.",
+ "Browse my collection and refine an existing asset."
+ ]
+ },
+ "mcpServers": {
+ "kiln": {
+ "command": "node",
+ "args": [
+ "dist/mcp-server.mjs"
+ ],
+ "cwd": ".",
+ "env": {
+ "KILN_RENDER": "auto"
+ }
+ }
},
- "mcpServers": "./.mcp.json",
"license": "MIT"
}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8435983f..9813bad5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -41,6 +41,9 @@ jobs:
- name: Check toolchain metadata
run: bun run check:toolchain
+ - name: Check skills against the Agent Skills specification
+ run: bun run check:skills
+
- name: Install
run: bun install --frozen-lockfile
diff --git a/.gitignore b/.gitignore
index ac4de1b5..a2aa2265 100644
--- a/.gitignore
+++ b/.gitignore
@@ -40,7 +40,11 @@ site/dist/
# Local agent config (launch profiles, per-machine settings). The shipped
# plugin manifest lives in .claude-plugin/, which is tracked.
-.claude/
+# .claude/ is local state. The exception is .claude/skills/, which is committed so
+# a bare clone registers the setup skill; git will not descend into a wholly
+# excluded directory, hence the `/*` form rather than `.claude/`.
+.claude/*
+!.claude/skills/
# Gallery posters are fetched from R2 by site/scripts/verify-assets.mjs and cached here.
.poster-cache/
diff --git a/.mcp.json b/.mcp.json
index 0bdeca51..0dd26137 100644
--- a/.mcp.json
+++ b/.mcp.json
@@ -1,8 +1,9 @@
{
"mcpServers": {
"kiln": {
+ "type": "stdio",
"command": "node",
- "args": ["${PLUGIN_ROOT}/dist/mcp-server.mjs"],
+ "args": ["${CLAUDE_PROJECT_DIR:-.}/dist/mcp-server.mjs"],
"env": { "KILN_RENDER": "auto" }
}
}
diff --git a/AGENTS.md b/AGENTS.md
index fc59a555..d5c678f6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -11,6 +11,18 @@ Read [README.md](./README.md) before changing exports or package contents. Runti
`scripts/`. The package intentionally ships TypeScript source through the explicit `files` and
`exports` lists in `package.json`.
+## Authoring an asset is a different task from changing the engine
+
+This guide covers changing the engine. Authoring an asset does not happen here: it happens in a
+separate workspace, because the authoring skills assume a live `kiln_workspace` server, and giving a
+model this implementation and the example collection alongside an asset brief changes what it
+produces.
+
+If the request is to make or refine an asset, read the `kiln-setup-workspace` skill and create a
+workspace first. It is registered for a bare clone at `.claude/skills/` and `.agents/skills/`, and
+the maintained copy is `skills/kiln-setup-workspace/`. Everything else in this file assumes you are
+working on the engine itself.
+
## The tool registry is the single source of truth
`src/tools/registry.ts` owns tool names, descriptions, and schemas. Two skins consume it: the
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..36773394
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,5 @@
+# Kiln
+
+`AGENTS.md` is the maintained agent guide for this repository. It is imported below rather than duplicated, so there is one source of truth for every harness.
+
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjs
index 75c12b32..fb6a6614 100644
--- a/dist/agent-run.mjs
+++ b/dist/agent-run.mjs
@@ -16,6 +16,928 @@ var __export = (target, all) => {
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = /* @__PURE__ */ createRequire(import.meta.url);
+// src/geometry-catalog.ts
+var geometryPrimitives;
+var init_geometry_catalog = __esm(() => {
+ geometryPrimitives = [
+ {
+ name: "copyGeometry",
+ signature: "copyGeometry(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "instancing",
+ description: "Returns an independent geometry with copied vertex buffers. Use before direct mutation of a cached primitive.",
+ example: "const editable = copyGeometry(boxGeo(1, 1, 1)); editable.translate(0, 0.5, 0);"
+ },
+ {
+ name: "copyMaterial",
+ signature: "copyMaterial(material: Material)",
+ returns: "THREE.Material (same subtype)",
+ category: "instancing",
+ description: "Copies material properties so edits do not change other parts. Referenced textures remain shared.",
+ example: "const red = copyMaterial(steel); red.color.set(0xaa2222);"
+ },
+ {
+ name: "meshGeo",
+ signature: "meshGeo({ positions: number[], indices?: number[], normals?: number[], uvs?: number[], tangents?: number[] })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Builds an owned triangle mesh from flat numeric arrays. Validates finite values, attribute lengths and indices; computes normals if absent. Counterclockwise winding.",
+ example: "const triangle = meshGeo({ positions: [0,0,0, 1,0,0, 0,1,0], indices: [0,1,2] });"
+ },
+ {
+ name: "parametricSurface",
+ signature: "parametricSurface(sample: (u,v) => [x,y,z], opts?: { u?: [0,1], v?: [0,1], uSegments?: 24, vSegments?: 24, periodicU?: false, periodicV?: false, orientation?: 'uv'|'vu' })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Samples an equation into an owned surface with UVs. Periodic endpoints must coincide; UV seams retain matching normals. A surface is not automatically a watertight solid.",
+ example: "const canopy = parametricSurface((u,v) => [u, 0.3*Math.sin(u*3)*Math.cos(v*2), v], { u: [-2,2], v: [-1,1] });"
+ },
+ {
+ name: "geometryDiagnostics",
+ signature: "geometryDiagnostics(geometry: BufferGeometry, tolerance?: 1e-6)",
+ returns: "{ vertices, triangles, boundaryEdges, nonManifoldEdges, orientationConflicts, degenerateTriangles, invalidIndices, nonFiniteVertices }",
+ category: "utility",
+ description: "Counts mesh topology problems after position-based seam matching. Open boundaries are valid for sheets; closed edges alone do not prove a self-intersection-free solid.",
+ example: "const topology = geometryDiagnostics(shell);"
+ },
+ {
+ name: "creaseNormals",
+ signature: "creaseNormals(geometry: BufferGeometry, opts?: { angle?: 60, tolerance?: number })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Returns owned geometry with angle-limited smooth normals, preserving UV corners. Angle is degrees. Invalidates tangents; use after shaping for sharp rims and smooth walls.",
+ example: "const shell = creaseNormals(cylinderGeo(1,1,2,32), { angle: 45 });"
+ },
+ {
+ name: "bend",
+ signature: "bend(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Bends local +Y toward +X through angle degrees. Returns owned geometry and updated normals/bounds; preserves UVs, invalidates tangents. Frame rotation is Euler XYZ degrees.",
+ promptNotes: "Deformation interval uses local Y distances; outside vertices stay unchanged. Add enough segments before bending. Falloff returns 0..1; use it to avoid a discontinuity at a selected interval boundary.",
+ example: "const arch = bend(planeGeo(1,4,4,32), { angle: 90 });"
+ },
+ {
+ name: "twist",
+ signature: "twist(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Rotates the cross-section progressively around local +Y, reaching angle degrees at the end. Returns owned geometry; frame rotation uses Euler XYZ degrees.",
+ example: "const spiral = twist(column, { angle: 120 });"
+ },
+ {
+ name: "taper",
+ signature: "taper(geometry, { startScale?: [1,1], endScale: [x,z], frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Scales local X/Z across the local Y interval using positive start/end scale pairs. Returns owned geometry; preserves UVs and invalidates tangents.",
+ example: "const narrowed = taper(column, { endScale: [0.4,0.7] });"
+ },
+ {
+ name: "displace",
+ signature: "displace(geometry, offset: ([x,y,z], t) => [dx,dy,dz], opts?: { frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Adds an authored displacement vector in the chosen local frame. Returns owned geometry; callback coordinates are local and t is normalized along the interval.",
+ example: "const rippled = displace(surface, ([x,y,z]) => [0, 0.1*Math.sin(x*8), 0]);"
+ },
+ {
+ name: "sweepProfile",
+ signature: "sweepProfile(profile: [x,z][], path: [x,y,z][], opts?: { cap?: true, closed?: false, up?: [x,y,z], twist?: 0, scale?: number | [x,z][] })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Sweeps a simple noncircular profile along polyline stations using transported frames. Supports total twist in degrees and per-station scales. Generates UVs and optional caps.",
+ promptNotes: "First version supports one simple profile without holes. Closed paths omit the repeated endpoint and require twist to be a multiple of 360. up sets the initial profile +Z direction and cannot parallel the path. Tight-turn warnings do not replace visual inspection for self-intersections.",
+ example: "const rail = sweepProfile([[-.1,-.2],[.1,-.2],[.1,.2],[-.1,.2]], [[0,0,0],[0,1,0],[1,2,0]]);"
+ },
+ {
+ name: "loftProfiles",
+ signature: "loftProfiles(sections: { profile: [x,z][], frame?: { origin, rotation } }[], opts?: { cap?: true })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Joins corresponding simple profiles in explicit local XZ planes. Each frame uses Euler XYZ degrees and local +Y along the loft. Profiles need equal point counts and corresponding vertices.",
+ promptNotes: "No holes or automatic profile correspondence. Opposite winding is normalized while preserving the first point. Caps close boundaries but do not prove the loft has no self-intersections.",
+ example: "const hull = loftProfiles([{ profile: wide }, { profile: narrow, frame: { origin: [0,2,0] } }]);"
+ },
+ {
+ name: "implicitSurface",
+ signature: "await implicitSurface(sample: ([x,y,z]) => signedValue, { bounds: { min, max }, edgeLength, maxCells?: 1000000, maxEvaluations?: 8000000, level?: 0, tolerance?: -1, smooth?: true })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "geometry",
+ description: "Experimental positive-inside implicit field sampled into a solid mesh. Requires explicit bounds and resolution; checks grid size and actual evaluation count. Output has no UVs.",
+ promptNotes: "Use async build and await. Smaller edgeLength increases cost sharply. This helper cannot stop a callback that never returns; the host evaluator process provides that boundary. Thin features and geometric accuracy require inspection.",
+ example: "const blob = await implicitSurface(([x,y,z]) => 1-Math.hypot(x,y,z), { bounds: { min: [-1.2,-1.2,-1.2], max: [1.2,1.2,1.2] }, edgeLength: 0.15 });"
+ }
+ ];
+});
+
+// src/list-primitives.ts
+function listPrimitives() {
+ return PRIMITIVES.map((p) => ({ ...p }));
+}
+var PRIMITIVES;
+var init_list_primitives = __esm(() => {
+ init_geometry_catalog();
+ PRIMITIVES = [
+ ...geometryPrimitives,
+ {
+ name: "createRoot",
+ signature: "createRoot(name: string)",
+ returns: "THREE.Object3D",
+ category: "structure",
+ description: "Creates the root Object3D for an asset. Call first in build().",
+ example: "const root = createRoot('FuelDrum');"
+ },
+ {
+ name: "createPivot",
+ signature: "createPivot(name: string, position?: [x, y, z], parent?: Object3D)",
+ returns: "THREE.Object3D (prefixed `Joint_`)",
+ category: "structure",
+ description: "Creates an empty pivot node for skeletal animation. Name is auto-prefixed with `Joint_`.",
+ example: "const hip = createPivot('Hip', [0, 1, 0], root);"
+ },
+ {
+ name: "createJointChain",
+ signature: "createJointChain(name, segments: { role, offset, aliases?, side?, localForwardAxis?, localBendAxis?, endEffector?, contact? }[], opts?: { parent?, parentRole? })",
+ returns: "{ root, end, nodes, byRole, descriptors }",
+ category: "structure",
+ description: "Creates one body-plan-neutral deterministic Joint_* chain with explicit parent edges, rest frames, local axes, end effectors, contacts, and semantic metadata.",
+ example: "const leg = createJointChain('LegL', [{ role: 'hip.left', offset: [0, 1, -0.2], side: 'left' }, { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' }, { role: 'ankle.left', offset: [0, -0.5, 0], side: 'left', endEffector: true, contact: true }], { parent: root });",
+ promptNotes: "Use only the resolved body-plan graph. Offsets are local to the previous joint; contact end effectors must land at world Y=0."
+ },
+ {
+ name: "createVehicleFrame",
+ signature: "createVehicleFrame(name, opts?: { chassis?, axles?, seats?, contacts?, steering?, propulsion?, parent? })",
+ returns: "{ root, chassis, axles, seats, contacts, steering, propulsion }",
+ category: "structure",
+ description: "Creates a canonical +X-forward/+Y-up/+Z-right vehicle frame with typed semantic sockets for chassis, support, steering, and propulsion.",
+ example: "const frame = createVehicleFrame('CarFrame', { axles: [{ id: 'front', position: [1.2, 0.45, 0] }, { id: 'rear', position: [-1.2, 0.45, 0] }], parent: root });",
+ promptNotes: "Generated vehicles keep +X as front. Boats and other non-wheeled subtypes use declared support/propulsion sockets, not wheel rules."
+ },
+ {
+ name: "createWheelGeometrySet",
+ signature: "createWheelGeometrySet(radius: number, width: number)",
+ returns: "{ tire, rim, hub } shared THREE.BufferGeometry set",
+ category: "instancing",
+ description: "Creates one reusable +Z-axle tire/rim/hub geometry set for instanced wheel assemblies.",
+ example: "const wheelGeo = createWheelGeometrySet(0.45, 0.22);"
+ },
+ {
+ name: "createWheelAssembly",
+ signature: "createWheelAssembly(name, { tire, rim, hub? }, { radius, width, side, index, position?, rimRadius?, hubRadius?, steering?, loadBearing?, geometries?, parent? })",
+ returns: "{ root, steeringPivot?, spinPivot, tire, rim, hub, contact, radius, width, side, index, spinAxis }",
+ category: "structure",
+ description: "Creates one axle-centered wheel pivot containing concentric tire/rim/hub roles, a contact marker, +Z spin frame, and optional steering pivot.",
+ example: "createWheelAssembly('FrontLeft', { tire: rubber, rim: metal }, { radius: 0.45, width: 0.22, side: 'left', index: 'front', position: [1.2, 0.45, -0.9], steering: true, geometries: wheelGeo, parent: frame.root });",
+ promptNotes: "Keep tire, rim, and hub descendants concentric at the axle pivot. Reuse one geometry set across matching wheels."
+ },
+ {
+ name: "createPart",
+ signature: "createPart(name, geometry, material, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, pivot, parent })",
+ returns: "THREE.Object3D (mesh or wrapping pivot)",
+ category: "structure",
+ description: "Creates a mesh, optionally wrapped in a pivot, and attaches it to `opts.parent`. `rotation` is in DEGREES (like rotationTrack), NOT radians: [0, 0, 90] is a quarter turn; [0, 0, 1.57] is a no-op.",
+ example: "createPart('Barrel', cylinderGeo(0.1, 0.1, 1), gameMaterial(0x556b2f), { position: [0, 0.5, 0], rotation: [0, 0, 90], parent: root });",
+ promptNotes: "AUTO-ADDS to opts.parent. NEVER call parent.add(createPart(...)) — pass { parent } instead. rotation is DEGREES — writing radians (e.g. 0.785 or Math.PI/4) silently produces ~zero rotation."
+ },
+ {
+ name: "beamBetween",
+ signature: "beamBetween(name, start: [x,y,z], end: [x,y,z], radius, material, opts?: { segments, parent })",
+ returns: "THREE.Object3D (prefixed `Mesh_`)",
+ category: "structure",
+ description: "Creates a cylindrical rail/strut exactly between two endpoints. Use for braces, gun barrels, skid struts, cables, and scaffolding.",
+ example: "beamBetween('SkidBraceA', [0.8, 0.3, 0.7], [0.8, 1.0, 0.45], 0.025, black, { parent: root });"
+ },
+ {
+ name: "snapTo",
+ signature: "snapTo(part: Object3D, host: Object3D, opts?: { axis?: 'x'|'y'|'z', overlap?: 0.02 })",
+ returns: "THREE.Object3D (the part, for chaining)",
+ category: "structure",
+ description: 'Translates `part` by the minimal vector that brings its bounding box into contact with `host` (plus a small overlap). The direct cure for a "Floating parts" warning — attach the part instead of eyeballing a corrective offset. No-op if they already touch.',
+ example: `const scope = createPart('Scope', cylinderXGeo(0.04, 0.04, 0.3), steel, { parent: root, position: [0.1, 0.32, 0] });
+snapTo(scope, receiver);`
+ },
+ {
+ name: "createLadder",
+ signature: "createLadder(name, { bottom, top, material, width?, rungCount?, railRadius?, rungRadius?, widthAxis?, parent? })",
+ returns: "{ leftRail: Object3D, rightRail: Object3D, rungs: Object3D[] }",
+ category: "structure",
+ description: "Builds two continuous rails plus evenly-spaced rungs. Use this instead of loose boxes for ladders.",
+ example: "createLadder('TowerLadder', { bottom: [0,0,0], top: [0,2.2,0], width: 0.45, rungCount: 7, material: steel, parent: root });"
+ },
+ {
+ name: "createWingPair",
+ signature: "createWingPair(name, material, { rootZ, span, rootChord, tipChord, sweep?, thickness?, dihedral?, rootX?, rootY?, parent? })",
+ returns: "{ right: Object3D, left: Object3D }",
+ category: "structure",
+ description: "Creates mirrored trapezoid aircraft wings with roots attached at +/-rootZ. Use for aircraft wings and helicopter stub wings.",
+ example: "createWingPair('MainWing', olive, { rootX: 0, rootY: 1.0, rootZ: 0.42, span: 2.4, rootChord: 0.9, tipChord: 0.35, sweep: 0.25, dihedral: 0.08, parent: root });"
+ },
+ {
+ name: "room",
+ signature: "room(name, material, { width?, depth?, height?, wallThickness?, floor?, floorThickness?, openings?: [{ wall: 'front'|'back'|'left'|'right', kind?: 'door'|'window', offset?, width?, height?, sill? }], parent? })",
+ returns: "{ root: Object3D, walls: { front, back, left, right }, floor: Object3D | null }",
+ category: "structure",
+ description: "Builds a HOLLOW, enterable room: four thin walls + a floor, human-scaled (defaults: 2.8m ceiling, a centered 1.1x2.1m front door so it is enterable by default). `front` faces +X; the floor sits on the ground. The keystone of an architecture asset — add a roof with createRoofPlanes and fixtures as separate parts.",
+ example: "const { root: hut } = room('Hut', wood, { width: 5, depth: 4, height: 2.8, openings: [{ wall: 'front', kind: 'door' }, { wall: 'right', kind: 'window' }], parent: root });",
+ promptNotes: "Use for any building the player enters. Do NOT model a building as a solid block — room() guarantees real interior space and a doorway gap. Pass openings to add windows / side doors."
+ },
+ {
+ name: "wallWithOpening",
+ signature: "wallWithOpening(name, material, { length, height, thickness, axis?: 'x'|'z', opening?: { kind?: 'door'|'window', offset?, width?, height?, sill? }, parent? })",
+ returns: "THREE.Object3D (wall container)",
+ category: "structure",
+ description: "A single wall panel with an optional real door/window cut, composed from solid box segments (side panels + lintel + window sill) — no CSG. Base at local Y=0, centered on the run axis. Use to compose custom building layouts or interior dividing walls beyond the default room().",
+ example: "wallWithOpening('Partition', plaster, { length: 4, height: 2.8, thickness: 0.12, axis: 'x', opening: { kind: 'door', offset: 0.5 }, parent: root });"
+ },
+ {
+ name: "createRoofPlanes",
+ signature: "createRoofPlanes(name, material, { width, depth, height, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",
+ returns: "{ root: Object3D, slopes: [Object3D, Object3D] }",
+ category: "structure",
+ description: "A pitched roof: two thin slopes meeting at one ridge and falling DOWN-AND-OUTWARD (opposite tilts — never mirrored the same way), footprint-matched with an eave overhang. Eave at local Y=0, ridge at Y=height, so position the group at Y=wallHeight. Returns a named group (e.g. `Roof`) the engine can lift to reveal the interior.",
+ example: `const { root: roof } = createRoofPlanes('Roof', shingle, { width: 5, depth: 4, height: 1.6, overhang: 0.4, ridgeAxis: 'x', parent: root });
+roof.position.y = 2.8;`,
+ promptNotes: "The two slopes must fall AWAY from each other from the ridge — createRoofPlanes does this for you. Drop it onto the walls (position.y = wall height)."
+ },
+ {
+ name: "createGableRoof",
+ signature: "createGableRoof(name, material, { spanX, spanZ, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",
+ returns: "{ root, slopes: [Object3D, Object3D], faces: [RoofFaceFrame, RoofFaceFrame], rise, pitchDegrees }",
+ category: "structure",
+ description: "Explicit-axis gable roof using unambiguous footprint spans. Each face owns a rigid frame with ridge tangent, outward normal, downhill direction, ridge/eave endpoints, dimensions, and a live local-to-world transform.",
+ example: "const roof = createGableRoof('Roof', shingles, { spanX: 8, spanZ: 5, pitchDegrees: 35, overhang: 0.35, ridgeAxis: 'x', parent: root });",
+ promptNotes: "Prefer this over width/depth roof math. ridgeAxis is the direction of the ridge; roof panels run along each returned face downhill direction."
+ },
+ {
+ name: "createGableEndPanel",
+ signature: "createGableEndPanel(name, material, { span, rise, thickness?, ridgeAxis?: 'x'|'z', side?: 'positive'|'negative', openings?: [{ id?, offset?, bottom?, width, height }], parent? })",
+ returns: "{ root, geometry, openings }",
+ category: "structure",
+ description: "Exact thick triangular end closure for a gable roof, with optional rectangular openings cut from the geometry and semantic boundary metadata.",
+ example: "createGableEndPanel('FrontGable', siding, { span: 5, rise: 1.8, ridgeAxis: 'x', side: 'positive', parent: root });"
+ },
+ {
+ name: "createGableShell",
+ signature: "createGableShell(name, { wall, roof, floor?, gable? }, { spanX, spanZ, wallHeight?, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, wallThickness?, floorThickness?, closedEnds?, enterable?, openings?, gableOpenings?, parent? })",
+ returns: "{ root, walls, floor, roof, gables, openings }",
+ category: "structure",
+ description: "Closed-by-default, correct-by-construction gable building: hollow room, floor, two opposing roof slopes, two complete gable ends, and a real front doorway when enterable.",
+ example: "const house = createGableShell('House', { wall: plaster, roof: shingles }, { spanX: 8, spanZ: 5, wallHeight: 2.8, pitchDegrees: 35, ridgeAxis: 'x', parent: root });",
+ promptNotes: "Use for complete gable buildings. It stamps wall, floor, slope, gable, opening, adjacency, coverage, and separability semantics for deterministic QA and roof-off views."
+ },
+ {
+ name: "createRoofSurfaceLayout",
+ signature: "createRoofSurfaceLayout(name, material, { face, kind: 'panels'|'shingles'|'seams'|'corrugations', parent?, panelWidth?, rowHeight?, spacing?, thickness? })",
+ returns: "{ root, items: Object3D[] }",
+ category: "structure",
+ description: "Places roof-local panels, shingles, seams, or corrugations from a returned RoofFaceFrame, so repeated elements run ridge-to-eave for either ridge axis without manual Euler rotations.",
+ example: "for (const face of roof.faces) createRoofSurfaceLayout('Panels_' + face.side, metal, { face, kind: 'panels', parent: roof.root });",
+ promptNotes: "Always pass the face object returned by createGableRoof/createGableShell. Never infer the panel rotation from world axes."
+ },
+ {
+ name: "createStairs",
+ signature: "createStairs(name, material, { steps?, totalRise, totalRun, width, axis?: 'x'|'z', treadThickness?, riser?, parent? })",
+ returns: "{ root: Object3D, steps: Object3D[] }",
+ category: "structure",
+ description: "A straight flight of stairs: box treads (with optional risers) climbing totalRise over totalRun from local origin toward +axis. Use for porch/entry steps or to connect storeys in a multi-storey building.",
+ example: "createStairs('Porch', stone, { steps: 4, totalRise: 0.6, totalRun: 1.0, width: 1.4, axis: 'x', parent: root });"
+ },
+ {
+ name: "boxGeo",
+ signature: "boxGeo(width: number, height: number, depth: number)",
+ returns: "THREE.BoxGeometry",
+ category: "geometry",
+ description: "6-face box. 12 tris regardless of size. Cheapest geometry.",
+ example: "const geo = boxGeo(1, 0.5, 2);"
+ },
+ {
+ name: "sphereGeo",
+ signature: "sphereGeo(radius: number, widthSegments?: 8, heightSegments?: 6)",
+ returns: "THREE.SphereGeometry",
+ category: "geometry",
+ description: "UV sphere. Default 8x6 segments = 84 tris. Bump segments for smoother curves.",
+ example: "const geo = sphereGeo(0.5, 12, 8);"
+ },
+ {
+ name: "cylinderGeo",
+ signature: "cylinderGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Y-axis cylinder. Use radiusTop != radiusBottom for cones / tapered pieces.",
+ example: "const geo = cylinderGeo(0.25, 0.25, 1, 12);"
+ },
+ {
+ name: "cylinderYGeo",
+ signature: "cylinderYGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Alias for cylinderGeo — a Y-axis cylinder. Provided because the sandbox exposes cylinderXGeo / cylinderZGeo and the symmetric Y form is commonly reached for.",
+ example: "const geo = cylinderYGeo(0.25, 0.25, 1, 12);"
+ },
+ {
+ name: "cylinderXGeo",
+ signature: "cylinderXGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Cylinder pre-rotated to run along +X/-X. Use for fuselages, cannons, barrels, axles, and forward-facing tubes.",
+ example: "const geo = cylinderXGeo(0.1, 0.1, 1.2, 12);"
+ },
+ {
+ name: "cylinderZGeo",
+ signature: "cylinderZGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Cylinder pre-rotated to run along +Z/-Z. Use for side-mounted weapons, rails, crossbars, and pipes.",
+ example: "const geo = cylinderZGeo(0.08, 0.08, 0.9, 10);"
+ },
+ {
+ name: "cylinderOnAxis",
+ signature: "cylinderOnAxis(center: [x,y,z], normal: [x,y,z], radiusBottom: number, height: number, opts?: { radiusTop?, segments? })",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Frame-first cylinder: position + axis specified directly, no post-hoc rotation. Use when the cylinder needs to point along a non-cardinal direction (struts inside CSG operands, antennas off a tilted surface). For cardinal axes prefer the terser cylinderXGeo / cylinderYGeo / cylinderZGeo helpers.",
+ example: "const strut = cylinderOnAxis([0.5, 0.7, 0], [1, 1, 0.3], 0.05, 0.9);"
+ },
+ {
+ name: "capsuleGeo",
+ signature: "capsuleGeo(radius: number, height: number, segments?: 6)",
+ returns: "THREE.CapsuleGeometry",
+ category: "geometry",
+ description: "Stadium shape (cylinder with hemispherical caps). Good for limbs.",
+ example: "const geo = capsuleGeo(0.1, 0.5, 6);"
+ },
+ {
+ name: "capsuleYGeo",
+ signature: "capsuleYGeo(radius: number, height: number, segments?: 6)",
+ returns: "THREE.CapsuleGeometry",
+ category: "geometry",
+ description: "Alias for capsuleGeo — a Y-axis capsule. Provided for symmetry with capsuleXGeo / capsuleZGeo.",
+ example: "const geo = capsuleYGeo(0.1, 0.5, 6);"
+ },
+ {
+ name: "capsuleXGeo",
+ signature: "capsuleXGeo(radius: number, length: number, segments?: 6)",
+ returns: "THREE.CapsuleGeometry",
+ category: "geometry",
+ description: "Capsule pre-rotated to run along +X/-X. Use for aircraft bodies, rounded vehicle hulls, and missiles.",
+ example: "const geo = capsuleXGeo(0.35, 2.4, 10);"
+ },
+ {
+ name: "capsuleZGeo",
+ signature: "capsuleZGeo(radius: number, length: number, segments?: 6)",
+ returns: "THREE.CapsuleGeometry",
+ category: "geometry",
+ description: "Capsule pre-rotated to run along +Z/-Z. Use for lateral pods, floats, and side tanks.",
+ example: "const geo = capsuleZGeo(0.18, 1.1, 8);"
+ },
+ {
+ name: "coneGeo",
+ signature: "coneGeo(radius: number, height: number, segments?: 8)",
+ returns: "THREE.ConeGeometry",
+ category: "geometry",
+ description: "Y-axis cone (pointed up). Use for spikes, roofs, projectiles.",
+ example: "const geo = coneGeo(0.3, 0.8, 8);"
+ },
+ {
+ name: "coneYGeo",
+ signature: "coneYGeo(radius: number, height: number, segments?: 8)",
+ returns: "THREE.ConeGeometry",
+ category: "geometry",
+ description: "Alias for coneGeo — a Y-axis cone (point +Y). Provided for symmetry with coneXGeo / coneZGeo.",
+ example: "const geo = coneYGeo(0.3, 0.8, 8);"
+ },
+ {
+ name: "coneXGeo",
+ signature: "coneXGeo(radius: number, length: number, segments?: 8)",
+ returns: "THREE.ConeGeometry",
+ category: "geometry",
+ description: "Cone pre-rotated so its point faces +X. Use for noses, rockets, shells, and forward-facing tips.",
+ example: "const geo = coneXGeo(0.18, 0.45, 12);"
+ },
+ {
+ name: "coneZGeo",
+ signature: "coneZGeo(radius: number, length: number, segments?: 8)",
+ returns: "THREE.ConeGeometry",
+ category: "geometry",
+ description: "Cone pre-rotated so its point faces +Z. Use for side-facing projectiles and tips.",
+ example: "const geo = coneZGeo(0.12, 0.35, 10);"
+ },
+ {
+ name: "taperConeGeo",
+ signature: "taperConeGeo(radiusBottom: number, radiusTop: number, height: number, axis?: 'x'|'y'|'z', segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Truncated cone (frustum) — exposes both bottom and top radius. radiusTop=0 matches coneGeo, radiusTop=radiusBottom matches cylinderGeo. Use for pylon caps, soda cans, lampshades, anything tapered that does not come to a point. axis selects orientation (default Y).",
+ example: "const cap = taperConeGeo(0.3, 0.18, 0.4); // frustum"
+ },
+ {
+ name: "torusGeo",
+ signature: "torusGeo(radius: number, tube: number, radialSegments?: 8, tubularSegments?: 12)",
+ returns: "THREE.TorusGeometry",
+ category: "geometry",
+ description: "Donut shape. For rings, tyres, barrel ribs.",
+ example: "const geo = torusGeo(0.4, 0.04, 8, 16);"
+ },
+ {
+ name: "planeGeo",
+ signature: "planeGeo(width: number, height: number, widthSegments?: 1, heightSegments?: 1)",
+ returns: "THREE.PlaneGeometry",
+ category: "geometry",
+ description: "Flat quad for TEXTURED surfaces (ground, signs, walls with albedo maps). For solid-color decals like red stars, hull numbers, stamps, or window cutouts on no-texture assets use decalBox — a bare planeGeo without a texture will render as a disconnected 2-tri square and get flagged as a stray plane.",
+ example: "const geo = planeGeo(4, 4);"
+ },
+ {
+ name: "decalBox",
+ signature: "decalBox(width: number, height: number, depth?: 0.01)",
+ returns: "THREE.BoxGeometry",
+ category: "geometry",
+ description: "Thin box for solid-color surface decals: red stars, hull numbers, stamps, no-texture windows. Unlike planeGeo, has real depth so it visibly attaches to its host surface. Must be placed on a surface with position + rotation.",
+ example: `const star = decalBox(0.18, 0.18, 0.01);
+createPart('Mesh_StarPort', star, gameMaterial(0xc61f2a), { position: [0.4, 0.6, 0.41], parent: fuselage });`,
+ promptNotes: "Offset at least 0.01 outside the host surface to avoid z-fighting (a 0.8-wide hull has faces at z=±0.4, so place the decal at z=±0.41)."
+ },
+ {
+ name: "foliageCardGeo",
+ signature: "foliageCardGeo(opts?: { width?, height?, yPivot?: 0..1 })",
+ returns: "THREE.PlaneGeometry",
+ category: "geometry",
+ description: "Single-quad foliage card with a configurable Y pivot. yPivot=0 plants the quad on the ground. Pair with an alpha-tested material and a leaf/plant sprite.",
+ example: `const leaves = await materialRecipe('kiln.material.leaf.v1');
+const quad = foliageCardGeo({ width: 4, height: 6, yPivot: 0 });
+createPart('Mesh_Fern', quad, leaves, { parent: root });`
+ },
+ {
+ name: "crossedQuadsGeo",
+ signature: "crossedQuadsGeo(opts?: { width?, height?, planes?: 2 | 3, yPivot? })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Cross-billboard bush primitive: 2 or 3 planes intersecting along the Y axis. Reads as a dense plant from any angle, cheaper than real geometry.",
+ example: `const leaves = await materialRecipe('kiln.material.leaf.v1');
+const bush = crossedQuadsGeo({ width: 2, height: 2, planes: 3 });
+createPart('Mesh_Bush', bush, leaves, { parent: root });`
+ },
+ {
+ name: "octaGridPlane",
+ signature: "octaGridPlane({ tilesX, tilesY, width?, height?, yPivot? })",
+ returns: "THREE.PlaneGeometry",
+ category: "geometry",
+ description: "Atlas-ready billboard quad. UVs are pre-scaled to cover one tile of a tilesX×tilesY atlas; the consumer shader adds per-instance tile offsets at draw time.",
+ example: "const card = octaGridPlane({ tilesX: 4, tilesY: 4, width: 6, height: 6 });"
+ },
+ {
+ name: "wingGeo",
+ signature: "wingGeo(opts?: { span, rootChord, tipChord, sweep, thickness, dihedral })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Trapezoid wing panel. Local root edge is at Z=0, span extends toward +Z, positive sweep moves the tip aft along -X.",
+ example: "const geo = wingGeo({ span: 2.2, rootChord: 0.8, tipChord: 0.3, sweep: 0.25, dihedral: 0.08 });"
+ },
+ {
+ name: "gearGeo",
+ signature: "gearGeo(opts?: { teeth?: 12, rootRadius?: 0.8, tipRadius?: 1.0, boreRadius?: 0.2, height?: 0.3, toothWidthFrac?: 0.5 })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Stylized gear with flat edges and an optional center bore; no CSG. Use boreRadius < rootRadius < tipRadius. Radii are absolute: an omitted rootRadius stays 0.8 when tipRadius changes. Set all three radii for small gears.",
+ example: `const g = gearGeo({ teeth: 28, rootRadius: 0.063, tipRadius: 0.075, boreRadius: 0.012, height: 0.024 });
+createPart('Gear', g, gameMaterial(0x909090, { metalness: 0.8 }), { parent: root });`
+ },
+ {
+ name: "bladeGeo",
+ signature: "bladeGeo(opts?: { length?: 1.5, baseWidth?: 0.1, thickness?: 0.015, tipLength?: 0.25, edgeBevel?: 0 })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Parametric sword blade: rectangular base tapering to a point over tipLength. edgeBevel > 0 pinches the cross-section toward a diamond ridge.",
+ example: `const b = bladeGeo({ length: 1.6, baseWidth: 0.09, tipLength: 0.3, edgeBevel: 0.5 });
+createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`
+ },
+ {
+ name: "gameMaterial",
+ signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Flat-shaded PBR material. Default for game-ready low-poly. Use for 95% of parts.",
+ example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9 });"
+ },
+ {
+ name: "materialRecipe",
+ signature: "await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })",
+ returns: "Promise<THREE.MeshStandardMaterial>",
+ category: "material",
+ description: "Resolves a versioned portable bark/leaf/wood/stone/rubber/painted-metal/cloth/skin/glass/emissive recipe to standard glTF PBR.",
+ example: "const bark = await materialRecipe('kiln.material.bark.v1', { baseColor: '#6b4328' });",
+ promptNotes: "Use only listed kiln.material.*.v1 IDs and approved kiln.texture.* resource IDs. Leaf is MASK, glass is BLEND, and host file paths are forbidden."
+ },
+ {
+ name: "compilePortableMaterialSpecV2",
+ signature: "await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', name?, baseColor?, roughness?, metalness?, emissive?, emissiveIntensity?, alphaMode?, alphaCutoff?, doubleSided?, textures?: { baseColor?, normal?, metallicRoughness?, emissive?, occlusion? } })",
+ returns: "Promise<THREE.MeshStandardMaterial>",
+ category: "material",
+ description: "Compiles the strict portable material contract. Texture refs are either typed procedural V2 specs or closed approved kiln.texture.* IDs; paths, URLs, raw textures, callbacks, and shader source are rejected.",
+ example: "const steel = await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', roughness: 0.45, metalness: 0.85, textures: { metallicRoughness: { kind: 'procedural', spec: { schemaVersion: 2, usage: 'metallicRoughness', size: 64, layers: [{ op: 'solid', color: 0x0080cc }] } } } });",
+ promptNotes: "Use metallicRoughness as one packed G=roughness/B=metalness map. Every procedural ref usage must match its slot; resource refs must be approved for that exact slot."
+ },
+ {
+ name: "basicMaterial",
+ signature: "basicMaterial(color, opts?: { transparent, opacity })",
+ returns: "THREE.MeshBasicMaterial",
+ category: "material",
+ description: "Unlit flat material. For UI / effects where lighting is baked in.",
+ example: "const mat = basicMaterial(0xffffff, { transparent: true, opacity: 0.5 });"
+ },
+ {
+ name: "glassMaterial",
+ signature: "glassMaterial(color, opts?: { opacity, roughness, metalness })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.",
+ example: "const mat = glassMaterial(0x66ccff, { opacity: 0.3 });"
+ },
+ {
+ name: "lambertMaterial",
+ signature: "lambertMaterial(color, opts?: { flatShading, emissive })",
+ returns: "THREE.MeshLambertMaterial",
+ category: "material",
+ description: "Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.",
+ example: "const mat = lambertMaterial(0x2a4d14, { flatShading: true });"
+ },
+ {
+ name: "rotationTrack",
+ signature: "rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP')",
+ returns: "THREE.QuaternionKeyframeTrack",
+ category: "animation",
+ description: "Rotation track in degrees, auto-converted to quaternions. Joint name must include `Joint_` prefix.",
+ example: "rotationTrack('Joint_Lid', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [90, 0, 0] }]);"
+ },
+ {
+ name: "positionTrack",
+ signature: "positionTrack(jointName: string, keyframes: Array<{ time, position: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')",
+ returns: "THREE.VectorKeyframeTrack",
+ category: "animation",
+ description: "Position track in world units. Always use `position:` not `value:` in keyframes.",
+ example: "positionTrack('Joint_Body', [{ time: 0, position: [0, 0, 0] }, { time: 1, position: [0, 0.1, 0] }]);"
+ },
+ {
+ name: "scaleTrack",
+ signature: "scaleTrack(jointName: string, keyframes: Array<{ time, scale: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')",
+ returns: "THREE.VectorKeyframeTrack",
+ category: "animation",
+ description: "Uniform or per-axis scale track.",
+ example: "scaleTrack('Joint_Chest', [{ time: 0, scale: [1, 1, 1] }, { time: 1, scale: [1.1, 1.1, 1.1] }]);"
+ },
+ {
+ name: "createClip",
+ signature: "createClip(name: string, duration: number, tracks: KeyframeTrack[])",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "Collects tracks into a named clip. Returned from animate().",
+ example: "return [createClip('Open', 1, [rotationTrack('Joint_Lid', [...])])];"
+ },
+ {
+ name: "idleBreathing",
+ signature: "idleBreathing(bodyJoint: string, duration?: 2, amount?: 0.02)",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "Gentle Y-axis bob. For NPC idle states.",
+ example: "return [idleBreathing('Joint_Body')];"
+ },
+ {
+ name: "bobbingAnimation",
+ signature: "bobbingAnimation(rootName: string, duration?: 2, height?: 0.1)",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "Floating / bobbing loop for pickups and effects.",
+ example: "return [bobbingAnimation('Joint_Root', 1.5, 0.08)];"
+ },
+ {
+ name: "spinAnimation",
+ signature: "spinAnimation(jointName: string, duration?: 2, axis?: 'x' | 'y' | 'z')",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "360° rotation over `duration` around `axis`.",
+ example: "return [spinAnimation('Joint_Rotor', 0.5, 'y')];"
+ },
+ {
+ name: "cloneGeometry",
+ signature: "cloneGeometry(geo: BufferGeometry)",
+ returns: "THREE.BufferGeometry (same ref)",
+ category: "instancing",
+ description: "Deprecated name: returns the SAME geometry, without copying. Use copyGeometry for independent vertex edits, or pass the original geometry directly for intentional sharing.",
+ example: "const wheelGeo = cylinderGeo(0.4, 0.4, 0.2, 12);"
+ },
+ {
+ name: "cloneMaterial",
+ signature: "cloneMaterial(mat: Material)",
+ returns: "THREE.Material (same ref)",
+ category: "instancing",
+ description: "Deprecated name: returns the SAME material. Use copyMaterial for independent property edits, or pass the original for intentional sharing.",
+ example: "const rubberMat = gameMaterial(0x1a1a1a, { roughness: 0.95 });"
+ },
+ {
+ name: "createInstance",
+ signature: "createInstance(name, source, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, parent })",
+ returns: "THREE.Object3D",
+ category: "instancing",
+ description: "Creates a new mesh reusing an existing part's geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows. `rotation` is in DEGREES, like createPart.",
+ example: `const wheelFL = createPart('WheelFL', wheelGeo, rubberMat, { position: [-0.8, 0.3, 1.2], parent: root });
+createInstance('WheelFR', wheelFL, { position: [0.8, 0.3, 1.2], parent: root });
+createInstance('WheelRL', wheelFL, { position: [-0.8, 0.3, -1.2], parent: root });
+createInstance('WheelRR', wheelFL, { position: [0.8, 0.3, -1.2], parent: root });`
+ },
+ {
+ name: "boolUnion",
+ signature: "await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Merges two or more parts into one watertight manifold mesh. Default flat shading (hard edges) — pass { smooth: true } as last arg for averaged normals on organic merges.",
+ example: `const body = new THREE.Mesh(boxGeo(2, 1, 1), steel);
+const turret = new THREE.Mesh(cylinderGeo(0.3, 0.3, 0.4, 16), steel);
+turret.position.y = 0.5;
+const hull = await boolUnion('Hull', body, turret);`
+ },
+ {
+ name: "boolDiff",
+ signature: "await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Subtracts cutters from a body (holes, button recesses, window slots). Default flat shading for sharp mechanical edges.",
+ example: `const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel);
+const teeth = [...]; // 8 radially-arrayed box meshes
+const gear = await boolDiff('Gear', body, ...teeth); // hard-edged`
+ },
+ {
+ name: "roundedBoxGeo",
+ signature: "await roundedBoxGeo(width: number, height: number, depth: number, radius: number, opts?: { style?: 'round' | 'chamfer', segments?: 12, smooth?: boolean })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "csg",
+ description: "A box with all twelve edges rounded (or chamfered) at the EXACT outer size requested — roundedBoxGeo(1, 1, 1, 0.1) measures 1x1x1, it does not grow. Use it anywhere boxGeo reads too sharp: consoles, crates, appliances, handheld props, machined blocks.",
+ promptNotes: "Real objects almost never have perfectly sharp box edges, and a small radius is the single cheapest upgrade to how manufactured an asset looks. Prefer this over boxGeo for anything moulded, cast, or machined. Keep radius small relative to the box (5-10% of the smallest dimension); radius must be less than half the smallest dimension or the call throws. style: 'chamfer' reads as machined metal, 'round' as moulded plastic. This is async — build() must be async and the call must use await.",
+ example: `const geo = await roundedBoxGeo(1.2, 0.6, 0.8, 0.05);
+createPart('Console', geo, plastic, { position: [0, 0.3, 0], parent: root });`
+ },
+ {
+ name: "extrudeProfile",
+ signature: "await extrudeProfile(profile: [number, number][], opts?: { depth?: 1, holes?: [number, number][][], bevel?: 0, bevelStyle?: 'round' | 'chamfer', segments?: 12, twist?: 0, taper?: number | [number, number], divisions?: number, axis?: 'x' | 'y' | 'z', center?: true, smooth?: false })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "csg",
+ description: "Sweeps a closed 2D outline into a watertight solid, with optional holes, corner rounding/chamfering, twist, and taper. The way to build any cross-section that is not a box or a cylinder: L-brackets, I-beams, gaskets, washers, star and gear plates, signage, extruded trim.",
+ promptNotes: "The bevel rounds the edges PARALLEL to the sweep axis (the profile corners) — the two flat caps stay sharp. For a box rounded on all twelve edges use roundedBoxGeo instead. Holes are subtracted, so their winding order does not matter. A bevel larger than half the outline's narrowest feature throws rather than silently returning an empty solid. Output is manifold, so it feeds straight into boolUnion / boolDiff / boolIntersect. Async — await it inside an async build().",
+ example: `// L-bracket, inner AND outer corners filleted
+const outline = [[0, 0], [2, 0], [2, 0.4], [0.4, 0.4], [0.4, 2], [0, 2]];
+const geo = await extrudeProfile(outline, { depth: 0.5, bevel: 0.06 });
+createPart('Bracket', geo, steel, { parent: root });`
+ },
+ {
+ name: "revolveProfile",
+ signature: "await revolveProfile(profile: [number, number][], opts?: { segments?: 24, angle?: 360, bevel?: 0, bevelStyle?: 'round' | 'chamfer', bevelSegments?: 12, axis?: 'x' | 'y' | 'z', smooth?: true })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "csg",
+ description: "Revolves a closed 2D outline around an axis into a watertight SOLID, optionally rounding the profile corners first. Bottles, tanks, pressure vessels, wheels, turned wood, domes, buttons, pills.",
+ promptNotes: "Use this instead of lathe/revolveGeo whenever the result must survive a boolean or needs a rounded rim — lathe and revolveGeo build an open surface, this builds a closed solid. Profile convention matches lathe: x is distance from the axis, y is position along it, and only the x >= 0 side is used. Async — await it inside an async build().",
+ example: `// capsule tank with a rounded rim, then carve a port into it
+const profile = [[0, -0.5], [0.4, -0.5], [0.4, 0.5], [0, 0.5]];
+const body = await revolveProfile(profile, { bevel: 0.08, segments: 32 });
+const tank = await boolDiff('Tank', createPart('B', body, steel), portCutter);`
+ },
+ {
+ name: "circleProfile",
+ signature: "circleProfile(radius: number, segments?: 24, center?: [number, number])",
+ returns: "[number, number][]",
+ category: "csg",
+ description: "Builds a closed circular outline for extrudeProfile / revolveProfile, so you never hand-write the trigonometry. Synchronous.",
+ example: `const washer = await extrudeProfile(circleProfile(1), {
+ depth: 0.1,
+ holes: [circleProfile(0.4), circleProfile(0.1, 16, [0.7, 0])],
+});`
+ },
+ {
+ name: "boolIntersect",
+ signature: "await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Keeps only the volume where both operands overlap. Default flat shading.",
+ example: "const lens = await boolIntersect('Lens', boxMesh, sphereMesh);"
+ },
+ {
+ name: "hull",
+ signature: "await hull(name: string, ...parts: Object3D[], opts?: { smooth?: true })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Tightest convex mesh enclosing all input points. Default smooth shading (rocks, collision volumes). Pass { smooth: false } for a faceted look.",
+ example: `const rockChunks = [...]; // scattered box meshes
+const rock = await hull('Rock', ...rockChunks);`
+ },
+ {
+ name: "arrayLinear",
+ signature: "arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)",
+ returns: "THREE.Object3D[]",
+ category: "arrays",
+ description: "Places N copies of `source` along a constant offset vector. Copies share geometry + material via createInstance.",
+ example: `const post = createPart('Post0', cylinderGeo(0.05,0.05,1.5,6), wood, { position: [0,0.75,0], parent: root });
+arrayLinear('Post', post, 10, [0.5, 0, 0], root);`
+ },
+ {
+ name: "arrayRadial",
+ signature: "arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?)",
+ returns: "THREE.Object3D[]",
+ category: "arrays",
+ description: "Places N copies of `source` around the given axis. Source's local rotation is oriented outward. Perfect for gear teeth, radial bolts, circle of columns.",
+ example: `const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });
+arrayRadial('Bolt', bolt, 8, 'y', root);`
+ },
+ {
+ name: "mirror",
+ signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",
+ returns: "THREE.Object3D",
+ category: "arrays",
+ description: "Reflects source across the plane whose normal is `axis`. Uses negative scale (winding flip handled by viewers).",
+ example: "mirror('WingR', wingL, 'x', root);"
+ },
+ {
+ name: "subdivide",
+ signature: "subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { preserveUV?: boolean, split?: boolean, uvSmooth?: boolean, preserveEdges?: boolean, flatOnly?: boolean, weld?: boolean })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Loop subdivision returns new geometry; each iteration roughly quadruples triangles and smooths the surface. Use preserveUV:true for textured meshes. Legacy position-only welding discards UVs and reports that loss. This smooths shapes, not selected-edge beveling.",
+ example: "const smoothRock = subdivide(boxGeo(1, 1, 1), 2);"
+ },
+ {
+ name: "mergeVertices",
+ signature: "mergeVertices(geometry: BufferGeometry, opts?: { tolerance?: 1e-4, positionOnly?: boolean } | number)",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Returns indexed geometry. Default welding preserves attribute seams, so a textured cube retains separate face corners. positionOnly:true welds coincident positions and discards other attributes; use it explicitly when changing topology and regenerate shading/UVs afterward.",
+ example: `const welded = mergeVertices(boxGeo(1, 1, 1), { positionOnly: true });
+const rock = displace(subdivide(welded, 2), ([x,y,z]) => [0.08*Math.sin(y*7+z*3), 0.04*Math.sin(x*9), 0]);`
+ },
+ {
+ name: "curveToMesh",
+ signature: "curveToMesh(points: [x,y,z][], radius, tubularSegs?: 32, radialSegs?: 8, closed?: false)",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Sweeps a circular profile along a path. Equivalent to Blender's Curve to Mesh node with a circle profile. Use for pipes, cables, tubular frames.",
+ example: "const pipe = curveToMesh([[0,0,0],[0,1,0],[1,1,0],[1,2,0]], 0.1);"
+ },
+ {
+ name: "pipeAlongPath",
+ signature: "pipeAlongPath(points: [x,y,z][], radius: number, opts?: { bendRadius?: 0, closed?: false, tubularSegments?: 32, radialSegments?: 8 })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Path-driven swept circle with optional bend smoothing. Generalises beamBetween (point-to-point) and curveToMesh (raw spline) into one helper. bendRadius>0 inserts interpolated waypoints near interior corners so the spline reads as a rounded turn instead of pinching to the control point.",
+ example: "const cable = pipeAlongPath([[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]], 0.02, { bendRadius: 0.1 });"
+ },
+ {
+ name: "lathe",
+ signature: "lathe(profile: [x,y][], segments?: 12)",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Surface of revolution. Spins a 2D profile around the Y axis. For bottles, vases, wheels, turned wood parts.",
+ example: "const vase = lathe([[0.1,0],[0.3,0.5],[0.2,1],[0.1,1.2]], 16);"
+ },
+ {
+ name: "revolveGeo",
+ signature: "revolveGeo(profile: [x,y][], opts?: { angle?: 2π, axis?: [x,y,z]=[0,1,0], segments?: 12 })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Surface of revolution with explicit axis + sweep angle. Generalises lathe — use it when you need a partial sweep (half-dome, 90° wedge) or revolution around a non-Y axis. Profile convention is identical to lathe: x = radial distance, y = position along the axis.",
+ example: `// Half-dome (180° sweep around +Y):
+const quarter = [...Array(8)].map((_, i) => { const t = (i/7)*Math.PI/2; return [Math.cos(t), Math.sin(t)] as [number, number]; });
+const dome = revolveGeo(quarter, { angle: Math.PI });`
+ },
+ {
+ name: "bezierCurve",
+ signature: "bezierCurve(controlPoints: [x,y,z][], samples?: 32)",
+ returns: "[x,y,z][]",
+ category: "curves",
+ description: "Samples a quadratic (3 ctrl pts) or cubic (4 ctrl pts) Bézier into a point list you can feed into curveToMesh.",
+ example: `const path = bezierCurve([[0,0,0],[1,2,0],[3,2,0],[4,0,0]], 24);
+const geo = curveToMesh(path, 0.1);`
+ },
+ {
+ name: "autoUnwrap",
+ signature: "await autoUnwrap(geometry: BufferGeometry, opts?: { resolution?: 1024, padding?: 2, useNormals?: false })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "uv",
+ description: "xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware unwraps below.",
+ example: `const unwrapped = await autoUnwrap(someCsgResult, { resolution: 1024 });
+const mesh = new THREE.Mesh(unwrapped, bakedPbr);`
+ },
+ {
+ name: "boxUnwrap",
+ signature: "boxUnwrap(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Preserves BoxGeometry's built-in per-face UVs — every face maps [0,1] with consistent orientation. Use for crates/blocks with a tileable texture. Sync; no WASM cost.",
+ example: `const crate = boxUnwrap(boxGeo(1, 1, 1));
+const mesh = new THREE.Mesh(crate, pbrMaterial({ albedo: planksTex }));`
+ },
+ {
+ name: "cylinderUnwrap",
+ signature: "cylinderUnwrap(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Preserves CylinderGeometry's built-in UVs: u wraps around the axis (horizontal texture features ring the cylinder), v runs up the height. Caps use circle-in-square. Sync; no WASM cost.",
+ example: `const barrel = cylinderUnwrap(cylinderGeo(0.5, 0.5, 1.2, 24));
+const mesh = new THREE.Mesh(barrel, pbrMaterial({ albedo: bandsTex }));`
+ },
+ {
+ name: "planeUnwrap",
+ signature: "planeUnwrap(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Projects xy-extent of the bbox to [0,1]. Use for signs/decals/posters where you want ONE readable texture and no edge-face bleeding. Sync.",
+ example: `const sign = planeUnwrap(planeGeo(1, 0.6));
+const mesh = new THREE.Mesh(sign, pbrMaterial({ albedo: kilnTextTex }));`
+ },
+ {
+ name: "panelRemapV",
+ signature: "panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Scales an existing UV attribute so a small mesh samples a sub-region of a SHARED texture. Replaces the broken texture.clone() pattern (Three.js Texture.clone() runs JSON.stringify on userData, mangling encoded PNG bytes — panelRemapV avoids that by remapping UVs on the geometry instead). Typical use: multi-zone albedo where v=0..0.30 is plain panel and v=0.30..1 has windows/markings — small parts call panelRemapV(unwrap(geo), 0.30) to sample only the clean strip.",
+ example: `const cowlGeo = panelRemapV(cylinderUnwrap(capsuleXGeo(0.45, 1.0)), 0.30);
+const cowl = new THREE.Mesh(cowlGeo, bodyMat); // SAME bodyMat as fuselage, no clone needed`
+ },
+ {
+ name: "loadApprovedTexture",
+ signature: "await loadApprovedTexture(resourceId)",
+ returns: "Promise<THREE.DataTexture>",
+ category: "textures",
+ description: "Loads one approved kiln.texture.* resource ID through the host-injected closed resolver. The registry fixes bytes, MIME, usage, dimensions, hash, and deadline; paths, URLs, byte arrays, resolver objects, hashes, and options are rejected.",
+ example: "const bark = await loadApprovedTexture('kiln.texture.bark-brown-01-albedo.v1');",
+ promptNotes: "Use only a concrete resource ID listed in material capabilities; never invent one. Prefer materialRecipe when a recipe already binds the family, or proceduralTexture V2 for authored surfaces. NEVER texture.clone() a loaded texture (clone() corrupts encoded bytes and breaks GLB export)."
+ },
+ {
+ name: "proceduralTexture",
+ signature: "proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })",
+ returns: "THREE.DataTexture (tiling, sRGB or linear per usage)",
+ category: "textures",
+ description: "Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.",
+ example: "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",
+ promptNotes: "Sync — no await. Strict V2 JSON boundary: unknown/prototype keys, callbacks, paths, URLs, and shader source are rejected. Prefer this over approved resources for describable surfaces. Max 8 layers, power-of-two size up to 1024. Only the six listed ops exist."
+ },
+ {
+ name: "normalMapFromHeight",
+ signature: "normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })",
+ returns: "THREE.DataTexture (linear normal map)",
+ category: "textures",
+ description: "Derives a tangent-space normal map from the source texture's brightness, treating it as height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at the edges, so a tiling source gives a tiling normal map.",
+ example: `const bark = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] });
+const mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });`,
+ promptNotes: "strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always linear data — never assign it to an albedo/emissive slot."
+ },
+ {
+ name: "pbrMaterial",
+ signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, aoMap?, alphaMode?, alphaCutoff?, doubleSided? })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. Supports OPAQUE/MASK/BLEND and double-sided output.",
+ example: `const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });
+const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });`
+ },
+ {
+ name: "foliageMaterial",
+ signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",
+ example: "const mat = await materialRecipe('kiln.material.leaf.v1');"
+ },
+ {
+ name: "countTriangles",
+ signature: "countTriangles(root: Object3D)",
+ returns: "number",
+ category: "utility",
+ description: "Sums triangle count across every mesh in the subtree.",
+ example: "meta.tris = countTriangles(root);"
+ },
+ {
+ name: "countMaterials",
+ signature: "countMaterials(root: Object3D)",
+ returns: "number",
+ category: "utility",
+ description: "Unique material count (by reference) across the subtree.",
+ example: "const mats = countMaterials(root);"
+ },
+ {
+ name: "getJointNames",
+ signature: "getJointNames(root: Object3D)",
+ returns: "string[]",
+ category: "utility",
+ description: "All node names beginning with `Joint_`. Use to sanity-check animation targets.",
+ example: "const joints = getJointNames(root);"
+ },
+ {
+ name: "validateAsset",
+ signature: "validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture' | 'vegetation' | 'vehicle')",
+ returns: "{ valid, errors, warnings }",
+ category: "utility",
+ description: "Checks geometry and material costs for the selected category. No default triangle limit; choose detail for the intended runtime and inspect measured draw calls.",
+ example: "const v = validateAsset(root, 'prop');"
+ }
+ ];
+});
+
// src/contracts/breadth.ts
function cloneVfxIntentV1(value) {
return {
@@ -7288,7 +8210,7 @@ function rethrowAuthoringError(error) {
}
throw error;
}
-var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", AuthoringDiagnosticError;
+var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_list_primitives to confirm the exact name and signature; the sandbox exposes only those globals.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", AuthoringDiagnosticError;
var init_authoring_diagnostic = __esm(() => {
AuthoringDiagnosticError = class AuthoringDiagnosticError extends Error {
diagnostic;
@@ -19950,8 +20872,74 @@ function validate(code, _opts = {}) {
line: smell.line
});
}
+ warnings.push(...unknownHelperWarnings(ast));
return toResult(issues, warnings, analysis.estimatedTris);
}
+function unknownHelperWarnings(ast) {
+ const declared = new Set;
+ const bind = (node) => {
+ const target = node;
+ if (!target?.type)
+ return;
+ if (target.type === "Identifier")
+ declared.add(target["name"]);
+ else if (target.type === "ObjectPattern")
+ for (const prop of target["properties"])
+ bind(prop.value ?? prop.argument);
+ else if (target.type === "ArrayPattern")
+ for (const el of target["elements"])
+ bind(el);
+ else if (target.type === "AssignmentPattern")
+ bind(target["left"]);
+ else if (target.type === "RestElement")
+ bind(target["argument"]);
+ };
+ const params = (node) => {
+ const fn = node;
+ if (fn.id?.name)
+ declared.add(fn.id.name);
+ for (const param of fn.params ?? [])
+ bind(param);
+ };
+ walk.simple(ast, {
+ VariableDeclarator(node) {
+ bind(node.id);
+ },
+ FunctionDeclaration(node) {
+ params(node);
+ },
+ FunctionExpression(node) {
+ params(node);
+ },
+ ArrowFunctionExpression(node) {
+ params(node);
+ },
+ ClassDeclaration(node) {
+ params(node);
+ },
+ CatchClause(node) {
+ bind(node.param);
+ }
+ });
+ const seen = new Map;
+ walk.simple(ast, {
+ CallExpression(node) {
+ const callee = node.callee;
+ if (callee?.type !== "Identifier" || !callee.name)
+ return;
+ const name = callee.name;
+ if (declared.has(name) || SANDBOX_CALLABLES.has(name) || seen.has(name))
+ return;
+ seen.set(name, node.loc?.start?.line);
+ }
+ });
+ return [...seen].map(([name, line]) => ({
+ code: "UNKNOWN_HELPER",
+ message: `${name}() is not declared in this program and is not a Kiln sandbox global; the build will fail when it runs.`,
+ fixHint: "Call kiln_list_primitives to confirm the helper name and signature, or declare the function in this program.",
+ ...line === undefined ? {} : { line }
+ }));
+}
function assertGeneratedSourceSafe(code) {
let ast;
try {
@@ -20466,8 +21454,45 @@ function hasBreak(body) {
});
return found;
}
-var GeneratedSourcePolicyError, FORBIDDEN_AMBIENT_IDENTIFIERS, FORBIDDEN_THREE_CONSTRUCTORS, ROTATION_OPTION_FNS;
+var SANDBOX_CALLABLES, GeneratedSourcePolicyError, FORBIDDEN_AMBIENT_IDENTIFIERS, FORBIDDEN_THREE_CONSTRUCTORS, ROTATION_OPTION_FNS;
var init_validation = __esm(() => {
+ init_list_primitives();
+ SANDBOX_CALLABLES = new Set([
+ ...listPrimitives().map((primitive) => primitive.name),
+ "Array",
+ "BigInt",
+ "Boolean",
+ "Error",
+ "Float32Array",
+ "Float64Array",
+ "Int16Array",
+ "Int32Array",
+ "Int8Array",
+ "Map",
+ "Number",
+ "Object",
+ "Promise",
+ "Proxy",
+ "RangeError",
+ "Reflect",
+ "RegExp",
+ "Set",
+ "String",
+ "Symbol",
+ "TypeError",
+ "Uint16Array",
+ "Uint32Array",
+ "Uint8Array",
+ "WeakMap",
+ "WeakSet",
+ "decodeURIComponent",
+ "encodeURIComponent",
+ "isFinite",
+ "isNaN",
+ "parseFloat",
+ "parseInt",
+ "structuredClone"
+ ]);
GeneratedSourcePolicyError = class GeneratedSourcePolicyError extends Error {
code;
line;
@@ -25920,920 +26945,8 @@ import {
} from "@strands-agents/sdk";
import { AgentSkills } from "@strands-agents/sdk/vended-plugins/skills";
-// src/geometry-catalog.ts
-var geometryPrimitives = [
- {
- name: "copyGeometry",
- signature: "copyGeometry(geometry: BufferGeometry)",
- returns: "THREE.BufferGeometry",
- category: "instancing",
- description: "Returns an independent geometry with copied vertex buffers. Use before direct mutation of a cached primitive.",
- example: "const editable = copyGeometry(boxGeo(1, 1, 1)); editable.translate(0, 0.5, 0);"
- },
- {
- name: "copyMaterial",
- signature: "copyMaterial(material: Material)",
- returns: "THREE.Material (same subtype)",
- category: "instancing",
- description: "Copies material properties so edits do not change other parts. Referenced textures remain shared.",
- example: "const red = copyMaterial(steel); red.color.set(0xaa2222);"
- },
- {
- name: "meshGeo",
- signature: "meshGeo({ positions: number[], indices?: number[], normals?: number[], uvs?: number[], tangents?: number[] })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Builds an owned triangle mesh from flat numeric arrays. Validates finite values, attribute lengths and indices; computes normals if absent. Counterclockwise winding.",
- example: "const triangle = meshGeo({ positions: [0,0,0, 1,0,0, 0,1,0], indices: [0,1,2] });"
- },
- {
- name: "parametricSurface",
- signature: "parametricSurface(sample: (u,v) => [x,y,z], opts?: { u?: [0,1], v?: [0,1], uSegments?: 24, vSegments?: 24, periodicU?: false, periodicV?: false, orientation?: 'uv'|'vu' })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Samples an equation into an owned surface with UVs. Periodic endpoints must coincide; UV seams retain matching normals. A surface is not automatically a watertight solid.",
- example: "const canopy = parametricSurface((u,v) => [u, 0.3*Math.sin(u*3)*Math.cos(v*2), v], { u: [-2,2], v: [-1,1] });"
- },
- {
- name: "geometryDiagnostics",
- signature: "geometryDiagnostics(geometry: BufferGeometry, tolerance?: 1e-6)",
- returns: "{ vertices, triangles, boundaryEdges, nonManifoldEdges, orientationConflicts, degenerateTriangles, invalidIndices, nonFiniteVertices }",
- category: "utility",
- description: "Counts mesh topology problems after position-based seam matching. Open boundaries are valid for sheets; closed edges alone do not prove a self-intersection-free solid.",
- example: "const topology = geometryDiagnostics(shell);"
- },
- {
- name: "creaseNormals",
- signature: "creaseNormals(geometry: BufferGeometry, opts?: { angle?: 60, tolerance?: number })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Returns owned geometry with angle-limited smooth normals, preserving UV corners. Angle is degrees. Invalidates tangents; use after shaping for sharp rims and smooth walls.",
- example: "const shell = creaseNormals(cylinderGeo(1,1,2,32), { angle: 45 });"
- },
- {
- name: "bend",
- signature: "bend(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Bends local +Y toward +X through angle degrees. Returns owned geometry and updated normals/bounds; preserves UVs, invalidates tangents. Frame rotation is Euler XYZ degrees.",
- promptNotes: "Deformation interval uses local Y distances; outside vertices stay unchanged. Add enough segments before bending. Falloff returns 0..1; use it to avoid a discontinuity at a selected interval boundary.",
- example: "const arch = bend(planeGeo(1,4,4,32), { angle: 90 });"
- },
- {
- name: "twist",
- signature: "twist(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Rotates the cross-section progressively around local +Y, reaching angle degrees at the end. Returns owned geometry; frame rotation uses Euler XYZ degrees.",
- example: "const spiral = twist(column, { angle: 120 });"
- },
- {
- name: "taper",
- signature: "taper(geometry, { startScale?: [1,1], endScale: [x,z], frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Scales local X/Z across the local Y interval using positive start/end scale pairs. Returns owned geometry; preserves UVs and invalidates tangents.",
- example: "const narrowed = taper(column, { endScale: [0.4,0.7] });"
- },
- {
- name: "displace",
- signature: "displace(geometry, offset: ([x,y,z], t) => [dx,dy,dz], opts?: { frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Adds an authored displacement vector in the chosen local frame. Returns owned geometry; callback coordinates are local and t is normalized along the interval.",
- example: "const rippled = displace(surface, ([x,y,z]) => [0, 0.1*Math.sin(x*8), 0]);"
- },
- {
- name: "sweepProfile",
- signature: "sweepProfile(profile: [x,z][], path: [x,y,z][], opts?: { cap?: true, closed?: false, up?: [x,y,z], twist?: 0, scale?: number | [x,z][] })",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Sweeps a simple noncircular profile along polyline stations using transported frames. Supports total twist in degrees and per-station scales. Generates UVs and optional caps.",
- promptNotes: "First version supports one simple profile without holes. Closed paths omit the repeated endpoint and require twist to be a multiple of 360. up sets the initial profile +Z direction and cannot parallel the path. Tight-turn warnings do not replace visual inspection for self-intersections.",
- example: "const rail = sweepProfile([[-.1,-.2],[.1,-.2],[.1,.2],[-.1,.2]], [[0,0,0],[0,1,0],[1,2,0]]);"
- },
- {
- name: "loftProfiles",
- signature: "loftProfiles(sections: { profile: [x,z][], frame?: { origin, rotation } }[], opts?: { cap?: true })",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Joins corresponding simple profiles in explicit local XZ planes. Each frame uses Euler XYZ degrees and local +Y along the loft. Profiles need equal point counts and corresponding vertices.",
- promptNotes: "No holes or automatic profile correspondence. Opposite winding is normalized while preserving the first point. Caps close boundaries but do not prove the loft has no self-intersections.",
- example: "const hull = loftProfiles([{ profile: wide }, { profile: narrow, frame: { origin: [0,2,0] } }]);"
- },
- {
- name: "implicitSurface",
- signature: "await implicitSurface(sample: ([x,y,z]) => signedValue, { bounds: { min, max }, edgeLength, maxCells?: 1000000, maxEvaluations?: 8000000, level?: 0, tolerance?: -1, smooth?: true })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "geometry",
- description: "Experimental positive-inside implicit field sampled into a solid mesh. Requires explicit bounds and resolution; checks grid size and actual evaluation count. Output has no UVs.",
- promptNotes: "Use async build and await. Smaller edgeLength increases cost sharply. This helper cannot stop a callback that never returns; the host evaluator process provides that boundary. Thin features and geometric accuracy require inspection.",
- example: "const blob = await implicitSurface(([x,y,z]) => 1-Math.hypot(x,y,z), { bounds: { min: [-1.2,-1.2,-1.2], max: [1.2,1.2,1.2] }, edgeLength: 0.15 });"
- }
-];
-
-// src/list-primitives.ts
-var PRIMITIVES = [
- ...geometryPrimitives,
- {
- name: "createRoot",
- signature: "createRoot(name: string)",
- returns: "THREE.Object3D",
- category: "structure",
- description: "Creates the root Object3D for an asset. Call first in build().",
- example: "const root = createRoot('FuelDrum');"
- },
- {
- name: "createPivot",
- signature: "createPivot(name: string, position?: [x, y, z], parent?: Object3D)",
- returns: "THREE.Object3D (prefixed `Joint_`)",
- category: "structure",
- description: "Creates an empty pivot node for skeletal animation. Name is auto-prefixed with `Joint_`.",
- example: "const hip = createPivot('Hip', [0, 1, 0], root);"
- },
- {
- name: "createJointChain",
- signature: "createJointChain(name, segments: { role, offset, aliases?, side?, localForwardAxis?, localBendAxis?, endEffector?, contact? }[], opts?: { parent?, parentRole? })",
- returns: "{ root, end, nodes, byRole, descriptors }",
- category: "structure",
- description: "Creates one body-plan-neutral deterministic Joint_* chain with explicit parent edges, rest frames, local axes, end effectors, contacts, and semantic metadata.",
- example: "const leg = createJointChain('LegL', [{ role: 'hip.left', offset: [0, 1, -0.2], side: 'left' }, { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' }, { role: 'ankle.left', offset: [0, -0.5, 0], side: 'left', endEffector: true, contact: true }], { parent: root });",
- promptNotes: "Use only the resolved body-plan graph. Offsets are local to the previous joint; contact end effectors must land at world Y=0."
- },
- {
- name: "createVehicleFrame",
- signature: "createVehicleFrame(name, opts?: { chassis?, axles?, seats?, contacts?, steering?, propulsion?, parent? })",
- returns: "{ root, chassis, axles, seats, contacts, steering, propulsion }",
- category: "structure",
- description: "Creates a canonical +X-forward/+Y-up/+Z-right vehicle frame with typed semantic sockets for chassis, support, steering, and propulsion.",
- example: "const frame = createVehicleFrame('CarFrame', { axles: [{ id: 'front', position: [1.2, 0.45, 0] }, { id: 'rear', position: [-1.2, 0.45, 0] }], parent: root });",
- promptNotes: "Generated vehicles keep +X as front. Boats and other non-wheeled subtypes use declared support/propulsion sockets, not wheel rules."
- },
- {
- name: "createWheelGeometrySet",
- signature: "createWheelGeometrySet(radius: number, width: number)",
- returns: "{ tire, rim, hub } shared THREE.BufferGeometry set",
- category: "instancing",
- description: "Creates one reusable +Z-axle tire/rim/hub geometry set for instanced wheel assemblies.",
- example: "const wheelGeo = createWheelGeometrySet(0.45, 0.22);"
- },
- {
- name: "createWheelAssembly",
- signature: "createWheelAssembly(name, { tire, rim, hub? }, { radius, width, side, index, position?, rimRadius?, hubRadius?, steering?, loadBearing?, geometries?, parent? })",
- returns: "{ root, steeringPivot?, spinPivot, tire, rim, hub, contact, radius, width, side, index, spinAxis }",
- category: "structure",
- description: "Creates one axle-centered wheel pivot containing concentric tire/rim/hub roles, a contact marker, +Z spin frame, and optional steering pivot.",
- example: "createWheelAssembly('FrontLeft', { tire: rubber, rim: metal }, { radius: 0.45, width: 0.22, side: 'left', index: 'front', position: [1.2, 0.45, -0.9], steering: true, geometries: wheelGeo, parent: frame.root });",
- promptNotes: "Keep tire, rim, and hub descendants concentric at the axle pivot. Reuse one geometry set across matching wheels."
- },
- {
- name: "createPart",
- signature: "createPart(name, geometry, material, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, pivot, parent })",
- returns: "THREE.Object3D (mesh or wrapping pivot)",
- category: "structure",
- description: "Creates a mesh, optionally wrapped in a pivot, and attaches it to `opts.parent`. `rotation` is in DEGREES (like rotationTrack), NOT radians: [0, 0, 90] is a quarter turn; [0, 0, 1.57] is a no-op.",
- example: "createPart('Barrel', cylinderGeo(0.1, 0.1, 1), gameMaterial(0x556b2f), { position: [0, 0.5, 0], rotation: [0, 0, 90], parent: root });",
- promptNotes: "AUTO-ADDS to opts.parent. NEVER call parent.add(createPart(...)) — pass { parent } instead. rotation is DEGREES — writing radians (e.g. 0.785 or Math.PI/4) silently produces ~zero rotation."
- },
- {
- name: "beamBetween",
- signature: "beamBetween(name, start: [x,y,z], end: [x,y,z], radius, material, opts?: { segments, parent })",
- returns: "THREE.Object3D (prefixed `Mesh_`)",
- category: "structure",
- description: "Creates a cylindrical rail/strut exactly between two endpoints. Use for braces, gun barrels, skid struts, cables, and scaffolding.",
- example: "beamBetween('SkidBraceA', [0.8, 0.3, 0.7], [0.8, 1.0, 0.45], 0.025, black, { parent: root });"
- },
- {
- name: "snapTo",
- signature: "snapTo(part: Object3D, host: Object3D, opts?: { axis?: 'x'|'y'|'z', overlap?: 0.02 })",
- returns: "THREE.Object3D (the part, for chaining)",
- category: "structure",
- description: 'Translates `part` by the minimal vector that brings its bounding box into contact with `host` (plus a small overlap). The direct cure for a "Floating parts" warning — attach the part instead of eyeballing a corrective offset. No-op if they already touch.',
- example: `const scope = createPart('Scope', cylinderXGeo(0.04, 0.04, 0.3), steel, { parent: root, position: [0.1, 0.32, 0] });
-snapTo(scope, receiver);`
- },
- {
- name: "createLadder",
- signature: "createLadder(name, { bottom, top, material, width?, rungCount?, railRadius?, rungRadius?, widthAxis?, parent? })",
- returns: "{ leftRail: Object3D, rightRail: Object3D, rungs: Object3D[] }",
- category: "structure",
- description: "Builds two continuous rails plus evenly-spaced rungs. Use this instead of loose boxes for ladders.",
- example: "createLadder('TowerLadder', { bottom: [0,0,0], top: [0,2.2,0], width: 0.45, rungCount: 7, material: steel, parent: root });"
- },
- {
- name: "createWingPair",
- signature: "createWingPair(name, material, { rootZ, span, rootChord, tipChord, sweep?, thickness?, dihedral?, rootX?, rootY?, parent? })",
- returns: "{ right: Object3D, left: Object3D }",
- category: "structure",
- description: "Creates mirrored trapezoid aircraft wings with roots attached at +/-rootZ. Use for aircraft wings and helicopter stub wings.",
- example: "createWingPair('MainWing', olive, { rootX: 0, rootY: 1.0, rootZ: 0.42, span: 2.4, rootChord: 0.9, tipChord: 0.35, sweep: 0.25, dihedral: 0.08, parent: root });"
- },
- {
- name: "room",
- signature: "room(name, material, { width?, depth?, height?, wallThickness?, floor?, floorThickness?, openings?: [{ wall: 'front'|'back'|'left'|'right', kind?: 'door'|'window', offset?, width?, height?, sill? }], parent? })",
- returns: "{ root: Object3D, walls: { front, back, left, right }, floor: Object3D | null }",
- category: "structure",
- description: "Builds a HOLLOW, enterable room: four thin walls + a floor, human-scaled (defaults: 2.8m ceiling, a centered 1.1x2.1m front door so it is enterable by default). `front` faces +X; the floor sits on the ground. The keystone of an architecture asset — add a roof with createRoofPlanes and fixtures as separate parts.",
- example: "const { root: hut } = room('Hut', wood, { width: 5, depth: 4, height: 2.8, openings: [{ wall: 'front', kind: 'door' }, { wall: 'right', kind: 'window' }], parent: root });",
- promptNotes: "Use for any building the player enters. Do NOT model a building as a solid block — room() guarantees real interior space and a doorway gap. Pass openings to add windows / side doors."
- },
- {
- name: "wallWithOpening",
- signature: "wallWithOpening(name, material, { length, height, thickness, axis?: 'x'|'z', opening?: { kind?: 'door'|'window', offset?, width?, height?, sill? }, parent? })",
- returns: "THREE.Object3D (wall container)",
- category: "structure",
- description: "A single wall panel with an optional real door/window cut, composed from solid box segments (side panels + lintel + window sill) — no CSG. Base at local Y=0, centered on the run axis. Use to compose custom building layouts or interior dividing walls beyond the default room().",
- example: "wallWithOpening('Partition', plaster, { length: 4, height: 2.8, thickness: 0.12, axis: 'x', opening: { kind: 'door', offset: 0.5 }, parent: root });"
- },
- {
- name: "createRoofPlanes",
- signature: "createRoofPlanes(name, material, { width, depth, height, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",
- returns: "{ root: Object3D, slopes: [Object3D, Object3D] }",
- category: "structure",
- description: "A pitched roof: two thin slopes meeting at one ridge and falling DOWN-AND-OUTWARD (opposite tilts — never mirrored the same way), footprint-matched with an eave overhang. Eave at local Y=0, ridge at Y=height, so position the group at Y=wallHeight. Returns a named group (e.g. `Roof`) the engine can lift to reveal the interior.",
- example: `const { root: roof } = createRoofPlanes('Roof', shingle, { width: 5, depth: 4, height: 1.6, overhang: 0.4, ridgeAxis: 'x', parent: root });
-roof.position.y = 2.8;`,
- promptNotes: "The two slopes must fall AWAY from each other from the ridge — createRoofPlanes does this for you. Drop it onto the walls (position.y = wall height)."
- },
- {
- name: "createGableRoof",
- signature: "createGableRoof(name, material, { spanX, spanZ, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",
- returns: "{ root, slopes: [Object3D, Object3D], faces: [RoofFaceFrame, RoofFaceFrame], rise, pitchDegrees }",
- category: "structure",
- description: "Explicit-axis gable roof using unambiguous footprint spans. Each face owns a rigid frame with ridge tangent, outward normal, downhill direction, ridge/eave endpoints, dimensions, and a live local-to-world transform.",
- example: "const roof = createGableRoof('Roof', shingles, { spanX: 8, spanZ: 5, pitchDegrees: 35, overhang: 0.35, ridgeAxis: 'x', parent: root });",
- promptNotes: "Prefer this over width/depth roof math. ridgeAxis is the direction of the ridge; roof panels run along each returned face downhill direction."
- },
- {
- name: "createGableEndPanel",
- signature: "createGableEndPanel(name, material, { span, rise, thickness?, ridgeAxis?: 'x'|'z', side?: 'positive'|'negative', openings?: [{ id?, offset?, bottom?, width, height }], parent? })",
- returns: "{ root, geometry, openings }",
- category: "structure",
- description: "Exact thick triangular end closure for a gable roof, with optional rectangular openings cut from the geometry and semantic boundary metadata.",
- example: "createGableEndPanel('FrontGable', siding, { span: 5, rise: 1.8, ridgeAxis: 'x', side: 'positive', parent: root });"
- },
- {
- name: "createGableShell",
- signature: "createGableShell(name, { wall, roof, floor?, gable? }, { spanX, spanZ, wallHeight?, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, wallThickness?, floorThickness?, closedEnds?, enterable?, openings?, gableOpenings?, parent? })",
- returns: "{ root, walls, floor, roof, gables, openings }",
- category: "structure",
- description: "Closed-by-default, correct-by-construction gable building: hollow room, floor, two opposing roof slopes, two complete gable ends, and a real front doorway when enterable.",
- example: "const house = createGableShell('House', { wall: plaster, roof: shingles }, { spanX: 8, spanZ: 5, wallHeight: 2.8, pitchDegrees: 35, ridgeAxis: 'x', parent: root });",
- promptNotes: "Use for complete gable buildings. It stamps wall, floor, slope, gable, opening, adjacency, coverage, and separability semantics for deterministic QA and roof-off views."
- },
- {
- name: "createRoofSurfaceLayout",
- signature: "createRoofSurfaceLayout(name, material, { face, kind: 'panels'|'shingles'|'seams'|'corrugations', parent?, panelWidth?, rowHeight?, spacing?, thickness? })",
- returns: "{ root, items: Object3D[] }",
- category: "structure",
- description: "Places roof-local panels, shingles, seams, or corrugations from a returned RoofFaceFrame, so repeated elements run ridge-to-eave for either ridge axis without manual Euler rotations.",
- example: "for (const face of roof.faces) createRoofSurfaceLayout('Panels_' + face.side, metal, { face, kind: 'panels', parent: roof.root });",
- promptNotes: "Always pass the face object returned by createGableRoof/createGableShell. Never infer the panel rotation from world axes."
- },
- {
- name: "createStairs",
- signature: "createStairs(name, material, { steps?, totalRise, totalRun, width, axis?: 'x'|'z', treadThickness?, riser?, parent? })",
- returns: "{ root: Object3D, steps: Object3D[] }",
- category: "structure",
- description: "A straight flight of stairs: box treads (with optional risers) climbing totalRise over totalRun from local origin toward +axis. Use for porch/entry steps or to connect storeys in a multi-storey building.",
- example: "createStairs('Porch', stone, { steps: 4, totalRise: 0.6, totalRun: 1.0, width: 1.4, axis: 'x', parent: root });"
- },
- {
- name: "boxGeo",
- signature: "boxGeo(width: number, height: number, depth: number)",
- returns: "THREE.BoxGeometry",
- category: "geometry",
- description: "6-face box. 12 tris regardless of size. Cheapest geometry.",
- example: "const geo = boxGeo(1, 0.5, 2);"
- },
- {
- name: "sphereGeo",
- signature: "sphereGeo(radius: number, widthSegments?: 8, heightSegments?: 6)",
- returns: "THREE.SphereGeometry",
- category: "geometry",
- description: "UV sphere. Default 8x6 segments = 84 tris. Bump segments for smoother curves.",
- example: "const geo = sphereGeo(0.5, 12, 8);"
- },
- {
- name: "cylinderGeo",
- signature: "cylinderGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",
- returns: "THREE.CylinderGeometry",
- category: "geometry",
- description: "Y-axis cylinder. Use radiusTop != radiusBottom for cones / tapered pieces.",
- example: "const geo = cylinderGeo(0.25, 0.25, 1, 12);"
- },
- {
- name: "cylinderYGeo",
- signature: "cylinderYGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",
- returns: "THREE.CylinderGeometry",
- category: "geometry",
- description: "Alias for cylinderGeo — a Y-axis cylinder. Provided because the sandbox exposes cylinderXGeo / cylinderZGeo and the symmetric Y form is commonly reached for.",
- example: "const geo = cylinderYGeo(0.25, 0.25, 1, 12);"
- },
- {
- name: "cylinderXGeo",
- signature: "cylinderXGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",
- returns: "THREE.CylinderGeometry",
- category: "geometry",
- description: "Cylinder pre-rotated to run along +X/-X. Use for fuselages, cannons, barrels, axles, and forward-facing tubes.",
- example: "const geo = cylinderXGeo(0.1, 0.1, 1.2, 12);"
- },
- {
- name: "cylinderZGeo",
- signature: "cylinderZGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",
- returns: "THREE.CylinderGeometry",
- category: "geometry",
- description: "Cylinder pre-rotated to run along +Z/-Z. Use for side-mounted weapons, rails, crossbars, and pipes.",
- example: "const geo = cylinderZGeo(0.08, 0.08, 0.9, 10);"
- },
- {
- name: "cylinderOnAxis",
- signature: "cylinderOnAxis(center: [x,y,z], normal: [x,y,z], radiusBottom: number, height: number, opts?: { radiusTop?, segments? })",
- returns: "THREE.CylinderGeometry",
- category: "geometry",
- description: "Frame-first cylinder: position + axis specified directly, no post-hoc rotation. Use when the cylinder needs to point along a non-cardinal direction (struts inside CSG operands, antennas off a tilted surface). For cardinal axes prefer the terser cylinderXGeo / cylinderYGeo / cylinderZGeo helpers.",
- example: "const strut = cylinderOnAxis([0.5, 0.7, 0], [1, 1, 0.3], 0.05, 0.9);"
- },
- {
- name: "capsuleGeo",
- signature: "capsuleGeo(radius: number, height: number, segments?: 6)",
- returns: "THREE.CapsuleGeometry",
- category: "geometry",
- description: "Stadium shape (cylinder with hemispherical caps). Good for limbs.",
- example: "const geo = capsuleGeo(0.1, 0.5, 6);"
- },
- {
- name: "capsuleYGeo",
- signature: "capsuleYGeo(radius: number, height: number, segments?: 6)",
- returns: "THREE.CapsuleGeometry",
- category: "geometry",
- description: "Alias for capsuleGeo — a Y-axis capsule. Provided for symmetry with capsuleXGeo / capsuleZGeo.",
- example: "const geo = capsuleYGeo(0.1, 0.5, 6);"
- },
- {
- name: "capsuleXGeo",
- signature: "capsuleXGeo(radius: number, length: number, segments?: 6)",
- returns: "THREE.CapsuleGeometry",
- category: "geometry",
- description: "Capsule pre-rotated to run along +X/-X. Use for aircraft bodies, rounded vehicle hulls, and missiles.",
- example: "const geo = capsuleXGeo(0.35, 2.4, 10);"
- },
- {
- name: "capsuleZGeo",
- signature: "capsuleZGeo(radius: number, length: number, segments?: 6)",
- returns: "THREE.CapsuleGeometry",
- category: "geometry",
- description: "Capsule pre-rotated to run along +Z/-Z. Use for lateral pods, floats, and side tanks.",
- example: "const geo = capsuleZGeo(0.18, 1.1, 8);"
- },
- {
- name: "coneGeo",
- signature: "coneGeo(radius: number, height: number, segments?: 8)",
- returns: "THREE.ConeGeometry",
- category: "geometry",
- description: "Y-axis cone (pointed up). Use for spikes, roofs, projectiles.",
- example: "const geo = coneGeo(0.3, 0.8, 8);"
- },
- {
- name: "coneYGeo",
- signature: "coneYGeo(radius: number, height: number, segments?: 8)",
- returns: "THREE.ConeGeometry",
- category: "geometry",
- description: "Alias for coneGeo — a Y-axis cone (point +Y). Provided for symmetry with coneXGeo / coneZGeo.",
- example: "const geo = coneYGeo(0.3, 0.8, 8);"
- },
- {
- name: "coneXGeo",
- signature: "coneXGeo(radius: number, length: number, segments?: 8)",
- returns: "THREE.ConeGeometry",
- category: "geometry",
- description: "Cone pre-rotated so its point faces +X. Use for noses, rockets, shells, and forward-facing tips.",
- example: "const geo = coneXGeo(0.18, 0.45, 12);"
- },
- {
- name: "coneZGeo",
- signature: "coneZGeo(radius: number, length: number, segments?: 8)",
- returns: "THREE.ConeGeometry",
- category: "geometry",
- description: "Cone pre-rotated so its point faces +Z. Use for side-facing projectiles and tips.",
- example: "const geo = coneZGeo(0.12, 0.35, 10);"
- },
- {
- name: "taperConeGeo",
- signature: "taperConeGeo(radiusBottom: number, radiusTop: number, height: number, axis?: 'x'|'y'|'z', segments?: 8)",
- returns: "THREE.CylinderGeometry",
- category: "geometry",
- description: "Truncated cone (frustum) — exposes both bottom and top radius. radiusTop=0 matches coneGeo, radiusTop=radiusBottom matches cylinderGeo. Use for pylon caps, soda cans, lampshades, anything tapered that does not come to a point. axis selects orientation (default Y).",
- example: "const cap = taperConeGeo(0.3, 0.18, 0.4); // frustum"
- },
- {
- name: "torusGeo",
- signature: "torusGeo(radius: number, tube: number, radialSegments?: 8, tubularSegments?: 12)",
- returns: "THREE.TorusGeometry",
- category: "geometry",
- description: "Donut shape. For rings, tyres, barrel ribs.",
- example: "const geo = torusGeo(0.4, 0.04, 8, 16);"
- },
- {
- name: "planeGeo",
- signature: "planeGeo(width: number, height: number, widthSegments?: 1, heightSegments?: 1)",
- returns: "THREE.PlaneGeometry",
- category: "geometry",
- description: "Flat quad for TEXTURED surfaces (ground, signs, walls with albedo maps). For solid-color decals like red stars, hull numbers, stamps, or window cutouts on no-texture assets use decalBox — a bare planeGeo without a texture will render as a disconnected 2-tri square and get flagged as a stray plane.",
- example: "const geo = planeGeo(4, 4);"
- },
- {
- name: "decalBox",
- signature: "decalBox(width: number, height: number, depth?: 0.01)",
- returns: "THREE.BoxGeometry",
- category: "geometry",
- description: "Thin box for solid-color surface decals: red stars, hull numbers, stamps, no-texture windows. Unlike planeGeo, has real depth so it visibly attaches to its host surface. Must be placed on a surface with position + rotation.",
- example: `const star = decalBox(0.18, 0.18, 0.01);
-createPart('Mesh_StarPort', star, gameMaterial(0xc61f2a), { position: [0.4, 0.6, 0.41], parent: fuselage });`,
- promptNotes: "Offset at least 0.01 outside the host surface to avoid z-fighting (a 0.8-wide hull has faces at z=±0.4, so place the decal at z=±0.41)."
- },
- {
- name: "foliageCardGeo",
- signature: "foliageCardGeo(opts?: { width?, height?, yPivot?: 0..1 })",
- returns: "THREE.PlaneGeometry",
- category: "geometry",
- description: "Single-quad foliage card with a configurable Y pivot. yPivot=0 plants the quad on the ground. Pair with an alpha-tested material and a leaf/plant sprite.",
- example: `const leaves = await materialRecipe('kiln.material.leaf.v1');
-const quad = foliageCardGeo({ width: 4, height: 6, yPivot: 0 });
-createPart('Mesh_Fern', quad, leaves, { parent: root });`
- },
- {
- name: "crossedQuadsGeo",
- signature: "crossedQuadsGeo(opts?: { width?, height?, planes?: 2 | 3, yPivot? })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Cross-billboard bush primitive: 2 or 3 planes intersecting along the Y axis. Reads as a dense plant from any angle, cheaper than real geometry.",
- example: `const leaves = await materialRecipe('kiln.material.leaf.v1');
-const bush = crossedQuadsGeo({ width: 2, height: 2, planes: 3 });
-createPart('Mesh_Bush', bush, leaves, { parent: root });`
- },
- {
- name: "octaGridPlane",
- signature: "octaGridPlane({ tilesX, tilesY, width?, height?, yPivot? })",
- returns: "THREE.PlaneGeometry",
- category: "geometry",
- description: "Atlas-ready billboard quad. UVs are pre-scaled to cover one tile of a tilesX×tilesY atlas; the consumer shader adds per-instance tile offsets at draw time.",
- example: "const card = octaGridPlane({ tilesX: 4, tilesY: 4, width: 6, height: 6 });"
- },
- {
- name: "wingGeo",
- signature: "wingGeo(opts?: { span, rootChord, tipChord, sweep, thickness, dihedral })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Trapezoid wing panel. Local root edge is at Z=0, span extends toward +Z, positive sweep moves the tip aft along -X.",
- example: "const geo = wingGeo({ span: 2.2, rootChord: 0.8, tipChord: 0.3, sweep: 0.25, dihedral: 0.08 });"
- },
- {
- name: "gearGeo",
- signature: "gearGeo(opts?: { teeth?: 12, rootRadius?: 0.8, tipRadius?: 1.0, boreRadius?: 0.2, height?: 0.3, toothWidthFrac?: 0.5 })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Stylized gear with flat edges and an optional center bore; no CSG. Use boreRadius < rootRadius < tipRadius. Radii are absolute: an omitted rootRadius stays 0.8 when tipRadius changes. Set all three radii for small gears.",
- example: `const g = gearGeo({ teeth: 28, rootRadius: 0.063, tipRadius: 0.075, boreRadius: 0.012, height: 0.024 });
-createPart('Gear', g, gameMaterial(0x909090, { metalness: 0.8 }), { parent: root });`
- },
- {
- name: "bladeGeo",
- signature: "bladeGeo(opts?: { length?: 1.5, baseWidth?: 0.1, thickness?: 0.015, tipLength?: 0.25, edgeBevel?: 0 })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Parametric sword blade: rectangular base tapering to a point over tipLength. edgeBevel > 0 pinches the cross-section toward a diamond ridge.",
- example: `const b = bladeGeo({ length: 1.6, baseWidth: 0.09, tipLength: 0.3, edgeBevel: 0.5 });
-createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`
- },
- {
- name: "gameMaterial",
- signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })",
- returns: "THREE.MeshStandardMaterial",
- category: "material",
- description: "Flat-shaded PBR material. Default for game-ready low-poly. Use for 95% of parts.",
- example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9 });"
- },
- {
- name: "materialRecipe",
- signature: "await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })",
- returns: "Promise<THREE.MeshStandardMaterial>",
- category: "material",
- description: "Resolves a versioned portable bark/leaf/wood/stone/rubber/painted-metal/cloth/skin/glass/emissive recipe to standard glTF PBR.",
- example: "const bark = await materialRecipe('kiln.material.bark.v1', { baseColor: '#6b4328' });",
- promptNotes: "Use only listed kiln.material.*.v1 IDs and approved kiln.texture.* resource IDs. Leaf is MASK, glass is BLEND, and host file paths are forbidden."
- },
- {
- name: "compilePortableMaterialSpecV2",
- signature: "await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', name?, baseColor?, roughness?, metalness?, emissive?, emissiveIntensity?, alphaMode?, alphaCutoff?, doubleSided?, textures?: { baseColor?, normal?, metallicRoughness?, emissive?, occlusion? } })",
- returns: "Promise<THREE.MeshStandardMaterial>",
- category: "material",
- description: "Compiles the strict portable material contract. Texture refs are either typed procedural V2 specs or closed approved kiln.texture.* IDs; paths, URLs, raw textures, callbacks, and shader source are rejected.",
- example: "const steel = await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', roughness: 0.45, metalness: 0.85, textures: { metallicRoughness: { kind: 'procedural', spec: { schemaVersion: 2, usage: 'metallicRoughness', size: 64, layers: [{ op: 'solid', color: 0x0080cc }] } } } });",
- promptNotes: "Use metallicRoughness as one packed G=roughness/B=metalness map. Every procedural ref usage must match its slot; resource refs must be approved for that exact slot."
- },
- {
- name: "basicMaterial",
- signature: "basicMaterial(color, opts?: { transparent, opacity })",
- returns: "THREE.MeshBasicMaterial",
- category: "material",
- description: "Unlit flat material. For UI / effects where lighting is baked in.",
- example: "const mat = basicMaterial(0xffffff, { transparent: true, opacity: 0.5 });"
- },
- {
- name: "glassMaterial",
- signature: "glassMaterial(color, opts?: { opacity, roughness, metalness })",
- returns: "THREE.MeshStandardMaterial",
- category: "material",
- description: "Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.",
- example: "const mat = glassMaterial(0x66ccff, { opacity: 0.3 });"
- },
- {
- name: "lambertMaterial",
- signature: "lambertMaterial(color, opts?: { flatShading, emissive })",
- returns: "THREE.MeshLambertMaterial",
- category: "material",
- description: "Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.",
- example: "const mat = lambertMaterial(0x2a4d14, { flatShading: true });"
- },
- {
- name: "rotationTrack",
- signature: "rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP')",
- returns: "THREE.QuaternionKeyframeTrack",
- category: "animation",
- description: "Rotation track in degrees, auto-converted to quaternions. Joint name must include `Joint_` prefix.",
- example: "rotationTrack('Joint_Lid', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [90, 0, 0] }]);"
- },
- {
- name: "positionTrack",
- signature: "positionTrack(jointName: string, keyframes: Array<{ time, position: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')",
- returns: "THREE.VectorKeyframeTrack",
- category: "animation",
- description: "Position track in world units. Always use `position:` not `value:` in keyframes.",
- example: "positionTrack('Joint_Body', [{ time: 0, position: [0, 0, 0] }, { time: 1, position: [0, 0.1, 0] }]);"
- },
- {
- name: "scaleTrack",
- signature: "scaleTrack(jointName: string, keyframes: Array<{ time, scale: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')",
- returns: "THREE.VectorKeyframeTrack",
- category: "animation",
- description: "Uniform or per-axis scale track.",
- example: "scaleTrack('Joint_Chest', [{ time: 0, scale: [1, 1, 1] }, { time: 1, scale: [1.1, 1.1, 1.1] }]);"
- },
- {
- name: "createClip",
- signature: "createClip(name: string, duration: number, tracks: KeyframeTrack[])",
- returns: "THREE.AnimationClip",
- category: "animation",
- description: "Collects tracks into a named clip. Returned from animate().",
- example: "return [createClip('Open', 1, [rotationTrack('Joint_Lid', [...])])];"
- },
- {
- name: "idleBreathing",
- signature: "idleBreathing(bodyJoint: string, duration?: 2, amount?: 0.02)",
- returns: "THREE.AnimationClip",
- category: "animation",
- description: "Gentle Y-axis bob. For NPC idle states.",
- example: "return [idleBreathing('Joint_Body')];"
- },
- {
- name: "bobbingAnimation",
- signature: "bobbingAnimation(rootName: string, duration?: 2, height?: 0.1)",
- returns: "THREE.AnimationClip",
- category: "animation",
- description: "Floating / bobbing loop for pickups and effects.",
- example: "return [bobbingAnimation('Joint_Root', 1.5, 0.08)];"
- },
- {
- name: "spinAnimation",
- signature: "spinAnimation(jointName: string, duration?: 2, axis?: 'x' | 'y' | 'z')",
- returns: "THREE.AnimationClip",
- category: "animation",
- description: "360° rotation over `duration` around `axis`.",
- example: "return [spinAnimation('Joint_Rotor', 0.5, 'y')];"
- },
- {
- name: "cloneGeometry",
- signature: "cloneGeometry(geo: BufferGeometry)",
- returns: "THREE.BufferGeometry (same ref)",
- category: "instancing",
- description: "Deprecated name: returns the SAME geometry, without copying. Use copyGeometry for independent vertex edits, or pass the original geometry directly for intentional sharing.",
- example: "const wheelGeo = cylinderGeo(0.4, 0.4, 0.2, 12);"
- },
- {
- name: "cloneMaterial",
- signature: "cloneMaterial(mat: Material)",
- returns: "THREE.Material (same ref)",
- category: "instancing",
- description: "Deprecated name: returns the SAME material. Use copyMaterial for independent property edits, or pass the original for intentional sharing.",
- example: "const rubberMat = gameMaterial(0x1a1a1a, { roughness: 0.95 });"
- },
- {
- name: "createInstance",
- signature: "createInstance(name, source, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, parent })",
- returns: "THREE.Object3D",
- category: "instancing",
- description: "Creates a new mesh reusing an existing part's geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows. `rotation` is in DEGREES, like createPart.",
- example: `const wheelFL = createPart('WheelFL', wheelGeo, rubberMat, { position: [-0.8, 0.3, 1.2], parent: root });
-createInstance('WheelFR', wheelFL, { position: [0.8, 0.3, 1.2], parent: root });
-createInstance('WheelRL', wheelFL, { position: [-0.8, 0.3, -1.2], parent: root });
-createInstance('WheelRR', wheelFL, { position: [0.8, 0.3, -1.2], parent: root });`
- },
- {
- name: "boolUnion",
- signature: "await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
- returns: "Promise<THREE.Mesh>",
- category: "csg",
- description: "Merges two or more parts into one watertight manifold mesh. Default flat shading (hard edges) — pass { smooth: true } as last arg for averaged normals on organic merges.",
- example: `const body = new THREE.Mesh(boxGeo(2, 1, 1), steel);
-const turret = new THREE.Mesh(cylinderGeo(0.3, 0.3, 0.4, 16), steel);
-turret.position.y = 0.5;
-const hull = await boolUnion('Hull', body, turret);`
- },
- {
- name: "boolDiff",
- signature: "await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
- returns: "Promise<THREE.Mesh>",
- category: "csg",
- description: "Subtracts cutters from a body (holes, button recesses, window slots). Default flat shading for sharp mechanical edges.",
- example: `const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel);
-const teeth = [...]; // 8 radially-arrayed box meshes
-const gear = await boolDiff('Gear', body, ...teeth); // hard-edged`
- },
- {
- name: "roundedBoxGeo",
- signature: "await roundedBoxGeo(width: number, height: number, depth: number, radius: number, opts?: { style?: 'round' | 'chamfer', segments?: 12, smooth?: boolean })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "csg",
- description: "A box with all twelve edges rounded (or chamfered) at the EXACT outer size requested — roundedBoxGeo(1, 1, 1, 0.1) measures 1x1x1, it does not grow. Use it anywhere boxGeo reads too sharp: consoles, crates, appliances, handheld props, machined blocks.",
- promptNotes: "Real objects almost never have perfectly sharp box edges, and a small radius is the single cheapest upgrade to how manufactured an asset looks. Prefer this over boxGeo for anything moulded, cast, or machined. Keep radius small relative to the box (5-10% of the smallest dimension); radius must be less than half the smallest dimension or the call throws. style: 'chamfer' reads as machined metal, 'round' as moulded plastic. This is async — build() must be async and the call must use await.",
- example: `const geo = await roundedBoxGeo(1.2, 0.6, 0.8, 0.05);
-createPart('Console', geo, plastic, { position: [0, 0.3, 0], parent: root });`
- },
- {
- name: "extrudeProfile",
- signature: "await extrudeProfile(profile: [number, number][], opts?: { depth?: 1, holes?: [number, number][][], bevel?: 0, bevelStyle?: 'round' | 'chamfer', segments?: 12, twist?: 0, taper?: number | [number, number], divisions?: number, axis?: 'x' | 'y' | 'z', center?: true, smooth?: false })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "csg",
- description: "Sweeps a closed 2D outline into a watertight solid, with optional holes, corner rounding/chamfering, twist, and taper. The way to build any cross-section that is not a box or a cylinder: L-brackets, I-beams, gaskets, washers, star and gear plates, signage, extruded trim.",
- promptNotes: "The bevel rounds the edges PARALLEL to the sweep axis (the profile corners) — the two flat caps stay sharp. For a box rounded on all twelve edges use roundedBoxGeo instead. Holes are subtracted, so their winding order does not matter. A bevel larger than half the outline's narrowest feature throws rather than silently returning an empty solid. Output is manifold, so it feeds straight into boolUnion / boolDiff / boolIntersect. Async — await it inside an async build().",
- example: `// L-bracket, inner AND outer corners filleted
-const outline = [[0, 0], [2, 0], [2, 0.4], [0.4, 0.4], [0.4, 2], [0, 2]];
-const geo = await extrudeProfile(outline, { depth: 0.5, bevel: 0.06 });
-createPart('Bracket', geo, steel, { parent: root });`
- },
- {
- name: "revolveProfile",
- signature: "await revolveProfile(profile: [number, number][], opts?: { segments?: 24, angle?: 360, bevel?: 0, bevelStyle?: 'round' | 'chamfer', bevelSegments?: 12, axis?: 'x' | 'y' | 'z', smooth?: true })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "csg",
- description: "Revolves a closed 2D outline around an axis into a watertight SOLID, optionally rounding the profile corners first. Bottles, tanks, pressure vessels, wheels, turned wood, domes, buttons, pills.",
- promptNotes: "Use this instead of lathe/revolveGeo whenever the result must survive a boolean or needs a rounded rim — lathe and revolveGeo build an open surface, this builds a closed solid. Profile convention matches lathe: x is distance from the axis, y is position along it, and only the x >= 0 side is used. Async — await it inside an async build().",
- example: `// capsule tank with a rounded rim, then carve a port into it
-const profile = [[0, -0.5], [0.4, -0.5], [0.4, 0.5], [0, 0.5]];
-const body = await revolveProfile(profile, { bevel: 0.08, segments: 32 });
-const tank = await boolDiff('Tank', createPart('B', body, steel), portCutter);`
- },
- {
- name: "circleProfile",
- signature: "circleProfile(radius: number, segments?: 24, center?: [number, number])",
- returns: "[number, number][]",
- category: "csg",
- description: "Builds a closed circular outline for extrudeProfile / revolveProfile, so you never hand-write the trigonometry. Synchronous.",
- example: `const washer = await extrudeProfile(circleProfile(1), {
- depth: 0.1,
- holes: [circleProfile(0.4), circleProfile(0.1, 16, [0.7, 0])],
-});`
- },
- {
- name: "boolIntersect",
- signature: "await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })",
- returns: "Promise<THREE.Mesh>",
- category: "csg",
- description: "Keeps only the volume where both operands overlap. Default flat shading.",
- example: "const lens = await boolIntersect('Lens', boxMesh, sphereMesh);"
- },
- {
- name: "hull",
- signature: "await hull(name: string, ...parts: Object3D[], opts?: { smooth?: true })",
- returns: "Promise<THREE.Mesh>",
- category: "csg",
- description: "Tightest convex mesh enclosing all input points. Default smooth shading (rocks, collision volumes). Pass { smooth: false } for a faceted look.",
- example: `const rockChunks = [...]; // scattered box meshes
-const rock = await hull('Rock', ...rockChunks);`
- },
- {
- name: "arrayLinear",
- signature: "arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)",
- returns: "THREE.Object3D[]",
- category: "arrays",
- description: "Places N copies of `source` along a constant offset vector. Copies share geometry + material via createInstance.",
- example: `const post = createPart('Post0', cylinderGeo(0.05,0.05,1.5,6), wood, { position: [0,0.75,0], parent: root });
-arrayLinear('Post', post, 10, [0.5, 0, 0], root);`
- },
- {
- name: "arrayRadial",
- signature: "arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?)",
- returns: "THREE.Object3D[]",
- category: "arrays",
- description: "Places N copies of `source` around the given axis. Source's local rotation is oriented outward. Perfect for gear teeth, radial bolts, circle of columns.",
- example: `const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });
-arrayRadial('Bolt', bolt, 8, 'y', root);`
- },
- {
- name: "mirror",
- signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",
- returns: "THREE.Object3D",
- category: "arrays",
- description: "Reflects source across the plane whose normal is `axis`. Uses negative scale (winding flip handled by viewers).",
- example: "mirror('WingR', wingL, 'x', root);"
- },
- {
- name: "subdivide",
- signature: "subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { preserveUV?: boolean, split?: boolean, uvSmooth?: boolean, preserveEdges?: boolean, flatOnly?: boolean, weld?: boolean })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Loop subdivision returns new geometry; each iteration roughly quadruples triangles and smooths the surface. Use preserveUV:true for textured meshes. Legacy position-only welding discards UVs and reports that loss. This smooths shapes, not selected-edge beveling.",
- example: "const smoothRock = subdivide(boxGeo(1, 1, 1), 2);"
- },
- {
- name: "mergeVertices",
- signature: "mergeVertices(geometry: BufferGeometry, opts?: { tolerance?: 1e-4, positionOnly?: boolean } | number)",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Returns indexed geometry. Default welding preserves attribute seams, so a textured cube retains separate face corners. positionOnly:true welds coincident positions and discards other attributes; use it explicitly when changing topology and regenerate shading/UVs afterward.",
- example: `const welded = mergeVertices(boxGeo(1, 1, 1), { positionOnly: true });
-const rock = displace(subdivide(welded, 2), ([x,y,z]) => [0.08*Math.sin(y*7+z*3), 0.04*Math.sin(x*9), 0]);`
- },
- {
- name: "curveToMesh",
- signature: "curveToMesh(points: [x,y,z][], radius, tubularSegs?: 32, radialSegs?: 8, closed?: false)",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Sweeps a circular profile along a path. Equivalent to Blender's Curve to Mesh node with a circle profile. Use for pipes, cables, tubular frames.",
- example: "const pipe = curveToMesh([[0,0,0],[0,1,0],[1,1,0],[1,2,0]], 0.1);"
- },
- {
- name: "pipeAlongPath",
- signature: "pipeAlongPath(points: [x,y,z][], radius: number, opts?: { bendRadius?: 0, closed?: false, tubularSegments?: 32, radialSegments?: 8 })",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Path-driven swept circle with optional bend smoothing. Generalises beamBetween (point-to-point) and curveToMesh (raw spline) into one helper. bendRadius>0 inserts interpolated waypoints near interior corners so the spline reads as a rounded turn instead of pinching to the control point.",
- example: "const cable = pipeAlongPath([[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]], 0.02, { bendRadius: 0.1 });"
- },
- {
- name: "lathe",
- signature: "lathe(profile: [x,y][], segments?: 12)",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Surface of revolution. Spins a 2D profile around the Y axis. For bottles, vases, wheels, turned wood parts.",
- example: "const vase = lathe([[0.1,0],[0.3,0.5],[0.2,1],[0.1,1.2]], 16);"
- },
- {
- name: "revolveGeo",
- signature: "revolveGeo(profile: [x,y][], opts?: { angle?: 2π, axis?: [x,y,z]=[0,1,0], segments?: 12 })",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Surface of revolution with explicit axis + sweep angle. Generalises lathe — use it when you need a partial sweep (half-dome, 90° wedge) or revolution around a non-Y axis. Profile convention is identical to lathe: x = radial distance, y = position along the axis.",
- example: `// Half-dome (180° sweep around +Y):
-const quarter = [...Array(8)].map((_, i) => { const t = (i/7)*Math.PI/2; return [Math.cos(t), Math.sin(t)] as [number, number]; });
-const dome = revolveGeo(quarter, { angle: Math.PI });`
- },
- {
- name: "bezierCurve",
- signature: "bezierCurve(controlPoints: [x,y,z][], samples?: 32)",
- returns: "[x,y,z][]",
- category: "curves",
- description: "Samples a quadratic (3 ctrl pts) or cubic (4 ctrl pts) Bézier into a point list you can feed into curveToMesh.",
- example: `const path = bezierCurve([[0,0,0],[1,2,0],[3,2,0],[4,0,0]], 24);
-const geo = curveToMesh(path, 0.1);`
- },
- {
- name: "autoUnwrap",
- signature: "await autoUnwrap(geometry: BufferGeometry, opts?: { resolution?: 1024, padding?: 2, useNormals?: false })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "uv",
- description: "xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware unwraps below.",
- example: `const unwrapped = await autoUnwrap(someCsgResult, { resolution: 1024 });
-const mesh = new THREE.Mesh(unwrapped, bakedPbr);`
- },
- {
- name: "boxUnwrap",
- signature: "boxUnwrap(geometry: BufferGeometry)",
- returns: "THREE.BufferGeometry",
- category: "uv",
- description: "Preserves BoxGeometry's built-in per-face UVs — every face maps [0,1] with consistent orientation. Use for crates/blocks with a tileable texture. Sync; no WASM cost.",
- example: `const crate = boxUnwrap(boxGeo(1, 1, 1));
-const mesh = new THREE.Mesh(crate, pbrMaterial({ albedo: planksTex }));`
- },
- {
- name: "cylinderUnwrap",
- signature: "cylinderUnwrap(geometry: BufferGeometry)",
- returns: "THREE.BufferGeometry",
- category: "uv",
- description: "Preserves CylinderGeometry's built-in UVs: u wraps around the axis (horizontal texture features ring the cylinder), v runs up the height. Caps use circle-in-square. Sync; no WASM cost.",
- example: `const barrel = cylinderUnwrap(cylinderGeo(0.5, 0.5, 1.2, 24));
-const mesh = new THREE.Mesh(barrel, pbrMaterial({ albedo: bandsTex }));`
- },
- {
- name: "planeUnwrap",
- signature: "planeUnwrap(geometry: BufferGeometry)",
- returns: "THREE.BufferGeometry",
- category: "uv",
- description: "Projects xy-extent of the bbox to [0,1]. Use for signs/decals/posters where you want ONE readable texture and no edge-face bleeding. Sync.",
- example: `const sign = planeUnwrap(planeGeo(1, 0.6));
-const mesh = new THREE.Mesh(sign, pbrMaterial({ albedo: kilnTextTex }));`
- },
- {
- name: "panelRemapV",
- signature: "panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)",
- returns: "THREE.BufferGeometry",
- category: "uv",
- description: "Scales an existing UV attribute so a small mesh samples a sub-region of a SHARED texture. Replaces the broken texture.clone() pattern (Three.js Texture.clone() runs JSON.stringify on userData, mangling encoded PNG bytes — panelRemapV avoids that by remapping UVs on the geometry instead). Typical use: multi-zone albedo where v=0..0.30 is plain panel and v=0.30..1 has windows/markings — small parts call panelRemapV(unwrap(geo), 0.30) to sample only the clean strip.",
- example: `const cowlGeo = panelRemapV(cylinderUnwrap(capsuleXGeo(0.45, 1.0)), 0.30);
-const cowl = new THREE.Mesh(cowlGeo, bodyMat); // SAME bodyMat as fuselage, no clone needed`
- },
- {
- name: "loadApprovedTexture",
- signature: "await loadApprovedTexture(resourceId)",
- returns: "Promise<THREE.DataTexture>",
- category: "textures",
- description: "Loads one approved kiln.texture.* resource ID through the host-injected closed resolver. The registry fixes bytes, MIME, usage, dimensions, hash, and deadline; paths, URLs, byte arrays, resolver objects, hashes, and options are rejected.",
- example: "const bark = await loadApprovedTexture('kiln.texture.bark-brown-01-albedo.v1');",
- promptNotes: "Use only a concrete resource ID listed in material capabilities; never invent one. Prefer materialRecipe when a recipe already binds the family, or proceduralTexture V2 for authored surfaces. NEVER texture.clone() a loaded texture (clone() corrupts encoded bytes and breaks GLB export)."
- },
- {
- name: "proceduralTexture",
- signature: "proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })",
- returns: "THREE.DataTexture (tiling, sRGB or linear per usage)",
- category: "textures",
- description: "Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.",
- example: "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",
- promptNotes: "Sync — no await. Strict V2 JSON boundary: unknown/prototype keys, callbacks, paths, URLs, and shader source are rejected. Prefer this over approved resources for describable surfaces. Max 8 layers, power-of-two size up to 1024. Only the six listed ops exist."
- },
- {
- name: "normalMapFromHeight",
- signature: "normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })",
- returns: "THREE.DataTexture (linear normal map)",
- category: "textures",
- description: "Derives a tangent-space normal map from the source texture's brightness, treating it as height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at the edges, so a tiling source gives a tiling normal map.",
- example: `const bark = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] });
-const mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });`,
- promptNotes: "strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always linear data — never assign it to an albedo/emissive slot."
- },
- {
- name: "pbrMaterial",
- signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, aoMap?, alphaMode?, alphaCutoff?, doubleSided? })",
- returns: "THREE.MeshStandardMaterial",
- category: "material",
- description: "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. Supports OPAQUE/MASK/BLEND and double-sided output.",
- example: `const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });
-const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });`
- },
- {
- name: "foliageMaterial",
- signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",
- returns: "THREE.MeshStandardMaterial",
- category: "material",
- description: "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",
- example: "const mat = await materialRecipe('kiln.material.leaf.v1');"
- },
- {
- name: "countTriangles",
- signature: "countTriangles(root: Object3D)",
- returns: "number",
- category: "utility",
- description: "Sums triangle count across every mesh in the subtree.",
- example: "meta.tris = countTriangles(root);"
- },
- {
- name: "countMaterials",
- signature: "countMaterials(root: Object3D)",
- returns: "number",
- category: "utility",
- description: "Unique material count (by reference) across the subtree.",
- example: "const mats = countMaterials(root);"
- },
- {
- name: "getJointNames",
- signature: "getJointNames(root: Object3D)",
- returns: "string[]",
- category: "utility",
- description: "All node names beginning with `Joint_`. Use to sanity-check animation targets.",
- example: "const joints = getJointNames(root);"
- },
- {
- name: "validateAsset",
- signature: "validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture' | 'vegetation' | 'vehicle')",
- returns: "{ valid, errors, warnings }",
- category: "utility",
- description: "Checks geometry and material costs for the selected category. No default triangle limit; choose detail for the intended runtime and inspect measured draw calls.",
- example: "const v = validateAsset(root, 'prop');"
- }
-];
-function listPrimitives() {
- return PRIMITIVES.map((p) => ({ ...p }));
-}
+// src/prompt.ts
+init_list_primitives();
// src/prompt-api.ts
var CATEGORY_HEADERS = [
@@ -28167,6 +28280,7 @@ import { z as z2 } from "zod";
var refInput = z2.string().regex(programRefPattern).describe("Returned p_ handle or full sha256 ref.");
// src/tools/discovery.ts
+init_list_primitives();
import { z as z3 } from "zod";
init_protocol();
init_capture_limits();
@@ -28233,10 +28347,12 @@ class MemoryBuildCache {
// src/tools/registry.ts
init_validation();
+init_protocol();
init_render();
-import * as THREE35 from "three";
+init_list_primitives();
init_evaluator();
init_material_resources();
+import * as THREE35 from "three";
// src/edit-buffer.ts
class KilnDraftBuffer {
@@ -28827,6 +28943,17 @@ function collectSceneMetrics(root) {
}
return { meshes, materials: materialSet.size, bbox, lowestPart };
}
+function withSyntaxDetail(message, code) {
+ if (!message.startsWith(evaluatorOutcomeMessage("EXECUTION_REJECTED")))
+ return message;
+ let syntax;
+ try {
+ syntax = validate(code).errors.find((error) => error.startsWith("Syntax error:"));
+ } catch {
+ return message;
+ }
+ return syntax ? `${message} ${syntax}` : message;
+}
async function runRender(input, context) {
try {
const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);
@@ -28845,6 +28972,7 @@ async function runRender(input, context) {
tris: rendered.tris,
meshes: metrics.meshes,
materials: metrics.materials,
+ ...rendered.meta.instanceability ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials } : {},
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
...instanceability ? {
@@ -28859,7 +28987,7 @@ async function runRender(input, context) {
} catch (err) {
return {
ok: false,
- error: err instanceof Error ? err.message : String(err),
+ error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
warnings: []
};
}
@@ -28883,7 +29011,7 @@ async function runScreenshot(input, context) {
} catch (err) {
return {
ok: false,
- error: err instanceof Error ? err.message : String(err),
+ error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
warnings: []
};
}
@@ -28916,6 +29044,7 @@ async function runRenderViews(input, context) {
tris: rendered.tris,
meshes: metrics.meshes,
materials: metrics.materials,
+ ...rendered.meta.instanceability ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials } : {},
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
views: grid2.views,
@@ -29012,6 +29141,7 @@ async function runRenderViews(input, context) {
tris: rendered.tris,
meshes: metrics.meshes,
materials: metrics.materials,
+ ...rendered.meta.instanceability ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials } : {},
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
...rendered.meta.instanceability ? {
@@ -29035,7 +29165,7 @@ async function runRenderViews(input, context) {
} catch (err) {
return {
ok: false,
- error: err instanceof Error ? err.message : String(err),
+ error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
warnings: []
};
}
diff --git a/dist/build.json b/dist/build.json
index d5227fed..e729a1da 100644
--- a/dist/build.json
+++ b/dist/build.json
@@ -2,10 +2,10 @@
"schemaVersion": 1,
"entries": {
"mcp": {
- "identity": "sha256:23ec3588dd0208ab28858afb8ab9f42ab350a416d5743252e6c49535a2a88094",
+ "identity": "sha256:70c6c949f1dd2a9dbd878e97d7ed45530200f2f9d08ed7dc9d03ac8eb3547bbb",
"engineVersion": "0.6.0",
"toolchain": "[email protected]",
- "sourceHash": "74be9350cb13fe199f9bc54bfeba6f9f4482424fb12b6fe5e788a14ed3c097b5",
+ "sourceHash": "0ca9c934aa03b96edece8ad4b89e63828df404309d23f8da9d8de25e51a2950f",
"dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",
"dependencies": {
"@gltf-transform/core": "^4.4.1",
@@ -27,13 +27,13 @@
},
"target": "node",
"file": "mcp-server.mjs",
- "bundleHash": "sha256:b97a72e1c1c791e9273fe3b9ee276cc6d19b264d2c152c40af6c1871fe5f4770"
+ "bundleHash": "sha256:addada60e499bc4394c047ec3c04065c3c9d068539ecdc9b2007c177baac350f"
},
"cli": {
- "identity": "sha256:23ec3588dd0208ab28858afb8ab9f42ab350a416d5743252e6c49535a2a88094",
+ "identity": "sha256:70c6c949f1dd2a9dbd878e97d7ed45530200f2f9d08ed7dc9d03ac8eb3547bbb",
"engineVersion": "0.6.0",
"toolchain": "[email protected]",
- "sourceHash": "74be9350cb13fe199f9bc54bfeba6f9f4482424fb12b6fe5e788a14ed3c097b5",
+ "sourceHash": "0ca9c934aa03b96edece8ad4b89e63828df404309d23f8da9d8de25e51a2950f",
"dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",
"dependencies": {
"@gltf-transform/core": "^4.4.1",
@@ -55,13 +55,13 @@
},
"target": "node",
"file": "cli.mjs",
- "bundleHash": "sha256:4d73ef2f0f79a0f74599c560137ecd20d975c2143569b6506d4e89b5eb2a91e3"
+ "bundleHash": "sha256:9b152ea485159e4feee717a3d860f5f962cd108018dc215466f68d506702bbd1"
},
"worker": {
- "identity": "sha256:23ec3588dd0208ab28858afb8ab9f42ab350a416d5743252e6c49535a2a88094",
+ "identity": "sha256:70c6c949f1dd2a9dbd878e97d7ed45530200f2f9d08ed7dc9d03ac8eb3547bbb",
"engineVersion": "0.6.0",
"toolchain": "[email protected]",
- "sourceHash": "74be9350cb13fe199f9bc54bfeba6f9f4482424fb12b6fe5e788a14ed3c097b5",
+ "sourceHash": "0ca9c934aa03b96edece8ad4b89e63828df404309d23f8da9d8de25e51a2950f",
"dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",
"dependencies": {
"@gltf-transform/core": "^4.4.1",
@@ -83,13 +83,13 @@
},
"target": "node",
"file": "evaluator-worker.mjs",
- "bundleHash": "sha256:d8fa92970ab9f09634a4f5dbfef3b0709998500e0ac4df618eeb0a08ec90c3e0"
+ "bundleHash": "sha256:bb463f3b33b7474ed8f2c0626fa4bde8c64101182b11aac042491f7077e6cbdd"
},
"agent-run": {
- "identity": "sha256:23ec3588dd0208ab28858afb8ab9f42ab350a416d5743252e6c49535a2a88094",
+ "identity": "sha256:70c6c949f1dd2a9dbd878e97d7ed45530200f2f9d08ed7dc9d03ac8eb3547bbb",
"engineVersion": "0.6.0",
"toolchain": "[email protected]",
- "sourceHash": "74be9350cb13fe199f9bc54bfeba6f9f4482424fb12b6fe5e788a14ed3c097b5",
+ "sourceHash": "0ca9c934aa03b96edece8ad4b89e63828df404309d23f8da9d8de25e51a2950f",
"dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",
"dependencies": {
"@gltf-transform/core": "^4.4.1",
@@ -111,13 +111,13 @@
},
"target": "node",
"file": "agent-run.mjs",
- "bundleHash": "sha256:0d69f758083673b6e2640bb3a45a021ef640fce277dfbe05a0154a51dda82d05"
+ "bundleHash": "sha256:4966a3d3fff0ca42fc8b77e2c0d5bf07af5966adb5fe80a67b3d0285325badf7"
},
"agent-providers": {
- "identity": "sha256:23ec3588dd0208ab28858afb8ab9f42ab350a416d5743252e6c49535a2a88094",
+ "identity": "sha256:70c6c949f1dd2a9dbd878e97d7ed45530200f2f9d08ed7dc9d03ac8eb3547bbb",
"engineVersion": "0.6.0",
"toolchain": "[email protected]",
- "sourceHash": "74be9350cb13fe199f9bc54bfeba6f9f4482424fb12b6fe5e788a14ed3c097b5",
+ "sourceHash": "0ca9c934aa03b96edece8ad4b89e63828df404309d23f8da9d8de25e51a2950f",
"dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",
"dependencies": {
"@gltf-transform/core": "^4.4.1",
diff --git a/dist/cli.mjs b/dist/cli.mjs
index 71aaee5b..060108da 100644
--- a/dist/cli.mjs
+++ b/dist/cli.mjs
@@ -31,7 +31,7 @@ function rethrowAuthoringError(error) {
}
throw error;
}
-var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", AuthoringDiagnosticError;
+var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_list_primitives to confirm the exact name and signature; the sandbox exposes only those globals.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", AuthoringDiagnosticError;
var init_authoring_diagnostic = __esm(() => {
AuthoringDiagnosticError = class AuthoringDiagnosticError extends Error {
diagnostic;
@@ -17965,8768 +17965,180 @@ var init_texture_resolver = __esm(() => {
DEFAULT_TEXTURE_RESOLVER = createTextureResolver();
});
-// src/validation.ts
-import * as acorn from "acorn";
-import * as walk from "acorn-walk";
-function estimateGeometryTris(name, args) {
- function asNum(node) {
- if (!node)
- return null;
- if (node.type === "Literal" && typeof node.value === "number")
- return node.value;
- if (node.type === "UnaryExpression" && node.operator === "-") {
- const inner = asNum(node.argument);
- return inner === null ? null : -inner;
- }
- return null;
- }
- function asObjNum(node, prop) {
- if (!node || node.type !== "ObjectExpression")
- return null;
- for (const p of node.properties) {
- if (p.type === "Property" && !p.computed && (p.key.type === "Identifier" && p.key.name === prop || p.key.type === "Literal" && p.key.value === prop)) {
- return asNum(p.value);
- }
- }
- return null;
- }
- switch (name) {
- case "boxGeo":
- case "decalBox":
- return 12;
- case "planeGeo": {
- const ws = asNum(args[2]) ?? 1;
- const hs = asNum(args[3]) ?? 1;
- return Math.max(1, ws * hs) * 2;
- }
- case "coneGeo":
- case "coneXGeo":
- case "coneYGeo":
- case "coneZGeo": {
- const segs = asNum(args[2]) ?? 8;
- return segs * 2;
- }
- case "cylinderGeo":
- case "cylinderXGeo":
- case "cylinderYGeo":
- case "cylinderZGeo": {
- const segs = asNum(args[3]) ?? 8;
- return segs * 4;
- }
- case "taperConeGeo": {
- const segs = asNum(args[4]) ?? 8;
- return segs * 4;
- }
- case "sphereGeo": {
- const w = asNum(args[1]) ?? 8;
- const h = asNum(args[2]) ?? 6;
- return w * h * 2;
- }
- case "capsuleGeo":
- case "capsuleXGeo":
- case "capsuleYGeo":
- case "capsuleZGeo": {
- const segs = asNum(args[2]) ?? 6;
- return segs * 8;
- }
- case "torusGeo": {
- const rad = asNum(args[2]) ?? 8;
- const tub = asNum(args[3]) ?? 12;
- return rad * tub * 2;
- }
- case "gearGeo": {
- const teeth = asObjNum(args[0], "teeth") ?? 12;
- return teeth * 32;
+// src/geometry-catalog.ts
+var geometryPrimitives;
+var init_geometry_catalog = __esm(() => {
+ geometryPrimitives = [
+ {
+ name: "copyGeometry",
+ signature: "copyGeometry(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "instancing",
+ description: "Returns an independent geometry with copied vertex buffers. Use before direct mutation of a cached primitive.",
+ example: "const editable = copyGeometry(boxGeo(1, 1, 1)); editable.translate(0, 0.5, 0);"
+ },
+ {
+ name: "copyMaterial",
+ signature: "copyMaterial(material: Material)",
+ returns: "THREE.Material (same subtype)",
+ category: "instancing",
+ description: "Copies material properties so edits do not change other parts. Referenced textures remain shared.",
+ example: "const red = copyMaterial(steel); red.color.set(0xaa2222);"
+ },
+ {
+ name: "meshGeo",
+ signature: "meshGeo({ positions: number[], indices?: number[], normals?: number[], uvs?: number[], tangents?: number[] })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Builds an owned triangle mesh from flat numeric arrays. Validates finite values, attribute lengths and indices; computes normals if absent. Counterclockwise winding.",
+ example: "const triangle = meshGeo({ positions: [0,0,0, 1,0,0, 0,1,0], indices: [0,1,2] });"
+ },
+ {
+ name: "parametricSurface",
+ signature: "parametricSurface(sample: (u,v) => [x,y,z], opts?: { u?: [0,1], v?: [0,1], uSegments?: 24, vSegments?: 24, periodicU?: false, periodicV?: false, orientation?: 'uv'|'vu' })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Samples an equation into an owned surface with UVs. Periodic endpoints must coincide; UV seams retain matching normals. A surface is not automatically a watertight solid.",
+ example: "const canopy = parametricSurface((u,v) => [u, 0.3*Math.sin(u*3)*Math.cos(v*2), v], { u: [-2,2], v: [-1,1] });"
+ },
+ {
+ name: "geometryDiagnostics",
+ signature: "geometryDiagnostics(geometry: BufferGeometry, tolerance?: 1e-6)",
+ returns: "{ vertices, triangles, boundaryEdges, nonManifoldEdges, orientationConflicts, degenerateTriangles, invalidIndices, nonFiniteVertices }",
+ category: "utility",
+ description: "Counts mesh topology problems after position-based seam matching. Open boundaries are valid for sheets; closed edges alone do not prove a self-intersection-free solid.",
+ example: "const topology = geometryDiagnostics(shell);"
+ },
+ {
+ name: "creaseNormals",
+ signature: "creaseNormals(geometry: BufferGeometry, opts?: { angle?: 60, tolerance?: number })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Returns owned geometry with angle-limited smooth normals, preserving UV corners. Angle is degrees. Invalidates tangents; use after shaping for sharp rims and smooth walls.",
+ example: "const shell = creaseNormals(cylinderGeo(1,1,2,32), { angle: 45 });"
+ },
+ {
+ name: "bend",
+ signature: "bend(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Bends local +Y toward +X through angle degrees. Returns owned geometry and updated normals/bounds; preserves UVs, invalidates tangents. Frame rotation is Euler XYZ degrees.",
+ promptNotes: "Deformation interval uses local Y distances; outside vertices stay unchanged. Add enough segments before bending. Falloff returns 0..1; use it to avoid a discontinuity at a selected interval boundary.",
+ example: "const arch = bend(planeGeo(1,4,4,32), { angle: 90 });"
+ },
+ {
+ name: "twist",
+ signature: "twist(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Rotates the cross-section progressively around local +Y, reaching angle degrees at the end. Returns owned geometry; frame rotation uses Euler XYZ degrees.",
+ example: "const spiral = twist(column, { angle: 120 });"
+ },
+ {
+ name: "taper",
+ signature: "taper(geometry, { startScale?: [1,1], endScale: [x,z], frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Scales local X/Z across the local Y interval using positive start/end scale pairs. Returns owned geometry; preserves UVs and invalidates tangents.",
+ example: "const narrowed = taper(column, { endScale: [0.4,0.7] });"
+ },
+ {
+ name: "displace",
+ signature: "displace(geometry, offset: ([x,y,z], t) => [dx,dy,dz], opts?: { frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Adds an authored displacement vector in the chosen local frame. Returns owned geometry; callback coordinates are local and t is normalized along the interval.",
+ example: "const rippled = displace(surface, ([x,y,z]) => [0, 0.1*Math.sin(x*8), 0]);"
+ },
+ {
+ name: "sweepProfile",
+ signature: "sweepProfile(profile: [x,z][], path: [x,y,z][], opts?: { cap?: true, closed?: false, up?: [x,y,z], twist?: 0, scale?: number | [x,z][] })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Sweeps a simple noncircular profile along polyline stations using transported frames. Supports total twist in degrees and per-station scales. Generates UVs and optional caps.",
+ promptNotes: "First version supports one simple profile without holes. Closed paths omit the repeated endpoint and require twist to be a multiple of 360. up sets the initial profile +Z direction and cannot parallel the path. Tight-turn warnings do not replace visual inspection for self-intersections.",
+ example: "const rail = sweepProfile([[-.1,-.2],[.1,-.2],[.1,.2],[-.1,.2]], [[0,0,0],[0,1,0],[1,2,0]]);"
+ },
+ {
+ name: "loftProfiles",
+ signature: "loftProfiles(sections: { profile: [x,z][], frame?: { origin, rotation } }[], opts?: { cap?: true })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Joins corresponding simple profiles in explicit local XZ planes. Each frame uses Euler XYZ degrees and local +Y along the loft. Profiles need equal point counts and corresponding vertices.",
+ promptNotes: "No holes or automatic profile correspondence. Opposite winding is normalized while preserving the first point. Caps close boundaries but do not prove the loft has no self-intersections.",
+ example: "const hull = loftProfiles([{ profile: wide }, { profile: narrow, frame: { origin: [0,2,0] } }]);"
+ },
+ {
+ name: "implicitSurface",
+ signature: "await implicitSurface(sample: ([x,y,z]) => signedValue, { bounds: { min, max }, edgeLength, maxCells?: 1000000, maxEvaluations?: 8000000, level?: 0, tolerance?: -1, smooth?: true })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "geometry",
+ description: "Experimental positive-inside implicit field sampled into a solid mesh. Requires explicit bounds and resolution; checks grid size and actual evaluation count. Output has no UVs.",
+ promptNotes: "Use async build and await. Smaller edgeLength increases cost sharply. This helper cannot stop a callback that never returns; the host evaluator process provides that boundary. Thin features and geometric accuracy require inspection.",
+ example: "const blob = await implicitSurface(([x,y,z]) => 1-Math.hypot(x,y,z), { bounds: { min: [-1.2,-1.2,-1.2], max: [1.2,1.2,1.2] }, edgeLength: 0.15 });"
}
- case "bladeGeo":
- return 36;
- case "wingGeo":
- return 24;
- default:
- return null;
- }
+ ];
+});
+
+// src/list-primitives.ts
+function listPrimitives() {
+ return PRIMITIVES.map((p) => ({ ...p }));
}
-function validate(code, _opts = {}) {
- const issues = [];
- const warnings = [];
- if (!code || typeof code !== "string" || code.trim().length === 0) {
- issues.push({
- code: "EMPTY_CODE",
- message: "Empty or missing code",
- fixHint: "Provide a non-empty code string from the code generator."
- });
- return toResult(issues, warnings);
- }
- const normalized = code.replace(/\r\n/g, `
-`);
- if (/^\s*import\s+/m.test(normalized)) {
- issues.push({
- code: "HAS_IMPORT",
- message: "Contains import statements — code must use sandbox globals only",
- fixHint: "Remove all `import` lines; primitives like boxGeo are already in scope.",
- line: findLineOf(normalized, /^\s*import\s+/m)
- });
- }
- if (/^\s*export\s+/m.test(normalized)) {
- issues.push({
- code: "HAS_EXPORT",
- message: "Contains export statements — just define meta, build, animate",
- fixHint: "Remove `export` keywords; the sandbox evaluator picks up `meta` and `build` by name.",
- line: findLineOf(normalized, /^\s*export\s+/m)
- });
- }
- const valueMatch = /\{\s*time:\s*[^,]+,\s*value:\s*\[/.exec(normalized);
- if (valueMatch) {
- issues.push({
- code: "KEYFRAME_VALUE_KEY",
- message: "Uses `value:` in keyframes — must use `rotation:` or `position:` instead",
- fixHint: "In every `{ time, value: [...] }` change `value:` to `rotation:` (degrees) or `position:`.",
- line: lineOfIndex(normalized, valueMatch.index)
- });
- }
- let ast;
- try {
- ast = acorn.parse(normalized, {
- ecmaVersion: 2022,
- sourceType: "script",
- allowReturnOutsideFunction: false,
- locations: true
- });
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- const locMatch = /\((\d+):\d+\)/.exec(msg);
- issues.push({
- code: "SYNTAX_ERROR",
- message: `Syntax error: ${msg}`,
- fixHint: "Fix the syntax error at the reported line/column.",
- line: locMatch ? Number(locMatch[1]) : undefined
- });
- return toResult(issues, warnings);
- }
- issues.push(...analyzeGeneratedSourceSafety(ast));
- const structure = analyzeTopLevel(ast);
- if (!structure.hasMetaConst) {
- issues.push({
- code: "MISSING_META",
- message: "Missing `const meta = { ... }` declaration at top level",
- fixHint: 'Add `const meta = { name: "YourAsset" };` at the top of the file.'
- });
- } else if (!structure.metaHasName) {
- warnings.push({
- code: "META_MISSING_NAME",
- message: "`meta` object has no `name` property",
- fixHint: 'Add `name: "YourAsset"` to the meta object.'
- });
- }
- if (!structure.hasBuildFn) {
- issues.push({
- code: "MISSING_BUILD",
- message: "Missing top-level `function build()` declaration",
- fixHint: 'Add `function build() { const root = createRoot("..."); ...; return root; }` at top level.'
- });
- }
- const analysis = analyzeBody(ast);
- if (analysis.infiniteLoops.length > 0) {
- for (const hit of analysis.infiniteLoops) {
- issues.push({
- code: "INFINITE_LOOP",
- message: `${hit.kind} with no break statement`,
- fixHint: `Add a break/return condition inside the ${hit.kind} loop, or switch to a bounded for/forEach.`,
- line: hit.line
- });
- }
- }
- if (analysis.recursiveBuild) {
- issues.push({
- code: "RECURSIVE_BUILD",
- message: "`build()` calls itself — will blow the stack at render time",
- fixHint: "Refactor the recursive step into a helper function; keep `build()` non-recursive.",
- line: analysis.recursiveBuild
- });
- }
- for (const smell of analyzeRotationUnits(ast, normalized)) {
- warnings.push({
- code: "ROTATION_RADIANS_SUSPECTED",
- message: `${smell.fn} rotation ${smell.rendered} looks like RADIANS — the rotation option is DEGREES${smell.suggestion ? `; did you mean ${smell.suggestion}?` : ""}`,
- fixHint: "createPart/createInstance rotation is degrees ([0,0,90] = quarter turn). Convert: deg = rad * 180 / Math.PI. Direct THREE properties (obj.rotation.z) stay radians.",
- line: smell.line
- });
- }
- return toResult(issues, warnings, analysis.estimatedTris);
-}
-function assertGeneratedSourceSafe(code) {
- let ast;
- try {
- ast = acorn.parse(code, {
- ecmaVersion: 2022,
- sourceType: "script",
- allowReturnOutsideFunction: false,
- locations: true
- });
- } catch (error) {
- const line = error && typeof error === "object" && "loc" in error ? error.loc?.line : undefined;
- throw new GeneratedSourcePolicyError({
- code: "SYNTAX_ERROR",
- message: "Generated source has invalid syntax.",
- line
- });
- }
- const issue = analyzeGeneratedSourceSafety(ast)[0];
- if (issue)
- throw new GeneratedSourcePolicyError(issue);
-}
-function issueKey(issue) {
- return `${issue.code}:${issue.line ?? 0}:${issue.message}`;
-}
-function analyzeGeneratedSourceSafety(ast) {
- const issues = [];
- const seen = new Set;
- const staticStrings = collectStaticStringBindings(ast);
- const add2 = (issue) => {
- const key = issueKey(issue);
- if (seen.has(key))
- return;
- seen.add(key);
- issues.push(issue);
- };
- const ambient = (name, line) => add2({
- code: "UNSAFE_GLOBAL_ACCESS",
- message: `Generated code cannot access ambient capability \`${name}\`.`,
- fixHint: "Use only the documented sandbox globals and approved resource helpers.",
- line
- });
- const dynamicCode = (line) => add2({
- code: "DYNAMIC_CODE_ACCESS",
- message: "Generated code cannot access constructor chains or dynamic-code constructors.",
- fixHint: "Call documented sandbox helpers directly; do not derive constructors at runtime.",
- line
- });
- const unsafeThree = (name, line) => add2({
- code: "UNSAFE_THREE_CONSTRUCTOR",
- message: `Generated code cannot access raw THREE constructor \`${name}\`.`,
- fixHint: "Use approved texture loading, proceduralTexture, pbrMaterial, or materialRecipe instead.",
- line
- });
- const unsafeThreeNamespace = (code, line) => add2({
- code,
- message: code === "UNSAFE_THREE_ALIAS" ? "Generated code cannot alias the THREE namespace." : "Generated code cannot use non-static computed access on the THREE namespace.",
- fixHint: "Use a documented direct THREE constructor or a sandbox material/texture helper.",
- line
- });
- walk.ancestor(ast, {
- Identifier(node, _state, ancestors) {
- const parent = ancestors.at(-2);
- if (identifierIsNonReferenceKey(node, parent))
- return;
- if (FORBIDDEN_AMBIENT_IDENTIFIERS.has(node.name)) {
- ambient(node.name, node.loc?.start.line);
- }
+var PRIMITIVES;
+var init_list_primitives = __esm(() => {
+ init_geometry_catalog();
+ PRIMITIVES = [
+ ...geometryPrimitives,
+ {
+ name: "createRoot",
+ signature: "createRoot(name: string)",
+ returns: "THREE.Object3D",
+ category: "structure",
+ description: "Creates the root Object3D for an asset. Call first in build().",
+ example: "const root = createRoot('FuelDrum');"
},
- ThisExpression(node) {
- ambient("this", node.loc?.start.line);
+ {
+ name: "createPivot",
+ signature: "createPivot(name: string, position?: [x, y, z], parent?: Object3D)",
+ returns: "THREE.Object3D (prefixed `Joint_`)",
+ category: "structure",
+ description: "Creates an empty pivot node for skeletal animation. Name is auto-prefixed with `Joint_`.",
+ example: "const hip = createPivot('Hip', [0, 1, 0], root);"
},
- ImportExpression(node) {
- add2({
- code: "DYNAMIC_IMPORT",
- message: "Generated code cannot use dynamic import.",
- fixHint: "Remove import(); all supported helpers are already sandbox globals.",
- line: node.loc?.start.line
- });
+ {
+ name: "createJointChain",
+ signature: "createJointChain(name, segments: { role, offset, aliases?, side?, localForwardAxis?, localBendAxis?, endEffector?, contact? }[], opts?: { parent?, parentRole? })",
+ returns: "{ root, end, nodes, byRole, descriptors }",
+ category: "structure",
+ description: "Creates one body-plan-neutral deterministic Joint_* chain with explicit parent edges, rest frames, local axes, end effectors, contacts, and semantic metadata.",
+ example: "const leg = createJointChain('LegL', [{ role: 'hip.left', offset: [0, 1, -0.2], side: 'left' }, { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' }, { role: 'ankle.left', offset: [0, -0.5, 0], side: 'left', endEffector: true, contact: true }], { parent: root });",
+ promptNotes: "Use only the resolved body-plan graph. Offsets are local to the previous joint; contact end effectors must land at world Y=0."
},
- MemberExpression(node) {
- const property = staticPropertyName(node, staticStrings);
- if (property === "constructor")
- dynamicCode(node.loc?.start.line);
- if (property && FORBIDDEN_THREE_CONSTRUCTORS.has(property) && expressionReferencesThree(node.object)) {
- unsafeThree(property, node.loc?.start.line);
- }
- if (node.computed && property === undefined && expressionReferencesThree(node.object)) {
- unsafeThreeNamespace("UNSAFE_THREE_COMPUTED_ACCESS", node.loc?.start.line);
- }
+ {
+ name: "createVehicleFrame",
+ signature: "createVehicleFrame(name, opts?: { chassis?, axles?, seats?, contacts?, steering?, propulsion?, parent? })",
+ returns: "{ root, chassis, axles, seats, contacts, steering, propulsion }",
+ category: "structure",
+ description: "Creates a canonical +X-forward/+Y-up/+Z-right vehicle frame with typed semantic sockets for chassis, support, steering, and propulsion.",
+ example: "const frame = createVehicleFrame('CarFrame', { axles: [{ id: 'front', position: [1.2, 0.45, 0] }, { id: 'rear', position: [-1.2, 0.45, 0] }], parent: root });",
+ promptNotes: "Generated vehicles keep +X as front. Boats and other non-wheeled subtypes use declared support/propulsion sockets, not wheel rules."
},
- VariableDeclarator(node) {
- if (node.id.type === "Identifier" && expressionReferencesThree(node.init)) {
- unsafeThreeNamespace("UNSAFE_THREE_ALIAS", node.loc?.start.line);
- }
- if (node.id.type !== "ObjectPattern")
- return;
- analyzeObjectPatternSafety(node.id, node.init?.type === "Identifier" && node.init.name === "THREE", staticStrings, dynamicCode, unsafeThree);
+ {
+ name: "createWheelGeometrySet",
+ signature: "createWheelGeometrySet(radius: number, width: number)",
+ returns: "{ tire, rim, hub } shared THREE.BufferGeometry set",
+ category: "instancing",
+ description: "Creates one reusable +Z-axle tire/rim/hub geometry set for instanced wheel assemblies.",
+ example: "const wheelGeo = createWheelGeometrySet(0.45, 0.22);"
},
- AssignmentExpression(node) {
- if (node.left.type === "Identifier" && expressionReferencesThree(node.right)) {
- unsafeThreeNamespace("UNSAFE_THREE_ALIAS", node.loc?.start.line);
- }
- if (node.left.type !== "ObjectPattern")
- return;
- analyzeObjectPatternSafety(node.left, node.right.type === "Identifier" && node.right.name === "THREE", staticStrings, dynamicCode, unsafeThree);
- },
- CallExpression(node) {
- if (node.callee.type !== "MemberExpression" || node.callee.object.type !== "Identifier") {
- return;
- }
- const owner = node.callee.object.name;
- const method = staticPropertyName(node.callee, staticStrings);
- if (!(owner === "Reflect" && method === "get" || owner === "Object" && method === "getOwnPropertyDescriptor")) {
- return;
- }
- const property = staticExpressionString(node.arguments[1], staticStrings);
- if (property === "constructor")
- dynamicCode(node.loc?.start.line);
- if (owner === "Reflect" && property && FORBIDDEN_THREE_CONSTRUCTORS.has(property) && expressionReferencesThree(node.arguments[0])) {
- unsafeThree(property, node.loc?.start.line);
- }
- }
- });
- return issues;
-}
-function expressionReferencesThree(node) {
- if (!node || typeof node !== "object")
- return false;
- const expression = node;
- if (expression.type === "Identifier")
- return expression.name === "THREE";
- if (expression.type === "ChainExpression")
- return expressionReferencesThree(expression.expression);
- if (expression.type === "SequenceExpression") {
- return expressionReferencesThree(expression.expressions.at(-1));
- }
- return false;
-}
-function identifierIsNonReferenceKey(node, parent) {
- if (!parent)
- return false;
- if (parent.type === "MemberExpression") {
- const member = parent;
- if (member.property === node && !member.computed)
- return true;
- }
- if (parent.type === "Property") {
- const property = parent;
- if (property.key === node && !property.computed && !property.shorthand)
- return true;
- }
- if (parent.type === "MethodDefinition") {
- const method = parent;
- if (method.key === node && !method.computed)
- return true;
- }
- if (parent.type === "LabeledStatement") {
- if (parent.label === node)
- return true;
- }
- if (parent.type === "BreakStatement" || parent.type === "ContinueStatement") {
- if (parent.label === node)
- return true;
- }
- return false;
-}
-function analyzeObjectPatternSafety(pattern, fromThree, staticStrings, dynamicCode, unsafeThree) {
- for (const entry of pattern.properties) {
- if (entry.type !== "Property")
- continue;
- const property = !entry.computed && entry.key.type === "Identifier" ? entry.key.name : staticExpressionString(entry.key, staticStrings);
- if (property === "constructor")
- dynamicCode(entry.loc?.start.line);
- if (fromThree && property && FORBIDDEN_THREE_CONSTRUCTORS.has(property)) {
- unsafeThree(property, entry.loc?.start.line);
- }
- }
-}
-function staticPropertyName(node, staticStrings) {
- if (!node.computed && node.property.type === "Identifier")
- return node.property.name;
- return staticExpressionString(node.property, staticStrings);
-}
-function staticExpressionString(node, staticStrings = new Map) {
- if (!node || typeof node !== "object")
- return;
- const expression = node;
- if (expression.type === "Literal") {
- return typeof expression.value === "string" || typeof expression.value === "number" ? String(expression.value) : undefined;
- }
- if (expression.type === "Identifier")
- return staticStrings.get(expression.name);
- if (expression.type === "TemplateLiteral") {
- let value = expression.quasis[0]?.value.cooked ?? expression.quasis[0]?.value.raw ?? "";
- for (let index = 0;index < expression.expressions.length; index++) {
- const part = staticExpressionString(expression.expressions[index], staticStrings);
- if (part === undefined)
- return;
- const quasi = expression.quasis[index + 1];
- value += part + (quasi?.value.cooked ?? quasi?.value.raw ?? "");
- }
- return value;
- }
- if (expression.type === "BinaryExpression" && expression.operator === "+") {
- const left = staticExpressionString(expression.left, staticStrings);
- const right = staticExpressionString(expression.right, staticStrings);
- return left === undefined || right === undefined ? undefined : left + right;
- }
- return;
-}
-function collectStaticStringBindings(ast) {
- const candidates = new Map;
- const duplicateNames = new Set;
- walk.simple(ast, {
- VariableDeclaration(node) {
- if (node.kind !== "const")
- return;
- for (const declaration of node.declarations) {
- if (declaration.id.type !== "Identifier" || !declaration.init)
- continue;
- if (candidates.has(declaration.id.name))
- duplicateNames.add(declaration.id.name);
- else
- candidates.set(declaration.id.name, declaration.init);
- }
- }
- });
- for (const name of duplicateNames)
- candidates.delete(name);
- const values = new Map;
- for (let pass = 0;pass < candidates.size; pass++) {
- let changed = false;
- for (const [name, expression] of candidates) {
- if (values.has(name))
- continue;
- const value = staticExpressionString(expression, values);
- if (value === undefined)
- continue;
- values.set(name, value);
- changed = true;
- }
- if (!changed)
- break;
- }
- return values;
-}
-function toResult(issues, warnings, estimatedTris) {
- return {
- valid: issues.length === 0,
- errors: issues.map((i) => i.message),
- issues,
- warnings,
- ...estimatedTris === undefined ? {} : { estimatedTris }
- };
-}
-function findLineOf(code, re) {
- const match = re.exec(code);
- if (!match)
- return;
- return lineOfIndex(code, match.index);
-}
-function lineOfIndex(code, idx) {
- let line = 1;
- for (let i = 0;i < idx; i++)
- if (code.charCodeAt(i) === 10)
- line++;
- return line;
-}
-function analyzeRotationUnits(ast, source) {
- const smells = [];
- walk.simple(ast, {
- CallExpression(node) {
- if (node.callee.type !== "Identifier" || !ROTATION_OPTION_FNS.has(node.callee.name))
- return;
- const fn = node.callee.name;
- for (const arg of node.arguments) {
- if (arg.type !== "ObjectExpression")
- continue;
- for (const prop of arg.properties) {
- if (prop.type !== "Property" || prop.computed)
- continue;
- const key = prop.key.type === "Identifier" ? prop.key.name : prop.key.type === "Literal" ? String(prop.key.value) : "";
- if (key !== "rotation" || prop.value.type !== "ArrayExpression")
- continue;
- const smell = classifyRotationArray(prop.value, fn, source);
- if (smell)
- smells.push(smell);
- }
- }
- }
- });
- return smells;
-}
-function classifyRotationArray(arr, fn, source) {
- const rendered = () => {
- const text = source.slice(arr.start, arr.end).replace(/\s+/g, " ");
- return text.length > 64 ? `${text.slice(0, 61)}...` : text;
- };
- let sawPI = false;
- let onlyConversions = true;
- for (const el of arr.elements) {
- if (!el || el.type === "SpreadElement")
- continue;
- if (containsMathPI(el)) {
- sawPI = true;
- if (!dividesByMathPI(el))
- onlyConversions = false;
- }
- }
- if (sawPI) {
- if (onlyConversions)
- return null;
- return { fn, rendered: rendered(), line: arr.loc?.start.line };
- }
- const nums = [];
- for (const el of arr.elements) {
- if (!el || el.type === "SpreadElement")
- return null;
- const n = literalNumber(el);
- if (n === undefined)
- return null;
- nums.push(n);
- }
- const nonZero = nums.filter((n) => n !== 0);
- if (nonZero.length === 0)
- return null;
- if (!nonZero.every((n) => Math.abs(n) < 6.3))
- return null;
- if (!nonZero.some((n) => !Number.isInteger(n)))
- return null;
- const deg = nums.map((n) => n === 0 ? 0 : Math.round(n * 180 / Math.PI));
- return {
- fn,
- rendered: rendered(),
- suggestion: `[${deg.join(", ")}]`,
- line: arr.loc?.start.line
- };
-}
-function literalNumber(el) {
- if (el.type === "Literal" && typeof el.value === "number")
- return el.value;
- if (el.type === "UnaryExpression" && el.operator === "-") {
- const inner = literalNumber(el.argument);
- return inner === undefined ? undefined : -inner;
- }
- return;
-}
-function containsMathPI(node) {
- if (!node || typeof node !== "object")
- return false;
- const n = node;
- if (n.type === "MemberExpression") {
- const obj = n["object"];
- const prop = n["property"];
- if (obj?.type === "Identifier" && obj.name === "Math" && prop?.type === "Identifier" && prop.name === "PI") {
- return true;
- }
- }
- for (const key of Object.keys(n)) {
- if (key === "loc" || key === "start" || key === "end")
- continue;
- const v = n[key];
- if (Array.isArray(v)) {
- for (const item of v)
- if (containsMathPI(item))
- return true;
- } else if (v && typeof v === "object" && v.type) {
- if (containsMathPI(v))
- return true;
- }
- }
- return false;
-}
-function dividesByMathPI(node) {
- if (!node || typeof node !== "object")
- return false;
- const n = node;
- if (n.type === "BinaryExpression" && n.operator === "/" && containsMathPI(n.right))
- return true;
- if (n.type === "BinaryExpression")
- return dividesByMathPI(n.left) || dividesByMathPI(n.right);
- if (n.type === "UnaryExpression")
- return dividesByMathPI(n.argument);
- return false;
-}
-function analyzeTopLevel(ast) {
- const out = {
- hasMetaConst: false,
- metaHasName: false,
- hasBuildFn: false,
- hasAnimateFn: false
- };
- for (const stmt of ast.body) {
- if (stmt.type === "VariableDeclaration" && (stmt.kind === "const" || stmt.kind === "let")) {
- for (const decl of stmt.declarations) {
- if (decl.id.type === "Identifier" && decl.id.name === "meta") {
- out.hasMetaConst = true;
- if (decl.init && decl.init.type === "ObjectExpression") {
- out.metaHasName = decl.init.properties.some((p) => p.type === "Property" && !p.computed && (p.key.type === "Identifier" && p.key.name === "name" || p.key.type === "Literal" && p.key.value === "name"));
- }
- }
- }
- } else if (stmt.type === "FunctionDeclaration" && stmt.id) {
- if (stmt.id.name === "build")
- out.hasBuildFn = true;
- if (stmt.id.name === "animate")
- out.hasAnimateFn = true;
- }
- }
- return out;
-}
-function analyzeBody(ast) {
- const infiniteLoops = [];
- let recursiveBuild;
- let estimatedTris = 0;
- const stack = [];
- walk.ancestor(ast, {
- FunctionDeclaration(node, _state, ancestors) {
- if (node.id?.name)
- stack.push(node.id.name);
- },
- WhileStatement(node) {
- if (isConstantTruthy(node.test) && !hasBreak(node.body)) {
- infiniteLoops.push({ kind: "while(true)", line: node.loc?.start.line });
- }
- },
- ForStatement(node) {
- if (!node.test && !hasBreak(node.body)) {
- infiniteLoops.push({ kind: "for(;;)", line: node.loc?.start.line });
- } else if (node.test && isConstantTruthy(node.test) && !hasBreak(node.body)) {
- infiniteLoops.push({ kind: "for(;;)", line: node.loc?.start.line });
- }
- },
- CallExpression(node, _state, ancestors) {
- if (node.callee.type === "Identifier" && node.callee.name === "build" && insideFunctionNamed(ancestors, "build")) {
- recursiveBuild ??= node.loc?.start.line;
- }
- if (node.callee.type === "Identifier") {
- let est = estimateGeometryTris(node.callee.name, node.arguments);
- if (est === null && node.callee.name === "subdivide") {
- const inner = node.arguments[0];
- if (inner && inner.type === "CallExpression" && inner.callee.type === "Identifier") {
- const base = estimateGeometryTris(inner.callee.name, inner.arguments);
- if (base !== null) {
- const nArg = node.arguments[1];
- const n = Math.min(4, nArg && nArg.type === "Literal" && typeof nArg.value === "number" ? nArg.value : 1);
- est = base * (4 ** Math.max(0, n) - 1);
- }
- }
- }
- if (est !== null) {
- estimatedTris += est * loopMultiplier(ancestors);
- }
- }
- }
- });
- return { infiniteLoops, recursiveBuild, estimatedTris };
-}
-function loopMultiplier(ancestors) {
- let mult = 1;
- for (const node of ancestors) {
- if (node.type !== "ForStatement")
- continue;
- const f = node;
- if (!f.test || f.test.type !== "BinaryExpression")
- continue;
- const { operator, right } = f.test;
- if (operator !== "<" && operator !== "<=")
- continue;
- if (right.type !== "Literal" || typeof right.value !== "number")
- continue;
- const n = operator === "<" ? right.value : right.value + 1;
- if (n > 1 && Number.isFinite(n))
- mult *= Math.min(n, 256);
- }
- return Math.min(mult, 4096);
-}
-function insideFunctionNamed(ancestors, name) {
- for (let i = ancestors.length - 1;i >= 0; i--) {
- const node = ancestors[i];
- if (!node)
- continue;
- if (node.type === "FunctionDeclaration" && node.id?.name === name)
- return true;
- }
- return false;
-}
-function isConstantTruthy(node) {
- if (node.type === "Literal") {
- return Boolean(node.value);
- }
- if (node.type === "Identifier")
- return false;
- if (node.type === "UnaryExpression" && node.operator === "!") {
- if (node.argument.type === "Literal")
- return !node.argument.value;
- }
- return false;
-}
-function hasBreak(body) {
- let found = false;
- walk.simple(body, {
- BreakStatement() {
- found = true;
- },
- ReturnStatement() {
- found = true;
- },
- ThrowStatement() {
- found = true;
- }
- });
- return found;
-}
-var GeneratedSourcePolicyError, FORBIDDEN_AMBIENT_IDENTIFIERS, FORBIDDEN_THREE_CONSTRUCTORS, ROTATION_OPTION_FNS;
-var init_validation = __esm(() => {
- GeneratedSourcePolicyError = class GeneratedSourcePolicyError extends Error {
- code;
- line;
- constructor(issue) {
- super(`Generated source rejected by policy (${issue.code})${issue.line ? ` at line ${issue.line}` : ""}.`);
- this.name = "GeneratedSourcePolicyError";
- this.code = issue.code;
- this.line = issue.line;
- }
- };
- FORBIDDEN_AMBIENT_IDENTIFIERS = new Set([
- "globalThis",
- "global",
- "process",
- "fetch",
- "XMLHttpRequest",
- "WebSocket",
- "Function",
- "eval",
- "window",
- "self",
- "document",
- "navigator",
- "location",
- "Bun",
- "Deno",
- "Reflect",
- "require",
- "module"
- ]);
- FORBIDDEN_THREE_CONSTRUCTORS = new Set([
- "DataTexture",
- "ShaderMaterial",
- "RawShaderMaterial"
- ]);
- ROTATION_OPTION_FNS = new Set(["createPart", "createInstance"]);
-});
-
-// src/kit.ts
-import { execFile } from "node:child_process";
-import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { promisify } from "node:util";
-import { KHRMaterialsVariants, KHRTextureBasisu } from "@gltf-transform/extensions";
-async function findKtxEncoder() {
- if (cachedEncoder !== undefined)
- return cachedEncoder ?? undefined;
- for (const candidate of KTX_ENCODER_CANDIDATES) {
- try {
- await run(candidate, ["--version"], { timeout: 1e4 });
- cachedEncoder = candidate;
- return candidate;
- } catch {}
- }
- cachedEncoder = null;
- return;
-}
-function disposeIfOrphaned(texture) {
- const stillUsed = texture.listParents().some((parent) => parent.propertyType !== "Root");
- if (!stillUsed)
- texture.dispose();
-}
-async function packOcclusionIntoMetallicRoughness(doc) {
- const sharp = (await import("sharp")).default;
- let packed = 0;
- for (const material of doc.getRoot().listMaterials()) {
- const occlusion = material.getOcclusionTexture();
- const metallicRoughness = material.getMetallicRoughnessTexture();
- if (!occlusion || !metallicRoughness || occlusion === metallicRoughness)
- continue;
- if (!isPng(occlusion) || !isPng(metallicRoughness))
- continue;
- const occlusionBytes = occlusion.getImage();
- const mrBytes = metallicRoughness.getImage();
- if (!occlusionBytes || !mrBytes)
- continue;
- try {
- const [occImage, mrImage] = await Promise.all([
- sharp(Buffer.from(occlusionBytes)).ensureAlpha().raw().toBuffer({ resolveWithObject: true }),
- sharp(Buffer.from(mrBytes)).ensureAlpha().raw().toBuffer({ resolveWithObject: true })
- ]);
- if (occImage.info.width !== mrImage.info.width || occImage.info.height !== mrImage.info.height) {
- continue;
- }
- const { width, height } = mrImage.info;
- const merged = Buffer.allocUnsafe(width * height * 3);
- for (let i = 0, o = 0;o < merged.length; i += 4, o += 3) {
- merged[o] = occImage.data[i] ?? 255;
- merged[o + 1] = mrImage.data[i + 1] ?? 255;
- merged[o + 2] = mrImage.data[i + 2] ?? 255;
- }
- const png = await sharp(merged, { raw: { width, height, channels: 3 } }).png({ compressionLevel: 9 }).toBuffer();
- metallicRoughness.setImage(new Uint8Array(png));
- material.setOcclusionTexture(metallicRoughness);
- const info = material.getOcclusionTextureInfo();
- const mrInfo = material.getMetallicRoughnessTextureInfo();
- if (info && mrInfo)
- info.setTexCoord(mrInfo.getTexCoord());
- disposeIfOrphaned(occlusion);
- packed += 1;
- } catch {}
- }
- return packed;
-}
-function recolorForPalette(doc, material, slots, variantName) {
- const clone = doc.createMaterial(`${material.getName()}__${variantName}`).copy(material);
- if (material.getBaseColorTexture())
- return { material: clone, changed: false };
- const index = buildSlotIndex(slots);
- const base = material.getBaseColorFactor();
- const emissive = material.getEmissiveFactor();
- const slot = chooseSlot(index, {
- baseLinear: [base[0], base[1], base[2]],
- emissiveLinear: [emissive[0], emissive[1], emissive[2]],
- transparent: material.getAlphaMode() === "BLEND" || material.getAlpha() < 0.98
- });
- if (slot === undefined)
- return { material: clone, changed: false };
- const chosen = slots[slot];
- if (!chosen)
- return { material: clone, changed: false };
- const [r, g, b] = hexToLinearRgb(chosen.color);
- if (chosen.kind === "glow") {
- clone.setEmissiveFactor([r, g, b]);
- } else {
- clone.setBaseColorFactor([r, g, b, base[3]]);
- if (typeof chosen.roughness === "number")
- clone.setRoughnessFactor(chosen.roughness);
- if (typeof chosen.metalness === "number")
- clone.setMetallicFactor(chosen.metalness);
- if (chosen.kind === "glass" && typeof chosen.opacity === "number") {
- clone.setBaseColorFactor([r, g, b, chosen.opacity]);
- }
- }
- return { material: clone, changed: true };
-}
-function addPaletteVariants(doc, specs) {
- const extension = doc.createExtension(KHRMaterialsVariants);
- const names = [];
- let materialsCreated = 0;
- const variants = specs.map((spec) => {
- names.push(spec.name);
- return { spec, variant: extension.createVariant(spec.name) };
- });
- for (const mesh of doc.getRoot().listMeshes()) {
- for (const primitive of mesh.listPrimitives()) {
- const base = primitive.getMaterial();
- if (!base)
- continue;
- const mappings = variants.map(({ spec, variant }) => {
- const { material, changed } = recolorForPalette(doc, base, spec.slots, spec.name);
- if (!changed) {
- material.dispose();
- return;
- }
- materialsCreated += 1;
- return extension.createMapping().addVariant(variant).setMaterial(material);
- }).filter((value) => value !== undefined);
- if (mappings.length === 0)
- continue;
- const list = extension.createMappingList();
- for (const mapping of mappings)
- list.addMapping(mapping);
- primitive.setExtension("KHR_materials_variants", list);
- }
- }
- if (names.length === 0 || materialsCreated === 0)
- extension.dispose();
- return { names: materialsCreated > 0 ? names : [], materialsCreated };
-}
-async function encodeTexturesToKtx2(doc, encoder) {
- const textures = doc.getRoot().listTextures().filter(isPng);
- if (textures.length === 0)
- return { encoded: 0, before: 0, after: 0 };
- const dir = await mkdtemp(join(tmpdir(), "kiln-ktx2-"));
- const staged = [];
- let encoded = 0;
- let before = 0;
- let after = 0;
- try {
- for (const [index, texture] of textures.entries()) {
- const bytes = texture.getImage();
- if (!bytes)
- continue;
- const src = join(dir, `t${index}.png`);
- const dst = join(dir, `t${index}.ktx2`);
- await writeFile(src, bytes);
- const srgb = doc.getRoot().listMaterials().some((material) => material.getBaseColorTexture() === texture || material.getEmissiveTexture() === texture);
- await run(encoder, [
- "create",
- "--format",
- srgb ? "R8G8B8A8_SRGB" : "R8G8B8A8_UNORM",
- "--encode",
- KTX_ENCODE_MODE,
- "--generate-mipmap",
- src,
- dst
- ], { timeout: 120000 });
- const out = await readFile(dst);
- before += bytes.byteLength;
- after += out.byteLength;
- staged.push({ texture, original: bytes, encodedBytes: new Uint8Array(out) });
- }
- } finally {
- await rm(dir, { recursive: true, force: true });
- }
- if (staged.length === 0)
- return { encoded: 0, before, after };
- if (after >= before * KTX2_SIZE_ACCEPT_RATIO) {
- return { encoded: 0, before, after };
- }
- for (const entry of staged) {
- entry.texture.setImage(entry.encodedBytes).setMimeType("image/ktx2");
- encoded += 1;
- }
- doc.createExtension(KHRTextureBasisu).setRequired(true);
- return { encoded, before, after };
-}
-async function applyKitContract(doc, options = {}) {
- const ormPacked = options.packOrm === false ? 0 : await packOcclusionIntoMetallicRoughness(doc);
- const specs = options.variants ?? [];
- const { names, materialsCreated } = specs.length ? addPaletteVariants(doc, specs) : { names: [], materialsCreated: 0 };
- let ktx2 = {
- applied: false,
- skipped: "disabled by caller",
- texturesEncoded: 0,
- bytesBefore: 0,
- bytesAfter: 0
- };
- if (options.ktx2 !== false) {
- const encoder = await findKtxEncoder();
- if (!encoder) {
- ktx2 = {
- applied: false,
- skipped: "no KTX-Software encoder on PATH (set KILN_KTX_BIN to override)",
- texturesEncoded: 0,
- bytesBefore: 0,
- bytesAfter: 0
- };
- } else {
- try {
- const result = await encodeTexturesToKtx2(doc, encoder);
- ktx2 = {
- applied: result.encoded > 0,
- ...result.encoded > 0 ? {} : {
- skipped: result.before === 0 ? "no PNG textures to encode" : `KTX2 was not smaller (${result.after} vs ${result.before} bytes); kept PNG`
- },
- encoder,
- texturesEncoded: result.encoded,
- bytesBefore: result.before,
- bytesAfter: result.after
- };
- } catch (error) {
- ktx2 = {
- applied: false,
- skipped: `encoder failed: ${error instanceof Error ? error.message : String(error)}`,
- encoder,
- texturesEncoded: 0,
- bytesBefore: 0,
- bytesAfter: 0
- };
- }
- }
- }
- return { ormPacked, variantsAdded: names, variantMaterialsCreated: materialsCreated, ktx2 };
-}
-var run, KTX_ENCODER_CANDIDATES, KTX_ENCODE_MODE = "basis-lz", KTX2_SIZE_ACCEPT_RATIO = 0.9, cachedEncoder, isPng = (texture) => texture.getMimeType() === "image/png";
-var init_kit = __esm(() => {
- run = promisify(execFile);
- KTX_ENCODER_CANDIDATES = Object.freeze([
- process.env["KILN_KTX_BIN"] ?? "",
- "ktx",
- "/usr/bin/ktx",
- "/usr/local/bin/ktx",
- "C:/Program Files/KTX-Software/bin/ktx.exe"
- ].filter((value) => value.length > 0));
-});
-
-// src/texture-bake.ts
-import { createHash as createHash3 } from "node:crypto";
-import * as THREE29 from "three";
-function readPixels(texture) {
- const image = texture.image;
- if (!image)
- return "it has no image data";
- const { width, height } = image;
- if (!Number.isFinite(width) || !Number.isFinite(height) || !width || !height) {
- return "its image has no usable width/height";
- }
- const data = image.data;
- if (!data) {
- return "its pixels are not readable in Node (only DataTexture-style byte arrays can be baked)";
- }
- if (!(data instanceof Uint8Array) && !(data instanceof Uint8ClampedArray)) {
- return `its pixel data is ${data.constructor?.name ?? "an unknown type"}, not 8-bit bytes (float/half-float textures cannot be baked to PNG)`;
- }
- const pixels = width * height;
- const channels = data.length / pixels;
- if (channels !== 3 && channels !== 4) {
- return `its pixel data is ${data.length} bytes for ${width}x${height}, which is neither RGB nor RGBA`;
- }
- return {
- data: data instanceof Uint8Array ? data : new Uint8Array(data),
- width,
- height,
- channels
- };
-}
-async function encodePngFromRaw(raw) {
- const sharp = (await import("sharp")).default;
- const out = await sharp(Buffer.from(raw.data.buffer, raw.data.byteOffset, raw.data.length), {
- raw: { width: raw.width, height: raw.height, channels: raw.channels }
- }).png({ compressionLevel: 9, adaptiveFiltering: false, palette: false }).toBuffer();
- return new Uint8Array(out);
-}
-function hasTranslucentPixel(raw) {
- if (raw.channels !== 4)
- return false;
- for (let i = 3;i < raw.data.length; i += 4) {
- if ((raw.data[i] ?? 255) < 255)
- return true;
- }
- return false;
-}
-function isTexture2(value) {
- return value?.isTexture === true;
-}
-async function bakeSceneTextures(root, warnings) {
- const pending = new Map;
- root.traverse((node) => {
- const material = node.material;
- const materials = Array.isArray(material) ? material : material ? [material] : [];
- for (const item of materials) {
- const bag = item;
- for (const [slot, usage2] of SLOT_USAGE2) {
- const texture = bag[slot];
- if (!isTexture2(texture))
- continue;
- if (texture.userData["encoded"])
- continue;
- const existing = pending.get(texture) ?? { texture, bindings: [] };
- existing.bindings.push({
- node: node.name || "(unnamed node)",
- material: item.name || "(unnamed material)",
- slot,
- usage: usage2
- });
- pending.set(texture, existing);
- }
- }
- });
- const baked = [];
- for (const entry of pending.values()) {
- const name = entry.texture.name || "(unnamed texture)";
- const raw = readPixels(entry.texture);
- const firstBinding = entry.bindings[0];
- const bindingSummary = `material ${JSON.stringify(firstBinding.material)} (${firstBinding.slot})${entry.bindings.length > 1 ? ` and ${entry.bindings.length - 1} other binding(s)` : ""}`;
- if (typeof raw === "string") {
- warnings.push(`Texture ${JSON.stringify(name)} on ${bindingSummary} was dropped from the GLB: ${raw}.`);
- continue;
- }
- let bytes;
- try {
- bytes = await encodePngFromRaw(raw);
- } catch (err) {
- warnings.push(`Texture ${JSON.stringify(name)} on ${bindingSummary} was dropped from the GLB: PNG encoding failed (${err instanceof Error ? err.message : String(err)}).`);
- continue;
- }
- entry.texture.userData["encoded"] = {
- mime: "image/png",
- bytes
- };
- const colorSpace = entry.texture.colorSpace === THREE29.SRGBColorSpace ? "srgb" : "linear";
- const recipe2 = entry.texture.userData["kilnProcedural"];
- const primaryUsage = recipe2?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");
- entry.texture.userData["kilnTexture"] = {
- usage: primaryUsage,
- colorSpace,
- width: raw.width,
- height: raw.height,
- hasAlpha: hasTranslucentPixel(raw)
- };
- const sha1 = createHash3("sha1").update(bytes).digest("hex");
- const imageSha256 = `sha256:${createHash3("sha256").update(bytes).digest("hex")}`;
- baked.push({
- schemaVersion: 1,
- texture: name,
- node: firstBinding.node,
- material: firstBinding.material,
- slot: firstBinding.slot,
- usage: primaryUsage,
- bindings: entry.bindings,
- width: raw.width,
- height: raw.height,
- channels: raw.channels,
- bytes: bytes.length,
- mime: "image/png",
- colorSpace,
- imageSha256,
- sha1,
- ...recipe2 ? { procedural: recipe2 } : {}
- });
- }
- return baked.sort((a, b) => `${a.node}:${a.material}:${a.texture}:${a.slot}`.localeCompare(`${b.node}:${b.material}:${b.texture}:${b.slot}`));
-}
-function computeTangentBasis(geometry2) {
- const index = geometry2.getIndex();
- const position = geometry2.getAttribute("position");
- const normal = geometry2.getAttribute("normal");
- const uv = geometry2.getAttribute("uv");
- if (!position || !normal || !uv) {
- throw new Error("position, normal, and uv are all required");
- }
- const vertexCount = position.count;
- const triangleIndices = index ? index.count : vertexCount;
- const at = index ? (i) => index.getX(i) : (i) => i;
- const tan1 = new Float32Array(vertexCount * 3);
- const tan2 = new Float32Array(vertexCount * 3);
- for (let i = 0;i + 2 < triangleIndices; i += 3) {
- const a = at(i);
- const b = at(i + 1);
- const c = at(i + 2);
- const x1 = position.getX(b) - position.getX(a);
- const y1 = position.getY(b) - position.getY(a);
- const z1 = position.getZ(b) - position.getZ(a);
- const x2 = position.getX(c) - position.getX(a);
- const y2 = position.getY(c) - position.getY(a);
- const z2 = position.getZ(c) - position.getZ(a);
- const s1 = uv.getX(b) - uv.getX(a);
- const t1 = uv.getY(b) - uv.getY(a);
- const s2 = uv.getX(c) - uv.getX(a);
- const t2 = uv.getY(c) - uv.getY(a);
- const det = s1 * t2 - s2 * t1;
- if (det === 0 || !Number.isFinite(det))
- continue;
- const r = 1 / det;
- const sdx = (t2 * x1 - t1 * x2) * r;
- const sdy = (t2 * y1 - t1 * y2) * r;
- const sdz = (t2 * z1 - t1 * z2) * r;
- const tdx = (s1 * x2 - s2 * x1) * r;
- const tdy = (s1 * y2 - s2 * y1) * r;
- const tdz = (s1 * z2 - s2 * z1) * r;
- for (const v of [a, b, c]) {
- const o = v * 3;
- tan1[o] = (tan1[o] ?? 0) + sdx;
- tan1[o + 1] = (tan1[o + 1] ?? 0) + sdy;
- tan1[o + 2] = (tan1[o + 2] ?? 0) + sdz;
- tan2[o] = (tan2[o] ?? 0) + tdx;
- tan2[o + 1] = (tan2[o + 1] ?? 0) + tdy;
- tan2[o + 2] = (tan2[o + 2] ?? 0) + tdz;
- }
- }
- const out = new Float32Array(vertexCount * 4);
- const n = new THREE29.Vector3;
- const t = new THREE29.Vector3;
- const tmp = new THREE29.Vector3;
- const tmp2 = new THREE29.Vector3;
- for (let v = 0;v < vertexCount; v++) {
- n.set(normal.getX(v), normal.getY(v), normal.getZ(v));
- t.set(tan1[v * 3], tan1[v * 3 + 1], tan1[v * 3 + 2]);
- if (t.lengthSq() === 0) {
- t.set(1, 0, 0);
- if (Math.abs(n.x) > 0.9)
- t.set(0, 1, 0);
- }
- tmp.copy(t).sub(tmp2.copy(n).multiplyScalar(n.dot(t)));
- if (tmp.lengthSq() === 0)
- tmp.set(1, 0, 0);
- tmp.normalize();
- tmp2.set(tan2[v * 3], tan2[v * 3 + 1], tan2[v * 3 + 2]);
- const w = n.clone().cross(t).dot(tmp2) < 0 ? -1 : 1;
- out[v * 4] = tmp.x;
- out[v * 4 + 1] = tmp.y;
- out[v * 4 + 2] = tmp.z;
- out[v * 4 + 3] = w;
- }
- geometry2.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));
-}
-function ensureNormalMapTangents(root, warnings) {
- let count = 0;
- const done = new Set;
- root.traverse((node) => {
- const mesh = node;
- if (!mesh.isMesh)
- return;
- const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
- const needsTangents = materials.some((m) => m?.normalMap);
- if (!needsTangents)
- return;
- const geometry2 = mesh.geometry;
- if (!geometry2 || done.has(geometry2) || geometry2.getAttribute("tangent"))
- return;
- done.add(geometry2);
- const name = mesh.name || "(unnamed mesh)";
- if (!geometry2.getAttribute("uv")) {
- warnings.push(`Mesh ${JSON.stringify(name)} uses a normal map but has no UV coordinates, so tangents could not be computed — and the normal map cannot be sampled either. Unwrap it first: mesh.geometry = await autoUnwrap(mesh.geometry).`);
- return;
- }
- if (!geometry2.getAttribute("normal"))
- geometry2.computeVertexNormals();
- try {
- computeTangentBasis(geometry2);
- count++;
- } catch (err) {
- warnings.push(`Mesh ${JSON.stringify(name)} uses a normal map but tangents could not be computed (${err instanceof Error ? err.message : String(err)}). Each runtime will generate its own tangent basis.`);
- }
- });
- return count;
-}
-var SLOT_USAGE2;
-var init_texture_bake = __esm(() => {
- SLOT_USAGE2 = [
- ["map", "albedo"],
- ["normalMap", "normal"],
- ["roughnessMap", "roughness"],
- ["metalnessMap", "metalness"],
- ["emissiveMap", "emissive"],
- ["aoMap", "occlusion"]
- ];
-});
-
-// src/views/character.ts
-import * as THREE30 from "three";
-function rounded(value) {
- const result = Math.round(value * 1e9) / 1e9;
- return Object.is(result, -0) ? 0 : result;
-}
-function tuple2(vector) {
- return [rounded(vector.x), rounded(vector.y), rounded(vector.z)];
-}
-function chainIdFor(descriptor2, byRole) {
- if (AXIAL_ROLES.has(descriptor2.role))
- return "axial";
- let current = descriptor2;
- const seen = new Set([current.role]);
- while (current.parentRole && !AXIAL_ROLES.has(current.parentRole)) {
- const parent = byRole.get(current.parentRole);
- if (!parent || seen.has(parent.role))
- break;
- seen.add(parent.role);
- current = parent;
- }
- return current.role;
-}
-function colorFor(value) {
- let hash = 2166136261;
- for (let index = 0;index < value.length; index++) {
- hash ^= value.charCodeAt(index);
- hash = Math.imul(hash, 16777619);
- }
- return CHAIN_COLORS[Math.abs(hash) % CHAIN_COLORS.length];
-}
-function buildCharacterDiagnosticDescriptor(root, findings = []) {
- root.updateMatrixWorld(true);
- const rootInverse2 = root.matrixWorld.clone().invert();
- const evidence2 = collectCharacterJointNodes(root);
- const descriptorByRole = new Map(evidence2.map((joint) => [joint.descriptor.role, joint.descriptor]));
- const evidenceByRole = new Map(evidence2.map((joint) => [joint.descriptor.role, joint]));
- const invalidFindingNodePaths = [
- ...new Set(findings.filter((finding6) => finding6.code === "CHAR_PARENT_EDGE").map((finding6) => finding6.affected?.nodePath).filter((path) => Boolean(path)))
- ].sort();
- const invalidPaths = new Set(invalidFindingNodePaths);
- const joints = evidence2.map((joint) => {
- const relative = rootInverse2.clone().multiply(joint.node.matrixWorld);
- const position = new THREE30.Vector3().setFromMatrixPosition(relative);
- const forward = new THREE30.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
- const bend2 = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
- const chainId = chainIdFor(joint.descriptor, descriptorByRole);
- return {
- role: joint.descriptor.role,
- aliases: [...joint.descriptor.aliases],
- side: joint.descriptor.side,
- nodeName: joint.node.name,
- nodePath: joint.nodePath,
- label: joint.descriptor.role,
- chainId,
- color: colorFor(chainId),
- assetPosition: tuple2(position),
- forwardAxisEnd: tuple2(forward),
- bendAxisEnd: tuple2(bend2),
- endEffector: joint.descriptor.endEffector,
- contact: joint.descriptor.contact
- };
- });
- const edges = evidence2.filter((joint) => joint.descriptor.parentRole).map((joint) => {
- const parentRole = joint.descriptor.parentRole;
- const parent = evidenceByRole.get(parentRole);
- const chainId = chainIdFor(joint.descriptor, descriptorByRole);
- return {
- parentRole,
- childRole: joint.descriptor.role,
- ...parent ? { parentNodePath: parent.nodePath } : {},
- childNodePath: joint.nodePath,
- valid: Boolean(parent) && !invalidPaths.has(joint.nodePath),
- color: colorFor(chainId)
- };
- }).sort((a, b) => `${a.parentRole}:${a.childRole}`.localeCompare(`${b.parentRole}:${b.childRole}`));
- return {
- schemaVersion: 1,
- joints,
- edges,
- contacts: joints.filter((joint) => joint.contact).map((joint) => ({
- role: joint.role,
- nodePath: joint.nodePath,
- assetPosition: joint.assetPosition
- })),
- canonicalForwardArrow: { start: [0, 0, 0], end: [1, 0, 0], label: "+X forward" },
- invalidFindingNodePaths
- };
-}
-function safeClipId(name) {
- return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
-}
-function planCharacterDiagnosticRequests(intent) {
- const requests = [
- diagnosticRequest({
- id: "character.skeleton.front",
- label: "Character skeleton front",
- cameraId: "front",
- buffer: "semantic-overlay",
- variant: "character-skeleton",
- focusRolePrefixes: ["skeleton.", "joint.", "contact."],
- automatic: true
- }),
- diagnosticRequest({
- id: "character.skeleton.right",
- label: "Character skeleton right",
- cameraId: "right",
- buffer: "semantic-overlay",
- variant: "character-skeleton",
- focusRolePrefixes: ["skeleton.", "joint.", "contact."],
- automatic: true
- })
- ];
- const locomotion = intent.clips.find((clip) => clip.playback === "loop" && new RegExp(intent.locomotion === "stationary" ? "idle" : intent.locomotion, "i").test(clip.name)) ?? intent.clips.find((clip) => clip.playback === "loop");
- const action = intent.clips.find((clip) => clip.playback === "oneShot");
- const selected = [locomotion, action].filter((clip, index, values) => Boolean(clip) && values.findIndex((candidate) => candidate?.name === clip?.name) === index);
- for (const clip of selected) {
- for (const cameraId of ["front", "right"]) {
- requests.push(diagnosticRequest({
- id: `character.motion-strip.${cameraId}.${safeClipId(clip.name)}`,
- label: `${clip.name} fixed-phase ${cameraId} strip`,
- cameraId,
- buffer: "silhouette-unlit",
- variant: "character-motion-strip",
- clipName: clip.name,
- phaseFractions: CHARACTER_MOTION_DIAGNOSTIC_PHASES,
- focusRolePrefixes: ["skeleton.", "joint.", "limb.", "held-item"],
- automatic: true
- }));
- }
- }
- return Object.freeze(requests);
-}
-var CHAIN_COLORS, AXIAL_ROLES, CHARACTER_MOTION_DIAGNOSTIC_PHASES, diagnosticRequest = (value) => Object.freeze({
- ...value,
- focusRolePrefixes: Object.freeze([...value.focusRolePrefixes]),
- ...value.phaseFractions ? { phaseFractions: Object.freeze([...value.phaseFractions]) } : {}
-});
-var init_character3 = __esm(() => {
- init_character();
- CHAIN_COLORS = Object.freeze([
- "#4fc3f7",
- "#ff8a65",
- "#81c784",
- "#ba68c8",
- "#ffd54f",
- "#4db6ac",
- "#f06292",
- "#90a4ae"
- ]);
- AXIAL_ROLES = new Set(["root", "hips", "spine", "neck", "head"]);
- CHARACTER_MOTION_DIAGNOSTIC_PHASES = Object.freeze([0, 0.2, 0.4, 0.6, 0.8, 1]);
-});
-
-// src/views/png.ts
-import { deflateSync, inflateSync } from "node:zlib";
-function crc32(buf) {
- let c = 4294967295;
- for (let i = 0;i < buf.length; i++) {
- c = CRC_TABLE[(c ^ buf[i]) & 255] ^ c >>> 8;
- }
- return (c ^ 4294967295) >>> 0;
-}
-function chunk(type, data) {
- const out = Buffer.alloc(8 + data.length + 4);
- out.writeUInt32BE(data.length, 0);
- out.write(type, 4, "ascii");
- out.set(data, 8);
- const crcInput = out.subarray(4, 8 + data.length);
- out.writeUInt32BE(crc32(crcInput), 8 + data.length);
- return out;
-}
-function encodePng(rgb2, width, height) {
- if (rgb2.length !== width * height * 3) {
- throw new Error(`encodePng: expected ${width * height * 3} bytes, got ${rgb2.length}`);
- }
- const ihdr = Buffer.alloc(13);
- ihdr.writeUInt32BE(width, 0);
- ihdr.writeUInt32BE(height, 4);
- ihdr[8] = 8;
- ihdr[9] = 2;
- ihdr[10] = 0;
- ihdr[11] = 0;
- ihdr[12] = 0;
- const raw = Buffer.alloc(height * (1 + width * 3));
- for (let y = 0;y < height; y++) {
- const rowStart = y * (1 + width * 3);
- raw[rowStart] = 0;
- raw.set(rgb2.subarray(y * width * 3, (y + 1) * width * 3), rowStart + 1);
- }
- return Buffer.concat([
- Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
- chunk("IHDR", ihdr),
- chunk("IDAT", deflateSync(raw)),
- chunk("IEND", new Uint8Array(0))
- ]);
-}
-function decodePng(png) {
- if (png.length < 8 || PNG_SIGNATURE.some((b, i) => png[i] !== b)) {
- throw new Error("decodePng: not a PNG (bad signature)");
- }
- const view = new DataView(png.buffer, png.byteOffset, png.byteLength);
- let width = 0;
- let height = 0;
- let bitDepth = 0;
- let colorType = 0;
- let interlace = 0;
- let sawIhdr = false;
- const idat = [];
- let off = 8;
- while (off + 8 <= png.length) {
- const len = view.getUint32(off);
- const type = String.fromCharCode(png[off + 4], png[off + 5], png[off + 6], png[off + 7]);
- const dataStart = off + 8;
- if (dataStart + len + 4 > png.length)
- throw new Error("decodePng: truncated chunk");
- if (type === "IHDR") {
- width = view.getUint32(dataStart);
- height = view.getUint32(dataStart + 4);
- bitDepth = png[dataStart + 8];
- colorType = png[dataStart + 9];
- interlace = png[dataStart + 12];
- sawIhdr = true;
- } else if (type === "IDAT") {
- idat.push(Buffer.from(png.subarray(dataStart, dataStart + len)));
- } else if (type === "IEND") {
- break;
- }
- off = dataStart + len + 4;
- }
- if (!sawIhdr || idat.length === 0)
- throw new Error("decodePng: missing IHDR or IDAT");
- if (bitDepth !== 8 || colorType !== 2 && colorType !== 6 || interlace !== 0) {
- throw new Error(`decodePng: unsupported PNG (bitDepth ${bitDepth}, colorType ${colorType}, interlace ` + `${interlace}); only 8-bit non-interlaced RGB/RGBA is supported`);
- }
- if (width <= 0 || height <= 0)
- throw new Error("decodePng: empty image");
- const channels = colorType === 6 ? 4 : 3;
- const stride = width * channels;
- const raw = inflateSync(idat.length === 1 ? idat[0] : Buffer.concat(idat));
- if (raw.length !== height * (1 + stride)) {
- throw new Error(`decodePng: expected ${height * (1 + stride)} raw bytes, got ${raw.length}`);
- }
- const rgb2 = new Uint8Array(width * height * 3);
- const cur = new Uint8Array(stride);
- const prior = new Uint8Array(stride);
- for (let y = 0;y < height; y++) {
- const rowStart = y * (1 + stride);
- const filter = raw[rowStart];
- if (filter > 4)
- throw new Error(`decodePng: unknown filter type ${filter}`);
- for (let i = 0;i < stride; i++) {
- const x = raw[rowStart + 1 + i];
- const a = i >= channels ? cur[i - channels] : 0;
- const b = prior[i];
- let value;
- if (filter === 0)
- value = x;
- else if (filter === 1)
- value = x + a;
- else if (filter === 2)
- value = x + b;
- else if (filter === 3)
- value = x + (a + b >> 1);
- else {
- const c = i >= channels ? prior[i - channels] : 0;
- const p = a + b - c;
- const pa = Math.abs(p - a);
- const pb = Math.abs(p - b);
- const pc = Math.abs(p - c);
- value = x + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c);
- }
- cur[i] = value & 255;
- }
- for (let px = 0;px < width; px++) {
- const src = px * channels;
- const dst = (y * width + px) * 3;
- rgb2[dst] = cur[src];
- rgb2[dst + 1] = cur[src + 1];
- rgb2[dst + 2] = cur[src + 2];
- }
- prior.set(cur);
- }
- return { rgb: rgb2, width, height };
-}
-var CRC_TABLE, PNG_SIGNATURE;
-var init_png = __esm(() => {
- CRC_TABLE = (() => {
- const table = new Uint32Array(256);
- for (let n = 0;n < 256; n++) {
- let c = n;
- for (let k = 0;k < 8; k++) {
- c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
- }
- table[n] = c >>> 0;
- }
- return table;
- })();
- PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
-});
-
-// src/views/diagnostic.ts
-function architectureDiagnosticRequests(intent) {
- const architecture = intent.architecture;
- if (!architecture)
- return [];
- const requests = [];
- const buildingProfile = architecture.roof.type === "gable" || /(?:building|house|cottage|barn|hut|gable)/i.test(architecture.subtype);
- if (buildingProfile) {
- const ridgeX = architecture.roof.ridgeAxis === "x";
- requests.push(request({
- id: "architecture.gable.positive",
- label: "Architecture positive gable elevation",
- cameraId: ridgeX ? "front" : "right",
- buffer: "semantic-overlay",
- scope: "category",
- variant: "architecture-gable-elevation",
- focusRolePrefixes: ["roof.gable.positive", "roof.slope.", "wall."]
- }), request({
- id: "architecture.gable.negative",
- label: "Architecture negative gable elevation",
- cameraId: ridgeX ? "back" : "left",
- buffer: "semantic-overlay",
- scope: "category",
- variant: "architecture-gable-elevation",
- focusRolePrefixes: ["roof.gable.negative", "roof.slope.", "wall."]
- }));
- }
- requests.push(request({
- id: "architecture.cutaway.plan",
- label: "Architecture roof-off plan",
- cameraId: "top",
- buffer: "semantic-overlay",
- scope: "category",
- variant: "architecture-cutaway",
- omitRolePrefixes: ["roof."]
- }), request({
- id: "architecture.cutaway.dollhouse",
- label: "Architecture roof-off dollhouse",
- cameraId: "three-quarter",
- buffer: "semantic-overlay",
- scope: "category",
- variant: "architecture-cutaway",
- omitRolePrefixes: ["roof."]
- }));
- if (architecture.enterable) {
- requests.push(request({
- id: "architecture.portal.eye",
- label: "Architecture portal eye view",
- cameraId: "front",
- buffer: "depth-contact",
- scope: "category",
- variant: "architecture-portal-eye",
- focusRolePrefixes: ["opening.", "wall.", "floor"]
- }));
- }
- return Object.freeze(requests);
-}
-function characterDiagnosticRequests(intent) {
- if (!intent.character)
- return [];
- return Object.freeze(planCharacterDiagnosticRequests(intent.character).map((value) => request({
- id: value.id,
- label: value.label,
- cameraId: value.cameraId,
- buffer: value.buffer,
- scope: "category",
- variant: value.variant,
- focusRolePrefixes: value.focusRolePrefixes,
- ...value.phaseFractions ? { phaseFractions: value.phaseFractions } : {},
- ...value.clipName ? { clipName: value.clipName } : {}
- })));
-}
-function planDiagnosticViews(intent) {
- const categoryRequests = intent.category === "architecture" ? architectureDiagnosticRequests(intent) : intent.category === "character" ? characterDiagnosticRequests(intent) : CATEGORY_REQUESTS[intent.category];
- const includeGrazing = intent.material.mode !== "flatOptimized";
- return {
- schemaVersion: 1,
- category: intent.category,
- qaProfile: intent.qaProfile,
- genericCameraIds: Object.freeze(GENERIC_DIAGNOSTIC_CAMERAS.map((camera) => camera.id)),
- generic: GENERIC_DIAGNOSTIC_REQUESTS,
- extra: includeGrazing ? Object.freeze([...categoryRequests, MATERIAL_GRAZING_REQUEST]) : categoryRequests
- };
-}
-function multiplyMatrices(a, b) {
- const out = new Float64Array(16);
- for (let column = 0;column < 4; column++) {
- for (let row = 0;row < 4; row++) {
- let value = 0;
- for (let k = 0;k < 4; k++)
- value += a[k * 4 + row] * b[column * 4 + k];
- out[column * 4 + row] = value;
- }
- }
- return out;
-}
-function composeLocalMatrix(node) {
- if (node.matrixAutoUpdate === false && node.matrix?.elements) {
- return new Float64Array(Array.from(node.matrix.elements));
- }
- const p = node.position;
- const q = node.quaternion;
- const s = node.scale;
- if (!p || !q || !s) {
- return node.matrix?.elements ? new Float64Array(Array.from(node.matrix.elements)) : new Float64Array(IDENTITY);
- }
- const x2 = q.x + q.x;
- const y2 = q.y + q.y;
- const z2 = q.z + q.z;
- const xx = q.x * x2;
- const xy = q.x * y2;
- const xz = q.x * z2;
- const yy = q.y * y2;
- const yz = q.y * z2;
- const zz = q.z * z2;
- const wx = q.w * x2;
- const wy = q.w * y2;
- const wz = q.w * z2;
- return new Float64Array([
- (1 - (yy + zz)) * s.x,
- (xy + wz) * s.x,
- (xz - wy) * s.x,
- 0,
- (xy - wz) * s.y,
- (1 - (xx + zz)) * s.y,
- (yz + wx) * s.y,
- 0,
- (xz + wy) * s.z,
- (yz - wx) * s.z,
- (1 - (xx + yy)) * s.z,
- 0,
- p.x,
- p.y,
- p.z,
- 1
- ]);
-}
-function transformPoint2(matrix, x, y, z) {
- return [
- matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12],
- matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13],
- matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]
- ];
-}
-function matchesRole(roles2, prefixes) {
- return Boolean(prefixes?.some((prefix) => roles2.some((role) => role.startsWith(prefix))));
-}
-function semanticRoles2(node) {
- const metadata = readSemanticMetadataV1FromExtras(node.userData ?? {});
- if (metadata)
- return metadata.roles;
- const geometryRole = node.geometry?.userData?.["kilnGeometryRole"];
- return typeof geometryRole === "string" ? [geometryRole] : [];
-}
-function clamp01(value) {
- return value < 0 ? 0 : value > 1 ? 1 : value;
-}
-function collectScene(root, requestValue) {
- const triangles = [];
- const min = [Infinity, Infinity, Infinity];
- const max = [-Infinity, -Infinity, -Infinity];
- const focusMin = [Infinity, Infinity, Infinity];
- const focusMax = [-Infinity, -Infinity, -Infinity];
- const visit = (node, parentMatrix, parentPath, siblingIndex, ancestorVisible, inheritedRoles) => {
- const local = composeLocalMatrix(node);
- const world = multiplyMatrices(parentMatrix, local);
- const visible = ancestorVisible && node.visible !== false;
- const segment = `${node.name?.trim() || node.type || "Node"}[${siblingIndex}]`;
- const nodePath5 = parentPath ? `${parentPath}/${segment}` : segment;
- const roles2 = [...new Set([...inheritedRoles, ...semanticRoles2(node)])];
- const omitted = matchesRole(roles2, requestValue.omitRolePrefixes);
- if (visible && !omitted && node.isMesh && node.geometry) {
- const materials = Array.isArray(node.material) ? node.material : [node.material];
- const material = materials[0];
- if (material?.visible !== false) {
- const position = node.geometry.getAttribute?.("position");
- if (position?.itemSize === 3) {
- const worldPositions = [];
- for (let index2 = 0;index2 < position.count; index2++) {
- const point = transformPoint2(world, position.array[index2 * 3], position.array[index2 * 3 + 1], position.array[index2 * 3 + 2]);
- worldPositions.push(point);
- }
- const materialColor = material?.color;
- const color2 = materialColor ? [clamp01(materialColor.r), clamp01(materialColor.g), clamp01(materialColor.b)] : [0.7, 0.7, 0.7];
- const focused = matchesRole(roles2, requestValue.focusRolePrefixes);
- const addTriangle = (a, b, c) => {
- const points = [worldPositions[a], worldPositions[b], worldPositions[c]];
- if (points.some((point) => !point || point.some((value) => !Number.isFinite(value)))) {
- return;
- }
- const vertices = new Float64Array(9);
- points.forEach((point, pointIndex) => {
- for (let axis = 0;axis < 3; axis++) {
- const value = point[axis];
- vertices[pointIndex * 3 + axis] = value;
- min[axis] = Math.min(min[axis], value);
- max[axis] = Math.max(max[axis], value);
- if (focused) {
- focusMin[axis] = Math.min(focusMin[axis], value);
- focusMax[axis] = Math.max(focusMax[axis], value);
- }
- }
- });
- triangles.push({
- vertices,
- color: color2,
- nodeName: node.name ?? "",
- nodePath: nodePath5,
- semanticRoles: roles2
- });
- };
- const index = node.geometry.index;
- if (index) {
- for (let i = 0;i + 2 < index.count; i += 3) {
- addTriangle(index.array[i], index.array[i + 1], index.array[i + 2]);
- }
- } else {
- for (let i = 0;i + 2 < position.count; i += 3)
- addTriangle(i, i + 1, i + 2);
- }
- }
- }
- }
- (node.children ?? []).forEach((child, index) => {
- visit(child, world, nodePath5, index, visible && !omitted, roles2);
- });
- };
- visit(root, IDENTITY, "", 0, true, []);
- const empty = !Number.isFinite(min[0]);
- const focusEmpty = !Number.isFinite(focusMin[0]);
- return {
- triangles,
- bounds: empty ? { min: [0, 0, 0], max: [0, 0, 0] } : { min, max },
- ...!focusEmpty ? { focusBounds: { min: focusMin, max: focusMax } } : {}
- };
-}
-function normalize2(vector) {
- const length3 = Math.hypot(...vector) || 1;
- return [vector[0] / length3, vector[1] / length3, vector[2] / length3];
-}
-function cross2(a, b) {
- return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
-}
-function dot3(a, b) {
- return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
-}
-function stableColor(key) {
- let hash = 2166136261;
- for (let index = 0;index < key.length; index++) {
- hash ^= key.charCodeAt(index);
- hash = Math.imul(hash, 16777619);
- }
- return [96 + (hash & 127), 96 + (hash >>> 8 & 127), 96 + (hash >>> 16 & 127)];
-}
-function projectScene(scene, camera, size) {
- const zAxis = normalize2(camera.dir);
- const upHint = Math.abs(zAxis[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];
- const xAxis = normalize2(cross2(upHint, zAxis));
- const yAxis = cross2(zAxis, xAxis);
- const frame = scene.focusBounds ?? scene.bounds;
- const center = [
- (frame.min[0] + frame.max[0]) / 2,
- (frame.min[1] + frame.max[1]) / 2,
- (frame.min[2] + frame.max[2]) / 2
- ];
- let extent2 = 0.000001;
- for (let corner = 0;corner < 8; corner++) {
- const point = [
- (corner & 1 ? frame.max[0] : frame.min[0]) - center[0],
- (corner & 2 ? frame.max[1] : frame.min[1]) - center[1],
- (corner & 4 ? frame.max[2] : frame.min[2]) - center[2]
- ];
- extent2 = Math.max(extent2, Math.abs(dot3(point, xAxis)), Math.abs(dot3(point, yAxis)));
- }
- const scale2 = size * 0.45 / extent2;
- const half = size / 2;
- return scene.triangles.flatMap((triangle) => {
- const v = triangle.vertices;
- const edgeA = [v[3] - v[0], v[4] - v[1], v[5] - v[2]];
- const edgeB = [v[6] - v[0], v[7] - v[1], v[8] - v[2]];
- const normalRaw = cross2(edgeA, edgeB);
- const length3 = Math.hypot(...normalRaw);
- if (length3 < 0.000000000001)
- return [];
- const normal = normalRaw.map((component) => component / length3);
- const xs = [];
- const ys = [];
- const zs = [];
- const worldY = [];
- for (let index = 0;index < 3; index++) {
- const point = [
- v[index * 3] - center[0],
- v[index * 3 + 1] - center[1],
- v[index * 3 + 2] - center[2]
- ];
- xs.push(half + dot3(point, xAxis) * scale2);
- ys.push(half - dot3(point, yAxis) * scale2);
- zs.push(dot3(point, zAxis));
- worldY.push(v[index * 3 + 1]);
- }
- return [
- {
- source: triangle,
- x: xs,
- y: ys,
- z: zs,
- worldY,
- normal,
- frontFacing: dot3(normal, zAxis) > 0
- }
- ];
- });
-}
-function drawLine(rgb2, size, from, to, color2) {
- let x0 = Math.round(from[0]);
- let y0 = Math.round(from[1]);
- const x1 = Math.round(to[0]);
- const y1 = Math.round(to[1]);
- const dx = Math.abs(x1 - x0);
- const sx = x0 < x1 ? 1 : -1;
- const dy = -Math.abs(y1 - y0);
- const sy = y0 < y1 ? 1 : -1;
- let error = dx + dy;
- while (true) {
- if (x0 >= 0 && x0 < size && y0 >= 0 && y0 < size) {
- const offset = (y0 * size + x0) * 3;
- rgb2[offset] = color2[0];
- rgb2[offset + 1] = color2[1];
- rgb2[offset + 2] = color2[2];
- }
- if (x0 === x1 && y0 === y1)
- break;
- const doubled = 2 * error;
- if (doubled >= dy) {
- error += dy;
- x0 += sx;
- }
- if (doubled <= dx) {
- error += dx;
- y0 += sy;
- }
- }
-}
-function drawRegionBox(rgb2, size, region) {
- const [minX, minY, maxX, maxY] = region.pixelBounds;
- drawLine(rgb2, size, [minX, minY], [maxX, minY], region.color);
- drawLine(rgb2, size, [maxX, minY], [maxX, maxY], region.color);
- drawLine(rgb2, size, [maxX, maxY], [minX, maxY], region.color);
- drawLine(rgb2, size, [minX, maxY], [minX, minY], region.color);
-}
-function renderDiagnosticView(root, requestValue, options = {}) {
- const camera = cameraById.get(requestValue.cameraId);
- if (!camera)
- throw new TypeError(`Unknown diagnostic camera ${JSON.stringify(requestValue.cameraId)}.`);
- const size = Math.max(16, Math.min(1024, Math.round(options.size ?? 256)));
- const groundY = options.groundY ?? 0;
- const scene = collectScene(root, requestValue);
- const triangles = projectScene(scene, camera, size);
- const background = [18, 20, 24];
- const rgb2 = new Uint8Array(size * size * 3);
- for (let pixel = 0;pixel < size * size; pixel++) {
- rgb2[pixel * 3] = background[0];
- rgb2[pixel * 3 + 1] = background[1];
- rgb2[pixel * 3 + 2] = background[2];
- }
- const depth = new Float64Array(size * size).fill(-Infinity);
- const depths = triangles.flatMap((triangle) => triangle.z);
- const minDepth = depths.length > 0 ? Math.min(...depths) : 0;
- const maxDepth = depths.length > 0 ? Math.max(...depths) : 1;
- const depthRange = Math.max(0.000000001, maxDepth - minDepth);
- const contactTolerance = Math.max(0.0001, (scene.bounds.max[1] - scene.bounds.min[1]) * 0.015);
- const regionMap = new Map;
- for (const triangle of triangles) {
- const minX = Math.max(0, Math.floor(Math.min(...triangle.x)));
- const maxX = Math.min(size - 1, Math.ceil(Math.max(...triangle.x)));
- const minY = Math.max(0, Math.floor(Math.min(...triangle.y)));
- const maxY = Math.min(size - 1, Math.ceil(Math.max(...triangle.y)));
- if (minX > maxX || minY > maxY)
- continue;
- const key = triangle.source.semanticRoles.at(-1) ?? triangle.source.nodePath;
- const regionColor = stableColor(key);
- const existing = regionMap.get(triangle.source.nodePath);
- if (existing) {
- existing.pixelBounds[0] = Math.min(existing.pixelBounds[0], minX);
- existing.pixelBounds[1] = Math.min(existing.pixelBounds[1], minY);
- existing.pixelBounds[2] = Math.max(existing.pixelBounds[2], maxX);
- existing.pixelBounds[3] = Math.max(existing.pixelBounds[3], maxY);
- existing.triangleCount++;
- } else {
- regionMap.set(triangle.source.nodePath, {
- nodeName: triangle.source.nodeName,
- nodePath: triangle.source.nodePath,
- semanticRoles: [...triangle.source.semanticRoles],
- pixelBounds: [minX, minY, maxX, maxY],
- color: regionColor,
- triangleCount: 1
- });
- }
- if (requestValue.buffer === "wireframe")
- continue;
- const ax = triangle.x[0];
- const ay = triangle.y[0];
- const bx = triangle.x[1];
- const by = triangle.y[1];
- const cx = triangle.x[2];
- const cy = triangle.y[2];
- const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
- if (Math.abs(area) < 0.000000001)
- continue;
- const inverseArea = 1 / area;
- for (let py = minY;py <= maxY; py++) {
- for (let px = minX;px <= maxX; px++) {
- const sampleX = px + 0.5;
- const sampleY = py + 0.5;
- const w0 = ((bx - ax) * (sampleY - ay) - (by - ay) * (sampleX - ax)) * inverseArea;
- const w1 = ((cx - bx) * (sampleY - by) - (cy - by) * (sampleX - bx)) * inverseArea;
- const w2 = 1 - w0 - w1;
- if (w0 < 0 || w1 < 0 || w2 < 0)
- continue;
- const pixelDepth = w1 * triangle.z[0] + w2 * triangle.z[1] + w0 * triangle.z[2];
- const pixel = py * size + px;
- if (pixelDepth <= depth[pixel])
- continue;
- depth[pixel] = pixelDepth;
- const offset = pixel * 3;
- let color2;
- if (requestValue.variant === "material-grazing-light") {
- const grazingDirection = normalize2([0.25, 0.08, 1]);
- const light = 0.08 + 0.92 * Math.max(0, dot3(triangle.normal, grazingDirection));
- color2 = triangle.source.color.map((value) => Math.round(clamp01(value * light) * 255));
- } else if (requestValue.buffer === "silhouette-unlit") {
- color2 = [235, 238, 242];
- } else if (requestValue.buffer === "normals-backface") {
- color2 = triangle.frontFacing ? triangle.normal.map((value) => Math.round((value * 0.5 + 0.5) * 255)) : [238, 48, 64];
- } else if (requestValue.buffer === "depth-contact") {
- const worldY = w1 * triangle.worldY[0] + w2 * triangle.worldY[1] + w0 * triangle.worldY[2];
- if (Math.abs(worldY - groundY) <= contactTolerance)
- color2 = [58, 220, 126];
- else if (worldY < groundY - contactTolerance)
- color2 = [245, 94, 72];
- else {
- const value = Math.round(48 + 190 * ((pixelDepth - minDepth) / depthRange));
- color2 = [value, value, value];
- }
- } else {
- color2 = regionColor;
- }
- rgb2[offset] = color2[0];
- rgb2[offset + 1] = color2[1];
- rgb2[offset + 2] = color2[2];
- }
- }
- }
- if (requestValue.buffer === "wireframe") {
- for (const triangle of triangles) {
- const color2 = triangle.frontFacing ? [225, 235, 245] : [230, 72, 84];
- for (const [a, b] of [
- [0, 1],
- [1, 2],
- [2, 0]
- ]) {
- drawLine(rgb2, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color2);
- }
- }
- }
- const regions = [...regionMap.values()].sort((a, b) => a.nodePath.localeCompare(b.nodePath));
- if (requestValue.buffer === "semantic-overlay") {
- for (const region of regions)
- drawRegionBox(rgb2, size, region);
- }
- return {
- id: requestValue.id,
- label: requestValue.label,
- camera,
- buffer: requestValue.buffer,
- ...requestValue.variant ? { variant: requestValue.variant } : {},
- width: size,
- height: size,
- rgb: rgb2,
- png: encodePng(rgb2, size, size),
- regions,
- ...requestValue.phaseFractions ? { phaseFractions: requestValue.phaseFractions } : {}
- };
-}
-function renderDiagnosticViews(root, requests, options = {}) {
- return requests.map((viewRequest) => renderDiagnosticView(root, viewRequest, options));
-}
-var GENERIC_DIAGNOSTIC_BUFFER_IDS, frozenCamera = (id, name, dir) => Object.freeze({ id, name, dir: Object.freeze([...dir]) }), GENERIC_DIAGNOSTIC_CAMERAS, EXTRA_CAMERAS, cameraById, request = (value) => Object.freeze({
- ...value,
- ...value.omitRolePrefixes ? { omitRolePrefixes: Object.freeze([...value.omitRolePrefixes]) } : {},
- ...value.focusRolePrefixes ? { focusRolePrefixes: Object.freeze([...value.focusRolePrefixes]) } : {},
- ...value.phaseFractions ? { phaseFractions: Object.freeze([...value.phaseFractions]) } : {}
-}), GENERIC_DIAGNOSTIC_REQUESTS, CATEGORY_REQUESTS, MATERIAL_GRAZING_REQUEST, IDENTITY;
-var init_diagnostic = __esm(() => {
- init_contracts();
- init_character3();
- init_png();
- GENERIC_DIAGNOSTIC_BUFFER_IDS = [
- "silhouette-unlit",
- "wireframe",
- "normals-backface",
- "depth-contact",
- "semantic-overlay"
- ];
- GENERIC_DIAGNOSTIC_CAMERAS = Object.freeze([
- frozenCamera("front", "Front", [1, 0, 0]),
- frozenCamera("right", "Right", [0, 0, 1]),
- frozenCamera("back", "Back", [-1, 0, 0]),
- frozenCamera("left", "Left", [0, 0, -1]),
- frozenCamera("top", "Top", [0, 1, 0.0001]),
- frozenCamera("three-quarter", "3/4", [0.7, 0.5, 0.7])
- ]);
- EXTRA_CAMERAS = Object.freeze({
- underside: frozenCamera("underside", "Canopy underside", [0.15, -0.85, 0.5]),
- grazing: frozenCamera("grazing", "Material grazing light", [0.08, 0.12, 1])
- });
- cameraById = new Map([...GENERIC_DIAGNOSTIC_CAMERAS, ...Object.values(EXTRA_CAMERAS)].map((camera) => [
- camera.id,
- camera
- ]));
- GENERIC_DIAGNOSTIC_REQUESTS = Object.freeze(GENERIC_DIAGNOSTIC_CAMERAS.flatMap((camera) => GENERIC_DIAGNOSTIC_BUFFER_IDS.map((buffer) => request({
- id: `generic.${camera.id}.${buffer}`,
- label: `${camera.name} ${buffer}`,
- cameraId: camera.id,
- buffer,
- scope: "generic"
- }))));
- CATEGORY_REQUESTS = Object.freeze({
- prop: Object.freeze([]),
- vfx: Object.freeze([]),
- environment: Object.freeze([]),
- architecture: Object.freeze([]),
- character: Object.freeze([]),
- vehicle: Object.freeze([
- request({
- id: "vehicle.underbody",
- label: "Vehicle underbody and support plane",
- cameraId: "underside",
- buffer: "semantic-overlay",
- scope: "category",
- variant: "vehicle-underbody",
- focusRolePrefixes: [
- "chassis.",
- "wheel.",
- "axle.",
- "support.",
- "contact.",
- "diagnostic.vehicle."
- ]
- }),
- request({
- id: "vehicle.wheel-section.right",
- label: "Vehicle wheel section",
- cameraId: "right",
- buffer: "semantic-overlay",
- scope: "category",
- variant: "vehicle-wheel-section",
- focusRolePrefixes: ["wheel.", "axle.", "hub.", "tire."]
- })
- ]),
- vegetation: Object.freeze([
- request({
- id: "vegetation.canopy-underside",
- label: "Vegetation canopy underside",
- cameraId: "underside",
- buffer: "normals-backface",
- scope: "category",
- variant: "vegetation-canopy-underside",
- focusRolePrefixes: ["canopy.", "foliage.", "leaf."]
- })
- ])
- });
- MATERIAL_GRAZING_REQUEST = request({
- id: "material.grazing-light",
- label: "Material grazing light",
- cameraId: "grazing",
- buffer: "silhouette-unlit",
- scope: "material",
- variant: "material-grazing-light"
- });
- IDENTITY = new Float64Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
-});
-
-// src/views/pose.ts
-function findClip(clips, name) {
- const q = name.trim().toLowerCase();
- const named = clips.filter((c) => typeof c.name === "string");
- return named.find((c) => c.name.toLowerCase() === q) ?? named.find((c) => c.name.toLowerCase().includes(q)) ?? undefined;
-}
-function clipNames(clips) {
- return clips.map((c) => typeof c.name === "string" ? c.name : "(unnamed)");
-}
-function prepareClip(root, clip) {
- const nodeNames = new Set;
- root.traverse?.((obj) => {
- const n = obj.name;
- if (n)
- nodeNames.add(n);
- });
- const tracks = [];
- const unresolved = [];
- let maxTime = 0;
- for (const track of clip.tracks ?? []) {
- const raw = track.name;
- if (!raw)
- continue;
- const dot4 = raw.lastIndexOf(".");
- if (dot4 === -1)
- continue;
- const nodeName2 = raw.slice(0, dot4);
- const property = raw.slice(dot4 + 1);
- if (property !== "position" && property !== "quaternion" && property !== "scale")
- continue;
- const times = track.times ? Array.from(track.times) : [];
- const values = track.values ? Array.from(track.values) : [];
- if (times.length === 0 || values.length === 0)
- continue;
- if (!nodeNames.has(nodeName2))
- unresolved.push(raw);
- if (times[times.length - 1] > maxTime)
- maxTime = times[times.length - 1];
- tracks.push({ nodeName: nodeName2, prop: property, stride: PROP_STRIDE[property], times, values });
- }
- const duration = clip.duration && clip.duration > 0 ? clip.duration : maxTime;
- return { name: clip.name ?? "(unnamed)", duration, tracks, unresolved };
-}
-function keyframeIndexAtOrBefore(times, t) {
- let i = -1;
- for (let k = 0;k < times.length; k++) {
- if (times[k] <= t)
- i = k;
- else
- break;
- }
- return i;
-}
-function slerpFlat(out, src0, o0, src1, o1, t) {
- const x0 = src0[o0], y0 = src0[o0 + 1], z0 = src0[o0 + 2], w0 = src0[o0 + 3];
- const x1 = src1[o1], y1 = src1[o1 + 1], z1 = src1[o1 + 2], w1 = src1[o1 + 3];
- let cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
- let bx = x1, by = y1, bz = z1, bw = w1;
- if (cos < 0) {
- cos = -cos;
- bx = -x1;
- by = -y1;
- bz = -z1;
- bw = -w1;
- }
- let s0, s1;
- if (cos > 0.9995) {
- s0 = 1 - t;
- s1 = t;
- } else {
- const theta = Math.acos(cos);
- const sin = Math.sin(theta);
- s0 = Math.sin((1 - t) * theta) / sin;
- s1 = Math.sin(t * theta) / sin;
- }
- const rx = s0 * x0 + s1 * bx;
- const ry = s0 * y0 + s1 * by;
- const rz = s0 * z0 + s1 * bz;
- const rw = s0 * w0 + s1 * bw;
- const len = Math.hypot(rx, ry, rz, rw) || 1;
- out[0] = rx / len;
- out[1] = ry / len;
- out[2] = rz / len;
- out[3] = rw / len;
-}
-function sampleTrack(track, t, out) {
- const { times, values, stride } = track;
- const i = keyframeIndexAtOrBefore(times, t);
- if (i < 0) {
- for (let s = 0;s < stride; s++)
- out[s] = values[s];
- return;
- }
- if (i >= times.length - 1) {
- const base = (times.length - 1) * stride;
- for (let s = 0;s < stride; s++)
- out[s] = values[base + s];
- return;
- }
- const t0 = times[i];
- const t1 = times[i + 1];
- const span = t1 - t0;
- const a = span > 0.000000001 ? (t - t0) / span : 0;
- const o0 = i * stride;
- const o1 = (i + 1) * stride;
- if (stride === 4) {
- slerpFlat(quatTmp, values, o0, values, o1, a);
- out[0] = quatTmp[0];
- out[1] = quatTmp[1];
- out[2] = quatTmp[2];
- out[3] = quatTmp[3];
- } else {
- for (let s = 0;s < stride; s++)
- out[s] = values[o0 + s] + (values[o1 + s] - values[o0 + s]) * a;
- }
-}
-function poseSceneAtTime(root, prepared, t) {
- const byName = new Map;
- root.traverse?.((obj) => {
- const node = obj;
- if (node.name && !byName.has(node.name))
- byName.set(node.name, node);
- });
- const buf = [0, 0, 0, 0];
- for (const track of prepared.tracks) {
- const node = byName.get(track.nodeName);
- if (!node)
- continue;
- sampleTrack(track, t, buf);
- if (track.prop === "position")
- node.position?.set(buf[0], buf[1], buf[2]);
- else if (track.prop === "scale")
- node.scale?.set(buf[0], buf[1], buf[2]);
- else
- node.quaternion?.set(buf[0], buf[1], buf[2], buf[3]);
- }
- root.updateMatrixWorld?.(true);
-}
-function planFrameTimes(duration, count) {
- if (count <= 1 || duration <= 0)
- return new Array(Math.max(1, count)).fill(0);
- const out = [];
- for (let i = 0;i < count; i++)
- out.push(duration * i / (count - 1));
- return out;
-}
-function stampLabel(rgb2, width, height, x0, y0, text, scale2 = 3) {
- const gw = 3 * scale2;
- const gh = 5 * scale2;
- const gap = scale2;
- const pad = scale2;
- const totalW = text.length * gw + (text.length - 1) * gap + pad * 2;
- const totalH = gh + pad * 2;
- for (let y = y0;y < y0 + totalH; y++) {
- for (let x = x0;x < x0 + totalW; x++) {
- if (x < 0 || y < 0 || x >= width || y >= height)
- continue;
- const p = (y * width + x) * 3;
- rgb2[p] = LABEL_BG[0];
- rgb2[p + 1] = LABEL_BG[1];
- rgb2[p + 2] = LABEL_BG[2];
- }
- }
- let cx = x0 + pad;
- const cy = y0 + pad;
- for (const ch of text.toUpperCase()) {
- const glyph = GLYPHS[ch] ?? GLYPHS[" "];
- for (let row = 0;row < 5; row++) {
- const bits = glyph[row];
- for (let col = 0;col < 3; col++) {
- if (!(bits & 1 << 2 - col))
- continue;
- for (let sy = 0;sy < scale2; sy++) {
- for (let sx = 0;sx < scale2; sx++) {
- const x = cx + col * scale2 + sx;
- const y = cy + row * scale2 + sy;
- if (x < 0 || y < 0 || x >= width || y >= height)
- continue;
- const p = (y * width + x) * 3;
- rgb2[p] = LABEL_FG[0];
- rgb2[p + 1] = LABEL_FG[1];
- rgb2[p + 2] = LABEL_FG[2];
- }
- }
- }
- }
- cx += gw + gap;
- }
-}
-var PROP_STRIDE, quatTmp, GLYPHS, LABEL_FG, LABEL_BG;
-var init_pose = __esm(() => {
- PROP_STRIDE = { position: 3, quaternion: 4, scale: 3 };
- quatTmp = [0, 0, 0, 1];
- GLYPHS = {
- "0": [7, 5, 5, 5, 7],
- "1": [2, 6, 2, 2, 7],
- "2": [7, 1, 7, 4, 7],
- "3": [7, 1, 7, 1, 7],
- "4": [5, 5, 7, 1, 1],
- "5": [7, 4, 7, 1, 7],
- "6": [7, 4, 7, 5, 7],
- "7": [7, 1, 2, 2, 2],
- "8": [7, 5, 7, 5, 7],
- "9": [7, 5, 7, 1, 7],
- "%": [5, 1, 2, 4, 5],
- " ": [0, 0, 0, 0, 0],
- A: [2, 5, 7, 5, 5],
- B: [6, 5, 6, 5, 6],
- C: [3, 4, 4, 4, 3],
- D: [6, 5, 5, 5, 6],
- E: [7, 4, 6, 4, 7],
- F: [7, 4, 6, 4, 4],
- G: [3, 4, 5, 5, 3],
- H: [5, 5, 7, 5, 5],
- I: [7, 2, 2, 2, 7],
- J: [1, 1, 1, 5, 2],
- K: [5, 5, 6, 5, 5],
- L: [4, 4, 4, 4, 7],
- M: [5, 7, 7, 5, 5],
- N: [5, 7, 7, 7, 5],
- O: [2, 5, 5, 5, 2],
- P: [6, 5, 6, 4, 4],
- Q: [2, 5, 5, 2, 1],
- R: [6, 5, 6, 5, 5],
- S: [3, 4, 2, 1, 6],
- T: [7, 2, 2, 2, 2],
- U: [5, 5, 5, 5, 7],
- V: [5, 5, 5, 5, 2],
- W: [5, 5, 5, 7, 5],
- X: [5, 5, 2, 5, 5],
- Y: [5, 5, 2, 2, 2],
- Z: [7, 1, 2, 4, 7],
- "/": [1, 1, 2, 4, 4],
- "-": [0, 0, 7, 0, 0],
- ".": [0, 0, 0, 0, 2]
- };
- LABEL_FG = [255, 224, 64];
- LABEL_BG = [12, 12, 14];
-});
-
-// src/views/annotate.ts
-function stampAxisGnomon(rgb2, size, viewDir) {
- const zl = Math.hypot(viewDir[0], viewDir[1], viewDir[2]) || 1;
- const z = [viewDir[0] / zl, viewDir[1] / zl, viewDir[2] / zl];
- const up = Math.abs(z[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];
- const cx = [
- up[1] * z[2] - up[2] * z[1],
- up[2] * z[0] - up[0] * z[2],
- up[0] * z[1] - up[1] * z[0]
- ];
- const xl = Math.hypot(cx[0], cx[1], cx[2]) || 1;
- const bx = [cx[0] / xl, cx[1] / xl, cx[2] / xl];
- const by = [
- z[1] * bx[2] - z[2] * bx[1],
- z[2] * bx[0] - z[0] * bx[2],
- z[0] * bx[1] - z[1] * bx[0]
- ];
- const len = Math.max(12, Math.round(size * 0.055));
- const ox = len + 10;
- const oy = size - len - 10;
- for (const { label, axis, color: color2 } of GNOMON_AXES) {
- const dx = axis[0] * bx[0] + axis[1] * bx[1] + axis[2] * bx[2];
- const dy = axis[0] * by[0] + axis[1] * by[1] + axis[2] * by[2];
- if (Math.hypot(dx, dy) < 0.25)
- continue;
- const ex = ox + dx * len;
- const ey = oy - dy * len;
- const steps = Math.ceil(Math.hypot(ex - ox, ey - oy));
- for (let s = 0;s <= steps; s++) {
- const px = Math.round(ox + (ex - ox) * s / steps);
- const py = Math.round(oy + (ey - oy) * s / steps);
- for (let ty = 0;ty < 2; ty++) {
- for (let tx = 0;tx < 2; tx++) {
- const x = px + tx;
- const y = py + ty;
- if (x < 0 || y < 0 || x >= size || y >= size)
- continue;
- const p = (y * size + x) * 3;
- rgb2[p] = color2[0];
- rgb2[p + 1] = color2[1];
- rgb2[p + 2] = color2[2];
- }
- }
- }
- stampLabel(rgb2, size, size, Math.round(ex) + 2, Math.round(ey) - 6, label, 1);
- }
-}
-function annotateViewCell(rgb2, size, view) {
- const inset = Math.max(2, Math.round(size / 96));
- const width = size - inset * 2;
- if (width < 7 || (4 * view.name.length + 1) * inset <= width) {
- stampLabel(rgb2, size, size, inset, inset, view.name, inset);
- } else {
- const minimumScale = size >= 128 ? 2 : 1;
- const scale2 = Math.max(minimumScale, Math.floor(width / (4 * view.name.length + 1)));
- const columns = Math.max(1, Math.floor((width / scale2 - 1) / 4));
- const rows = Math.min(3, Math.floor((size - inset * 2) / (7 * scale2)));
- let remaining = view.name.toUpperCase();
- for (let row = 0;row < rows && remaining; row++) {
- let line = remaining;
- if (remaining.length > columns) {
- if (row === rows - 1) {
- line = `${remaining.slice(0, Math.max(0, columns - 3)).trimEnd()}${".".repeat(Math.min(3, columns))}`;
- remaining = "";
- } else {
- const space = remaining.lastIndexOf(" ", columns);
- const end = space > 0 ? space : columns;
- line = remaining.slice(0, end);
- remaining = remaining.slice(end).trimStart();
- }
- } else
- remaining = "";
- stampLabel(rgb2, size, size, inset, inset + row * 7 * scale2, line, scale2);
- }
- }
- stampAxisGnomon(rgb2, size, view.dir);
-}
-var GNOMON_AXES;
-var init_annotate = __esm(() => {
- init_pose();
- GNOMON_AXES = [
- { label: "X", axis: [1, 0, 0], color: [235, 80, 70] },
- { label: "Y", axis: [0, 1, 0], color: [90, 205, 90] },
- { label: "Z", axis: [0, 0, 1], color: [90, 145, 245] }
- ];
-});
-
-// src/views/grid.ts
-function compositeCellGrid(cells, size, cols = GRID_COLS) {
- if (cells.length === 0)
- throw new Error("compositeCellGrid: no cells to composite");
- const rows = Math.ceil(cells.length / cols);
- const width = cols * size + (cols + 1) * PAD;
- const height = rows * size + (rows + 1) * PAD;
- const grid = new Uint8Array(width * height * 3);
- for (let p = 0;p < width * height; p++) {
- grid[p * 3] = PAD_COLOR[0];
- grid[p * 3 + 1] = PAD_COLOR[1];
- grid[p * 3 + 2] = PAD_COLOR[2];
- }
- for (let i = 0;i < cells.length; i++) {
- const cell = cells[i];
- if (cell.length !== size * size * 3) {
- throw new Error(`compositeCellGrid: cell ${i} must be ${size * size * 3} bytes (size ${size}), got ${cell.length}`);
- }
- const col = i % cols;
- const row = Math.floor(i / cols);
- const x0 = PAD + col * (size + PAD);
- const y0 = PAD + row * (size + PAD);
- for (let y = 0;y < size; y++) {
- const src = y * size * 3;
- const dst = ((y0 + y) * width + x0) * 3;
- grid.set(cell.subarray(src, src + size * 3), dst);
- }
- }
- return { rgb: grid, width, height };
-}
-function compositeViewPngGrid(pngs, cols = GRID_COLS, views) {
- if (pngs.length === 0)
- throw new Error("compositeViewPngGrid: no views to composite");
- if (views && views.length !== pngs.length) {
- throw new Error(`compositeViewPngGrid: ${views.length} view specs for ${pngs.length} PNGs — they must align 1:1`);
- }
- const decoded = pngs.map((png) => decodePng(png));
- const size = decoded[0].width;
- for (const d of decoded) {
- if (d.width !== size || d.height !== size) {
- throw new Error(`compositeViewPngGrid: every view must be a ${size}x${size} square; got ${d.width}x${d.height}`);
- }
- }
- if (views) {
- for (let i = 0;i < decoded.length; i++)
- annotateViewCell(decoded[i].rgb, size, views[i]);
- }
- const { rgb: rgb2, width, height } = compositeCellGrid(decoded.map((d) => d.rgb), size, cols);
- return { png: encodePng(rgb2, width, height), width, height, cellSize: size };
-}
-var PAD = 4, PAD_COLOR, GRID_COLS = 3;
-var init_grid = __esm(() => {
- init_annotate();
- init_png();
- PAD_COLOR = [10, 11, 13];
-});
-
-// src/views/capture-limits.ts
-var exports_capture_limits = {};
-__export(exports_capture_limits, {
- resolveCaptureLimits: () => resolveCaptureLimits,
- enforcePngCaptureBudget: () => enforcePngCaptureBudget,
- enforceCapturePixels: () => enforceCapturePixels,
- enforceCaptureBytes: () => enforceCaptureBytes,
- DEFAULT_CAPTURE_LIMITS: () => DEFAULT_CAPTURE_LIMITS
-});
-function resolveCaptureLimits(limits = {}) {
- const result = { ...DEFAULT_CAPTURE_LIMITS };
- for (const key of ["maxTotalPixels", "maxOutputBytes"]) {
- const value = limits[key];
- if (value !== undefined) {
- if (!Number.isSafeInteger(value) || value < 1)
- throw new Error(`capture limit ${key} must be a positive integer`);
- result[key] = Math.min(value, result[key]);
- }
- }
- return result;
-}
-function enforceCapturePixels(cells, size, cols, limits, compose = true) {
- if (!Number.isSafeInteger(cells) || cells < 1 || !Number.isSafeInteger(size) || size < 1 || !Number.isSafeInteger(cols) || cols < 1)
- throw new Error("invalid capture dimensions");
- const pixels = cells * size * size + (compose ? (cols * size + (cols + 1) * PAD) * (Math.ceil(cells / cols) * size + (Math.ceil(cells / cols) + 1) * PAD) : 0);
- if (pixels > resolveCaptureLimits(limits).maxTotalPixels)
- throw new Error(`capture pixel budget exceeded: ${pixels}`);
- return pixels;
-}
-function enforceCaptureBytes(images, limits) {
- const bytes = images.reduce((sum, image) => sum + image.byteLength, 0);
- if (bytes > resolveCaptureLimits(limits).maxOutputBytes)
- throw new Error(`capture byte budget exceeded: ${bytes}`);
- return bytes;
-}
-function enforcePngCaptureBudget(images, limits) {
- enforceCaptureBytes(images, limits);
- let pixels = 0;
- for (const png of images) {
- if (png.byteLength < 24)
- throw new Error("invalid PNG header");
- const view = new DataView(png.buffer, png.byteOffset, png.byteLength);
- if (view.getUint32(0) !== 2303741511 || view.getUint32(12) !== 1229472850)
- throw new Error("invalid PNG header");
- pixels += view.getUint32(16) * view.getUint32(20);
- }
- if (pixels > resolveCaptureLimits(limits).maxTotalPixels)
- throw new Error(`capture pixel budget exceeded: ${pixels}`);
-}
-var DEFAULT_CAPTURE_LIMITS;
-var init_capture_limits = __esm(() => {
- init_grid();
- DEFAULT_CAPTURE_LIMITS = Object.freeze({
- maxTotalPixels: 24000000,
- maxOutputBytes: 32 * 1024 * 1024
- });
-});
-
-// src/views/background.ts
-var GRID_BACKGROUND_RGB, GRID_BACKGROUND_HEX = "#1a1a1a";
-var init_background = __esm(() => {
- GRID_BACKGROUND_RGB = [26, 26, 26];
-});
-
-// src/views/raster.ts
-function orbitDir(azimuthDeg, elevationDeg) {
- const el = Math.min(MAX_ELEVATION_DEG, Math.max(MIN_ELEVATION_DEG, elevationDeg)) * Math.PI / 180;
- const az = azimuthDeg * Math.PI / 180;
- const cosEl = Math.cos(el);
- return [cosEl * Math.cos(az), Math.sin(el), cosEl * Math.sin(az)];
-}
-function orbitAnglesOf(dir) {
- const [x, y, z] = normalize3(dir);
- const azimuthDeg = (Math.atan2(z, x) * 180 / Math.PI % 360 + 360) % 360;
- return {
- azimuthDeg: +azimuthDeg.toFixed(2),
- elevationDeg: +(Math.asin(Math.min(1, Math.max(-1, y))) * 180 / Math.PI).toFixed(2)
- };
-}
-function resolveGridViews(variant) {
- return variant?.trim().toLowerCase() === "rear-quarter" ? SIX_VIEWS_REAR_QUARTER : SIX_VIEWS;
-}
-function normalize3(v) {
- const len = Math.hypot(v[0], v[1], v[2]) || 1;
- return [v[0] / len, v[1] / len, v[2] / len];
-}
-function cross3(a, b) {
- return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
-}
-function dot4(a, b) {
- return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
-}
-function collectTriangles(root) {
- root.updateMatrixWorld?.(true);
- const tris = [];
- const min = [Infinity, Infinity, Infinity];
- const max = [-Infinity, -Infinity, -Infinity];
- root.traverse?.((obj) => {
- const mesh = obj;
- if (!mesh.isMesh || mesh.visible === false)
- return;
- const geo = mesh.geometry;
- const pos = geo?.getAttribute?.("position");
- if (!geo || !pos || pos.itemSize !== 3)
- return;
- const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
- const colorOf = (mat) => {
- const c = mat?.color;
- return c ? [clamp012(c.r), clamp012(c.g), clamp012(c.b)] : [0.7, 0.7, 0.7];
- };
- const groups = mats.length > 1 && geo.groups?.length ? geo.groups : undefined;
- const materialAt = (bufferPos) => {
- if (!groups)
- return mats[0];
- for (const g of groups) {
- if (bufferPos >= g.start && bufferPos < g.start + g.count) {
- return mats[g.materialIndex ?? 0];
- }
- }
- return mats[0];
- };
- const m = mesh.matrixWorld?.elements;
- if (!m)
- return;
- const arr = pos.array;
- const world = new Float64Array(pos.count * 3);
- for (let i = 0;i < pos.count; i++) {
- const x = arr[i * 3];
- const y = arr[i * 3 + 1];
- const z = arr[i * 3 + 2];
- const wx = m[0] * x + m[4] * y + m[8] * z + m[12];
- const wy = m[1] * x + m[5] * y + m[9] * z + m[13];
- const wz = m[2] * x + m[6] * y + m[10] * z + m[14];
- world[i * 3] = wx;
- world[i * 3 + 1] = wy;
- world[i * 3 + 2] = wz;
- if (wx < min[0])
- min[0] = wx;
- if (wy < min[1])
- min[1] = wy;
- if (wz < min[2])
- min[2] = wz;
- if (wx > max[0])
- max[0] = wx;
- if (wy > max[1])
- max[1] = wy;
- if (wz > max[2])
- max[2] = wz;
- }
- const pushTri = (a, b, c2, material) => {
- const v = new Float64Array(9);
- v[0] = world[a * 3];
- v[1] = world[a * 3 + 1];
- v[2] = world[a * 3 + 2];
- v[3] = world[b * 3];
- v[4] = world[b * 3 + 1];
- v[5] = world[b * 3 + 2];
- v[6] = world[c2 * 3];
- v[7] = world[c2 * 3 + 1];
- v[8] = world[c2 * 3 + 2];
- tris.push({
- v,
- color: colorOf(material),
- alpha: clamp012(material?.opacity ?? 1),
- doubleSided: material?.doubleSided === true
- });
- };
- const index = geo.index;
- if (index) {
- const ia = index.array;
- for (let i = 0;i + 2 < index.count; i += 3) {
- pushTri(ia[i], ia[i + 1], ia[i + 2], materialAt(i));
- }
- } else {
- for (let i = 0;i + 2 < pos.count; i += 3) {
- pushTri(i, i + 1, i + 2, materialAt(i));
- }
- }
- });
- if (!Number.isFinite(min[0])) {
- return { tris, bbox: { min: [0, 0, 0], max: [0, 0, 0] } };
- }
- return { tris, bbox: { min, max } };
-}
-function clamp012(n) {
- return n < 0 ? 0 : n > 1 ? 1 : n;
-}
-function linearToSrgb(c) {
- const v = clamp012(c);
- return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
-}
-function rasterizeView(root, dir, opts = {}) {
- const size = opts.size ?? 256;
- const cull = opts.backfaceCull ?? true;
- const { tris, bbox } = collectTriangles(root);
- const out = new Uint8Array(size * size * 3);
- for (let i = 0;i < size * size; i++) {
- out[i * 3] = BG[0];
- out[i * 3 + 1] = BG[1];
- out[i * 3 + 2] = BG[2];
- }
- if (tris.length === 0)
- return out;
- const z = normalize3(dir);
- const upHint = Math.abs(z[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];
- const x = normalize3(cross3(upHint, z));
- const y = cross3(z, x);
- const frameMin = opts.frameBounds ? opts.frameBounds.min : bbox.min;
- const frameMax = opts.frameBounds ? opts.frameBounds.max : bbox.max;
- const center = [
- (frameMin[0] + frameMax[0]) / 2,
- (frameMin[1] + frameMax[1]) / 2,
- (frameMin[2] + frameMax[2]) / 2
- ];
- let ext = 0.000001;
- for (let ci = 0;ci < 8; ci++) {
- const px = (ci & 1 ? frameMax[0] : frameMin[0]) - center[0];
- const py = (ci & 2 ? frameMax[1] : frameMin[1]) - center[1];
- const pz = (ci & 4 ? frameMax[2] : frameMin[2]) - center[2];
- const p = [px, py, pz];
- ext = Math.max(ext, Math.abs(dot4(p, x)), Math.abs(dot4(p, y)));
- }
- const scale2 = size * 0.45 / ext;
- const half = size / 2;
- const zbuf = new Float64Array(size * size).fill(-Infinity);
- const sx = new Float64Array(3);
- const sy = new Float64Array(3);
- const sz = new Float64Array(3);
- for (const tri of tris) {
- const e1 = [tri.v[3] - tri.v[0], tri.v[4] - tri.v[1], tri.v[5] - tri.v[2]];
- const e2 = [tri.v[6] - tri.v[0], tri.v[7] - tri.v[1], tri.v[8] - tri.v[2]];
- const n = cross3(e1, e2);
- const nLen = Math.hypot(n[0], n[1], n[2]);
- if (nLen < 0.000000000001)
- continue;
- const N = [n[0] / nLen, n[1] / nLen, n[2] / nLen];
- const facing = dot4(N, z);
- if (cull && facing <= 0 && !tri.doubleSided)
- continue;
- if (tri.alpha <= 0)
- continue;
- for (let i = 0;i < 3; i++) {
- const px = tri.v[i * 3] - center[0];
- const py = tri.v[i * 3 + 1] - center[1];
- const pz = tri.v[i * 3 + 2] - center[2];
- const p = [px, py, pz];
- sx[i] = half + dot4(p, x) * scale2;
- sy[i] = half - dot4(p, y) * scale2;
- sz[i] = dot4(p, z);
- }
- const lambert = Math.max(0, dot4(N, KEY_DIR));
- const lit = Math.min(1, AMBIENT + KEY_INTENSITY * lambert);
- const r = Math.round(linearToSrgb(tri.color[0] * lit) * 255);
- const g = Math.round(linearToSrgb(tri.color[1] * lit) * 255);
- const b = Math.round(linearToSrgb(tri.color[2] * lit) * 255);
- const minX = Math.max(0, Math.floor(Math.min(sx[0], sx[1], sx[2])));
- const maxX = Math.min(size - 1, Math.ceil(Math.max(sx[0], sx[1], sx[2])));
- const minY = Math.max(0, Math.floor(Math.min(sy[0], sy[1], sy[2])));
- const maxY = Math.min(size - 1, Math.ceil(Math.max(sy[0], sy[1], sy[2])));
- if (minX > maxX || minY > maxY)
- continue;
- const ax = sx[0], ay = sy[0], bx2 = sx[1], by = sy[1], cx = sx[2], cy = sy[2];
- const area = (bx2 - ax) * (cy - ay) - (by - ay) * (cx - ax);
- if (Math.abs(area) < 0.000000001)
- continue;
- const invArea = 1 / area;
- for (let py = minY;py <= maxY; py++) {
- for (let px = minX;px <= maxX; px++) {
- const cxp = px + 0.5;
- const cyp = py + 0.5;
- const w0 = ((bx2 - ax) * (cyp - ay) - (by - ay) * (cxp - ax)) * invArea;
- const w1 = ((cx - bx2) * (cyp - by) - (cy - by) * (cxp - bx2)) * invArea;
- const w2 = 1 - w0 - w1;
- if (w0 < 0 || w1 < 0 || w2 < 0)
- continue;
- const depth = w1 * sz[0] + w2 * sz[1] + w0 * sz[2];
- const pi = py * size + px;
- if (depth <= zbuf[pi])
- continue;
- zbuf[pi] = depth;
- if (tri.alpha >= 1) {
- out[pi * 3] = r;
- out[pi * 3 + 1] = g;
- out[pi * 3 + 2] = b;
- } else {
- const inverse = 1 - tri.alpha;
- out[pi * 3] = Math.round(r * tri.alpha + out[pi * 3] * inverse);
- out[pi * 3 + 1] = Math.round(g * tri.alpha + out[pi * 3 + 1] * inverse);
- out[pi * 3 + 2] = Math.round(b * tri.alpha + out[pi * 3 + 2] * inverse);
- }
- }
- }
- }
- return out;
-}
-function measureBounds(root) {
- const { bbox } = collectTriangles(root);
- return { min: [...bbox.min], max: [...bbox.max] };
-}
-function coverage(rgb2, size) {
- let filled = 0;
- for (let i = 0;i < size * size; i++) {
- if (rgb2[i * 3] !== BG[0] || rgb2[i * 3 + 1] !== BG[1] || rgb2[i * 3 + 2] !== BG[2])
- filled++;
- }
- return filled / (size * size);
-}
-function hideNodeInScene(root, match) {
- const test = typeof match === "function" ? match : (name) => {
- const t = match.toLowerCase();
- const n = name.toLowerCase();
- return n === t || n.startsWith(t);
- };
- let hidden = 0;
- const r = root;
- r.traverse?.((obj) => {
- const node = obj;
- if (!node.name || !test(node.name))
- return;
- hidden++;
- node.traverse?.((d) => {
- d.visible = false;
- });
- });
- return hidden;
-}
-var SIX_VIEWS, SIX_VIEWS_REAR_QUARTER, MIN_ELEVATION_DEG = -89, MAX_ELEVATION_DEG = 89, BG, AMBIENT = 0.25, KEY_INTENSITY = 1.1, KEY_DIR;
-var init_raster = __esm(() => {
- init_background();
- SIX_VIEWS = [
- { name: "Front", dir: [1, 0, 0] },
- { name: "Right", dir: [0, 0, 1] },
- { name: "Back", dir: [-1, 0, 0] },
- { name: "Left", dir: [0, 0, -1] },
- { name: "Top", dir: [0, 1, 0.0001] },
- { name: "3/4", dir: [0.7, 0.5, 0.7] }
- ];
- SIX_VIEWS_REAR_QUARTER = [
- ...SIX_VIEWS.slice(0, 5),
- { name: "3/4 Rear", dir: [-0.7, 0.5, -0.7] }
- ];
- BG = GRID_BACKGROUND_RGB;
- KEY_DIR = normalize3([1.5, 2, 1]);
-});
-
-// src/views/camera.ts
-import { Vector3 as Vector325, Matrix4 as Matrix46, Euler as Euler4 } from "three";
-function strict(value, keys, label) {
- for (const key of Object.keys(value))
- if (!keys.includes(key))
- throw new Error(`${label}.${key} is unknown`);
-}
-function finite2(n, label) {
- if (!Number.isFinite(n))
- throw new Error(`${label} must be finite`);
- return n;
-}
-function triple(v, label) {
- if (!Array.isArray(v) || v.length !== 3 || v.some((n) => !Number.isFinite(n)))
- throw new Error(`${label} must contain three finite numbers`);
- return [...v];
-}
-function listCameraSubjects(root) {
- const result = [];
- const visit = (node2, path) => {
- result.push({ node: node2, path, name: node2.name });
- const counts = new Map;
- for (const child of node2.children ?? []) {
- const count = counts.get(child.name) ?? 0;
- counts.set(child.name, count + 1);
- visit(child, `${path}/${encodeURIComponent(child.name)}[${count}]`);
- }
- };
- const node = root;
- visit(node, `/${encodeURIComponent(node.name)}[0]`);
- return result;
-}
-function selectCameraSubject(root, subject) {
- if (subject) {
- strict(subject, ["path", "name"], "subject");
- if (subject.path === undefined === (subject.name === undefined))
- throw new Error("subject requires exactly one of path or name");
- }
- const all = listCameraSubjects(root);
- const matches = !subject ? [all[0]] : all.filter((n) => subject.path !== undefined ? n.path === subject.path : n.name === subject.name);
- if (matches.length !== 1)
- throw new Error(`${matches.length ? "ambiguous" : "missing"} camera subject; choose an exact path: ${all.slice(0, 40).map((n) => n.path).join(", ")}`);
- return matches[0];
-}
-function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {
- if (!Number.isFinite(padding) || padding <= 0 || padding > 100)
- throw new Error("padding must be in (0,100]");
- const target = vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);
- const z = vec(dir).normalize();
- if (!z.length())
- throw new Error("camera direction must be non-zero");
- const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector325(0, 0, -1) : new Vector325(0, 1, 0);
- const x = hint.clone().cross(z).normalize();
- if (x.length() < 0.000000001)
- throw new Error("camera up must not be collinear with view");
- const y = z.clone().cross(x);
- let extent2 = 0.000001;
- for (let i = 0;i < 8; i++) {
- const p = new Vector325((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);
- extent2 = Math.max(extent2, Math.abs(p.dot(x)), Math.abs(p.dot(y)));
- }
- const depthMin = bounds.min.map((v, i) => Math.min(v, sceneBounds.min[i]));
- const depthMax = bounds.max.map((v, i) => Math.max(v, sceneBounds.max[i]));
- const radius = Math.max(vec(depthMax).distanceTo(target), vec(depthMin).distanceTo(target)) * 2;
- const distance = Math.max(radius * 2, 1);
- return {
- version: "kiln.camera.v1",
- projection: "orthographic",
- position: tuple5(target.clone().addScaledVector(z, distance)),
- target: tuple5(target),
- up: tuple5(y),
- aspect: 1,
- near: Math.max(0.000001, distance - radius),
- far: distance + radius + 1,
- halfHeight: extent2 * padding / 0.9
- };
-}
-function validateResolvedAssetCamera(value) {
- strict(value, [
- "version",
- "projection",
- "position",
- "target",
- "up",
- "aspect",
- "near",
- "far",
- "halfHeight",
- "fovDeg"
- ], "camera");
- if (value.version !== "kiln.camera.v1")
- throw new Error("camera.version must be kiln.camera.v1");
- const camera = {
- ...value,
- position: triple(value.position, "position"),
- target: triple(value.target, "target"),
- up: triple(value.up, "up")
- };
- const view = vec(camera.target).sub(vec(camera.position));
- const up = vec(camera.up);
- if (view.length() < 0.000000001)
- throw new Error("camera target must differ from position");
- if (up.length() < 0.000000001 || view.clone().cross(up).length() <= view.length() * up.length() * 0.000000001)
- throw new Error("camera up must be non-zero and not collinear with view");
- if (finite2(camera.aspect, "aspect") <= 0 || finite2(camera.near, "near") <= 0 || finite2(camera.far, "far") <= camera.near)
- throw new Error("camera requires positive aspect and 0 < near < far");
- if (camera.projection === "orthographic") {
- if (!Number.isFinite(camera.halfHeight) || camera.halfHeight <= 0 || camera.fovDeg !== undefined)
- throw new Error("orthographic camera requires positive halfHeight and no fovDeg");
- } else if (camera.projection === "perspective") {
- if (!Number.isFinite(camera.fovDeg) || camera.fovDeg <= 0 || camera.fovDeg >= 180 || camera.halfHeight !== undefined)
- throw new Error("perspective camera requires 0 < fovDeg < 180 and no halfHeight");
- } else
- throw new Error("unknown camera projection");
- return camera;
-}
-function resolveAssetCamera(root, shot = {}) {
- strict(shot, ["name", "subject", "visibility", "camera"], "shot");
- const rootNode = root;
- rootNode.updateMatrixWorld(true);
- const selected = selectCameraSubject(root, shot.subject);
- const bounds = measureBounds(selected.node);
- if (!collectTriangles(selected.node).tris.length)
- throw new Error(`subject ${selected.path} has no visible geometry`);
- const request2 = shot.camera ?? { type: "orbit" };
- let camera;
- if (request2.type === "orbit") {
- strict(request2, ["type", "azimuthDeg", "elevationDeg", "relativeTo", "padding"], "camera");
- const relative = request2.relativeTo ?? "world";
- if (!["world", "asset", "part"].includes(relative))
- throw new Error("invalid relativeTo");
- const dir = vec(orbitDir(finite2(request2.azimuthDeg ?? 45, "azimuthDeg"), finite2(request2.elevationDeg ?? 25, "elevationDeg")));
- let up;
- if (relative !== "world") {
- const node = relative === "part" ? selected.node : rootNode;
- dir.transformDirection(node.matrixWorld);
- up = tuple5(new Vector325(0, 1, 0).transformDirection(node.matrixWorld));
- }
- camera = cameraFromBounds(bounds, tuple5(dir), request2.padding ?? 1.2, up, measureBounds(root));
- } else if (request2.type === "explicit") {
- strict(request2, [
- "type",
- "projection",
- "position",
- "target",
- "up",
- "halfHeight",
- "fovDeg",
- "near",
- "far",
- "relativeTo",
- "frame",
- "framing",
- "padding",
- "targetOffset"
- ], "camera");
- if (request2.projection === "orthographic" && request2.fovDeg !== undefined || request2.projection === "perspective" && request2.halfHeight !== undefined)
- throw new Error("projection and lens fields conflict");
- const relative = request2.relativeTo ?? "world";
- if (!["world", "asset", "part", "local"].includes(relative))
- throw new Error("invalid relativeTo");
- if (relative === "local" !== Boolean(request2.frame))
- throw new Error("local coordinates require frame; frame is only valid for local coordinates");
- if (request2.framing !== undefined && !["explicit", "bounds"].includes(request2.framing))
- throw new Error("invalid framing");
- if (request2.target === undefined && request2.framing !== "bounds")
- throw new Error("explicit framing requires target");
- if (request2.padding !== undefined && request2.framing !== "bounds")
- throw new Error("padding requires bounds framing");
- if (request2.framing === "bounds" && request2.halfHeight !== undefined)
- throw new Error("bounds framing derives halfHeight");
- let matrix = new Matrix46;
- if (relative === "asset" || relative === "part")
- matrix = (relative === "asset" ? rootNode : selected.node).matrixWorld;
- if (request2.frame) {
- strict(request2.frame, ["origin", "rotation"], "frame");
- const rotation = triple(request2.frame.rotation ?? [0, 0, 0], "frame.rotation");
- matrix.makeRotationFromEuler(new Euler4(...rotation.map((n) => n * Math.PI / 180), "XYZ"));
- matrix.setPosition(...triple(request2.frame.origin ?? [0, 0, 0], "frame.origin"));
- }
- const position = vec(triple(request2.position, "position")).applyMatrix4(matrix);
- const target = request2.target ? vec(triple(request2.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);
- const up = vec(triple(request2.up ?? [0, 1, 0], "up")).transformDirection(matrix);
- const offset = vec(triple(request2.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector325().setFromMatrixPosition(matrix));
- const radius = vec(bounds.max).sub(vec(bounds.min)).length();
- camera = {
- version: "kiln.camera.v1",
- projection: request2.projection,
- position: tuple5(position),
- target: tuple5(target.clone().add(offset)),
- up: tuple5(up),
- aspect: 1,
- near: request2.near ?? 0.001,
- far: request2.far ?? Math.max(100, position.distanceTo(target) + radius * 4),
- ...request2.projection === "orthographic" ? { halfHeight: request2.halfHeight ?? Math.max(radius / 2, 0.000001) } : { fovDeg: request2.fovDeg ?? 50 }
- };
- if (request2.framing === "bounds") {
- const direction = position.clone().sub(target);
- if (direction.lengthSq() < 0.00000000000000000001)
- throw new Error("bounds framing position and target must differ");
- const padding = request2.padding ?? 1.2;
- const fit = cameraFromBounds(bounds, tuple5(direction), padding, tuple5(up), measureBounds(root));
- if (request2.projection === "orthographic")
- camera = { ...fit, near: request2.near ?? fit.near, far: request2.far ?? fit.far };
- else {
- const fov = finite2(request2.fovDeg ?? 50, "fovDeg");
- if (fov <= 0 || fov >= 180)
- throw new Error("invalid fovDeg");
- const distance = Math.max(radius / 2, 0.000001) * padding / Math.sin(fov * Math.PI / 360);
- const center = vec(fit.target);
- camera = {
- ...camera,
- position: tuple5(center.clone().add(direction.normalize().multiplyScalar(distance))),
- target: tuple5(center),
- far: request2.far ?? Math.max(100, distance + radius * 4)
- };
- }
- camera.position = tuple5(vec(camera.position).add(offset));
- camera.target = tuple5(vec(camera.target).add(offset));
- }
- } else
- throw new Error("unknown camera type");
- if (shot.visibility !== undefined && !["context", "isolate"].includes(shot.visibility))
- throw new Error("invalid visibility");
- return {
- name: shot.name ?? selected.name ?? "VIEW",
- camera: validateResolvedAssetCamera(camera),
- subject: { path: selected.path, name: selected.name, bounds },
- visibility: shot.visibility ?? "context"
- };
-}
-async function withCameraVisibility(root, shot, run2) {
- if (shot.visibility === "context")
- return run2();
- const keep = new Set;
- selectCameraSubject(root, { path: shot.subject.path }).node.traverse((n) => keep.add(n));
- const restore = [];
- root.traverse((n) => {
- if (n.isMesh && !keep.has(n)) {
- restore.push([n, n.visible]);
- n.visible = false;
- }
- });
- try {
- return await run2();
- } finally {
- for (const [node, visible] of restore)
- node.visible = visible;
- }
-}
-function rasterizeCamera(root, input, size = 384, backfaceCull = true) {
- const camera = validateResolvedAssetCamera(input);
- if (!Number.isInteger(size) || size < 1 || size > 2048)
- throw new Error("camera size must be an integer in 1..2048");
- const z = vec(camera.position).sub(vec(camera.target)).normalize(), x = vec(camera.up).cross(z).normalize(), y = z.clone().cross(x), position = vec(camera.position);
- const out = new Uint8Array(size * size * 3);
- for (let i = 0;i < size * size; i++)
- out.set(GRID_BACKGROUND_RGB, i * 3);
- const depth = new Float64Array(size * size).fill(Infinity);
- const clip = (points, plane, near) => {
- const result = [];
- for (let i = 0;i < points.length; i++) {
- const a = points[i], b = points[(i + 1) % points.length];
- const insideA = near ? a.z >= plane : a.z <= plane, insideB = near ? b.z >= plane : b.z <= plane;
- if (insideA)
- result.push(a);
- if (insideA !== insideB)
- result.push(a.clone().lerp(b, (plane - a.z) / (b.z - a.z)));
- }
- return result;
- };
- const key = new Vector325(1.5, 2, 1).normalize();
- const srgb = (n) => n <= 0.0031308 ? n * 12.92 : 1.055 * n ** (1 / 2.4) - 0.055;
- for (const tri of collectTriangles(root).tris) {
- const world = [0, 1, 2].map((i) => new Vector325(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));
- const normal = world[1].clone().sub(world[0]).cross(world[2].clone().sub(world[0])).normalize();
- if (backfaceCull && !tri.doubleSided && normal.dot(camera.projection === "perspective" ? position.clone().sub(world[0]) : z) <= 0)
- continue;
- if (tri.alpha <= 0)
- continue;
- const light = Math.min(1, 0.25 + 1.1 * Math.max(0, normal.dot(key)));
- const color2 = tri.color.map((c) => Math.round(srgb(c * light) * 255));
- let polygon = world.map((p) => {
- const d = p.clone().sub(position);
- return new Vector325(d.dot(x), d.dot(y), -d.dot(z));
- });
- polygon = clip(clip(polygon, camera.near, true), camera.far, false);
- for (let t = 1;t < polygon.length - 1; t++) {
- const p = [polygon[0], polygon[t], polygon[t + 1]];
- const screen = p.map((v) => {
- const half = camera.projection === "orthographic" ? camera.halfHeight : v.z * Math.tan(camera.fovDeg * Math.PI / 360);
- return [
- size / 2 + v.x * size / (2 * half * camera.aspect),
- size / 2 - v.y * size / (2 * half)
- ];
- });
- const [a, b, c] = screen;
- const area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
- if (Math.abs(area) < 0.000000001)
- continue;
- for (let py = Math.max(0, Math.floor(Math.min(...screen.map((s) => s[1]))));py <= Math.min(size - 1, Math.ceil(Math.max(...screen.map((s) => s[1])))); py++)
- for (let px = Math.max(0, Math.floor(Math.min(...screen.map((s) => s[0]))));px <= Math.min(size - 1, Math.ceil(Math.max(...screen.map((s) => s[0])))); px++) {
- const w0 = ((b[0] - a[0]) * (py + 0.5 - a[1]) - (b[1] - a[1]) * (px + 0.5 - a[0])) / area, w1 = ((c[0] - b[0]) * (py + 0.5 - b[1]) - (c[1] - b[1]) * (px + 0.5 - b[0])) / area, w2 = 1 - w0 - w1;
- if (w0 < 0 || w1 < 0 || w2 < 0)
- continue;
- const d = camera.projection === "perspective" ? 1 / (w1 / p[0].z + w2 / p[1].z + w0 / p[2].z) : w1 * p[0].z + w2 * p[1].z + w0 * p[2].z;
- const index = py * size + px;
- if (d >= depth[index])
- continue;
- depth[index] = d;
- for (let channel = 0;channel < 3; channel++)
- out[index * 3 + channel] = Math.round(color2[channel] * tri.alpha + out[index * 3 + channel] * (1 - tri.alpha));
- }
- }
- }
- return out;
-}
-var vec = (a) => new Vector325(...a), tuple5 = (v) => [v.x || 0, v.y || 0, v.z || 0];
-var init_camera = __esm(() => {
- init_raster();
- init_background();
-});
-
-// src/composer/render-port.ts
-function finiteTuple3(value, path) {
- if (!Array.isArray(value) || value.length !== 3 || value.some((entry) => typeof entry !== "number" || !Number.isFinite(entry)))
- throw new TypeError(`${path} must be a finite [x,y,z] tuple`);
- return [value[0], value[1], value[2]];
-}
-function boundedPixelSize(value, path) {
- if (!Number.isInteger(value) || value < 1 || value > 4096) {
- throw new TypeError(`${path} must be an integer in [1,4096]`);
- }
- return value;
-}
-function validatePbrRenderRequest(input) {
- if (!input || typeof input !== "object" || Array.isArray(input)) {
- throw new TypeError("PbrRenderRequest must be an object");
- }
- const source = input;
- for (const key of Object.keys(source)) {
- if (!PBR_REQUEST_KEYS.has(key))
- throw new TypeError(`PbrRenderRequest.${key} is unknown`);
- }
- if (!(source.glb instanceof Uint8Array) || source.glb.byteLength === 0) {
- throw new TypeError("PbrRenderRequest.glb must be a non-empty Uint8Array");
- }
- const result = { glb: source.glb };
- if (source.viewDirs !== undefined) {
- if (!Array.isArray(source.viewDirs) || source.viewDirs.length < 1 || source.viewDirs.length > 12) {
- throw new TypeError("PbrRenderRequest.viewDirs must contain 1..12 directions");
- }
- result.viewDirs = source.viewDirs.map((value, index) => {
- const direction = finiteTuple3(value, `PbrRenderRequest.viewDirs[${index}]`);
- if (Math.hypot(...direction) === 0) {
- throw new TypeError(`PbrRenderRequest.viewDirs[${index}] must be non-zero`);
- }
- return direction;
- });
- }
- if (source.size !== undefined)
- result.size = boundedPixelSize(source.size, "PbrRenderRequest.size");
- if (source.beautySize !== undefined) {
- result.beautySize = boundedPixelSize(source.beautySize, "PbrRenderRequest.beautySize");
- }
- const hasWidth = source.width !== undefined;
- const hasHeight = source.height !== undefined;
- if (hasWidth !== hasHeight) {
- throw new TypeError("PbrRenderRequest.width and height must be provided together");
- }
- if (hasWidth) {
- result.width = boundedPixelSize(source.width, "PbrRenderRequest.width");
- result.height = boundedPixelSize(source.height, "PbrRenderRequest.height");
- }
- if (source.cameras !== undefined) {
- if (source.viewDirs !== undefined) {
- throw new TypeError("PbrRenderRequest.cameras and viewDirs are mutually exclusive");
- }
- if (source.size !== undefined || source.beautySize !== undefined) {
- throw new TypeError("PbrRenderRequest camera mode cannot use legacy size or beautySize");
- }
- if (result.width === undefined || result.height === undefined) {
- throw new TypeError("PbrRenderRequest camera mode requires width and height");
- }
- if (!Array.isArray(source.cameras) || source.cameras.length < 1 || source.cameras.length > 12) {
- throw new TypeError("PbrRenderRequest.cameras must contain 1..12 cameras");
- }
- result.cameras = source.cameras.map((value, index) => {
- if (!value || typeof value !== "object" || Array.isArray(value)) {
- throw new TypeError(`PbrRenderRequest.cameras[${index}] must be an object`);
- }
- const camera = value;
- if (camera.version !== undefined || camera.projection !== undefined) {
- const parsed = validateResolvedAssetCamera(camera);
- if (Math.abs(parsed.aspect - result.width / result.height) > 0.000000001)
- throw new TypeError("camera aspect must equal width/height");
- return parsed;
- }
- const expected = new Set(["position", "target", "up", "fovDeg", "aspect", "near", "far"]);
- for (const key of Object.keys(camera)) {
- if (!expected.has(key))
- throw new TypeError(`PbrRenderRequest.cameras[${index}].${key} is unknown`);
- }
- const position = finiteTuple3(camera.position, `PbrRenderRequest.cameras[${index}].position`);
- const target = finiteTuple3(camera.target, `PbrRenderRequest.cameras[${index}].target`);
- const up = finiteTuple3(camera.up, `PbrRenderRequest.cameras[${index}].up`);
- if (Math.hypot(position[0] - target[0], position[1] - target[1], position[2] - target[2]) === 0) {
- throw new TypeError(`PbrRenderRequest.cameras[${index}].target must differ from position`);
- }
- if (Math.hypot(...up) === 0) {
- throw new TypeError(`PbrRenderRequest.cameras[${index}].up must be non-zero`);
- }
- const view = [
- target[0] - position[0],
- target[1] - position[1],
- target[2] - position[2]
- ];
- const cross4 = [
- view[1] * up[2] - view[2] * up[1],
- view[2] * up[0] - view[0] * up[2],
- view[0] * up[1] - view[1] * up[0]
- ];
- if (Math.hypot(...cross4) <= Math.hypot(...view) * Math.hypot(...up) * 0.000000001) {
- throw new TypeError(`PbrRenderRequest.cameras[${index}].up must not be collinear with view`);
- }
- const number = (key) => {
- const parsed = camera[key];
- if (typeof parsed !== "number" || !Number.isFinite(parsed)) {
- throw new TypeError(`PbrRenderRequest.cameras[${index}].${key} must be finite`);
- }
- return parsed;
- };
- const fovDeg = number("fovDeg");
- const aspect = number("aspect");
- const near = number("near");
- const far = number("far");
- if (fovDeg <= 0 || fovDeg >= 180) {
- throw new TypeError(`PbrRenderRequest.cameras[${index}].fovDeg must be in (0,180)`);
- }
- if (aspect <= 0)
- throw new TypeError(`PbrRenderRequest.cameras[${index}].aspect must be positive`);
- if (near <= 0)
- throw new TypeError(`PbrRenderRequest.cameras[${index}].near must be positive`);
- if (far <= near)
- throw new TypeError(`PbrRenderRequest.cameras[${index}].far must exceed near`);
- const targetAspect = result.width / result.height;
- if (Math.abs(aspect - targetAspect) > Math.max(1, targetAspect) * 0.000000001) {
- throw new TypeError(`PbrRenderRequest.cameras[${index}].aspect must equal width/height`);
- }
- return { position, target, up, fovDeg, aspect, near, far };
- });
- } else if (hasWidth) {
- throw new TypeError("PbrRenderRequest width and height require camera mode");
- }
- if (source.lightingPresetId !== undefined) {
- if (typeof source.lightingPresetId !== "string" || !source.lightingPresetId.trim() || source.lightingPresetId !== source.lightingPresetId.trim() || source.lightingPresetId.length > 128) {
- throw new TypeError("PbrRenderRequest.lightingPresetId must be a non-empty string");
- }
- result.lightingPresetId = source.lightingPresetId;
- }
- return result;
-}
-var PBR_REQUEST_KEYS;
-var init_render_port = __esm(() => {
- init_camera();
- init_background();
- PBR_REQUEST_KEYS = new Set([
- "glb",
- "viewDirs",
- "size",
- "beautySize",
- "cameras",
- "width",
- "height",
- "lightingPresetId"
- ]);
-});
-
-// src/views/capture-cache.ts
-var exports_capture_cache = {};
-__export(exports_capture_cache, {
- createCachedRenderPort: () => createCachedRenderPort,
- captureCpuCell: () => captureCpuCell,
- MemoryCaptureCache: () => MemoryCaptureCache
-});
-import { createHash as createHash4 } from "node:crypto";
-function clone(entry) {
- const result = structuredClone(entry);
- if (result.kind === "cpu")
- result.result.png = Buffer.from(result.result.png);
- return result;
-}
-
-class MemoryCaptureCache {
- maxBytes;
- entries = new Map;
- bytes = 0;
- constructor(maxBytes = 64 * 1024 * 1024) {
- this.maxBytes = maxBytes;
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 0)
- throw new Error("Capture cache bytes must be a nonnegative integer");
- }
- async get(key) {
- const value = this.entries.get(key);
- if (!value)
- return;
- this.entries.delete(key);
- this.entries.set(key, value);
- return clone(value.entry);
- }
- async put(key, value) {
- const entry = clone(value);
- let bytes;
- if (entry.kind === "gpu") {
- const { viewsPng, beautyPng, ...metadata } = entry.result;
- bytes = (viewsPng ?? []).reduce((sum, png) => sum + png.byteLength, 0) + (beautyPng?.byteLength ?? 0) + Buffer.byteLength(JSON.stringify(metadata));
- } else {
- const { png, ...metadata } = entry.result;
- bytes = png.byteLength + Buffer.byteLength(JSON.stringify(metadata));
- }
- if (bytes > this.maxBytes)
- return;
- const old = this.entries.get(key);
- if (old) {
- this.bytes -= old.bytes;
- this.entries.delete(key);
- }
- while (this.bytes + bytes > this.maxBytes) {
- const first = this.entries.keys().next().value;
- if (first === undefined)
- break;
- this.bytes -= this.entries.get(first).bytes;
- this.entries.delete(first);
- }
- this.entries.set(key, { entry, bytes });
- this.bytes += bytes;
- }
- stats() {
- return { entries: this.entries.size, bytes: this.bytes, maxBytes: this.maxBytes };
- }
-}
-function canonical(value) {
- if (Array.isArray(value))
- return value.map(canonical);
- if (value && typeof value === "object")
- return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, canonical(v)]));
- if (typeof value === "number" && !Number.isFinite(value))
- throw new Error("Non-finite capture identity");
- if (value === undefined || value === null || ["string", "number", "boolean"].includes(typeof value))
- return value;
- throw new Error("Capture identity must be data");
-}
-function usable(result, request2, hash) {
- try {
- if (!result.ok || !result.rendererId?.trim() || result.derivativeFidelity?.materialFaithful !== true || result.derivativeFidelity.inputGlbSha256 !== hash)
- return false;
- const count = (request2.cameras ?? request2.viewDirs).length;
- if (result.viewsPng?.length !== count)
- return false;
- if (request2.cameras && (result.width !== request2.width || result.height !== request2.height || text(result.cameras) !== text(request2.cameras)))
- return false;
- enforcePngCaptureBudget(result.viewsPng);
- for (const png of result.viewsPng) {
- const image = decodePng(png);
- if (image.width !== image.height || request2.cameras && (image.width !== request2.width || image.height !== request2.height))
- return false;
- }
- return true;
- } catch {
- return false;
- }
-}
-function createCachedRenderPort(port, options) {
- return async (input) => {
- const identity = await Promise.resolve().then(() => options.identity()).catch(() => {
- return;
- });
- if (!identity || input.beautySize !== undefined || !(input.cameras ?? input.viewDirs)?.length)
- return port(input);
- const validated = validatePbrRenderRequest(input);
- const request2 = { ...validated, glb: Uint8Array.from(validated.glb) };
- const hash = digest(request2.glb);
- const selectors = request2.cameras ?? request2.viewDirs;
- const keys = selectors.map((selector) => digest(text({
- version: "kiln.capture-cache.v1",
- kind: "gpu",
- identity,
- artifact: hash,
- selector,
- size: request2.size,
- width: request2.width,
- height: request2.height,
- lighting: request2.lightingPresetId
- })));
- const cells = [];
- const missing = [];
- for (let i = 0;i < keys.length; i++) {
- const cached = await options.cache.get(keys[i]).catch(() => {
- return;
- });
- const single = {
- ...request2,
- ...request2.cameras ? { cameras: [request2.cameras[i]] } : { viewDirs: [request2.viewDirs[i]] }
- };
- if (cached?.kind === "gpu" && usable(cached.result, single, hash))
- cells[i] = cached.result;
- else
- missing.push(i);
- }
- if (missing.length) {
- const subrequest = {
- ...request2,
- ...request2.cameras ? { cameras: missing.map((i) => request2.cameras[i]) } : { viewDirs: missing.map((i) => request2.viewDirs[i]) }
- };
- const produced = await port(subrequest);
- const afterIdentity = await Promise.resolve().then(() => options.identity()).catch(() => {
- return;
- });
- if (afterIdentity !== identity)
- return missing.length === selectors.length ? produced : {
- ok: false,
- rendererId: produced.rendererId,
- error: "capture producer changed during render"
- };
- if (!usable(produced, subrequest, hash)) {
- return missing.length === selectors.length ? produced : {
- ok: false,
- rendererId: produced.rendererId,
- error: produced.error ?? "uncacheable partial camera response"
- };
- }
- for (let j = 0;j < missing.length; j++) {
- const i = missing[j];
- const cell = {
- ...produced,
- viewsPng: [Uint8Array.from(produced.viewsPng[j])],
- ...produced.cameras ? { cameras: [produced.cameras[j]] } : {}
- };
- cells[i] = cell;
- await options.cache.put(keys[i], { kind: "gpu", result: cell }).catch(() => {});
- }
- }
- const first = cells[0];
- if (cells.some((c) => c.rendererId !== first.rendererId))
- return {
- ok: false,
- rendererId: first.rendererId,
- error: "capture producer changed; refresh host cache identity"
- };
- return {
- ...first,
- viewsPng: cells.map((c) => Uint8Array.from(c.viewsPng[0])),
- ...request2.cameras ? { cameras: structuredClone(request2.cameras) } : {},
- captureCache: {
- hit: missing.length === 0,
- reused: selectors.length - missing.length,
- total: selectors.length
- }
- };
- };
-}
-async function captureCpuCell(cache, identity, produce) {
- const snapshot = structuredClone(identity);
- const key = digest(text({ version: "kiln.capture-cache.v1", kind: "cpu", ...snapshot }));
- const valid = (result2) => {
- try {
- enforcePngCaptureBudget([result2.png]);
- const image = decodePng(result2.png);
- return result2.inputGlbSha256 === snapshot.artifactGlbSha256 && image.width === snapshot.size && image.height === snapshot.size && result2.width === snapshot.size && result2.height === snapshot.size;
- } catch {
- return false;
- }
- };
- const cached = await cache.get(key).catch(() => {
- return;
- });
- if (cached?.kind === "cpu" && valid(cached.result))
- return { ...cached.result, png: Buffer.from(cached.result.png), captureCache: { hit: true } };
- const result = await produce();
- if (!valid(result))
- return result;
- await cache.put(key, { kind: "cpu", result }).catch(() => {});
- return { ...result, png: Buffer.from(result.png), captureCache: { hit: false } };
-}
-var text = (value) => JSON.stringify(canonical(value)), digest = (value) => `sha256:${createHash4("sha256").update(value).digest("hex")}`;
-var init_capture_cache = __esm(() => {
- init_render_port();
- init_png();
- init_capture_limits();
-});
-
-// src/views/camera-capture.ts
-var exports_camera_capture = {};
-__export(exports_camera_capture, {
- validateAdvancedCapture: () => validateAdvancedCapture,
- renderCaptureGrid: () => renderCaptureGrid
-});
-function validateAdvancedCapture(config) {
- for (const key of Object.keys(config))
- if (!["version", "shots", "cols", "size", "output"].includes(key))
- throw new Error(`capture.${key} is unknown or incompatible with shots`);
- if (config.version !== "kiln.capture.v1")
- throw new Error("advanced capture requires version kiln.capture.v1");
- if (!Array.isArray(config.shots) || config.shots.length < 1 || config.shots.length > 9)
- throw new Error("capture.shots must contain 1..9 shots");
- if (config.cols !== undefined && (!Number.isInteger(config.cols) || config.cols < 1 || config.cols > 3))
- throw new Error("capture.cols must be 1..3");
- if (config.size !== undefined && (!Number.isInteger(config.size) || config.size < 128 || config.size > 1024))
- throw new Error("capture.size must be 128..1024");
- if (config.output !== undefined && !["grid", "separate"].includes(config.output))
- throw new Error("capture.output must be grid or separate");
-}
-async function renderCaptureGrid(root, config, render, limits) {
- validateAdvancedCapture(config);
- const shots = config.shots.map((s) => resolveAssetCamera(root, s));
- const size = config.size ?? 384;
- const cols = config.cols ?? Math.min(3, shots.length);
- enforceCapturePixels(shots.length, size, cols, limits);
- const cells = [];
- const perFramePngs = [];
- const derivativeReceipts = [];
- for (const shot of shots) {
- const dir = shot.camera.position.map((n, i) => n - shot.camera.target[i]);
- const view = { name: shot.name, dir };
- const png2 = await withCameraVisibility(root, shot, async () => {
- if (render) {
- const result = await render({ root, label: shot.name, view, size, camera: shot.camera });
- derivativeReceipts.push(result.receipt);
- return result.png;
- }
- return encodePng(rasterizeCamera(root, shot.camera, size), size, size);
- });
- const decoded = decodePng(png2);
- if (decoded.width !== size || decoded.height !== size)
- throw new Error("capture cell dimensions do not match request");
- annotateViewCell(decoded.rgb, size, view);
- cells.push(decoded.rgb);
- perFramePngs.push(encodePng(decoded.rgb, size, size));
- }
- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, cols);
- const png = encodePng(rgb2, width, height);
- enforceCaptureBytes(config.output === "separate" ? perFramePngs : [png], limits);
- return {
- png,
- width,
- height,
- views: shots.map((s) => s.name),
- capture: { preset: `${cols}x${Math.ceil(shots.length / cols)}`, cols, cells: shots.length },
- cameraShots: shots,
- perFramePngs,
- derivativeReceipts,
- ...derivativeReceipts.length ? {
- captureCache: {
- hit: derivativeReceipts.every((r) => r.captureCache?.hit),
- reused: derivativeReceipts.filter((r) => r.captureCache?.hit).length,
- total: derivativeReceipts.length
- }
- } : {}
- };
-}
-var init_camera_capture = __esm(() => {
- init_capture_limits();
- init_camera();
- init_png();
- init_grid();
- init_annotate();
-});
-
-// src/views/capture.ts
-var exports_capture = {};
-__export(exports_capture, {
- resolveGridCapture: () => resolveGridCapture,
- resolveCapture: () => resolveCapture,
- describeCapture: () => describeCapture,
- captureCellLabel: () => captureCellLabel,
- MAX_CAPTURE_CELLS: () => MAX_CAPTURE_CELLS,
- DEFAULT_CAPTURE_PRESET: () => DEFAULT_CAPTURE_PRESET,
- CaptureConfigError: () => CaptureConfigError,
- CAPTURE_PRESETS: () => CAPTURE_PRESETS
-});
-function captureCellLabel(azimuthDeg, elevationDeg) {
- const az = Math.round((azimuthDeg % 360 + 360) % 360);
- const el = Math.round(elevationDeg);
- return `A${az} ${el < 0 ? "D" : "U"}${Math.abs(el)}`;
-}
-function resolveCapture(config) {
- if (!config || config.preset === undefined && config.cells === undefined) {
- return {
- preset: DEFAULT_CAPTURE_PRESET,
- views: PRESET_VIEWS[DEFAULT_CAPTURE_PRESET],
- cols: PRESET_COLS[DEFAULT_CAPTURE_PRESET],
- zooms: new Array(PRESET_CAPACITY[DEFAULT_CAPTURE_PRESET]).fill(undefined),
- isDefault: true
- };
- }
- const cells = config.cells;
- let preset = config.preset;
- if (preset !== undefined && !CAPTURE_PRESETS.includes(preset)) {
- throw new CaptureConfigError(`capture.preset must be one of ${CAPTURE_PRESETS.join(", ")} (got ${JSON.stringify(preset)}).`);
- }
- if (cells !== undefined) {
- if (!Array.isArray(cells) || cells.length === 0) {
- throw new CaptureConfigError("capture.cells must be a non-empty array of camera angles.");
- }
- if (cells.length > MAX_CAPTURE_CELLS) {
- throw new CaptureConfigError(`capture.cells has ${cells.length} entries; the maximum is ${MAX_CAPTURE_CELLS}.`);
- }
- for (let i = 0;i < cells.length; i++) {
- const c = cells[i];
- if (!Number.isFinite(c?.azimuthDeg) || !Number.isFinite(c?.elevationDeg)) {
- throw new CaptureConfigError(`capture.cells[${i}] needs finite azimuthDeg and elevationDeg (got ${JSON.stringify(c)}).`);
- }
- if (c.zoom !== undefined && (!Number.isFinite(c.zoom) || c.zoom <= 0)) {
- throw new CaptureConfigError(`capture.cells[${i}].zoom must be a positive number (got ${c.zoom}).`);
- }
- }
- if (preset === undefined) {
- preset = CAPTURE_PRESETS.find((p) => PRESET_CAPACITY[p] >= cells.length);
- } else if (cells.length > PRESET_CAPACITY[preset]) {
- throw new CaptureConfigError(`capture.preset ${preset} holds ${PRESET_CAPACITY[preset]} cells but ${cells.length} were given. ` + `Use a larger preset or fewer cells.`);
- }
- return {
- preset,
- views: cells.map((c) => ({
- name: c.name?.trim().toUpperCase() || captureCellLabel(c.azimuthDeg, c.elevationDeg),
- dir: orbitDir(c.azimuthDeg, c.elevationDeg)
- })),
- cols: PRESET_COLS[preset],
- zooms: cells.map((c) => c.zoom),
- isDefault: false
- };
- }
- const chosen = preset;
- return {
- preset: chosen,
- views: PRESET_VIEWS[chosen],
- cols: PRESET_COLS[chosen],
- zooms: new Array(PRESET_VIEWS[chosen].length).fill(undefined),
- isDefault: chosen === DEFAULT_CAPTURE_PRESET
- };
-}
-function resolveGridCapture(config, envVariant) {
- const resolved2 = resolveCapture(config);
- if (config)
- return resolved2;
- const views = resolveGridViews(envVariant);
- return views === resolved2.views ? resolved2 : { ...resolved2, views };
-}
-function describeCapture(resolved2) {
- const angles = resolved2.views.map((v) => {
- const { azimuthDeg, elevationDeg } = orbitAnglesOf(v.dir);
- return `${v.name} (az ${azimuthDeg}, el ${elevationDeg})`;
- }).join("; ");
- return `${resolved2.preset} grid, ${resolved2.views.length} cell${resolved2.views.length === 1 ? "" : "s"}: ${angles}`;
-}
-var CAPTURE_PRESETS, DEFAULT_CAPTURE_PRESET = "3x2", MAX_CAPTURE_CELLS = 9, PRESET_COLS, PRESET_CAPACITY, BOTTOM, THREE_QUARTER_REAR, THREE_QUARTER_LOW, PRESET_VIEWS, CaptureConfigError;
-var init_capture = __esm(() => {
- init_raster();
- CAPTURE_PRESETS = [
- "1x1",
- "1x2",
- "2x1",
- "3x1",
- "2x2",
- "3x2",
- "3x3"
- ];
- PRESET_COLS = {
- "1x1": 1,
- "1x2": 1,
- "2x1": 2,
- "3x1": 3,
- "2x2": 2,
- "3x2": 3,
- "3x3": 3
- };
- PRESET_CAPACITY = {
- "1x1": 1,
- "1x2": 2,
- "2x1": 2,
- "3x1": 3,
- "2x2": 4,
- "3x2": 6,
- "3x3": 9
- };
- BOTTOM = { name: "BOTTOM", dir: [0, -1, 0.0001] };
- THREE_QUARTER_REAR = { name: "REAR 34", dir: [-0.7, 0.5, -0.7] };
- THREE_QUARTER_LOW = { name: "LOW 34", dir: [0.7, -0.35, 0.7] };
- PRESET_VIEWS = {
- "1x1": [SIX_VIEWS[5]],
- "1x2": [SIX_VIEWS[0], SIX_VIEWS[5]],
- "2x1": [SIX_VIEWS[0], SIX_VIEWS[5]],
- "3x1": [SIX_VIEWS[0], SIX_VIEWS[1], SIX_VIEWS[5]],
- "2x2": [SIX_VIEWS[0], SIX_VIEWS[1], SIX_VIEWS[4], SIX_VIEWS[5]],
- "3x2": SIX_VIEWS,
- "3x3": [...SIX_VIEWS, BOTTOM, THREE_QUARTER_REAR, THREE_QUARTER_LOW]
- };
- CaptureConfigError = class CaptureConfigError extends Error {
- };
-});
-
-// src/views/architecture.ts
-function nodeRoles(node) {
- return readSemanticMetadataV1FromExtras(node.userData ?? {})?.roles ?? [];
-}
-function hasArchitectureRoofRole(node) {
- return nodeRoles(node).some((role) => ARCHITECTURE_ROOF_ROLE_PREFIXES.some((prefix) => role.startsWith(prefix)));
-}
-function legacyRoofName(name) {
- if (!name)
- return false;
- return /^roof(?:$|[_. -]|(?:slope|panel|gable|ridge)|[ab](?:$|[_. -]))/i.test(name.trim());
-}
-function minimalMatches(root, predicate) {
- const matches = [];
- const visit = (node, ancestorMatched) => {
- const matched = predicate(node);
- if (matched && !ancestorMatched)
- matches.push(node);
- for (const child of node.children ?? [])
- visit(child, ancestorMatched || matched);
- };
- visit(root, false);
- return matches;
-}
-function selectArchitectureRoofNodes(root) {
- const candidate = root;
- const semantic3 = minimalMatches(candidate, hasArchitectureRoofRole);
- if (semantic3.length > 0)
- return { mode: "semantic", nodes: semantic3 };
- const legacy = minimalMatches(candidate, (node) => legacyRoofName(node.name));
- return legacy.length > 0 ? { mode: "legacy-name", nodes: legacy } : { mode: "none", nodes: [] };
-}
-function setSubtreeVisibility(node, visible) {
- node.visible = visible;
- for (const child of node.children ?? [])
- setSubtreeVisibility(child, visible);
-}
-function hideArchitectureRoofInScene(root) {
- const selection = selectArchitectureRoofNodes(root);
- for (const node of selection.nodes)
- setSubtreeVisibility(node, false);
- return selection;
-}
-var ARCHITECTURE_ROOF_ROLE_PREFIXES;
-var init_architecture3 = __esm(() => {
- init_contracts();
- ARCHITECTURE_ROOF_ROLE_PREFIXES = Object.freeze([
- `${KILN_SEMANTIC_ROLES.roof}.`,
- `${KILN_SEMANTIC_ROLES.architectureRoof}.`
- ]);
-});
-
-// src/views/glb.ts
-import {
- Primitive,
- WebIO as WebIO2
-} from "@gltf-transform/core";
-import {
- EXTMeshGPUInstancing as EXTMeshGPUInstancing2,
- KHRMaterialsVariants as KHRMaterialsVariants2,
- KHRTextureBasisu as KHRTextureBasisu2
-} from "@gltf-transform/extensions";
-import {
- BufferAttribute as BufferAttribute8,
- BufferGeometry as BufferGeometry14,
- Group,
- Matrix4 as Matrix47,
- Mesh as Mesh10,
- MeshStandardMaterial as MeshStandardMaterial5,
- NoColorSpace as NoColorSpace4,
- SRGBColorSpace as SRGBColorSpace5,
- Texture,
- AnimationClip as AnimationClip3,
- QuaternionKeyframeTrack as QuaternionKeyframeTrack2,
- VectorKeyframeTrack as VectorKeyframeTrack2,
- Quaternion as Quaternion14,
- Vector3 as Vector326
-} from "three";
-function record4(value) {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-function reviewClipsFromExtras(extras) {
- if (!record4(extras))
- return;
- const envelope = extras[REVIEW_CLIPS_EXTRAS_KEY];
- if (!record4(envelope) || envelope.version !== 1 || !Array.isArray(envelope.clips)) {
- return;
- }
- if (envelope.clips.length > REVIEW_CLIP_LIMITS.clips) {
- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Animation review clip limit exceeded.");
- }
- let trackCount = 0;
- return envelope.clips.map((candidate) => {
- if (!record4(candidate) || typeof candidate.name !== "string" || candidate.name.length > 256 || typeof candidate.duration !== "number" || !Number.isFinite(candidate.duration) || candidate.duration < 0 || !Array.isArray(candidate.tracks)) {
- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Invalid animation review clip.");
- }
- const tracks = candidate.tracks.map((track) => {
- trackCount++;
- if (trackCount > REVIEW_CLIP_LIMITS.tracks || !record4(track) || typeof track.name !== "string" || track.name.length > 512 || !Array.isArray(track.times) || !Array.isArray(track.values) || track.times.length > REVIEW_CLIP_LIMITS.samplesPerTrack || track.values.length > REVIEW_CLIP_LIMITS.valuesPerTrack || !track.times.every((value) => typeof value === "number" && Number.isFinite(value)) || !track.values.every((value) => typeof value === "number" && Number.isFinite(value))) {
- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Invalid animation review track.");
- }
- const property = track.name.slice(track.name.lastIndexOf(".") + 1);
- const Track = property === "quaternion" ? QuaternionKeyframeTrack2 : VectorKeyframeTrack2;
- return new Track(track.name, track.times, track.values);
- });
- return new AnimationClip3(candidate.name, candidate.duration, tracks);
- });
-}
-function geometryFlatTextureReasonCode(mimeType) {
- return mimeType === "image/ktx2" ? GLB_GEOMETRY_FLAT_REASON.KTX2_SAMPLING_UNSUPPORTED : GLB_GEOMETRY_FLAT_REASON.TEXTURE_SAMPLING_UNSUPPORTED;
-}
-function decodedAccessor(accessor) {
- const itemSize = accessor.getElementSize();
- const output = new Float64Array(accessor.getCount() * itemSize);
- const element = [];
- for (let index = 0;index < accessor.getCount(); index++) {
- accessor.getElement(index, element);
- for (let component = 0;component < itemSize; component++) {
- output[index * itemSize + component] = element[component];
- }
- }
- return output;
-}
-function triangleIndices(primitive, vertexCount) {
- const sourceAccessor = primitive.getIndices();
- const source = sourceAccessor ? Array.from(decodedAccessor(sourceAccessor), (value) => Math.trunc(value)) : Array.from({ length: vertexCount }, (_, index) => index);
- switch (primitive.getMode()) {
- case Primitive.Mode.TRIANGLES:
- return Uint32Array.from(source);
- case Primitive.Mode.TRIANGLE_STRIP: {
- const triangles = [];
- for (let index = 0;index + 2 < source.length; index++) {
- triangles.push(source[index], source[index + 1 + index % 2], source[index + 2 - index % 2]);
- }
- return Uint32Array.from(triangles);
- }
- case Primitive.Mode.TRIANGLE_FAN: {
- const triangles = [];
- for (let index = 1;index + 1 < source.length; index++) {
- triangles.push(source[index], source[index + 1], source[0]);
- }
- return Uint32Array.from(triangles);
- }
- default:
- return;
- }
-}
-function flatMaterial(material) {
- if (!material) {
- return {
- color: { r: 0.7, g: 0.7, b: 0.7 },
- opacity: 1,
- doubleSided: false,
- metalness: 0,
- roughness: 1,
- alphaMode: "OPAQUE",
- alphaCutoff: 0.5,
- emissive: [0, 0, 0]
- };
- }
- const [r, g, b, factorAlpha] = material.getBaseColorFactor();
- const alphaMode2 = material.getAlphaMode();
- const opacity = alphaMode2 === "BLEND" ? factorAlpha : alphaMode2 === "MASK" && factorAlpha < material.getAlphaCutoff() ? 0 : 1;
- return {
- color: { r, g, b },
- opacity,
- doubleSided: material.getDoubleSided(),
- metalness: material.getMetallicFactor(),
- roughness: material.getRoughnessFactor(),
- alphaMode: alphaMode2,
- alphaCutoff: material.getAlphaCutoff(),
- emissive: material.getEmissiveFactor()
- };
-}
-function preserveTexture(source, usage2, cache) {
- if (!source)
- return null;
- const encoded = source.getImage();
- const mime = source.getMimeType();
- if (!encoded || !mime)
- return null;
- let byUsage = cache.get(source);
- if (!byUsage) {
- byUsage = new Map;
- cache.set(source, byUsage);
- }
- const existing = byUsage.get(usage2);
- if (existing)
- return existing;
- const texture = new Texture;
- texture.name = source.getName();
- texture.colorSpace = usage2 === "color" ? SRGBColorSpace5 : NoColorSpace4;
- texture.userData.encoded = { mime, bytes: Uint8Array.from(encoded) };
- byUsage.set(usage2, texture);
- return texture;
-}
-function noteMaterialTextures(material, reasons) {
- if (!material)
- return;
- const textures = [
- material.getBaseColorTexture(),
- material.getNormalTexture(),
- material.getMetallicRoughnessTexture(),
- material.getEmissiveTexture(),
- material.getOcclusionTexture()
- ];
- for (const texture of textures) {
- if (texture)
- reasons.add(geometryFlatTextureReasonCode(texture.getMimeType()));
- }
-}
-function instanceMatrices(node) {
- const world = new Matrix47().fromArray(node.getWorldMatrix());
- const extension = node.getExtension("EXT_mesh_gpu_instancing");
- if (!extension)
- return { matrices: [world], count: 1 };
- const attributes = extension.listAttributes();
- if (attributes.length === 0) {
- throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", `Node ${JSON.stringify(node.getName())} has EXT_mesh_gpu_instancing with no attributes.`);
- }
- const count = attributes[0].getCount();
- if (attributes.some((attribute) => attribute.getCount() !== count)) {
- throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", `Node ${JSON.stringify(node.getName())} has mismatched EXT_mesh_gpu_instancing counts.`);
- }
- const translations = extension.getAttribute("TRANSLATION");
- const rotations = extension.getAttribute("ROTATION");
- const scales = extension.getAttribute("SCALE");
- const translation = [];
- const rotation = [];
- const scale2 = [];
- const matrices = [];
- for (let index = 0;index < count; index++) {
- translations?.getElement(index, translation);
- rotations?.getElement(index, rotation);
- scales?.getElement(index, scale2);
- const local = new Matrix47().compose(new Vector326(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion14(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector326(scales ? scale2[0] : 1, scales ? scale2[1] : 1, scales ? scale2[2] : 1));
- matrices.push(world.clone().multiply(local));
- }
- return { matrices, count };
-}
-async function loadGlbGeometryFlatScene(bytes) {
- let document;
- try {
- document = await glbIO().readBinary(Uint8Array.from(bytes));
- } catch (error) {
- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Could not parse final GLB bytes: ${error instanceof Error ? error.message : String(error)}`);
- }
- const scene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];
- if (!scene)
- throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");
- const reasons = new Set;
- const meshes = [];
- let instanceCount = 0;
- const sceneNodes2 = new Set;
- const visit = (node) => {
- if (sceneNodes2.has(node))
- return;
- sceneNodes2.add(node);
- for (const child of node.listChildren())
- visit(child);
- };
- for (const child of scene.listChildren())
- visit(child);
- for (const node of sceneNodes2) {
- const mesh = node.getMesh();
- if (!mesh)
- continue;
- if (node.getSkin())
- reasons.add(GLB_GEOMETRY_FLAT_REASON.SKIN_DEFORMATION_UNSUPPORTED);
- const instances = instanceMatrices(node);
- instanceCount += instances.count;
- for (const primitive of mesh.listPrimitives()) {
- if (primitive.listTargets().length > 0) {
- reasons.add(GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED);
- }
- const positionAccessor = primitive.getAttribute("POSITION");
- if (positionAccessor?.getElementSize() !== 3)
- continue;
- const positions = decodedAccessor(positionAccessor);
- const indices = triangleIndices(primitive, positionAccessor.getCount());
- if (!indices) {
- reasons.add(GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED);
- continue;
- }
- const material = primitive.getMaterial();
- noteMaterialTextures(material, reasons);
- const geometry2 = {
- getAttribute(name) {
- return name === "position" ? { array: positions, itemSize: 3, count: positionAccessor.getCount() } : undefined;
- },
- index: { array: indices, itemSize: 1, count: indices.length }
- };
- for (const matrix of instances.matrices) {
- meshes.push({
- isMesh: true,
- visible: true,
- geometry: geometry2,
- material: flatMaterial(material),
- matrixWorld: { elements: [...matrix.elements] }
- });
- }
- }
- }
- if (meshes.length === 0) {
- throw new GlbGeometryFlatError("GLB_FLAT_NO_RENDERABLE_GEOMETRY", "Final GLB contains no triangle geometry supported by the CPU fallback.");
- }
- const root = {
- updateMatrixWorld() {},
- traverse(callback) {
- for (const mesh of meshes)
- callback(mesh);
- }
- };
- return {
- root,
- reasonCodes: REASON_ORDER.filter((reason) => reasons.has(reason)),
- meshCount: meshes.length,
- instanceCount
- };
-}
-function localInstanceMatrices(node) {
- const extension = node.getExtension("EXT_mesh_gpu_instancing");
- if (!extension)
- return [new Matrix47];
- const attributes = extension.listAttributes();
- if (attributes.length === 0) {
- throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", "Invalid empty instancing data.");
- }
- const count = attributes[0].getCount();
- if (attributes.some((attribute) => attribute.getCount() !== count)) {
- throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", "Mismatched instancing data.");
- }
- const translations = extension.getAttribute("TRANSLATION");
- const rotations = extension.getAttribute("ROTATION");
- const scales = extension.getAttribute("SCALE");
- const translation = [];
- const rotation = [];
- const scale2 = [];
- return Array.from({ length: count }, (_, index) => {
- translations?.getElement(index, translation);
- rotations?.getElement(index, rotation);
- scales?.getElement(index, scale2);
- return new Matrix47().compose(new Vector326(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion14(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector326(...scales ? scale2.slice(0, 3) : [1, 1, 1]));
- });
-}
-async function loadGlbReviewScene(bytes) {
- let document;
- try {
- document = await glbIO().readBinary(Uint8Array.from(bytes));
- } catch {
- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Could not parse final GLB bytes.");
- }
- const sourceScene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];
- if (!sourceScene)
- throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");
- const reasons = new Set;
- const root = new Group;
- root.name = sourceScene.getName() || "Scene";
- const nodeMap = new Map;
- const textureCache = new Map;
- let meshCount = 0;
- let instanceCount = 0;
- const buildNode = (source) => {
- const existing = nodeMap.get(source);
- if (existing)
- return existing;
- const target = new Group;
- target.name = source.getName();
- target.position.fromArray(source.getTranslation());
- target.quaternion.fromArray(source.getRotation());
- target.scale.fromArray(source.getScale());
- target.userData = { ...source.getExtras() };
- nodeMap.set(source, target);
- const sourceMesh = source.getMesh();
- if (sourceMesh) {
- target.userData.kilnGlbMeshNode = true;
- if (source.getSkin())
- reasons.add(GLB_GEOMETRY_FLAT_REASON.SKIN_DEFORMATION_UNSUPPORTED);
- const matrices = localInstanceMatrices(source);
- instanceCount += matrices.length;
- for (const [primitiveIndex, primitive] of sourceMesh.listPrimitives().entries()) {
- if (primitive.listTargets().length)
- reasons.add(GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED);
- const position = primitive.getAttribute("POSITION");
- if (position?.getElementSize() !== 3)
- continue;
- const indices = triangleIndices(primitive, position.getCount());
- if (!indices) {
- reasons.add(GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED);
- continue;
- }
- const material = primitive.getMaterial();
- noteMaterialTextures(material, reasons);
- const flat = flatMaterial(material);
- const geometry2 = new BufferGeometry14;
- geometry2.setAttribute("position", new BufferAttribute8(Float32Array.from(decodedAccessor(position)), 3));
- const normal = primitive.getAttribute("NORMAL");
- if (normal) {
- geometry2.setAttribute("normal", new BufferAttribute8(Float32Array.from(decodedAccessor(normal)), 3));
- }
- const uv = primitive.getAttribute("TEXCOORD_0");
- if (uv) {
- geometry2.setAttribute("uv", new BufferAttribute8(Float32Array.from(decodedAccessor(uv)), 2));
- }
- const tangent = primitive.getAttribute("TANGENT");
- if (tangent) {
- geometry2.setAttribute("tangent", new BufferAttribute8(Float32Array.from(decodedAccessor(tangent)), 4));
- }
- geometry2.setIndex(new BufferAttribute8(indices, 1));
- const threeMaterial = new MeshStandardMaterial5({
- opacity: flat.opacity,
- transparent: flat.alphaMode === "BLEND",
- alphaTest: flat.alphaMode === "MASK" ? flat.alphaCutoff : 0,
- side: flat.doubleSided ? 2 : 0,
- metalness: flat.metalness,
- roughness: flat.roughness
- });
- threeMaterial.color.setRGB(flat.color.r, flat.color.g, flat.color.b);
- threeMaterial.emissive.fromArray(flat.emissive);
- if (material) {
- threeMaterial.map = preserveTexture(material.getBaseColorTexture(), "color", textureCache);
- threeMaterial.normalMap = preserveTexture(material.getNormalTexture(), "data", textureCache);
- threeMaterial.normalScale.setScalar(material.getNormalScale());
- const metallicRoughness = preserveTexture(material.getMetallicRoughnessTexture(), "data", textureCache);
- threeMaterial.metalnessMap = metallicRoughness;
- threeMaterial.roughnessMap = metallicRoughness;
- threeMaterial.emissiveMap = preserveTexture(material.getEmissiveTexture(), "color", textureCache);
- threeMaterial.aoMap = preserveTexture(material.getOcclusionTexture(), "data", textureCache);
- threeMaterial.aoMapIntensity = material.getOcclusionStrength();
- }
- for (const [index, matrix] of matrices.entries()) {
- const mesh = new Mesh10(geometry2, threeMaterial);
- const baseName = source.getName() || sourceMesh.getName() || "Mesh";
- mesh.name = `${baseName}:primitive-${primitiveIndex}${matrices.length === 1 ? "" : `:instance-${index}`}`;
- mesh.matrixAutoUpdate = false;
- mesh.matrix.copy(matrix);
- target.add(mesh);
- meshCount++;
- }
- }
- }
- for (const child of source.listChildren())
- target.add(buildNode(child));
- return target;
- };
- for (const child of sourceScene.listChildren())
- root.add(buildNode(child));
- root.updateMatrixWorld(true);
- if (meshCount === 0)
- throw new GlbGeometryFlatError("GLB_FLAT_NO_RENDERABLE_GEOMETRY", "Final GLB contains no renderable geometry.");
- const nativeClips = document.getRoot().listAnimations().map((animation) => new AnimationClip3(animation.getName(), -1, animation.listChannels().flatMap((channel) => {
- const node = channel.getTargetNode();
- const path = channel.getTargetPath();
- const sampler = channel.getSampler();
- const input = sampler?.getInput()?.getArray();
- const output = sampler?.getOutput()?.getArray();
- const property = path === "translation" ? "position" : path === "rotation" ? "quaternion" : path;
- if (!node || !property || property === "weights" || !input || !output)
- return [];
- const Track = path === "rotation" ? QuaternionKeyframeTrack2 : VectorKeyframeTrack2;
- return [new Track(`${node.getName()}.${property}`, input, output)];
- })));
- const clips = reviewClipsFromExtras(sourceScene.getExtras()) ?? nativeClips;
- return {
- root,
- clips,
- reasonCodes: REASON_ORDER.filter((reason) => reasons.has(reason)),
- meshCount,
- instanceCount
- };
-}
-var GLB_GEOMETRY_FLAT_REASON, REASON_ORDER, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, GlbGeometryFlatError, glbIO = () => new WebIO2().registerExtensions([EXTMeshGPUInstancing2, KHRMaterialsVariants2, KHRTextureBasisu2]);
-var init_glb = __esm(() => {
- GLB_GEOMETRY_FLAT_REASON = {
- TEXTURE_SAMPLING_UNSUPPORTED: "GLB_FLAT_TEXTURE_SAMPLING_UNSUPPORTED",
- KTX2_SAMPLING_UNSUPPORTED: "GLB_FLAT_KTX2_SAMPLING_UNSUPPORTED",
- NON_TRIANGLE_PRIMITIVE_UNSUPPORTED: "GLB_FLAT_NON_TRIANGLE_PRIMITIVE_UNSUPPORTED",
- SKIN_DEFORMATION_UNSUPPORTED: "GLB_FLAT_SKIN_DEFORMATION_UNSUPPORTED",
- MORPH_TARGETS_UNSUPPORTED: "GLB_FLAT_MORPH_TARGETS_UNSUPPORTED"
- };
- REASON_ORDER = [
- GLB_GEOMETRY_FLAT_REASON.KTX2_SAMPLING_UNSUPPORTED,
- GLB_GEOMETRY_FLAT_REASON.TEXTURE_SAMPLING_UNSUPPORTED,
- GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED,
- GLB_GEOMETRY_FLAT_REASON.SKIN_DEFORMATION_UNSUPPORTED,
- GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED
- ];
- REVIEW_CLIP_LIMITS = {
- clips: 32,
- tracks: 256,
- samplesPerTrack: 4096,
- valuesPerTrack: 16384
- };
- GlbGeometryFlatError = class GlbGeometryFlatError extends Error {
- code;
- constructor(code, message) {
- super(message);
- this.code = code;
- this.name = "GlbGeometryFlatError";
- }
- };
-});
-
-// src/evaluator/handler.ts
-var init_handler = __esm(() => {
- init_authoring_diagnostic();
- init_render();
- init_run();
- init_protocol();
-});
-
-// src/evaluator/isolation.ts
-var exports_isolation = {};
-__export(exports_isolation, {
- renderGLBViaIsolatedEvaluator: () => renderGLBViaIsolatedEvaluator,
- isolationReadinessFailureCode: () => isolationReadinessFailureCode,
- isolatedEvaluatorLaunch: () => isolatedEvaluatorLaunch,
- decodeEvaluatorIsolationTransport: () => decodeEvaluatorIsolationTransport,
- decodeEvaluatorIsolationReadiness: () => decodeEvaluatorIsolationReadiness,
- assertIsolatedEvaluatorReady: () => assertIsolatedEvaluatorReady,
- EvaluatorIsolationReadinessError: () => EvaluatorIsolationReadinessError
-});
-import { spawn } from "node:child_process";
-import { existsSync } from "node:fs";
-import { posix } from "node:path";
-import { fileURLToPath } from "node:url";
-function isolationReadinessFailureCode(error) {
- if (!(error instanceof EvaluatorIsolationReadinessError))
- return;
- return READINESS_FAILURE_CODES.includes(error.readinessCode) ? error.readinessCode : undefined;
-}
-function isolationUnavailable() {
- throw new EvaluatorSubprocessError("ISOLATION_UNAVAILABLE", "Isolated evaluator is unavailable.");
-}
-function requiredAbsolutePath(value) {
- if (!posix.isAbsolute(value) || posix.normalize(value) !== value)
- isolationUnavailable();
- return value;
-}
-function requiredRuntimeRoot(value) {
- const root = requiredAbsolutePath(value);
- if (root !== DEFAULT_RUNTIME_ROOT)
- isolationUnavailable();
- return root;
-}
-function workerInsideRuntime(workerPath, runtimeRoot) {
- const normalized = requiredAbsolutePath(workerPath);
- const packageRoot = posix.join(runtimeRoot, "node_modules") + posix.sep;
- if (!normalized.startsWith(packageRoot))
- isolationUnavailable();
- return normalized;
-}
-function runtimeMounts(runtimeRoot, pathExists) {
- const mounts = ["/usr", "/lib", "/lib64", posix.join(runtimeRoot, "node_modules")];
- const existing = mounts.filter((path) => pathExists(path));
- if (!existing.includes("/usr") || !existing.includes(posix.join(runtimeRoot, "node_modules"))) {
- isolationUnavailable();
- }
- return existing;
-}
-function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx") {
- const platform = host.platform ?? process.platform;
- if (platform !== "linux")
- isolationUnavailable();
- const runtimeRoot = requiredRuntimeRoot(host.runtimeRoot ?? DEFAULT_RUNTIME_ROOT);
- const pathExists = host.pathExists ?? existsSync;
- const bwrapPath = requiredAbsolutePath(host.bwrapPath ?? DEFAULT_BWRAP_PATH);
- const setprivPath = requiredAbsolutePath(host.setprivPath ?? DEFAULT_SETPRIV_PATH);
- const prlimitPath = requiredAbsolutePath(host.prlimitPath ?? DEFAULT_PRLIMIT_PATH);
- const nodePath5 = requiredAbsolutePath(host.nodePath ?? DEFAULT_NODE_PATH);
- for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath5]) {
- if (!pathExists(executable))
- isolationUnavailable();
- }
- const resolvedWorkerPath = workerInsideRuntime(workerPath, runtimeRoot);
- if (!pathExists(resolvedWorkerPath))
- isolationUnavailable();
- const bwrapArgs = [
- "--unshare-all",
- "--die-with-parent",
- "--new-session",
- "--disable-userns",
- "--cap-drop",
- "ALL",
- "--clearenv",
- "--setenv",
- "NODE_ENV",
- "production",
- "--setenv",
- "NO_COLOR",
- "1",
- "--proc",
- "/proc",
- "--dev",
- "/dev",
- "--tmpfs",
- "/tmp",
- "--dir",
- runtimeRoot,
- "--dir",
- posix.join(runtimeRoot, "node_modules")
- ];
- for (const mount of runtimeMounts(runtimeRoot, pathExists)) {
- bwrapArgs.push("--ro-bind", mount, mount);
- }
- const nodeArgs = [nodePath5, "--max-old-space-size=512", "--disable-proto=throw"];
- if (loader === "tsx")
- nodeArgs.push("--import", "tsx");
- nodeArgs.push(resolvedWorkerPath);
- bwrapArgs.push("--chdir", runtimeRoot, "--preserve-fds", "1", "--", prlimitPath, "--cpu=65:65", "--as=6442450944:6442450944", "--fsize=100663296:100663296", "--nofile=64:64", "--nproc=64:64", "--", ...nodeArgs);
- return {
- command: setprivPath,
- args: [
- "--no-new-privs",
- "--inh-caps=-all",
- "--ambient-caps=-all",
- "--",
- bwrapPath,
- ...bwrapArgs
- ],
- env: sanitizedEvaluatorEnv({}),
- detached: true
- };
-}
-function isolatedEvaluatorLaunch(workerPath, host = {}) {
- return isolatedEvaluatorLaunchWithLoader(workerPath, host, "tsx");
-}
-async function renderGLBViaIsolatedEvaluator(code, options = {}, controls = {}) {
- const workerPath = fileURLToPath(new URL("./worker.ts", import.meta.url));
- const launch = isolatedEvaluatorLaunch(workerPath, controls.host);
- const { host: _, ...processControls } = controls;
- return renderGLBViaProcessLaunch(code, options, processControls, launch);
-}
-function decodeEvaluatorIsolationReadiness(value) {
- if (typeof value !== "object" || value === null || Array.isArray(value))
- isolationUnavailable();
- const record5 = value;
- if (Object.keys(record5).sort().join(",") === "failure,mode,version" && record5.version === READINESS_VERSION && record5.mode === "isolated" && [
- "loader-probe-boot",
- "invariant-namespace",
- "invariant-environment",
- "invariant-filesystem",
- "invariant-network",
- "invariant-generated-policy"
- ].includes(String(record5.failure))) {
- return record5;
- }
- if (Object.keys(record5).sort().join(",") !== "checks,mode,version" || record5.version !== READINESS_VERSION || record5.mode !== "isolated" || !Array.isArray(record5.checks) || record5.checks.length !== READINESS_CHECKS.length || record5.checks.join(",") !== READINESS_CHECKS.join(",")) {
- isolationUnavailable();
- }
- return record5;
-}
-function decodeEvaluatorIsolationTransport(value) {
- if (typeof value !== "object" || value === null || Array.isArray(value) || Object.keys(value).sort().join(",") !== "transport,version") {
- isolationUnavailable();
- }
- const record5 = value;
- if (record5.version !== TRANSPORT_VERSION || record5.transport !== "fd3")
- isolationUnavailable();
- return record5;
-}
-function terminateReadinessChild(child) {
- try {
- if (child.pid)
- process.kill(-child.pid, "SIGKILL");
- } catch {}
-}
-async function assertIsolationTransport(launch) {
- return await new Promise((resolve, reject) => {
- const child = spawn(launch.command, launch.args, {
- env: launch.env,
- windowsHide: true,
- detached: true,
- stdio: ["ignore", "pipe", "ignore", "pipe"]
- });
- const stdoutChunks = [];
- const protocolChunks = [];
- let stdoutBytes = 0;
- let protocolBytes = 0;
- let settled = false;
- const fail = (readinessCode) => {
- if (settled)
- return;
- settled = true;
- clearTimeout(timer);
- reject(new EvaluatorIsolationReadinessError(readinessCode));
- };
- const timer = setTimeout(() => {
- terminateReadinessChild(child);
- fail("deadline");
- }, PROBE_DEADLINE_MS);
- child.stdout?.on("data", (chunk2) => {
- stdoutBytes += chunk2.byteLength;
- if (stdoutBytes > MAX_TRANSPORT_STDOUT_BYTES) {
- terminateReadinessChild(child);
- fail("wrapper-launch");
- return;
- }
- stdoutChunks.push(Buffer.from(chunk2));
- });
- const protocol = child.stdio[3];
- if (!protocol) {
- terminateReadinessChild(child);
- fail("fd3-transport");
- return;
- }
- protocol.on("data", (chunk2) => {
- protocolBytes += chunk2.byteLength;
- if (protocolBytes > MAX_READINESS_PROTOCOL_BYTES) {
- terminateReadinessChild(child);
- fail("fd3-transport");
- return;
- }
- protocolChunks.push(Buffer.from(chunk2));
- });
- child.once("error", () => fail("wrapper-launch"));
- child.once("close", (code) => {
- if (settled)
- return;
- const stdout = Buffer.concat(stdoutChunks).toString("utf8");
- if (stdout !== TRANSPORT_STDOUT_MARKER)
- return fail("wrapper-launch");
- if (code !== 0 || protocolChunks.length === 0)
- return fail("fd3-transport");
- try {
- decodeEvaluatorIsolationTransport(JSON.parse(Buffer.concat(protocolChunks).toString("utf8")));
- settled = true;
- clearTimeout(timer);
- resolve();
- } catch {
- fail("fd3-transport");
- }
- });
- });
-}
-async function runIsolationProbe(launch) {
- return await new Promise((resolve, reject) => {
- const child = spawn(launch.command, launch.args, {
- env: launch.env,
- windowsHide: true,
- detached: true,
- stdio: ["ignore", "ignore", "ignore", "pipe"]
- });
- const protocol = child.stdio[3];
- const chunks = [];
- let bytes = 0;
- let settled = false;
- const fail = (readinessCode) => {
- if (settled)
- return;
- settled = true;
- clearTimeout(timer);
- reject(new EvaluatorIsolationReadinessError(readinessCode));
- };
- const timer = setTimeout(() => {
- terminateReadinessChild(child);
- fail("deadline");
- }, PROBE_DEADLINE_MS);
- if (!protocol) {
- terminateReadinessChild(child);
- fail("fd3-transport");
- return;
- }
- protocol.on("data", (chunk2) => {
- bytes += chunk2.byteLength;
- if (bytes > MAX_READINESS_PROTOCOL_BYTES) {
- terminateReadinessChild(child);
- fail("loader-probe-boot");
- return;
- }
- chunks.push(Buffer.from(chunk2));
- });
- child.once("error", () => fail("wrapper-launch"));
- child.once("close", (code) => {
- if (settled)
- return;
- if (chunks.length === 0)
- return fail("loader-probe-boot");
- try {
- const result = decodeEvaluatorIsolationReadiness(JSON.parse(Buffer.concat(chunks).toString("utf8")));
- if ("failure" in result)
- return fail(result.failure);
- if (code !== 0)
- return fail("loader-probe-boot");
- settled = true;
- clearTimeout(timer);
- resolve(result);
- } catch {
- fail("loader-probe-boot");
- }
- });
- });
-}
-async function assertIsolatedEvaluatorReady(host = {}) {
- if (typeof process.getuid !== "function" || process.getuid() === 0) {
- throw new EvaluatorIsolationReadinessError("invariant-namespace");
- }
- const transportPath = fileURLToPath(new URL("./transport-worker.mjs", import.meta.url));
- const probePath = fileURLToPath(new URL("./probe-worker.ts", import.meta.url));
- let transportLaunch;
- let probeLaunch;
- try {
- transportLaunch = isolatedEvaluatorLaunchWithLoader(transportPath, host, "module");
- probeLaunch = isolatedEvaluatorLaunch(probePath, host);
- } catch {
- throw new EvaluatorIsolationReadinessError("wrapper-launch");
- }
- await assertIsolationTransport(transportLaunch);
- return await runIsolationProbe(probeLaunch);
-}
-var DEFAULT_RUNTIME_ROOT = "/app", DEFAULT_BWRAP_PATH = "/usr/local/bin/bwrap", DEFAULT_SETPRIV_PATH = "/usr/bin/setpriv", DEFAULT_PRLIMIT_PATH = "/usr/bin/prlimit", DEFAULT_NODE_PATH = "/usr/local/bin/node", READINESS_VERSION = "kiln.evaluator.isolation-readiness.v1", TRANSPORT_VERSION = "kiln.evaluator.isolation-transport.v1", TRANSPORT_STDOUT_MARKER = `kiln-evaluator-transport-boot-v1
-`, PROBE_DEADLINE_MS = 8000, MAX_READINESS_PROTOCOL_BYTES, MAX_TRANSPORT_STDOUT_BYTES = 256, READINESS_FAILURE_CODES, READINESS_CHECKS, EvaluatorIsolationReadinessError;
-var init_isolation = __esm(() => {
- init_subprocess();
- MAX_READINESS_PROTOCOL_BYTES = 16 * 1024;
- READINESS_FAILURE_CODES = [
- "wrapper-launch",
- "fd3-transport",
- "loader-probe-boot",
- "invariant-namespace",
- "invariant-environment",
- "invariant-filesystem",
- "invariant-network",
- "invariant-generated-policy",
- "deadline"
- ];
- READINESS_CHECKS = [
- "user-namespace",
- "no-new-privileges",
- "capabilities-empty",
- "environment-exact",
- "product-filesystem-denied",
- "host-filesystem-denied",
- "runtime-filesystem-read-only",
- "network-namespace-empty",
- "metadata-and-local-network-denied",
- "generated-capabilities-denied"
- ];
- EvaluatorIsolationReadinessError = class EvaluatorIsolationReadinessError extends EvaluatorSubprocessError {
- readinessCode;
- constructor(readinessCode) {
- super("ISOLATION_UNAVAILABLE", "Isolated evaluator readiness check failed.");
- this.name = "EvaluatorIsolationReadinessError";
- this.readinessCode = readinessCode;
- }
- };
-});
-
-// src/evaluator/index.ts
-var init_evaluator = __esm(() => {
- init_protocol();
- init_handler();
- init_subprocess();
- init_isolation();
-});
-
-// src/views/evidence-history.ts
-function unique(values) {
- return [...new Set(values)];
-}
-function cloneReference(reference) {
- return {
- ...reference,
- inputGlbSha256: [...reference.inputGlbSha256],
- rendererIds: [...reference.rendererIds]
- };
-}
-function currentEvidence(sequence, surface, fidelity) {
- if (fidelity.version === "kiln.view-fidelity.v1") {
- const valid2 = SHA256.test(fidelity.inputGlbSha256) && fidelity.rendererId.trim().length > 0 && (!fidelity.materialFaithful || fidelity.delivered === "full-material" && !fidelity.degraded);
- if (!valid2) {
- return {
- sequence,
- surface,
- delivered: "none",
- materialFaithful: false,
- exactArtifact: false,
- degraded: true,
- inputGlbSha256: [],
- rendererIds: [],
- reasonCodes: ["DERIVATIVE_RECEIPT_INVALID"]
- };
- }
- return {
- sequence,
- surface,
- delivered: fidelity.delivered,
- materialFaithful: fidelity.materialFaithful,
- exactArtifact: fidelity.exactArtifact,
- degraded: fidelity.degraded,
- inputGlbSha256: [fidelity.inputGlbSha256],
- rendererIds: [fidelity.rendererId],
- ...fidelity.reasonCodes?.length ? { reasonCodes: [...fidelity.reasonCodes] } : {}
- };
- }
- const valid = fidelity.exactArtifact === false && fidelity.receipts.length > 0 && fidelity.receipts.every((receipt) => receipt.exactArtifact === false && receipt.derivativeLabel.trim().length > 0 && receipt.rendererId.trim().length > 0 && SHA256.test(receipt.inputGlbSha256)) && (!fidelity.materialFaithful || fidelity.delivered === "full-material" && !fidelity.degraded && fidelity.receipts.every((receipt) => receipt.materialFaithful && receipt.delivered === "full-material" && !receipt.degraded));
- if (!valid) {
- return {
- sequence,
- surface,
- delivered: "none",
- materialFaithful: false,
- exactArtifact: false,
- degraded: true,
- inputGlbSha256: [],
- rendererIds: [],
- reasonCodes: ["DERIVATIVE_RECEIPT_INVALID"]
- };
- }
- const reasonCodes = unique(fidelity.receipts.flatMap((receipt) => receipt.reasonCodes ?? []).concat(fidelity.reasonCodes ?? []));
- return {
- sequence,
- surface,
- delivered: fidelity.delivered,
- materialFaithful: fidelity.materialFaithful,
- exactArtifact: false,
- degraded: fidelity.degraded,
- inputGlbSha256: fidelity.receipts.map((receipt) => receipt.inputGlbSha256),
- rendererIds: unique(fidelity.receipts.map((receipt) => receipt.rendererId)),
- ...reasonCodes.length ? { reasonCodes } : {}
- };
-}
-
-class ViewEvidenceHistoryStore {
- limit;
- sequence = 0;
- current;
- faithful = [];
- constructor(limit = DEFAULT_LIMIT) {
- if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
- throw new RangeError(`view evidence history limit must be an integer in [1,${MAX_LIMIT}]`);
- }
- this.limit = limit;
- }
- record(surface, fidelity) {
- this.sequence++;
- this.current = currentEvidence(this.sequence, surface, fidelity);
- if (this.current.materialFaithful) {
- this.faithful.push({
- version: "kiln.faithful-view-evidence-ref.v1",
- sequence: this.current.sequence,
- surface,
- materialFaithful: true,
- exactArtifact: this.current.exactArtifact,
- inputGlbSha256: [...this.current.inputGlbSha256],
- rendererIds: [...this.current.rendererIds]
- });
- if (this.faithful.length > this.limit)
- this.faithful.splice(0, this.faithful.length - this.limit);
- }
- return this.snapshot();
- }
- snapshot() {
- if (!this.current)
- return;
- const faithfulHistory = this.faithful.map(cloneReference);
- return {
- version: "kiln.view-evidence-history.v1",
- current: {
- ...this.current,
- inputGlbSha256: [...this.current.inputGlbSha256],
- rendererIds: [...this.current.rendererIds],
- ...this.current.reasonCodes ? { reasonCodes: [...this.current.reasonCodes] } : {}
- },
- ...faithfulHistory.length ? { lastFaithful: cloneReference(faithfulHistory[faithfulHistory.length - 1]) } : {},
- faithfulHistory
- };
- }
-}
-var SHA256, DEFAULT_LIMIT = 4, MAX_LIMIT = 8;
-var init_evidence_history = __esm(() => {
- SHA256 = /^sha256:[0-9a-f]{64}$/;
-});
-
-// src/views/renderer-id.ts
-var exports_renderer_id = {};
-__export(exports_renderer_id, {
- CPU_RASTER_RENDERER_ID: () => CPU_RASTER_RENDERER_ID
-});
-import { readFileSync } from "node:fs";
-function engineVersion() {
- for (const path of ["../package.json", "../../package.json"]) {
- try {
- const raw = readFileSync(new URL(path, import.meta.url), "utf8");
- const pkg = JSON.parse(raw);
- if (pkg.name === "@kiln/engine" && typeof pkg.version === "string" && pkg.version) {
- return pkg.version;
- }
- } catch {}
- }
- return "unknown";
-}
-var CPU_RASTER_RENDERER_ID;
-var init_renderer_id = __esm(() => {
- CPU_RASTER_RENDERER_ID = `cpu-raster:${engineVersion()}`;
-});
-
-// src/views/scene-raster.ts
-import * as THREE31 from "three";
-async function rasterizeComposedScene(parts, opts = {}) {
- const views = opts.views?.length ? opts.views : SCENE_VIEWS;
- const size = opts.size ?? 320;
- const group = new THREE31.Group;
- const baseByInput = new Map;
- for (const part of parts) {
- if (part.code === undefined === (part.glb === undefined)) {
- throw new TypeError("Composed part must provide exactly one of code or glb.");
- }
- const key = part.glb ?? part.code;
- let base = baseByInput.get(key);
- if (!base) {
- const glb = part.glb ? Uint8Array.from(part.glb) : (await resolveEvaluatorPortV1(opts.evaluatorPort, opts.evaluatorProfile ?? "trusted-local").render(part.code)).glb;
- base = (await loadGlbReviewScene(glb)).root;
- baseByInput.set(key, base);
- }
- const inst = base.clone(true);
- inst.position.set(part.pos[0], part.pos[1], part.pos[2]);
- inst.rotation.set(0, part.rotYDeg * DEG2, 0);
- inst.scale.setScalar(part.scale);
- group.add(inst);
- }
- group.updateMatrixWorld(true);
- const cols = Math.min(Math.max(views.length, 1), 3);
- const rows = Math.ceil(views.length / cols);
- const width = cols * size + (cols + 1) * PAD2;
- const height = rows * size + (rows + 1) * PAD2;
- const grid = new Uint8Array(width * height * 3);
- for (let i = 0;i < width * height; i++) {
- grid[i * 3] = PAD_COLOR2[0];
- grid[i * 3 + 1] = PAD_COLOR2[1];
- grid[i * 3 + 2] = PAD_COLOR2[2];
- }
- for (let vi = 0;vi < views.length; vi++) {
- const cell = rasterizeView(group, views[vi].dir, { size });
- const col = vi % cols;
- const row = Math.floor(vi / cols);
- const x0 = PAD2 + col * (size + PAD2);
- const y0 = PAD2 + row * (size + PAD2);
- for (let y = 0;y < size; y++) {
- const src = y * size * 3;
- const dst = ((y0 + y) * width + x0) * 3;
- grid.set(cell.subarray(src, src + size * 3), dst);
- }
- }
- return { png: encodePng(grid, width, height), width, height, views: views.map((v) => v.name) };
-}
-var DEG2, PAD2 = 4, PAD_COLOR2, SCENE_VIEWS;
-var init_scene_raster = __esm(() => {
- init_evaluator();
- init_glb();
- init_png();
- init_raster();
- DEG2 = Math.PI / 180;
- PAD_COLOR2 = [10, 11, 13];
- SCENE_VIEWS = [
- { name: "Hero 3/4", dir: [0.7, 0.45, 0.7] },
- { name: "Reverse 3/4", dir: [-0.7, 0.45, -0.7] },
- { name: "Top", dir: [0, 1, 0.0001] }
- ];
-});
-
-// src/views/vehicle.ts
-import * as THREE32 from "three";
-function hasRole2(node, prefix) {
- return readSemanticMetadataV1(node)?.roles.some((role) => role === prefix || role.startsWith(`${prefix}.`)) ?? false;
-}
-function chassisBounds(root, inverse) {
- const bounds = new THREE32.Box3;
- let found = false;
- root.traverse((node) => {
- if (!hasRole2(node, "chassis"))
- return;
- node.traverse((part) => {
- if (!(part instanceof THREE32.Mesh) || !(part.geometry instanceof THREE32.BufferGeometry))
- return;
- part.geometry.computeBoundingBox();
- const box = part.geometry.boundingBox;
- if (!box)
- return;
- const matrix = inverse.clone().multiply(part.matrixWorld);
- for (const x of [box.min.x, box.max.x])
- for (const y of [box.min.y, box.max.y])
- for (const z of [box.min.z, box.max.z]) {
- bounds.expandByPoint(new THREE32.Vector3(x, y, z).applyMatrix4(matrix));
- found = true;
- }
- });
- });
- return found ? bounds : undefined;
-}
-function describeVehicleDiagnostics(root) {
- root.updateWorldMatrix(true, true);
- const inverse = root.matrixWorld.clone().invert();
- const assemblies = resolveVehicleWheelAssemblies(root);
- const wheels = assemblies.map((wheel) => ({
- id: wheel.id,
- center: tuple7(wheel.centerWorld.clone().applyMatrix4(inverse)),
- radius: wheel.radius ?? 0,
- width: wheel.width ?? 0,
- axle: tuple7(wheel.spinAxisWorld.clone().transformDirection(inverse)),
- loadBearing: wheel.loadBearing
- }));
- const byAxle = new Map;
- for (let index = 0;index < assemblies.length; index++) {
- const key = assemblies[index].index ?? assemblies[index].id;
- const group = byAxle.get(key) ?? [];
- group.push(wheels[index]);
- byAxle.set(key, group);
- }
- const axles = [...byAxle].flatMap(([id, members]) => {
- if (members.length < 2)
- return [];
- const sorted = [...members].sort((a, b) => a.center[2] - b.center[2]);
- return [{ id, start: sorted[0].center, end: sorted.at(-1).center }];
- });
- const contacts = wheels.filter((wheel) => wheel.loadBearing && wheel.radius > 0).map((wheel) => wheel.center[1] - wheel.radius);
- const supportPlaneY = contacts.length > 0 ? contacts.reduce((sum, value) => sum + value, 0) / contacts.length : undefined;
- const chassis = chassisBounds(root, inverse);
- const views = [
- { id: "vehicle.front-direction", label: "+X front and chassis", cameraDirection: [1, 0.15, 0] },
- {
- id: "vehicle.axles.top",
- label: "Chassis and axle projection",
- cameraDirection: [0.001, 1, 0]
- },
- {
- id: "vehicle.underbody",
- label: "Underbody support plane",
- cameraDirection: [-0.3, -0.8, 0.5]
- },
- ...wheels.slice(0, 2).map((wheel) => ({
- id: `vehicle.wheel-section.${wheel.id.replace(/[^a-zA-Z0-9.-]/g, "-")}`,
- label: `Wheel section ${wheel.id}`,
- cameraDirection: [0, 0, wheel.center[2] < 0 ? -1 : 1],
- focus: wheel.id
- }))
- ];
- return {
- schemaVersion: 1,
- forwardArrow: { start: [0, 0, 0], end: [1, 0, 0] },
- ...chassis ? { chassisBox: { min: tuple7(chassis.min), max: tuple7(chassis.max) } } : {},
- axles,
- wheels,
- ...supportPlaneY !== undefined ? { supportPlaneY } : {},
- views
- };
-}
-function tagDiagnostic(node, role) {
- stampSemanticMetadataV1(node, { roles: [role] });
-}
-function rod(name, start, end, radius, color2, role) {
- const from = new THREE32.Vector3(...start);
- const to = new THREE32.Vector3(...end);
- const direction = to.clone().sub(from);
- const length3 = direction.length();
- const geometry2 = length3 > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length3, 8) : new THREE32.SphereGeometry(radius, 8, 6);
- const result = new THREE32.Mesh(geometry2, new THREE32.MeshBasicMaterial({ color: color2 }));
- result.name = name;
- result.position.copy(from).add(to).multiplyScalar(0.5);
- if (length3 > 0.000000001) {
- result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length3));
- }
- tagDiagnostic(result, role);
- return result;
-}
-function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagnostics(root)) {
- const overlay = new THREE32.Group;
- overlay.name = "VehicleDiagnosticOverlay";
- const chassisSpan = descriptor2.chassisBox ? Math.max(descriptor2.chassisBox.max[0] - descriptor2.chassisBox.min[0], descriptor2.chassisBox.max[1] - descriptor2.chassisBox.min[1], descriptor2.chassisBox.max[2] - descriptor2.chassisBox.min[2]) : 1;
- const thickness = Math.max(0.01, chassisSpan * 0.008);
- const arrow = new THREE32.Group;
- arrow.name = "Diagnostic_Forward_+X";
- tagDiagnostic(arrow, "diagnostic.vehicle.forward");
- arrow.add(rod("Diagnostic_Forward_Shaft", descriptor2.forwardArrow.start, [descriptor2.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));
- const arrowHead = new THREE32.Mesh(new THREE32.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE32.MeshBasicMaterial({ color: 16724804 }));
- arrowHead.name = "Diagnostic_Forward_Head";
- arrowHead.position.set(descriptor2.forwardArrow.end[0] - 0.12, 0, 0);
- arrowHead.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), new THREE32.Vector3(1, 0, 0));
- tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");
- arrow.add(arrowHead);
- overlay.add(arrow);
- for (const axle of descriptor2.axles) {
- overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));
- }
- for (const wheel of descriptor2.wheels) {
- const ring = new THREE32.Mesh(new THREE32.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE32.MeshBasicMaterial({ color: 16763955 }));
- ring.name = `Diagnostic_Wheel_${wheel.id}`;
- ring.position.set(...wheel.center);
- const axle = new THREE32.Vector3(...wheel.axle);
- if (axle.lengthSq() > 0.000000000001) {
- ring.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 0, 1), axle.normalize());
- }
- tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);
- overlay.add(ring);
- }
- if (descriptor2.chassisBox) {
- const chassis = new THREE32.Group;
- chassis.name = "Diagnostic_ChassisBox";
- tagDiagnostic(chassis, "diagnostic.vehicle.chassis");
- const { min, max } = descriptor2.chassisBox;
- const corners = [
- [min[0], min[1], min[2]],
- [max[0], min[1], min[2]],
- [max[0], max[1], min[2]],
- [min[0], max[1], min[2]],
- [min[0], min[1], max[2]],
- [max[0], min[1], max[2]],
- [max[0], max[1], max[2]],
- [min[0], max[1], max[2]]
- ];
- const edges = [
- [0, 1],
- [1, 2],
- [2, 3],
- [3, 0],
- [4, 5],
- [5, 6],
- [6, 7],
- [7, 4],
- [0, 4],
- [1, 5],
- [2, 6],
- [3, 7]
- ];
- for (const [index, edge] of edges.entries()) {
- chassis.add(rod(`Diagnostic_ChassisEdge_${index}`, corners[edge[0]], corners[edge[1]], thickness, 5635959, "diagnostic.vehicle.chassis"));
- }
- overlay.add(chassis);
- }
- if (descriptor2.supportPlaneY !== undefined) {
- const plane = new THREE32.Group;
- plane.name = "Diagnostic_SupportPlane";
- tagDiagnostic(plane, "diagnostic.vehicle.support-plane");
- const halfX = Math.max(1, ...descriptor2.chassisBox ? [Math.abs(descriptor2.chassisBox.min[0]), Math.abs(descriptor2.chassisBox.max[0])] : [], ...descriptor2.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;
- const halfZ = Math.max(0.8, ...descriptor2.chassisBox ? [Math.abs(descriptor2.chassisBox.min[2]), Math.abs(descriptor2.chassisBox.max[2])] : [], ...descriptor2.wheels.map((wheel) => Math.abs(wheel.center[2]) + wheel.width / 2)) + 0.2;
- const y = descriptor2.supportPlaneY;
- const planeLines = [
- [
- [-halfX, y, -halfZ],
- [halfX, y, -halfZ]
- ],
- [
- [halfX, y, -halfZ],
- [halfX, y, halfZ]
- ],
- [
- [halfX, y, halfZ],
- [-halfX, y, halfZ]
- ],
- [
- [-halfX, y, halfZ],
- [-halfX, y, -halfZ]
- ],
- [
- [-halfX, y, 0],
- [halfX, y, 0]
- ],
- [
- [0, y, -halfZ],
- [0, y, halfZ]
- ]
- ];
- for (const [index, [start, end]] of planeLines.entries()) {
- plane.add(rod(`Diagnostic_SupportLine_${index}`, start, end, thickness * 0.7, 6750207, "diagnostic.vehicle.support-plane"));
- }
- overlay.add(plane);
- }
- return overlay;
-}
-function compositeForCapture(root, overlay) {
- if (root.matrixAutoUpdate === false) {
- overlay.matrix.copy(root.matrix);
- overlay.matrixAutoUpdate = false;
- } else {
- overlay.position.copy(root.position);
- overlay.quaternion.copy(root.quaternion);
- overlay.scale.copy(root.scale);
- }
- return {
- name: "VehicleDiagnosticCaptureRoot",
- type: "Group",
- visible: true,
- position: { x: 0, y: 0, z: 0 },
- quaternion: { x: 0, y: 0, z: 0, w: 1 },
- scale: { x: 1, y: 1, z: 1 },
- children: [root, overlay]
- };
-}
-function selectWheelSectionRequest(requestValue, descriptor2) {
- const target = descriptor2.wheels.find((wheel) => /right.*front|front.*right/i.test(wheel.id)) ?? descriptor2.wheels.find((wheel) => /right/i.test(wheel.id)) ?? descriptor2.wheels[0];
- if (!target?.id.startsWith("wheel.assembly."))
- return requestValue;
- const suffix = target.id.replace(/[^a-zA-Z0-9.-]/g, "-");
- return {
- ...requestValue,
- id: `vehicle.wheel-section.${suffix}`,
- label: `Vehicle wheel section ${target.id}`,
- focusRolePrefixes: [target.id]
- };
-}
-function captureVehicleDiagnosticViews(root, intent, size = 256) {
- if (intent.category !== "vehicle")
- return [];
- const descriptor2 = describeVehicleDiagnostics(root);
- const overlay = createVehicleDiagnosticOverlay(root, descriptor2);
- const composite = compositeForCapture(root, overlay);
- const requests = planDiagnosticViews(intent).extra.filter((value) => value.variant === "vehicle-underbody" || value.variant === "vehicle-wheel-section");
- return requests.map((baseRequest) => {
- const requestValue = baseRequest.variant === "vehicle-wheel-section" ? selectWheelSectionRequest(baseRequest, descriptor2) : baseRequest;
- const frame = renderDiagnosticView(composite, requestValue, { size });
- return {
- id: frame.id,
- label: frame.label,
- cameraId: frame.camera.id,
- kind: requestValue.variant === "vehicle-underbody" ? "underbody" : "wheel-section",
- buffer: "semantic-overlay",
- width: frame.width,
- height: frame.height,
- png: frame.png,
- regions: frame.regions,
- descriptor: descriptor2
- };
- });
-}
-var tuple7 = (value) => [value.x, value.y, value.z];
-var init_vehicle3 = __esm(() => {
- init_contracts();
- init_vehicle();
- init_diagnostic();
-});
-
-// src/views/index.ts
-var exports_views = {};
-__export(exports_views, {
- withCameraVisibility: () => withCameraVisibility,
- validateResolvedAssetCamera: () => validateResolvedAssetCamera,
- validateAdvancedCapture: () => validateAdvancedCapture,
- stampAxisGnomon: () => stampAxisGnomon,
- snapSceneToPalette: () => snapSceneToPalette,
- selectCameraSubject: () => selectCameraSubject,
- selectArchitectureRoofNodes: () => selectArchitectureRoofNodes,
- resolveGridViews: () => resolveGridViews,
- resolveGridCapture: () => resolveGridCapture,
- resolveCaptureLimits: () => resolveCaptureLimits,
- resolveCapture: () => resolveCapture,
- resolveAssetCamera: () => resolveAssetCamera,
- renderViewGrid: () => renderViewGrid,
- renderInteriorGrid: () => renderInteriorGrid,
- renderGlbViewGrid: () => renderGlbViewGrid,
- renderGlbViewCell: () => renderGlbViewCell,
- renderDiagnosticViews: () => renderDiagnosticViews,
- renderDiagnosticView: () => renderDiagnosticView,
- renderCodeViewGrid: () => renderCodeViewGrid,
- renderClipAnimation: () => renderClipAnimation,
- renderCaptureGrid: () => renderCaptureGrid,
- rasterizeView: () => rasterizeView,
- rasterizeComposedScene: () => rasterizeComposedScene,
- rasterizeCamera: () => rasterizeCamera,
- prepareClip: () => prepareClip,
- poseSceneAtTime: () => poseSceneAtTime,
- planFrameTimes: () => planFrameTimes,
- planDiagnosticViews: () => planDiagnosticViews,
- planCharacterDiagnosticRequests: () => planCharacterDiagnosticRequests,
- orbitDir: () => orbitDir,
- orbitAnglesOf: () => orbitAnglesOf,
- measureBounds: () => measureBounds,
- loadGlbReviewScene: () => loadGlbReviewScene,
- loadGlbGeometryFlatScene: () => loadGlbGeometryFlatScene,
- listCameraSubjects: () => listCameraSubjects,
- hideNodeInScene: () => hideNodeInScene,
- hideArchitectureRoofInScene: () => hideArchitectureRoofInScene,
- hasArchitectureRoofRole: () => hasArchitectureRoofRole,
- geometryFlatTextureReasonCode: () => geometryFlatTextureReasonCode,
- findClip: () => findClip,
- encodePng: () => encodePng,
- describeVehicleDiagnostics: () => describeVehicleDiagnostics,
- describeCapture: () => describeCapture,
- decodePng: () => decodePng,
- createVehicleDiagnosticOverlay: () => createVehicleDiagnosticOverlay,
- createCachedRenderPort: () => createCachedRenderPort,
- coverage: () => coverage,
- compositeViewPngGrid: () => compositeViewPngGrid,
- compositeCellGrid: () => compositeCellGrid,
- clipNames: () => clipNames,
- captureVehicleDiagnosticViews: () => captureVehicleDiagnosticViews,
- captureCpuCell: () => captureCpuCell,
- captureCellLabel: () => captureCellLabel,
- cameraFromBounds: () => cameraFromBounds,
- buildCharacterDiagnosticDescriptor: () => buildCharacterDiagnosticDescriptor,
- annotateViewCell: () => annotateViewCell,
- ViewEvidenceHistoryStore: () => ViewEvidenceHistoryStore,
- SIX_VIEWS_REAR_QUARTER: () => SIX_VIEWS_REAR_QUARTER,
- SIX_VIEWS: () => SIX_VIEWS,
- SCENE_VIEWS: () => SCENE_VIEWS,
- MemoryCaptureCache: () => MemoryCaptureCache,
- MIN_ELEVATION_DEG: () => MIN_ELEVATION_DEG,
- MAX_ELEVATION_DEG: () => MAX_ELEVATION_DEG,
- MAX_CAPTURE_CELLS: () => MAX_CAPTURE_CELLS,
- INTERIOR_VIEWS: () => INTERIOR_VIEWS,
- GlbGeometryFlatError: () => GlbGeometryFlatError,
- GRID_COLS: () => GRID_COLS,
- GRID_BACKGROUND_RGB: () => GRID_BACKGROUND_RGB,
- GRID_BACKGROUND_HEX: () => GRID_BACKGROUND_HEX,
- GLB_GEOMETRY_FLAT_REASON: () => GLB_GEOMETRY_FLAT_REASON,
- GENERIC_DIAGNOSTIC_REQUESTS: () => GENERIC_DIAGNOSTIC_REQUESTS,
- GENERIC_DIAGNOSTIC_CAMERAS: () => GENERIC_DIAGNOSTIC_CAMERAS,
- GENERIC_DIAGNOSTIC_BUFFER_IDS: () => GENERIC_DIAGNOSTIC_BUFFER_IDS,
- DEFAULT_CAPTURE_PRESET: () => DEFAULT_CAPTURE_PRESET,
- DEFAULT_CAPTURE_LIMITS: () => DEFAULT_CAPTURE_LIMITS,
- CaptureConfigError: () => CaptureConfigError,
- CPU_RASTER_RENDERER_ID: () => CPU_RASTER_RENDERER_ID,
- CHARACTER_MOTION_DIAGNOSTIC_PHASES: () => CHARACTER_MOTION_DIAGNOSTIC_PHASES,
- CAPTURE_PRESETS: () => CAPTURE_PRESETS,
- ARCHITECTURE_ROOF_ROLE_PREFIXES: () => ARCHITECTURE_ROOF_ROLE_PREFIXES
-});
-function setLinearColor(color2, rgb2) {
- if (!color2)
- return;
- color2.r = rgb2[0];
- color2.g = rgb2[1];
- color2.b = rgb2[2];
-}
-function snapMaterialToPalette(mat, slots, idx) {
- if (!mat.color)
- return;
- if (mat.map || mat.vertexColors)
- return false;
- const emissive = mat.emissive && (mat.emissiveIntensity ?? 1) > 0 ? [
- mat.emissive.r * (mat.emissiveIntensity ?? 1),
- mat.emissive.g * (mat.emissiveIntensity ?? 1),
- mat.emissive.b * (mat.emissiveIntensity ?? 1)
- ] : undefined;
- const slotI = chooseSlot(idx, {
- baseLinear: [mat.color.r, mat.color.g, mat.color.b],
- ...emissive ? { emissiveLinear: emissive } : {},
- transparent: mat.transparent === true || mat.opacity !== undefined && mat.opacity < 0.98
- });
- if (slotI === undefined)
- return false;
- const slot = slots[slotI];
- const kind = slot.kind ?? "opaque";
- const rgb2 = hexToLinearRgb(slot.color);
- setLinearColor(mat.color, rgb2);
- if (mat.metalness !== undefined)
- mat.metalness = slot.metalness ?? 0;
- if (mat.roughness !== undefined)
- mat.roughness = slot.roughness ?? (kind === "glass" ? 0.1 : 0.85);
- if (kind === "glass") {
- mat.transparent = true;
- mat.opacity = slot.opacity ?? 0.4;
- } else {
- if (mat.transparent !== undefined)
- mat.transparent = false;
- if (mat.opacity !== undefined)
- mat.opacity = 1;
- }
- if (mat.emissive) {
- if (kind === "glow") {
- setLinearColor(mat.emissive, rgb2);
- mat.emissiveIntensity = Math.max(mat.emissiveIntensity ?? 1, 1);
- } else {
- setLinearColor(mat.emissive, [0, 0, 0]);
- if (mat.emissiveIntensity !== undefined)
- mat.emissiveIntensity = 0;
- }
- }
- return true;
-}
-function snapSceneToPalette(root, slots) {
- if (slots.length === 0)
- return { snapped: 0, skipped: 0 };
- const traverse = root?.traverse;
- if (!traverse)
- return { snapped: 0, skipped: 0 };
- const idx = buildSlotIndex(slots);
- let snapped = 0;
- let skipped = 0;
- traverse.call(root, (obj) => {
- if (!obj.isMesh || !obj.material)
- return;
- const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
- for (const mat of materials) {
- const didSnap = snapMaterialToPalette(mat, slots, idx);
- if (didSnap === true)
- snapped++;
- else if (didSnap === false)
- skipped++;
- }
- });
- return { snapped, skipped };
-}
-async function renderViewGrid(root, opts = {}) {
- if (opts.capture?.shots || opts.capture?.version)
- return renderCaptureGrid(root, opts.capture, undefined, opts.captureLimits);
- const size = opts.size ?? 384;
- const resolved2 = resolveGridCapture(opts.capture, process.env["KILN_GRID_VARIANT"]);
- const views = opts.views ?? resolved2.views;
- const cols = opts.cols ?? resolved2.cols;
- enforceCapturePixels(views.length, size, cols, opts.captureLimits);
- if (opts.snapPalette?.length)
- snapSceneToPalette(root, opts.snapPalette);
- const wantsZoom = resolved2.zooms.some((z) => z !== undefined);
- const sceneBounds = wantsZoom ? measureBounds(root) : undefined;
- const cache = opts.snapPalette?.length ? undefined : opts.captureCache;
- let reused = 0;
- const cells = [];
- for (let vi = 0;vi < views.length; vi++) {
- const zoom = resolved2.zooms[vi];
- const rasterOptions = {
- size,
- backfaceCull: opts.backfaceCull,
- ...opts.frameBounds ? { frameBounds: opts.frameBounds } : {},
- ...sceneBounds && zoom !== undefined ? { frameBounds: expandFrameBounds(sceneBounds, zoom) } : {}
- };
- let cell;
- if (cache && opts.artifactGlbSha256) {
- const { CPU_RASTER_RENDERER_ID: CPU_RASTER_RENDERER_ID2 } = await Promise.resolve().then(() => (init_renderer_id(), exports_renderer_id));
- const camera2 = cameraFromBounds(rasterOptions.frameBounds ?? measureBounds(root), views[vi].dir);
- const result = await captureCpuCell(cache, {
- artifactGlbSha256: opts.artifactGlbSha256,
- rendererId: `${CPU_RASTER_RENDERER_ID2}/legacy-fit`,
- camera: camera2,
- size,
- backfaceCull: opts.backfaceCull ?? true
- }, async () => ({
- png: encodePng(rasterizeView(root, views[vi].dir, rasterOptions), size, size),
- width: size,
- height: size,
- inputGlbSha256: opts.artifactGlbSha256,
- reasonCodes: [],
- meshCount: 0,
- instanceCount: 0
- }));
- if (result.captureCache?.hit)
- reused++;
- cell = decodePng(result.png).rgb;
- } else
- cell = rasterizeView(root, views[vi].dir, rasterOptions);
- annotateViewCell(cell, size, views[vi]);
- cells.push(cell);
- }
- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, cols);
- const png = encodePng(rgb2, width, height);
- enforceCaptureBytes([png], opts.captureLimits);
- return {
- png,
- width,
- height,
- views: views.map((v) => v.name),
- capture: { preset: resolved2.preset, cols, cells: views.length },
- ...cache && opts.artifactGlbSha256 ? { captureCache: { hit: reused === views.length, reused, total: views.length } } : {}
- };
-}
-async function hashGlbViewInput(bytes) {
- const copy = Uint8Array.from(bytes);
- const digest2 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", copy));
- return `sha256:${[...digest2].map((value) => value.toString(16).padStart(2, "0")).join("")}`;
-}
-async function renderGlbViewCell(bytes, view, options = {}) {
- const exactBytes = Uint8Array.from(bytes);
- const loaded = await loadGlbGeometryFlatScene(exactBytes);
- const size = options.size ?? 256;
- const rgb2 = options.camera ? rasterizeCamera(loaded.root, options.camera, size, options.backfaceCull) : rasterizeView(loaded.root, view.dir, {
- size,
- ...options.backfaceCull !== undefined ? { backfaceCull: options.backfaceCull } : {},
- ...options.frameBounds ? { frameBounds: options.frameBounds } : {}
- });
- return {
- png: encodePng(rgb2, size, size),
- width: size,
- height: size,
- inputGlbSha256: await hashGlbViewInput(exactBytes),
- reasonCodes: loaded.reasonCodes,
- meshCount: loaded.meshCount,
- instanceCount: loaded.instanceCount
- };
-}
-async function renderGlbViewGrid(bytes, options = {}) {
- const exactBytes = Uint8Array.from(bytes);
- const loaded = await loadGlbGeometryFlatScene(exactBytes);
- const artifactGlbSha256 = await hashGlbViewInput(exactBytes);
- const grid = await renderViewGrid(loaded.root, { ...options, artifactGlbSha256 });
- return {
- ...grid,
- inputGlbSha256: await hashGlbViewInput(exactBytes),
- reasonCodes: loaded.reasonCodes,
- meshCount: loaded.meshCount,
- instanceCount: loaded.instanceCount
- };
-}
-function expandFrameBounds(b, factor) {
- const min = [0, 0, 0];
- const max = [0, 0, 0];
- for (let a = 0;a < 3; a++) {
- const center = (b.min[a] + b.max[a]) / 2;
- const half = (b.max[a] - b.min[a]) / 2 * factor;
- min[a] = center - half;
- max[a] = center + half;
- }
- return { min, max };
-}
-async function renderCodeViewGrid(code, opts = {}) {
- const { evaluatorPort, evaluatorProfile, ...viewOptions } = opts;
- const rendered = await resolveEvaluatorPortV1(evaluatorPort, evaluatorProfile ?? "trusted-local").render(code);
- return renderGlbViewGrid(rendered.glb, viewOptions);
-}
-function resolveCamera(name) {
- const key = (name ?? "right").trim().toLowerCase().replace(/[_\s]+/g, "-");
- return ANIM_CAMERAS[key] ?? ANIM_CAMERAS[ANIM_CAMERA_ALIASES[key] ?? ""] ?? ANIM_CAMERAS["right"];
-}
-async function renderClipAnimation(root, clips, opts = {}) {
- const size = opts.size ?? 256;
- const frameCount = Math.max(2, Math.min(opts.frames ?? 6, 6));
- const cam = resolveCamera(opts.camera);
- if (!clips || clips.length === 0) {
- return {
- ok: false,
- frames: 0,
- frameTimes: [],
- error: "this asset has no animation clips",
- availableClips: []
- };
- }
- const requested = opts.clip?.trim();
- const chosen = requested ? findClip(clips, requested) : clips[0];
- if (!chosen) {
- return {
- ok: false,
- frames: 0,
- frameTimes: [],
- ...requested ? { clip: requested } : {},
- error: `clip "${requested}" not found in this asset`,
- availableClips: clipNames(clips)
- };
- }
- const prepared = prepareClip(root, chosen);
- if (opts.frameTimes && opts.frames !== undefined)
- throw new Error("frameTimes and frames are mutually exclusive");
- if (opts.shot && opts.camera)
- throw new Error("shot and camera are mutually exclusive");
- if (opts.frameTimes && (opts.frameTimes.length < 1 || opts.frameTimes.length > 9 || opts.frameTimes.some((v, i) => !Number.isFinite(v) || v < 0 || v > 1 || i > 0 && v <= opts.frameTimes[i - 1])))
- throw new Error("frameTimes must contain 1..9 strictly increasing phases in 0..1");
- const times = opts.frameTimes ? opts.frameTimes.map((t) => t * prepared.duration) : planFrameTimes(prepared.duration, frameCount);
- const frameTimes = times.map((t) => prepared.duration > 0 ? t / prepared.duration : 0);
- const min = [Infinity, Infinity, Infinity];
- const max = [-Infinity, -Infinity, -Infinity];
- for (const t of times) {
- poseSceneAtTime(root, prepared, t);
- const b = measureBounds(opts.shot?.subject ? selectCameraSubject(root, opts.shot.subject).node : root);
- for (let a = 0;a < 3; a++) {
- const lo = b.min[a];
- const hi = b.max[a];
- if (lo < min[a])
- min[a] = lo;
- if (hi > max[a])
- max[a] = hi;
- }
- }
- const frameBounds = Number.isFinite(min[0]) ? { min, max } : undefined;
- poseSceneAtTime(root, prepared, times[0]);
- const initialShot = opts.shot ? resolveAssetCamera(root, opts.shot) : undefined;
- let lockedCamera = initialShot?.camera;
- if (initialShot && opts.shot?.camera?.type !== "explicit" && frameBounds) {
- const dir = initialShot.camera.position.map((v, i) => v - initialShot.camera.target[i]);
- lockedCamera = cameraFromBounds(frameBounds, dir, opts.shot?.camera?.type === "orbit" ? opts.shot.camera.padding ?? 1.2 : 1.2, initialShot.camera.up);
- }
- const cameraShots = [];
- const labelScale = Math.max(2, Math.round(size / 80));
- const cells = [];
- const derivativeReceipts = [];
- for (let i = 0;i < times.length; i++) {
- poseSceneAtTime(root, prepared, times[i]);
- const resolvedShot = opts.shot ? resolveAssetCamera(root, opts.shot) : undefined;
- if (resolvedShot) {
- if (opts.framing !== "follow")
- resolvedShot.camera = lockedCamera;
- cameraShots.push(resolvedShot);
- }
- let cell;
- if (opts.renderDerivativeCell) {
- const produce = () => opts.renderDerivativeCell({
- root,
- ...resolvedShot ? { camera: resolvedShot.camera } : {},
- label: `${Math.round(frameTimes[i] * 100)}%`,
- view: cam,
- size,
- ...opts.backfaceCull !== undefined ? { backfaceCull: opts.backfaceCull } : {},
- ...frameBounds ? { frameBounds } : {}
- });
- const rendered = resolvedShot ? await withCameraVisibility(root, resolvedShot, produce) : await produce();
- const decoded = decodePng(rendered.png);
- if (decoded.width !== size || decoded.height !== size) {
- throw new Error(`derivative animation cell must be ${size}x${size}; got ${decoded.width}x${decoded.height}`);
- }
- cell = decoded.rgb;
- derivativeReceipts.push(rendered.receipt);
- } else {
- cell = resolvedShot ? await withCameraVisibility(root, resolvedShot, async () => rasterizeCamera(root, resolvedShot.camera, size)) : rasterizeView(root, cam.dir, {
- size,
- ...opts.backfaceCull !== undefined ? { backfaceCull: opts.backfaceCull } : {},
- ...frameBounds ? { frameBounds } : {}
- });
- }
- stampLabel(cell, size, size, labelScale, labelScale, `${Math.round(frameTimes[i] * 100)}%`, labelScale);
- cells.push(cell);
- }
- const baseMeta = {
- ok: true,
- clip: prepared.name,
- camera: cam.name,
- frames: times.length,
- frameTimes,
- ...cameraShots.length ? { cameraShots } : {},
- duration: prepared.duration,
- ...prepared.unresolved.length ? { unresolvedTracks: prepared.unresolved } : {},
- ...derivativeReceipts.length ? { derivativeReceipts } : {}
- };
- if (opts.perFrame) {
- return {
- ...baseMeta,
- width: size,
- height: size,
- pngs: cells.map((c) => encodePng(c, size, size))
- };
- }
- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size);
- return { ...baseMeta, width, height, png: encodePng(rgb2, width, height) };
-}
-function normalizeVec(v) {
- const len = Math.hypot(v[0], v[1], v[2]) || 1;
- return [v[0] / len, v[1] / len, v[2] / len];
-}
-function dotVec(a, b) {
- return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
-}
-async function renderInteriorGrid(root, opts = {}) {
- const size = opts.size ?? 256;
- const labelScale = Math.max(2, Math.round(size / 80));
- const roofsHidden = opts.nodeName ? hideNodeInScene(root, opts.nodeName) : hideArchitectureRoofInScene(root).nodes.length;
- if (opts.capture) {
- const grid = await renderCaptureGrid(root, opts.capture, opts.renderDerivativeCell);
- return { ...grid, roofsHidden, wallsHidden: 0 };
- }
- let wallsHidden = 0;
- const cells = [];
- const derivativeReceipts = [];
- for (const view of INTERIOR_VIEWS) {
- if (view.name === "Eye-level") {
- const d = normalizeVec(view.dir);
- wallsHidden = hideNodeInScene(root, (name) => {
- const lower = name.toLowerCase();
- for (const w of ROOM_WALL_NORMALS) {
- if (lower.endsWith(w.suffix) && dotVec(w.n, d) > 0.2)
- return true;
- }
- return false;
- });
- }
- let cell;
- if (opts.renderDerivativeCell) {
- const rendered = await opts.renderDerivativeCell({
- root,
- label: view.name,
- view,
- size,
- backfaceCull: false
- });
- const decoded = decodePng(rendered.png);
- if (decoded.width !== size || decoded.height !== size) {
- throw new Error(`derivative interior cell must be ${size}x${size}; got ${decoded.width}x${decoded.height}`);
- }
- cell = decoded.rgb;
- derivativeReceipts.push(rendered.receipt);
- } else {
- cell = rasterizeView(root, view.dir, { size, backfaceCull: false });
- }
- stampLabel(cell, size, size, labelScale, labelScale, view.name, labelScale);
- cells.push(cell);
- }
- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, INTERIOR_VIEWS.length);
- return {
- png: encodePng(rgb2, width, height),
- width,
- height,
- views: INTERIOR_VIEWS.map((v) => v.name),
- roofsHidden,
- wallsHidden,
- ...derivativeReceipts.length ? { derivativeReceipts } : {}
- };
-}
-var ANIM_CAMERAS, ANIM_CAMERA_ALIASES, ROOM_WALL_NORMALS, INTERIOR_VIEWS;
-var init_views = __esm(() => {
- init_capture_limits();
- init_capture_limits();
- init_capture_cache();
- init_camera();
- init_camera_capture();
- init_raster();
- init_png();
- init_png();
- init_grid();
- init_annotate();
- init_capture();
- init_pose();
- init_architecture3();
- init_glb();
- init_evaluator();
- init_raster();
- init_annotate();
- init_background();
- init_png();
- init_capture();
- init_grid();
- init_evidence_history();
- init_renderer_id();
- init_glb();
- init_architecture3();
- init_scene_raster();
- init_diagnostic();
- init_character3();
- init_vehicle3();
- init_pose();
- init_capture_cache();
- init_camera();
- init_camera_capture();
- ANIM_CAMERAS = {
- front: { name: "Front", dir: [1, 0, 0] },
- right: { name: "Right", dir: [0, 0, 1] },
- back: { name: "Back", dir: [-1, 0, 0] },
- left: { name: "Left", dir: [0, 0, -1] },
- top: { name: "Top", dir: [0, 1, 0.0001] },
- "three-quarter": { name: "3/4", dir: [0.7, 0.5, 0.7] }
- };
- ANIM_CAMERA_ALIASES = {
- "3/4": "three-quarter",
- "34": "three-quarter",
- threequarter: "three-quarter",
- quarter: "three-quarter",
- perspective: "three-quarter",
- side: "right",
- profile: "right"
- };
- ROOM_WALL_NORMALS = [
- { suffix: "wallfront", n: [1, 0, 0] },
- { suffix: "wallback", n: [-1, 0, 0] },
- { suffix: "wallleft", n: [0, 0, -1] },
- { suffix: "wallright", n: [0, 0, 1] }
- ];
- INTERIOR_VIEWS = [
- { name: "Floor plan", dir: [0, 1, 0.0001] },
- { name: "Dollhouse", dir: [0.7, 0.5, 0.7] },
- { name: "Eye-level", dir: [0.55, 0.35, 0.45] }
- ];
-});
-
-// src/views/character-capture.ts
-import * as THREE33 from "three";
-function drawLine2(rgb2, width, height, from, to, color2) {
- let x0 = Math.round(from[0]);
- let y0 = Math.round(from[1]);
- const x1 = Math.round(to[0]);
- const y1 = Math.round(to[1]);
- const dx = Math.abs(x1 - x0);
- const sx = x0 < x1 ? 1 : -1;
- const dy = -Math.abs(y1 - y0);
- const sy = y0 < y1 ? 1 : -1;
- let error = dx + dy;
- while (true) {
- if (x0 >= 0 && x0 < width && y0 >= 0 && y0 < height) {
- const offset = (y0 * width + x0) * 3;
- rgb2[offset] = color2[0];
- rgb2[offset + 1] = color2[1];
- rgb2[offset + 2] = color2[2];
- }
- if (x0 === x1 && y0 === y1)
- break;
- const doubled = 2 * error;
- if (doubled >= dy) {
- error += dy;
- x0 += sx;
- }
- if (doubled <= dx) {
- error += dx;
- y0 += sy;
- }
- }
-}
-function drawCross(rgb2, width, height, point, color2, radius = 3) {
- drawLine2(rgb2, width, height, [point[0] - radius, point[1]], [point[0] + radius, point[1]], color2);
- drawLine2(rgb2, width, height, [point[0], point[1] - radius], [point[0], point[1] + radius], color2);
-}
-function projector(root, cameraId, size) {
- root.updateMatrixWorld(true);
- const bounds = new THREE33.Box3().setFromObject(root);
- if (bounds.isEmpty())
- bounds.set(new THREE33.Vector3(-0.5, 0, -0.5), new THREE33.Vector3(0.5, 1, 0.5));
- const center = bounds.getCenter(new THREE33.Vector3);
- const camera2 = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);
- const upHint = new THREE33.Vector3(0, 1, 0);
- const xAxis = new THREE33.Vector3().crossVectors(upHint, camera2).normalize();
- const yAxis = new THREE33.Vector3().crossVectors(camera2, xAxis).normalize();
- let extent2 = 0.000001;
- for (let corner = 0;corner < 8; corner++) {
- const point = new THREE33.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);
- extent2 = Math.max(extent2, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));
- }
- const scale2 = size * 0.45 / extent2;
- return (assetPoint) => {
- const world = new THREE33.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
- return [size / 2 + world.dot(xAxis) * scale2, size / 2 - world.dot(yAxis) * scale2];
- };
-}
-function skeletonCapture(root, request2, findings, size) {
- const baseRequest = {
- id: request2.id,
- label: request2.label,
- cameraId: request2.cameraId,
- buffer: "semantic-overlay",
- scope: "category",
- variant: "character-skeleton",
- focusRolePrefixes: request2.focusRolePrefixes
- };
- const frame = renderDiagnosticView(root, baseRequest, { size });
- const descriptor2 = buildCharacterDiagnosticDescriptor(root, findings);
- const project2 = projector(root, request2.cameraId, size);
- const byRole = new Map(descriptor2.joints.map((joint) => [joint.role, joint]));
- for (const edge of descriptor2.edges) {
- const parent = byRole.get(edge.parentRole);
- const child = byRole.get(edge.childRole);
- if (!parent || !child)
- continue;
- drawLine2(frame.rgb, frame.width, frame.height, project2(parent.assetPosition), project2(child.assetPosition), edge.valid ? rgbFromHex(edge.color) : [255, 62, 72]);
- }
- for (const joint of descriptor2.joints) {
- const point = project2(joint.assetPosition);
- const color2 = rgbFromHex(joint.color);
- drawCross(frame.rgb, frame.width, frame.height, point, joint.contact ? [55, 235, 130] : color2);
- drawLine2(frame.rgb, frame.width, frame.height, point, project2(joint.forwardAxisEnd), [64, 220, 255]);
- drawLine2(frame.rgb, frame.width, frame.height, point, project2(joint.bendAxisEnd), [255, 105, 210]);
- stampLabel(frame.rgb, frame.width, frame.height, Math.max(0, Math.min(frame.width - 2, Math.round(point[0] + 3))), Math.max(0, Math.min(frame.height - 7, Math.round(point[1] - 6))), joint.label.toUpperCase().replace(/[^A-Z0-9]+/g, " ").slice(0, 18), 1);
- frame.regions.push({
- nodeName: joint.nodeName,
- nodePath: joint.nodePath,
- semanticRoles: [`joint.${joint.role}`, ...joint.contact ? ["contact.character"] : []],
- pixelBounds: [
- Math.max(0, Math.round(point[0]) - 4),
- Math.max(0, Math.round(point[1]) - 4),
- Math.min(frame.width - 1, Math.round(point[0]) + 4),
- Math.min(frame.height - 1, Math.round(point[1]) + 4)
- ],
- color: color2,
- triangleCount: 0
- });
- }
- const arrow = descriptor2.canonicalForwardArrow;
- drawLine2(frame.rgb, frame.width, frame.height, project2(arrow.start), project2(arrow.end), [255, 220, 64]);
- frame.regions.sort((a, b) => a.nodePath.localeCompare(b.nodePath));
- return {
- id: frame.id,
- label: frame.label,
- cameraId: request2.cameraId,
- kind: "skeleton",
- width: frame.width,
- height: frame.height,
- png: encodePng(frame.rgb, frame.width, frame.height),
- regions: frame.regions
- };
-}
-async function captureCharacterDiagnosticViews(root, clips, intent, findings = [], size = 256) {
- const transforms = [];
- root.traverse((node) => {
- transforms.push({
- node,
- position: node.position.clone(),
- quaternion: node.quaternion.clone(),
- scale: node.scale.clone()
- });
- });
- const requests = planCharacterDiagnosticRequests(intent);
- const captures = [];
- try {
- for (const request2 of requests) {
- if (request2.variant === "character-skeleton") {
- captures.push(skeletonCapture(root, request2, findings, size));
- continue;
- }
- if (!request2.clipName)
- continue;
- const strip = await renderClipAnimation(root, clips, {
- clip: request2.clipName,
- camera: request2.cameraId,
- frames: request2.phaseFractions?.length ?? 6,
- size
- });
- if (!strip.ok || !strip.png || !strip.width || !strip.height)
- continue;
- captures.push({
- id: request2.id,
- label: request2.label,
- cameraId: request2.cameraId,
- kind: "motion-strip",
- width: strip.width,
- height: strip.height,
- png: strip.png,
- regions: [],
- clipName: request2.clipName,
- phaseFractions: request2.phaseFractions
- });
- }
- } finally {
- for (const saved of transforms) {
- saved.node.position.copy(saved.position);
- saved.node.quaternion.copy(saved.quaternion);
- saved.node.scale.copy(saved.scale);
- }
- root.updateMatrixWorld(true);
- }
- return captures;
-}
-var rgbFromHex = (value) => {
- const parsed = Number.parseInt(value.replace(/^#/, ""), 16);
- return [parsed >>> 16 & 255, parsed >>> 8 & 255, parsed & 255];
-};
-var init_character_capture = __esm(() => {
- init_character3();
- init_diagnostic();
- init_png();
- init_views();
- init_pose();
-});
-
-// src/render.ts
-var exports_render = {};
-__export(exports_render, {
- snapGlbToPalette: () => snapGlbToPalette,
- settleContacts: () => settleContacts,
- resolveEvaluatorMode: () => resolveEvaluatorMode,
- renderSceneToGLB: () => renderSceneToGLB,
- renderGLBInProcess: () => renderGLBInProcess,
- renderGLB: () => renderGLB,
- packKitGlb: () => packKitGlb,
- optimizeGlbBytes: () => optimizeGlbBytes,
- measureGlbBounds: () => measureGlbBounds,
- inspectSceneStructure: () => inspectSceneStructure,
- inspectGlbIntegration: () => inspectGlbIntegration,
- inspectGeneratedAnimation: () => inspectGeneratedAnimation,
- gradeGlbBytes: () => gradeGlbBytes,
- executeKilnCode: () => executeKilnCode,
- composeSceneGLB: () => composeSceneGLB,
- bindBakedTextureProvenanceToFinalGlb: () => bindBakedTextureProvenanceToFinalGlb
-});
-import * as THREE34 from "three";
-import { createHash as createHash5 } from "node:crypto";
-import { Document, WebIO as WebIO3, getBounds } from "@gltf-transform/core";
-import {
- EXTMeshGPUInstancing as EXTMeshGPUInstancing3,
- KHRMaterialsVariants as KHRMaterialsVariants3,
- KHRTextureBasisu as KHRTextureBasisu3
-} from "@gltf-transform/extensions";
-import {
- dedup,
- instance,
- palette,
- flatten,
- join as join2,
- weld,
- prune,
- mergeDocuments
-} from "@gltf-transform/functions";
-async function measureGlbBounds(bytes) {
- const doc = await engineIO().readBinary(bytes);
- const root = doc.getRoot();
- const scene = root.getDefaultScene() ?? root.listScenes()[0];
- if (!scene)
- return;
- const { min, max } = getBounds(scene);
- if (!min.every(Number.isFinite) || !max.every(Number.isFinite))
- return;
- return {
- min: [min[0], min[1], min[2]],
- max: [max[0], max[1], max[2]]
- };
-}
-function ensureDefaultScene(doc) {
- const root = doc.getRoot();
- const scene = root.getDefaultScene() ?? root.listScenes()[0];
- if (scene && !root.getDefaultScene())
- root.setDefaultScene(scene);
- return scene;
-}
-async function sha256Hex2(bytes) {
- const digest2 = await globalThis.crypto.subtle.digest("SHA-256", new Uint8Array(bytes).buffer);
- return [...new Uint8Array(digest2)].map((value) => value.toString(16).padStart(2, "0")).join("");
-}
-async function inspectGlbIntegration(bytes, opts = {}) {
- const doc = await engineIO().readBinary(bytes);
- const root = doc.getRoot();
- const explicitDefault = root.getDefaultScene();
- const scene = explicitDefault ?? root.listScenes()[0];
- if (!scene)
- return;
- const { min, max } = getBounds(scene);
- const finiteBounds = min.every(Number.isFinite) && max.every(Number.isFinite);
- if (!finiteBounds)
- return;
- const metrics = collectGlbMetrics(doc);
- const validation = opts.validation ?? await validateFinalGlbBytes(bytes);
- const scenes = root.listScenes();
- const minTuple = [min[0], min[1], min[2]];
- const maxTuple = [max[0], max[1], max[2]];
- const minY = minTuple[1];
- return {
- schemaVersion: "kiln.integration-manifest.v1",
- analyzerVersion: 1,
- artifactSha256: await sha256Hex2(bytes),
- units: "m",
- axes: { forward: "+X", up: "+Y", right: "+Z" },
- bounds: {
- min: minTuple,
- max: maxTuple,
- size: [maxTuple[0] - minTuple[0], maxTuple[1] - minTuple[1], maxTuple[2] - minTuple[2]],
- center: [
- (minTuple[0] + maxTuple[0]) / 2,
- (minTuple[1] + maxTuple[1]) / 2,
- (minTuple[2] + maxTuple[2]) / 2
- ]
- },
- pivot: { convention: "author-origin", position: [0, 0, 0] },
- ground: {
- groundY: 0,
- contactTolerance: GROUND_CONTACT_TOLERANCE,
- minY,
- offsetToGround: -minY,
- grounded: Math.abs(minY) <= GROUND_CONTACT_TOLERANCE
- },
- defaultScene: { index: scenes.indexOf(scene), name: scene.getName() },
- ...opts.requestedRole ? { requestedRole: opts.requestedRole } : {},
- ...opts.assessedRole ? { assessedRole: opts.assessedRole } : {},
- renderMetrics: {
- triangles: metrics.triangles,
- drawCalls: metrics.drawCalls,
- uniqueGeometries: metrics.uniqueGeometries,
- uniqueMaterials: metrics.uniqueMaterials,
- textureCount: metrics.textureCount,
- transparentMaterials: metrics.transparentMaterials,
- skinned: metrics.skinned
- },
- structuralQa: {
- hasDefaultScene: explicitDefault !== null,
- finiteBounds,
- validatorErrors: validation.issues.numErrors,
- validatorWarnings: validation.issues.numWarnings
- },
- visualQa: "not_assessed"
- };
-}
-async function executeKilnCode(code, options = {}) {
- if (!code || typeof code !== "string") {
- throw new Error("executeKilnCode: code must be a non-empty string");
- }
- const normalized = code.replace(/\r\n/g, `
-`);
- assertGeneratedSourceSafe(normalized);
- try {
- const primitiveUsage = {};
- const globals = buildSandboxGlobals(primitiveUsage, {
- textureResolver: options.textureResolver ?? DEFAULT_TEXTURE_RESOLVER
- });
- const globalNames = Object.keys(globals);
- const globalValues = Object.values(globals);
- const fn = new Function(...globalNames, `${normalized}
-return { meta: typeof meta !== 'undefined' ? meta : {}, build, animate: typeof animate !== 'undefined' ? animate : null };`);
- const { meta, build, animate } = fn(...globalValues);
- if (typeof build !== "function") {
- throw new Error("executeKilnCode: generated code did not define `build`");
- }
- const root = await build();
- if (!root?.isObject3D) {
- throw new Error("executeKilnCode: build() did not return a THREE.Object3D");
- }
- const clips = animate ? await animate(root) ?? [] : [];
- return { meta: meta ?? {}, root, clips, primitiveUsage };
- } catch (error) {
- rethrowAuthoringError(error);
- }
-}
-function bridgeMaterial(doc, threeMat, cache, textureCache) {
- const cached = cache.get(threeMat);
- if (cached)
- return cached;
- const mat = doc.createMaterial(threeMat.name || undefined);
- const matFlags = threeMat;
- if (matFlags.isMeshStandardMaterial) {
- const stdMat = threeMat;
- mat.setBaseColorFactor([stdMat.color.r, stdMat.color.g, stdMat.color.b, stdMat.opacity]);
- mat.setRoughnessFactor(stdMat.roughness);
- mat.setMetallicFactor(stdMat.metalness);
- if (stdMat.emissive) {
- mat.setEmissiveFactor([stdMat.emissive.r, stdMat.emissive.g, stdMat.emissive.b]);
- }
- if (stdMat.alphaTest > 0) {
- mat.setAlphaMode("MASK");
- mat.setAlphaCutoff(stdMat.alphaTest);
- } else if (stdMat.transparent) {
- mat.setAlphaMode("BLEND");
- }
- if (stdMat.side === THREE34.DoubleSide) {
- mat.setDoubleSided(true);
- }
- if (stdMat.map) {
- const t = bridgeTexture(doc, stdMat.map, textureCache);
- if (t)
- mat.setBaseColorTexture(t);
- }
- if (stdMat.normalMap) {
- const t = bridgeTexture(doc, stdMat.normalMap, textureCache);
- if (t)
- mat.setNormalTexture(t);
- }
- if (stdMat.roughnessMap && stdMat.metalnessMap && stdMat.roughnessMap !== stdMat.metalnessMap) {
- throw new TypeError(`Material ${JSON.stringify(threeMat.name || "(unnamed)")} uses separate roughness/metalness textures. Pack G=roughness/B=metalness before export.`);
- }
- const mrSource = stdMat.roughnessMap ?? stdMat.metalnessMap;
- if (mrSource) {
- const t = bridgeTexture(doc, mrSource, textureCache);
- if (t)
- mat.setMetallicRoughnessTexture(t);
- }
- if (stdMat.emissiveMap) {
- const t = bridgeTexture(doc, stdMat.emissiveMap, textureCache);
- if (t)
- mat.setEmissiveTexture(t);
- }
- if (stdMat.aoMap) {
- const t = bridgeTexture(doc, stdMat.aoMap, textureCache);
- if (t)
- mat.setOcclusionTexture(t);
- mat.setOcclusionStrength(stdMat.aoMapIntensity ?? 1);
- }
- } else if (matFlags.isMeshLambertMaterial) {
- const lambMat = threeMat;
- mat.setBaseColorFactor([lambMat.color.r, lambMat.color.g, lambMat.color.b, lambMat.opacity]);
- mat.setRoughnessFactor(1);
- mat.setMetallicFactor(0);
- if (lambMat.emissive) {
- mat.setEmissiveFactor([lambMat.emissive.r, lambMat.emissive.g, lambMat.emissive.b]);
- }
- } else if (matFlags.isMeshBasicMaterial) {
- const basicMat = threeMat;
- mat.setBaseColorFactor([
- basicMat.color.r,
- basicMat.color.g,
- basicMat.color.b,
- basicMat.opacity
- ]);
- mat.setRoughnessFactor(1);
- mat.setMetallicFactor(0);
- } else if (matFlags.isSpriteMaterial) {
- const spriteMat = threeMat;
- mat.setBaseColorFactor([
- spriteMat.color.r,
- spriteMat.color.g,
- spriteMat.color.b,
- spriteMat.opacity
- ]);
- mat.setRoughnessFactor(1);
- mat.setMetallicFactor(0);
- }
- const common = threeMat;
- if ((common.alphaTest ?? 0) > 0) {
- mat.setAlphaMode("MASK");
- mat.setAlphaCutoff(common.alphaTest ?? 0.5);
- } else if (common.transparent || (common.opacity ?? 1) < 1) {
- mat.setAlphaMode("BLEND");
- }
- if (threeMat.side === THREE34.DoubleSide)
- mat.setDoubleSided(true);
- if (common.map && !mat.getBaseColorTexture()) {
- const texture = bridgeTexture(doc, common.map, textureCache);
- if (texture)
- mat.setBaseColorTexture(texture);
- }
- cache.set(threeMat, mat);
- return mat;
-}
-function bridgeTexture(doc, threeTex, cache) {
- const cached = cache.get(threeTex);
- if (cached)
- return cached;
- const encoded = threeTex.userData["encoded"];
- if (!encoded)
- return null;
- const t = doc.createTexture(threeTex.name || "texture");
- t.setMimeType(encoded.mime);
- t.setImage(encoded.bytes);
- cache.set(threeTex, t);
- return t;
-}
-function bridgeGeometry(doc, buf, geometry2, material, meshName) {
- if (!geometry2.getAttribute("normal")) {
- geometry2.computeVertexNormals();
- }
- const prim = doc.createPrimitive().setMaterial(Array.isArray(material) ? material[0] : material);
- const posAttr = geometry2.getAttribute("position");
- if (posAttr) {
- prim.setAttribute("POSITION", doc.createAccessor(meshName + "_pos").setArray(geometryAttributeValues(posAttr)).setType(TYPE_VEC3).setBuffer(buf));
- }
- const normAttr = geometry2.getAttribute("normal");
- if (normAttr) {
- prim.setAttribute("NORMAL", doc.createAccessor(meshName + "_norm").setArray(geometryAttributeValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));
- }
- const uvAttr = geometry2.getAttribute("uv");
- if (uvAttr) {
- prim.setAttribute("TEXCOORD_0", doc.createAccessor(meshName + "_uv").setArray(geometryAttributeValues(uvAttr)).setType(TYPE_VEC2).setBuffer(buf));
- }
- const tangentAttr = geometry2.getAttribute("tangent");
- if (tangentAttr?.itemSize === 4) {
- prim.setAttribute("TANGENT", doc.createAccessor(meshName + "_tangent").setArray(geometryAttributeValues(tangentAttr)).setType(TYPE_VEC4).setBuffer(buf));
- }
- const indexAttr = geometry2.getIndex();
- if (indexAttr) {
- const IndexArray = posAttr && posAttr.count > 65535 ? Uint32Array : Uint16Array;
- prim.setIndices(doc.createAccessor(meshName + "_idx").setArray(new IndexArray(indexAttr.array)).setType(TYPE_SCALAR).setBuffer(buf));
- }
- const mesh = doc.createMesh(meshName);
- if (!Array.isArray(material))
- return mesh.addPrimitive(prim);
- const indexValues = indexAttr ? Array.from(indexAttr.array) : Array.from({ length: posAttr.count }, (_, i) => i);
- const groups = [...geometry2.groups].sort((a, b) => a.start - b.start);
- let covered = 0;
- for (const group of groups) {
- if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > indexValues.length || !material[group.materialIndex ?? 0]) {
- throw new TypeError(`${meshName}: material groups must cover every triangle exactly once with valid material indices.`);
- }
- const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]);
- for (const semantic3 of prim.listSemantics())
- part.setAttribute(semantic3, prim.getAttribute(semantic3));
- const IndexArray = posAttr.count > 65535 ? Uint32Array : Uint16Array;
- part.setIndices(doc.createAccessor(meshName + "_group_indices").setArray(new IndexArray(indexValues.slice(group.start, group.start + group.count))).setType(TYPE_SCALAR).setBuffer(buf));
- mesh.addPrimitive(part);
- covered += group.count;
- }
- if (covered !== indexValues.length)
- throw new TypeError(`${meshName}: material groups do not cover every triangle.`);
- prim.dispose();
- return mesh;
-}
-function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache) {
- const gtNode = doc.createNode(threeObj.name || undefined);
- const semanticValue = threeObj.userData[KILN_SEMANTIC_EXTRAS_KEY];
- let semanticForExport = semanticValue;
- if (threeObj.isSprite) {
- if (semanticValue === undefined) {
- semanticForExport = createSemanticMetadataV1({
- roles: ["vfx.facing.camera-spherical", "vfx.effect.surface.card"]
- });
- } else {
- const existing = validateSemanticMetadataV1(semanticValue);
- if (existing.valid && existing.value) {
- semanticForExport = {
- ...cloneSemanticMetadataV1(existing.value),
- roles: [
- ...existing.value.roles.filter((role) => !role.startsWith("vfx.facing.")),
- "vfx.facing.camera-spherical",
- ...existing.value.roles.some((role) => role.startsWith("vfx.effect.surface")) ? [] : ["vfx.effect.surface.card"]
- ]
- };
- }
- }
- }
- if (semanticForExport !== undefined) {
- const semantic3 = validateSemanticMetadataV1(semanticForExport);
- if (!semantic3.valid || !semantic3.value) {
- const detail = semantic3.issues.map((issue) => `${issue.path || "<root>"}: ${issue.message}`).join("; ");
- throw new TypeError(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY} on node ${threeObj.name || "<unnamed>"}: ${detail}`);
- }
- gtNode.setExtras({
- [KILN_SEMANTIC_EXTRAS_KEY]: cloneSemanticMetadataV1(semantic3.value)
- });
- }
- gtNode.setTranslation([threeObj.position.x, threeObj.position.y, threeObj.position.z]);
- gtNode.setRotation([
- threeObj.quaternion.x,
- threeObj.quaternion.y,
- threeObj.quaternion.z,
- threeObj.quaternion.w
- ]);
- gtNode.setScale([threeObj.scale.x, threeObj.scale.y, threeObj.scale.z]);
- if (threeObj.isMesh) {
- const threeMesh = threeObj;
- const threeMats = Array.isArray(threeMesh.material) ? threeMesh.material : [threeMesh.material];
- const gtMats = threeMats.map((material) => bridgeMaterial(doc, material, matCache, texCache));
- const gtMat = Array.isArray(threeMesh.material) ? gtMats : gtMats[0];
- const cacheKey = `${threeMesh.geometry.uuid}__${threeMats.map((material) => material.uuid).join("_")}`;
- let gtMesh = meshCache.get(cacheKey);
- if (!gtMesh) {
- gtMesh = bridgeGeometry(doc, buf, threeMesh.geometry, gtMat, threeMesh.name || "mesh");
- meshCache.set(cacheKey, gtMesh);
- }
- gtNode.setMesh(gtMesh);
- } else if (threeObj.isSprite) {
- const sprite = threeObj;
- const threeMat = sprite.material;
- const gtMat = bridgeMaterial(doc, threeMat, matCache, texCache);
- const centerX = sprite.center?.x ?? 0.5;
- const centerY = sprite.center?.y ?? 0.5;
- const rotation = sprite.material.rotation ?? 0;
- const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;
- let gtMesh = meshCache.get(cacheKey);
- if (!gtMesh) {
- const geometry2 = new THREE34.PlaneGeometry(1, 1);
- if (centerX !== 0.5 || centerY !== 0.5) {
- geometry2.translate(0.5 - centerX, 0.5 - centerY, 0);
- }
- if (rotation !== 0)
- geometry2.rotateZ(rotation);
- gtMesh = bridgeGeometry(doc, buf, geometry2, gtMat, sprite.name || "sprite-quad");
- meshCache.set(cacheKey, gtMesh);
- }
- gtNode.setMesh(gtMesh);
- }
- if (threeObj.name) {
- nodeMap.set(threeObj.name, gtNode);
- }
- for (const child of threeObj.children) {
- const childNode = bridgeNode(doc, buf, child, matCache, nodeMap, meshCache, texCache);
- gtNode.addChild(childNode);
- }
- return gtNode;
-}
-function bridgeAnimations(doc, buf, clips, nodeMap, warnings) {
- for (const clip of clips) {
- const anim = doc.createAnimation(clip.name);
- for (const track of clip.tracks) {
- const dotIdx = track.name.lastIndexOf(".");
- const nodeName2 = track.name.substring(0, dotIdx);
- const property = track.name.substring(dotIdx + 1);
- const targetNode = nodeMap.get(nodeName2);
- if (!targetNode) {
- warnings.push(`Animation target "${nodeName2}" not found - skipped`);
- continue;
- }
- let targetPath;
- let valueType;
- if (property === "position") {
- targetPath = "translation";
- valueType = TYPE_VEC3;
- } else if (property === "quaternion") {
- targetPath = "rotation";
- valueType = TYPE_VEC4;
- } else if (property === "scale") {
- targetPath = "scale";
- valueType = TYPE_VEC3;
- } else {
- warnings.push(`Unsupported animation property "${property}" on "${nodeName2}" - skipped`);
- continue;
- }
- const inputAcc = doc.createAccessor(clip.name + "_" + nodeName2 + "_input").setArray(new Float32Array(track.times)).setType(TYPE_SCALAR).setBuffer(buf);
- const outputAcc = doc.createAccessor(clip.name + "_" + nodeName2 + "_output").setArray(new Float32Array(track.values)).setType(valueType).setBuffer(buf);
- const sampler = doc.createAnimationSampler().setInput(inputAcc).setOutput(outputAcc).setInterpolation("LINEAR");
- const channel = doc.createAnimationChannel().setTargetNode(targetNode).setTargetPath(targetPath).setSampler(sampler);
- anim.addSampler(sampler);
- anim.addChannel(channel);
- }
- if (anim.listChannels().length === 0)
- anim.dispose();
- }
-}
-function reviewClipExtras(clips) {
- if (clips.length > REVIEW_CLIP_LIMITS2.clips) {
- throw new Error(`Animation review clip limit exceeded (${REVIEW_CLIP_LIMITS2.clips}).`);
- }
- let trackCount = 0;
- return {
- version: 1,
- clips: clips.map((clip) => ({
- name: clip.name,
- duration: clip.duration,
- tracks: clip.tracks.map((track) => {
- trackCount++;
- if (trackCount > REVIEW_CLIP_LIMITS2.tracks) {
- throw new Error(`Animation review track limit exceeded (${REVIEW_CLIP_LIMITS2.tracks}).`);
- }
- if (track.times.length > REVIEW_CLIP_LIMITS2.samplesPerTrack || track.values.length > REVIEW_CLIP_LIMITS2.valuesPerTrack) {
- throw new Error("Animation review sample limit exceeded.");
- }
- const times = Array.from(track.times);
- const values = Array.from(track.values);
- if (!times.every(Number.isFinite) || !values.every(Number.isFinite)) {
- throw new Error("Animation review tracks must contain only finite values.");
- }
- return { name: track.name, times, values };
- })
- }))
- };
-}
-function finalTextureForSlot(material, slot) {
- switch (slot) {
- case "map":
- return material.getBaseColorTexture();
- case "normalMap":
- return material.getNormalTexture();
- case "roughnessMap":
- case "metalnessMap":
- return material.getMetallicRoughnessTexture();
- case "emissiveMap":
- return material.getEmissiveTexture();
- case "aoMap":
- return material.getOcclusionTexture();
- default:
- return null;
- }
-}
-async function bindBakedTextureProvenanceToFinalGlb(baked, finalGlb) {
- if (baked.length === 0)
- return [];
- const doc = await engineIO().readBinary(finalGlb);
- const root = doc.getRoot();
- const byMaterialName = new Map;
- for (const material of root.listMaterials()) {
- const name = material.getName() || "(unnamed material)";
- const list = byMaterialName.get(name) ?? [];
- list.push(material);
- byMaterialName.set(name, list);
- }
- const nodesByName = new Map;
- for (const node of root.listNodes()) {
- const list = nodesByName.get(node.getName()) ?? [];
- list.push(node);
- nodesByName.set(node.getName(), list);
- }
- const artifactGlbSha256 = `sha256:${await sha256Hex2(finalGlb)}`;
- return baked.flatMap((entry) => {
- const resolved2 = new Set;
- for (const binding of entry.bindings) {
- const nodeMaterials = (nodesByName.get(binding.node) ?? []).flatMap((node) => node.getMesh()?.listPrimitives().flatMap((primitive) => {
- const material = primitive.getMaterial();
- return material ? [material] : [];
- }) ?? []);
- const materials = nodeMaterials.filter((material) => (material.getName() || "(unnamed material)") === binding.material);
- const candidates = materials.length ? materials : byMaterialName.get(binding.material) ?? [];
- for (const material of candidates) {
- const texture2 = finalTextureForSlot(material, binding.slot);
- if (texture2)
- resolved2.add(texture2);
- }
- }
- if (resolved2.size === 0 && entry.texture !== "(unnamed texture)") {
- for (const texture2 of root.listTextures()) {
- if (texture2.getName() === entry.texture)
- resolved2.add(texture2);
- }
- }
- if (resolved2.size !== 1)
- return [];
- const texture = [...resolved2][0];
- const image = texture.getImage();
- const mime = texture.getMimeType();
- if (!image || !mime)
- return [];
- return [
- {
- ...entry,
- artifactGlbSha256,
- finalMime: mime,
- finalImageSha256: `sha256:${createHash5("sha256").update(image).digest("hex")}`
- }
- ];
- });
-}
-function resolveOptimize(opt) {
- if (opt)
- return opt;
- const env = process.env["KILN_BAKE_OPTIMIZE"];
- return env === "auto" || env === "palette" || env === "full" ? env : "off";
-}
-function resolveInstance(opt) {
- if (opt)
- return opt;
- const env = process.env["KILN_BAKE_INSTANCE"];
- return env === "off" || env === "auto" || env === "on" ? env : "auto";
-}
-function hasJointPivots(doc) {
- return doc.getRoot().listNodes().some((n) => /^joint[_-]/i.test(n.getName()));
-}
-async function applyGpuInstancing(doc, mode, role) {
- if (mode === "off")
- return;
- if (mode === "auto" && role !== "fill")
- return;
- const root = doc.getRoot();
- if (root.listAnimations().length > 0 || root.listSkins().length > 0)
- return;
- if (hasJointPivots(doc))
- return;
- const before = collectGlbMetrics(doc);
- await doc.transform(instance({ min: INSTANCE_MIN }));
- let batches = 0;
- let instances = 0;
- for (const node of root.listNodes()) {
- const ext = node.getExtension("EXT_mesh_gpu_instancing");
- if (!ext)
- continue;
- batches += 1;
- instances += ext.getAttribute?.("TRANSLATION")?.getCount() ?? ext.getAttribute?.("ROTATION")?.getCount() ?? ext.getAttribute?.("SCALE")?.getCount() ?? 0;
- }
- if (batches === 0)
- return;
- const after = collectGlbMetrics(doc);
- return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };
-}
-async function consolidateMaterials(doc, mode) {
- const before = collectGlbMetrics(doc);
- const root = doc.getRoot();
- const animatedOrSkinned = root.listAnimations().length > 0 || root.listSkins().length > 0;
- const semanticGraph = root.listNodes().some((node) => node.getExtras()[KILN_SEMANTIC_EXTRAS_KEY] !== undefined);
- const effective = mode === "full" && (animatedOrSkinned || semanticGraph) ? "palette" : mode;
- const steps = [palette({ min: PALETTE_MIN })];
- if (effective === "full") {
- steps.push(flatten(), join2({ keepNamed: true }));
- }
- steps.push(weld(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));
- await doc.transform(...steps);
- const after = collectGlbMetrics(doc);
- return {
- mode: effective,
- materialsBefore: before.uniqueMaterials,
- materialsAfter: after.uniqueMaterials,
- drawsBefore: before.drawCalls,
- drawsAfter: after.drawCalls
- };
-}
-async function renderSceneToGLB(root, opts = {}) {
- const clips = opts.clips ?? [];
- if (opts.geometryPolicy !== undefined && !["warn", "strict"].includes(opts.geometryPolicy))
- throw new Error("geometryPolicy must be warn or strict");
- const warnings = inspectGeometryExport(root, opts.geometryPolicy);
- const tris = countTriangles(root);
- const intent = opts.intent ?? createAssetIntentV1({
- category: isAssetCategory(opts.category) ? opts.category : "prop"
- });
- const trustedCategory = intent.category;
- const materialRecipeApplications = collectMaterialRecipeApplications(root);
- const materialResourceProvenance = collectMaterialResourceProvenance(root);
- for (const w of inspectGeneratedAnimation(root, clips))
- warnings.push(w);
- for (const w of inspectSceneStructure(root, { category: trustedCategory }))
- warnings.push(w);
- const bakedTextures = await bakeSceneTextures(root, warnings);
- ensureNormalMapTangents(root, warnings);
- let partPenetration;
- try {
- partPenetration = await analyzePartPenetration(root);
- } catch (err) {
- warnings.push(`self-intersection analysis failed: ${err instanceof Error ? err.message : String(err)}`);
- }
- const sceneQaReport = runDeterministicSceneQa({
- intent,
- scene: root,
- clips,
- ...partPenetration ? { derivedEvidence: { source: "engine-scene-analysis", partPenetration } } : {}
- }, qaPolicyFromEnv());
- const qaBlocks = qaBlockingEnabled() && opts.derivative !== true;
- const qaSuppressedBy = opts.derivative === true ? "derivative re-serialization" : "KILN_QA_MODE";
- if (sceneQaReport.disposition === "block") {
- const blocked = new AssetQaBlockedError(sceneQaReport, "scene");
- if (qaBlocks)
- throw blocked;
- warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);
- }
- const doc = new Document;
- const buf = doc.createBuffer();
- const matCache = new Map;
- const meshCache = new Map;
- const texCache = new Map;
- const nodeMap = new Map;
- const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
- const gltfScene = doc.createScene(opts.sceneName ?? "Scene").addChild(rootNode);
- doc.getRoot().setDefaultScene(gltfScene);
- if (clips.length > 0) {
- gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: reviewClipExtras(clips) });
- bridgeAnimations(doc, buf, clips, nodeMap, warnings);
- }
- if (opts.dedup !== false) {
- try {
- await doc.transform(dedup());
- } catch (err) {
- warnings.push(`dedup transform failed: ${err instanceof Error ? err.message : String(err)}`);
- }
- }
- let instancing;
- try {
- instancing = await applyGpuInstancing(doc, resolveInstance(opts.instance), opts.role);
- } catch (err) {
- warnings.push(`instance transform failed: ${err instanceof Error ? err.message : String(err)}`);
- }
- const optimizeMode = resolveOptimize(opts.optimize);
- let effectiveOptimize = optimizeMode === "auto" ? "off" : optimizeMode;
- if (optimizeMode === "auto" && collectGlbMetrics(doc, tris).uniqueMaterials >= PALETTE_MIN) {
- effectiveOptimize = "palette";
- }
- let optimize;
- if (effectiveOptimize !== "off") {
- try {
- optimize = await consolidateMaterials(doc, effectiveOptimize);
- } catch (err) {
- warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);
- }
- }
- let instanceability;
- let metricsError;
- try {
- const metrics = collectGlbMetrics(doc, optimize || instancing ? undefined : tris);
- instanceability = gradeInstanceability(metrics, { category: trustedCategory });
- } catch (err) {
- metricsError = err instanceof Error ? err.message : String(err);
- }
- let materialMetrics;
- let materialBudgetWarnings = [];
- try {
- materialMetrics = collectMaterialMetricsV1(doc);
- const tier = /(?:^|\.)hero(?:\.|$)/i.test(intent.qaProfile) ? "hero" : /(?:^|\.)background(?:\.|$)/i.test(intent.qaProfile) ? "background" : "standard";
- materialBudgetWarnings = evaluateMaterialBudgetV1(materialMetrics, {
- profile: materialBudgetProfileForQaProfile(intent.qaProfile),
- tier
- });
- } catch (error) {
- warnings.push(`material metrics failed: ${error instanceof Error ? error.message : String(error)}`);
- }
- const io = engineIO();
- ensureDefaultScene(doc);
- const bytes = await io.writeBinary(doc);
- const artifactGlbSha256 = `sha256:${await sha256Hex2(bytes)}`;
- const boundBakedTextures = bakedTextures.map((entry) => ({
- ...entry,
- artifactGlbSha256
- }));
- const gltfValidation = await validateFinalGlbBytes(bytes);
- const finalGltfReport = appendFinalGltfQa(intent, sceneQaReport, gltfValidation);
- const runtimeQaReport = appendRuntimeCostQa(intent, finalGltfReport, instanceability, metricsError);
- const materialQaReport = materialMetrics ? appendMaterialMetricsQa(intent, runtimeQaReport, materialMetrics, materialBudgetWarnings) : runtimeQaReport;
- const qaReport = await appendFinalVfxGlbQa(intent, materialQaReport, bytes);
- if (qaReport.disposition === "block") {
- const blocked = new AssetQaBlockedError(qaReport, "final-glb", gltfValidation);
- if (qaBlocks)
- throw blocked;
- warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);
- }
- for (const issue of gltfValidation.issues.messages) {
- if (issue.severity !== 1)
- continue;
- warnings.push(`glTF ${issue.code}${issue.pointer ? ` at ${issue.pointer}` : ""}: ${issue.message}`);
- }
- const integrationManifest = await inspectGlbIntegration(bytes, {
- ...opts.role ? { requestedRole: opts.role } : {},
- validation: gltfValidation
- });
- if (!integrationManifest)
- throw new Error("renderSceneToGLB: final GLB has no measurable scene");
- let diagnosticViews;
- if (intent.category === "character" && intent.character) {
- try {
- const findings = Object.values(qaReport.dimensions).flatMap((dimension) => dimension.findings);
- diagnosticViews = await captureCharacterDiagnosticViews(root, clips, intent.character, findings);
- } catch (error) {
- warnings.push(`character diagnostic capture failed: ${error instanceof Error ? error.message : String(error)}`);
- }
- } else if (intent.category === "vehicle" && intent.vehicle) {
- try {
- diagnosticViews = captureVehicleDiagnosticViews(root, intent);
- } catch (error) {
- warnings.push(`vehicle diagnostic capture failed: ${error instanceof Error ? error.message : String(error)}`);
- }
- }
- return {
- bytes,
- artifactGlbSha256,
- tris,
- warnings,
- gltfValidation,
- qaReport,
- instanceability,
- metricsError,
- ...optimize ? { optimize } : {},
- ...instancing ? { instancing } : {},
- ...diagnosticViews ? { diagnosticViews } : {},
- ...materialMetrics ? { materialMetrics } : {},
- ...materialRecipeApplications.length ? { materialRecipeApplications } : {},
- ...materialResourceProvenance.length ? { materialResourceProvenance } : {},
- ...boundBakedTextures.length ? { bakedTextures: boundBakedTextures } : {},
- integrationManifest
- };
-}
-async function renderGLBInProcess(code, opts = {}) {
- if (opts.geometryPolicy !== undefined && !["warn", "strict"].includes(opts.geometryPolicy))
- throw new Error("geometryPolicy must be warn or strict");
- const { meta, root, clips, primitiveUsage } = await executeKilnCode(code, {
- textureResolver: opts.textureResolver ?? DEFAULT_TEXTURE_RESOLVER
- });
- const requestedCategory = opts.intent?.category ?? opts.category;
- const scene = await renderSceneToGLB(root, {
- sceneName: meta.name || "Scene",
- geometryPolicy: opts.geometryPolicy,
- clips,
- ...requestedCategory ? { category: requestedCategory } : {},
- ...opts.intent ? { intent: opts.intent } : {},
- role: meta.role,
- ...opts.optimize ? { optimize: opts.optimize } : {},
- ...opts.instance ? { instance: opts.instance } : {}
- });
- const { category: modelCategory, ...modelMeta } = meta;
- return {
- glb: Buffer.from(scene.bytes),
- artifactGlbSha256: scene.artifactGlbSha256,
- tris: scene.tris,
- meta: {
- ...modelMeta,
- ...modelCategory !== undefined ? { modelCategory } : {},
- ...requestedCategory ? { category: requestedCategory } : {},
- tris: scene.tris,
- primitiveUsage,
- ...scene.instanceability ? { instanceability: scene.instanceability, tier: scene.instanceability.grade } : {},
- ...scene.metricsError ? { metricsError: scene.metricsError } : {},
- ...scene.optimize ? { optimize: scene.optimize } : {},
- ...scene.instancing ? { instancing: scene.instancing } : {},
- gltfValidation: scene.gltfValidation,
- qaReport: scene.qaReport
- },
- warnings: scene.warnings,
- ...scene.diagnosticViews ? { diagnosticViews: scene.diagnosticViews } : {},
- ...scene.materialMetrics ? { materialMetrics: scene.materialMetrics } : {},
- ...scene.materialRecipeApplications ? { materialRecipeApplications: scene.materialRecipeApplications } : {},
- ...scene.materialResourceProvenance ? { materialResourceProvenance: scene.materialResourceProvenance } : {},
- ...scene.bakedTextures ? { bakedTextures: scene.bakedTextures } : {},
- integrationManifest: scene.integrationManifest
- };
-}
-function resolveEvaluatorMode(env = process.env) {
- const value = env["KILN_EVALUATOR_MODE"];
- if (value === undefined || value === "" || value === "in-process")
- return "in-process";
- if (value === "subprocess")
- return "subprocess";
- if (value === "isolated")
- return "isolated";
- throw new Error("Invalid KILN_EVALUATOR_MODE.");
-}
-async function renderGLB(code, opts = {}) {
- const mode = resolveEvaluatorMode();
- if (mode === "in-process")
- return renderGLBInProcess(code, opts);
- if (mode === "subprocess") {
- const { renderGLBViaSubprocess: renderGLBViaSubprocess2 } = await Promise.resolve().then(() => (init_subprocess(), exports_subprocess));
- return renderGLBViaSubprocess2(code, opts);
- }
- const { renderGLBViaIsolatedEvaluator: renderGLBViaIsolatedEvaluator2 } = await Promise.resolve().then(() => (init_isolation(), exports_isolation));
- return renderGLBViaIsolatedEvaluator2(code, opts);
-}
-async function gradeGlbBytes(bytes, opts = {}) {
- try {
- const doc = await engineIO().readBinary(bytes);
- return gradeInstanceability(collectGlbMetrics(doc), opts);
- } catch {
- return;
- }
-}
-async function optimizeGlbBytes(bytes, opts = {}) {
- const requested = opts.mode ?? "palette";
- try {
- const io = engineIO();
- const doc = await io.readBinary(bytes);
- let instancing;
- if (opts.instance && opts.instance !== "off") {
- instancing = await applyGpuInstancing(doc, opts.instance, opts.role);
- }
- let summary;
- let mode;
- if (requested !== "off") {
- if (requested === "auto") {
- if (collectGlbMetrics(doc).uniqueMaterials >= PALETTE_MIN)
- mode = "palette";
- } else {
- mode = requested;
- }
- }
- if (mode)
- summary = await consolidateMaterials(doc, mode);
- if (!summary && !instancing)
- return;
- ensureDefaultScene(doc);
- const outBytes = await io.writeBinary(doc);
- const gltfValidation = await assertFinalGlbValid(outBytes);
- let report;
- try {
- report = gradeInstanceability(collectGlbMetrics(doc), { category: opts.category });
- } catch {
- report = undefined;
- }
- return {
- bytes: outBytes,
- gltfValidation,
- ...report ? { report } : {},
- ...summary ? { summary } : {},
- ...instancing ? { instancing } : {}
- };
- } catch (error) {
- if (error instanceof GltfValidationError)
- throw error;
- return;
- }
-}
-async function packKitGlb(bytes, opts = {}) {
- let doc;
- try {
- doc = await engineIO().readBinary(bytes);
- } catch {
- return;
- }
- const summary = await applyKitContract(doc, opts);
- const changed = summary.ormPacked > 0 || summary.variantsAdded.length > 0 || summary.ktx2.applied;
- if (!changed)
- return;
- ensureDefaultScene(doc);
- const outBytes = await engineIO().writeBinary(doc);
- const gltfValidation = await assertFinalGlbValid(outBytes);
- return { bytes: outBytes, summary, gltfValidation };
-}
-async function snapGlbToPalette(bytes, slots, opts = {}) {
- if (slots.length === 0)
- return;
- try {
- const io = engineIO();
- const doc = await io.readBinary(bytes);
- const before = collectGlbMetrics(doc);
- const idx = buildSlotIndex(slots);
- let snapped = 0;
- let skipped = 0;
- for (const mat of doc.getRoot().listMaterials()) {
- if (mat.getBaseColorTexture()) {
- skipped++;
- continue;
- }
- const base = mat.getBaseColorFactor();
- const emissive = mat.getEmissiveFactor();
- const transparent = mat.getAlphaMode() === "BLEND" || mat.getAlpha() < 0.98;
- const slotI = chooseSlot(idx, {
- baseLinear: [base[0], base[1], base[2]],
- emissiveLinear: [emissive[0], emissive[1], emissive[2]],
- transparent
- });
- if (slotI === undefined) {
- skipped++;
- continue;
- }
- const slot = slots[slotI];
- const kind = slot.kind ?? "opaque";
- const [lr, lg, lb] = hexToLinearRgb(slot.color);
- const alpha = kind === "glass" ? slot.opacity ?? 0.4 : 1;
- mat.setBaseColorFactor([lr, lg, lb, alpha]);
- mat.setMetallicFactor(slot.metalness ?? 0);
- mat.setRoughnessFactor(slot.roughness ?? (kind === "glass" ? 0.1 : 0.85));
- if (kind === "glass")
- mat.setAlphaMode("BLEND");
- else if (mat.getAlphaMode() === "BLEND")
- mat.setAlphaMode("OPAQUE");
- mat.setEmissiveFactor(kind === "glow" ? [lr, lg, lb] : [0, 0, 0]);
- snapped++;
- }
- await doc.transform(dedup());
- await consolidateMaterials(doc, "palette");
- const after = collectGlbMetrics(doc);
- const summary = {
- mode: "palette",
- materialsBefore: before.uniqueMaterials,
- materialsAfter: after.uniqueMaterials,
- drawsBefore: before.drawCalls,
- drawsAfter: after.drawCalls
- };
- ensureDefaultScene(doc);
- const outBytes = await io.writeBinary(doc);
- const gltfValidation = await assertFinalGlbValid(outBytes);
- let report;
- try {
- report = gradeInstanceability(after, { category: opts.category });
- } catch {
- report = undefined;
- }
- return {
- bytes: outBytes,
- ...report ? { report } : {},
- summary,
- snapped,
- skipped,
- gltfValidation
- };
- } catch (error) {
- if (error instanceof GltfValidationError)
- throw error;
- return;
- }
-}
-function eulerDegToQuat(deg) {
- const e = new THREE34.Euler(THREE34.MathUtils.degToRad(deg[0]), THREE34.MathUtils.degToRad(deg[1]), THREE34.MathUtils.degToRad(deg[2]), "XYZ");
- const q = new THREE34.Quaternion().setFromEuler(e);
- return [q.x, q.y, q.z, q.w];
-}
-async function composeSceneGLB(parts, opts = {}) {
- const warnings = [];
- const io = engineIO();
- const master = new Document;
- const masterScene = master.createScene(opts.sceneName ?? "Scene");
- master.getRoot().setDefaultScene(masterScene);
- let composed = 0;
- for (let i = 0;i < parts.length; i++) {
- const part = parts[i];
- try {
- const src = await io.readBinary(part.bytes);
- const srcScene = src.getRoot().listScenes()[0];
- const map = mergeDocuments(master, src);
- const wrap = master.createNode(part.name ?? `part_${i}`).setTranslation([part.transform.pos[0], part.transform.pos[1], part.transform.pos[2]]).setRotation(eulerDegToQuat(part.transform.rotDeg)).setScale([part.transform.scale[0], part.transform.scale[1], part.transform.scale[2]]);
- const mergedScene = srcScene ? map.get(srcScene) : undefined;
- if (mergedScene) {
- for (const child of mergedScene.listChildren())
- wrap.addChild(child);
- mergedScene.dispose();
- }
- masterScene.addChild(wrap);
- composed++;
- } catch (err) {
- warnings.push(`part ${i} (${part.name ?? ""}) skipped: ${err instanceof Error ? err.message : String(err)}`);
- }
- }
- if (composed === 0)
- throw new Error("composeSceneGLB: no parts could be merged");
- if (!opts.keepAnimations) {
- for (const anim of master.getRoot().listAnimations())
- anim.dispose();
- }
- try {
- await master.transform(dedup());
- } catch (err) {
- warnings.push(`dedup failed: ${err instanceof Error ? err.message : String(err)}`);
- }
- const optimizeMode = opts.optimize ?? "palette";
- let effectiveOptimize = optimizeMode === "auto" ? "off" : optimizeMode;
- if (optimizeMode === "auto" && collectGlbMetrics(master).uniqueMaterials >= PALETTE_MIN) {
- effectiveOptimize = "palette";
- }
- if (effectiveOptimize !== "off") {
- try {
- await consolidateMaterials(master, effectiveOptimize);
- } catch (err) {
- warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);
- }
- }
- const rootBuffers = master.getRoot().listBuffers();
- if (rootBuffers.length > 1) {
- const main = rootBuffers[0];
- for (const acc of master.getRoot().listAccessors())
- acc.setBuffer(main);
- for (let i = 1;i < rootBuffers.length; i++)
- rootBuffers[i].dispose();
- }
- const metrics = collectGlbMetrics(master);
- ensureDefaultScene(master);
- const bytes = await io.writeBinary(master);
- const gltfValidation = await assertFinalGlbValid(bytes, "scene.glb");
- for (const issue of gltfValidation.issues.messages) {
- if (issue.severity !== 1)
- continue;
- warnings.push(`glTF ${issue.code}${issue.pointer ? ` at ${issue.pointer}` : ""}: ${issue.message}`);
- }
- return {
- bytes,
- tris: metrics.triangles,
- draws: metrics.drawCalls,
- materials: metrics.uniqueMaterials,
- warnings,
- gltfValidation
- };
-}
-function inspectGeneratedAnimation(root, clips) {
- const warnings = [];
- if (clips.length === 0)
- return warnings;
- const nodeNames = new Set;
- root.traverse((obj) => {
- if (obj.name)
- nodeNames.add(obj.name);
- });
- for (const clip of clips) {
- for (const track of clip.tracks) {
- const dotIdx = track.name.lastIndexOf(".");
- if (dotIdx === -1) {
- warnings.push(`Track "${track.name}" is missing a node.property separator`);
- continue;
- }
- const nodeName2 = track.name.substring(0, dotIdx);
- const property = track.name.substring(dotIdx + 1);
- if (!nodeNames.has(nodeName2)) {
- warnings.push(`Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName2}" — rename the pivot or fix the track`);
- }
- if (!["position", "quaternion", "scale"].includes(property)) {
- warnings.push(`Animation track "${clip.name}:${track.name}" uses unsupported property "${property}"`);
- }
- }
- }
- return warnings;
-}
-function collectMeshStats(root) {
- root.updateMatrixWorld(true);
- const out = [];
- root.traverse((obj) => {
- if (!obj.isMesh)
- return;
- const meshObj = obj;
- const geo = meshObj.geometry;
- if (!geo)
- return;
- const idx = geo.getIndex();
- const tri = idx ? idx.count / 3 : (geo.getAttribute("position")?.count ?? 0) / 3;
- const box = new THREE34.Box3().setFromObject(obj);
- if (!isFinite(box.min.x) || !isFinite(box.max.x)) {
- return;
- }
- const center = new THREE34.Vector3;
- const size = new THREE34.Vector3;
- box.getCenter(center);
- box.getSize(size);
- out.push({
- name: obj.name || "(unnamed)",
- triCount: Math.floor(tri),
- isPlaneGeo: geo.type === "PlaneGeometry",
- center,
- size,
- box
- });
- });
- return out;
-}
-function minimalGapVector(a, b) {
- const v = new THREE34.Vector3;
- for (const axis of ["x", "y", "z"]) {
- if (a.min[axis] > b.max[axis])
- v[axis] = b.max[axis] - a.min[axis];
- else if (a.max[axis] < b.min[axis])
- v[axis] = b.min[axis] - a.max[axis];
- else
- v[axis] = 0;
- }
- return v;
-}
-function inspectSceneStructure(root, opts = {}) {
- const warnings = [];
- const meshes = collectMeshStats(root);
- if (meshes.length === 0)
- return warnings;
- const cat = opts.category?.toLowerCase();
- if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {
- const all = new THREE34.Box3;
- for (const m of meshes)
- all.union(m.box);
- const size = new THREE34.Vector3;
- all.getSize(size);
- if (cat === "aircraft") {
- if (size.y > size.x * 1.2) {
- warnings.push(`Orientation: this aircraft is ${size.y.toFixed(2)} tall but only ${size.x.toFixed(2)} long along +X (the nose axis). Kiln aircraft fly nose-first along +X — it may be built vertically or sideways.`);
- }
- } else if (size.z > size.x * 1.3) {
- warnings.push(`Orientation: this ${cat} spans ${size.z.toFixed(2)} along Z but only ${size.x.toFixed(2)} along +X. Kiln ${cat}s face +X (forward/muzzle/bow) — it looks built sideways; rebuild the long axis along X.`);
- }
- }
- const STRAY_CENTROID_TOL = 0.02;
- const FLOATING_EXPAND = 0.02;
- const DECAL_EXTENT_MAX = 0.5;
- for (const m of meshes) {
- if (!m.isPlaneGeo)
- continue;
- if (m.triCount > 2)
- continue;
- if (m.size.length() > DECAL_EXTENT_MAX)
- continue;
- if (m.center.length() < STRAY_CENTROID_TOL) {
- warnings.push(`Stray plane "${m.name}" at world origin (centroid ≈ [0,0,0]). Replace planeGeo with decalBox and position on a host surface, or move this mesh into place.`);
- }
- }
- if (meshes.length > 1) {
- const floaters = [];
- for (let i = 0;i < meshes.length; i++) {
- const a = meshes[i];
- const ax = a.box.clone().expandByScalar(FLOATING_EXPAND);
- let overlapsAny = false;
- for (let j = 0;j < meshes.length; j++) {
- if (i === j)
- continue;
- const b = meshes[j];
- if (ax.intersectsBox(b.box)) {
- overlapsAny = true;
- break;
- }
- }
- if (overlapsAny)
- continue;
- let nearest;
- let nearestGap;
- for (let j = 0;j < meshes.length; j++) {
- if (i === j)
- continue;
- const gap = minimalGapVector(a.box, meshes[j].box);
- if (!nearestGap || gap.length() < nearestGap.length()) {
- nearest = meshes[j];
- nearestGap = gap;
- }
- }
- const fix = nearest && nearestGap ? ` Fix: shift "${a.name}" by [${nearestGap.x.toFixed(3)}, ${nearestGap.y.toFixed(3)}, ${nearestGap.z.toFixed(3)}] toward "${nearest.name}", or call snapTo(part, hostPart) to do it automatically.` : "";
- floaters.push(`${a.name}${fix ? " —" + fix : ""}`);
- }
- if (floaters.length > 0) {
- warnings.push(`Floating parts (no mesh overlap with any sibling, 2cm tol): ${floaters.join(" | ")}`);
- }
- }
- return warnings;
-}
-function settleContacts(root, opts = {}) {
- const maxGap = opts.maxGap ?? 0.05;
- const overlap = opts.overlap ?? 0.01;
- const settled = [];
- for (let pass = 0;pass < 8; pass++) {
- const meshes = collectMeshStats(root);
- if (meshes.length < 2)
- return settled;
- let pick;
- for (let i = 0;i < meshes.length; i++) {
- const a = meshes[i];
- const ax = a.box.clone().expandByScalar(0.02);
- if (meshes.some((b, j) => j !== i && ax.intersectsBox(b.box)))
- continue;
- let nearestGap;
- for (let j = 0;j < meshes.length; j++) {
- if (i === j)
- continue;
- const gap = minimalGapVector(a.box, meshes[j].box);
- if (!nearestGap || gap.length() < nearestGap.length())
- nearestGap = gap;
- }
- if (!nearestGap || nearestGap.length() === 0 || nearestGap.length() > maxGap)
- continue;
- const volume = a.size.x * a.size.y * a.size.z;
- if (!pick || volume < pick.volume)
- pick = { stats: a, gap: nearestGap, volume };
- }
- if (!pick)
- break;
- const delta = pick.gap.clone();
- const dominant = ["x", "y", "z"].reduce((d, axis) => Math.abs(delta[axis]) > Math.abs(delta[d]) ? axis : d, "x");
- delta[dominant] += Math.sign(delta[dominant]) * overlap;
- let target;
- root.traverse((obj) => {
- if (!target && obj.name === pick.stats.name && obj.isMesh)
- target = obj;
- });
- if (!target)
- break;
- const parent = target.parent ?? root;
- const p0 = new THREE34.Vector3;
- target.getWorldPosition(p0);
- const p1 = p0.clone().add(delta);
- const l0 = parent.worldToLocal(p0.clone());
- const l1 = parent.worldToLocal(p1.clone());
- target.position.add(l1.sub(l0));
- target.updateMatrixWorld(true);
- settled.push(pick.stats.name);
- }
- return settled;
-}
-var engineIO = () => new WebIO3().registerExtensions([EXTMeshGPUInstancing3, KHRMaterialsVariants3, KHRTextureBasisu3]), TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5;
-var init_render = __esm(() => {
- init_authoring_diagnostic();
- init_geometry_export();
- init_primitives();
- init_contracts();
- init_gltf();
- init_run();
- init_breadth_final();
- init_material_metrics();
- init_material_recipe_runtime();
- init_material_resources();
- init_texture_resolver();
- init_validation();
- init_self_intersection();
- init_kit();
- init_texture_bake();
- init_character_capture();
- init_vehicle3();
- REVIEW_CLIP_LIMITS2 = {
- clips: 32,
- tracks: 256,
- samplesPerTrack: 4096,
- valuesPerTrack: 16384
- };
-});
-
-// src/evaluator/protocol.ts
-var exports_protocol = {};
-__export(exports_protocol, {
- trustedInProcessEvaluatorPortV1: () => trustedInProcessEvaluatorPortV1,
- resolveEvaluatorPortV1: () => resolveEvaluatorPortV1,
- evaluatorOutcomeMessage: () => evaluatorOutcomeMessage,
- encodeRenderResultV1: () => encodeRenderResultV1,
- decodeEvaluatorResultV1: () => decodeEvaluatorResultV1,
- decodeEvaluatorRequestV1: () => decodeEvaluatorRequestV1,
- createEvaluatorRequestV1: () => createEvaluatorRequestV1,
- createEvaluatorPortV1: () => createEvaluatorPortV1,
- MAX_EVALUATOR_REQUEST_BYTES: () => MAX_EVALUATOR_REQUEST_BYTES,
- MAX_EVALUATOR_CODE_BYTES: () => MAX_EVALUATOR_CODE_BYTES,
- EvaluatorPortError: () => EvaluatorPortError,
- EVALUATOR_RESULT_VERSION: () => EVALUATOR_RESULT_VERSION,
- EVALUATOR_REQUEST_VERSION: () => EVALUATOR_REQUEST_VERSION,
- DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES: () => DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES,
- DEFAULT_EVALUATOR_MAX_GLB_BYTES: () => DEFAULT_EVALUATOR_MAX_GLB_BYTES,
- DEFAULT_EVALUATOR_DEADLINE_MS: () => DEFAULT_EVALUATOR_DEADLINE_MS
-});
-import { createHash as createHash6 } from "node:crypto";
-function evaluatorOutcomeMessage(code) {
- return EVALUATOR_OUTCOME_MESSAGES[code];
-}
-function resolveEvaluatorPortV1(port, profile) {
- if (port)
- return port;
- if (profile === "evaluator-required") {
- throw new EvaluatorPortError("ISOLATION_UNAVAILABLE", "Evaluator port is required.");
- }
- return trustedInProcessEvaluatorPortV1;
-}
-function isRecord6(value) {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-function hasExactKeys(value, allowed) {
- return Object.keys(value).every((key) => allowed.includes(key));
-}
-function fail(kind) {
- throw new Error(`invalid evaluator ${kind}`);
-}
-function validRequestId(value) {
- return typeof value === "string" && /^[A-Za-z0-9._-]{1,64}$/.test(value);
-}
-function validInteger(value, min, max) {
- return Number.isInteger(value) && Number(value) >= min && Number(value) <= max;
-}
-function validQaReport(value) {
- const dimensions2 = isRecord6(value) && isRecord6(value.dimensions) ? value.dimensions : undefined;
- if (!isRecord6(value) || !hasExactKeys(value, ["schemaVersion", "category", "qaProfile", "disposition", "dimensions"]) || value.schemaVersion !== 1 || !isAssetCategory(value.category) || typeof value.qaProfile !== "string" || value.qaProfile.length < 1 || value.qaProfile.length > 128 || !["pass", "warn", "block", "notEvaluated", "legacy-unassessed"].includes(String(value.disposition)) || !dimensions2 || !hasExactKeys(dimensions2, QA_DIMENSIONS) || !QA_DIMENSIONS.every((dimension) => (dimension in dimensions2))) {
- return false;
- }
- return QA_DIMENSIONS.every((dimension) => {
- const result = dimensions2[dimension];
- return isRecord6(result) && hasExactKeys(result, ["status", "findings", "metrics"]) && ["pass", "warn", "block", "notEvaluated"].includes(String(result.status)) && Array.isArray(result.findings) && result.findings.length <= 1000 && result.findings.every(isQaFinding) && (result.metrics === undefined || isRecord6(result.metrics));
- });
-}
-function validGltfValidation(value) {
- const issues = isRecord6(value) && isRecord6(value.issues) ? value.issues : undefined;
- if (!issues || !Array.isArray(issues.messages)) {
- return false;
- }
- return ["numErrors", "numWarnings", "numInfos", "numHints"].every((key) => validInteger(issues[key], 0, Number.MAX_SAFE_INTEGER)) && issues.messages.length <= 1000 && issues.messages.every((issue) => isRecord6(issue) && typeof issue.code === "string" && typeof issue.message === "string" && typeof issue.severity === "number" && Number.isFinite(issue.severity));
-}
-function boundedControl(value, fallback, max) {
- const resolved2 = value ?? fallback;
- if (!validInteger(resolved2, 1, max)) {
- throw new EvaluatorPortError("INPUT_INVALID");
- }
- return resolved2;
-}
-function createEvaluatorRequestV1(input) {
- if (input.options?.textureResolver) {
- throw new EvaluatorPortError("INPUT_INVALID", "Evaluator requests do not accept a host resolver capability.");
- }
- const maxGlbBytes = boundedControl(input.maxGlbBytes, DEFAULT_EVALUATOR_MAX_GLB_BYTES, 64 * 1024 * 1024);
- const { textureResolver: _, ...options } = input.options ?? {};
- const request2 = {
- version: EVALUATOR_REQUEST_VERSION,
- requestId: input.requestId,
- operation: "execute-export-glb",
- code: input.code,
- options,
- limits: { maxGlbBytes }
- };
- const json = JSON.stringify(request2);
- const decoded = decodeEvaluatorRequestV1(json);
- return { request: decoded, json };
-}
-function parseOptions(value) {
- if (!isRecord6(value) || !hasExactKeys(value, ["optimize", "instance", "intent", "category", "geometryPolicy"])) {
- return fail("request");
- }
- const options = {};
- if (value.geometryPolicy !== undefined) {
- if (!["warn", "strict"].includes(String(value.geometryPolicy)))
- fail("request");
- options.geometryPolicy = value.geometryPolicy;
- }
- if (value.optimize !== undefined) {
- if (!["off", "auto", "palette", "full"].includes(String(value.optimize)))
- fail("request");
- options.optimize = value.optimize;
- }
- if (value.instance !== undefined) {
- if (!["off", "auto", "on"].includes(String(value.instance)))
- fail("request");
- options.instance = value.instance;
- }
- if (value.category !== undefined) {
- if (!isAssetCategory(value.category))
- fail("request");
- options.category = value.category;
- }
- if (value.intent !== undefined) {
- const result = validateAssetIntentV1(value.intent);
- if (!result.valid)
- fail("request");
- options.intent = result.value;
- }
- return options;
-}
-function decodeEvaluatorRequestV1(json) {
- if (Buffer.byteLength(json, "utf8") > MAX_EVALUATOR_REQUEST_BYTES)
- fail("request");
- let value;
- try {
- value = JSON.parse(json);
- } catch {
- return fail("request");
- }
- if (!isRecord6(value) || !hasExactKeys(value, ["version", "requestId", "operation", "code", "options", "limits"]) || value.version !== EVALUATOR_REQUEST_VERSION || !validRequestId(value.requestId) || value.operation !== "execute-export-glb" || typeof value.code !== "string" || Buffer.byteLength(value.code, "utf8") > MAX_EVALUATOR_CODE_BYTES || !isRecord6(value.limits) || !hasExactKeys(value.limits, ["maxGlbBytes"]) || !validInteger(value.limits.maxGlbBytes, 1, 64 * 1024 * 1024)) {
- return fail("request");
- }
- return {
- version: EVALUATOR_REQUEST_VERSION,
- requestId: value.requestId,
- operation: "execute-export-glb",
- code: value.code,
- options: parseOptions(value.options),
- limits: { maxGlbBytes: value.limits.maxGlbBytes }
- };
-}
-function encodeRenderResultV1(requestId, render) {
- const { glb, diagnosticViews, buildCache: _hostCacheReceipt, ...rest } = render;
- return {
- version: EVALUATOR_RESULT_VERSION,
- requestId,
- ok: true,
- render: {
- ...rest,
- glbBase64: glb.toString("base64"),
- ...diagnosticViews ? {
- diagnosticViews: diagnosticViews.map(({ png, ...view }) => ({
- ...view,
- pngBase64: Buffer.from(png).toString("base64")
- }))
- } : {}
- }
- };
-}
-function isSha256(value) {
- return typeof value === "string" && /^sha256:[a-f0-9]{64}$/.test(value);
-}
-function decodeEvaluatorResultV1(json, maxGlbBytes, expectedRequestId) {
- let value;
- try {
- value = JSON.parse(json);
- } catch {
- return fail("result");
- }
- if (!isRecord6(value) || !hasExactKeys(value, ["version", "requestId", "ok", "render", "error"]) || value.version !== EVALUATOR_RESULT_VERSION || !validRequestId(value.requestId) || typeof value.ok !== "boolean") {
- return fail("result");
- }
- if (expectedRequestId !== undefined && value.requestId !== expectedRequestId)
- fail("result");
- if (!value.ok) {
- if (value.render !== undefined)
- return fail("result");
- if (!isRecord6(value.error) || !hasExactKeys(value.error, ["code", "message", "qa", "diagnostic"])) {
- return fail("result");
- }
- const codes = [
- "INPUT_INVALID",
- "EXECUTION_REJECTED",
- "QA_BLOCKED",
- "DEADLINE_EXCEEDED",
- "CANCELLED",
- "OUTPUT_LIMIT_EXCEEDED",
- "ISOLATION_UNAVAILABLE",
- "WORKER_FAILED",
- "PROTOCOL_ERROR"
- ];
- if (!codes.includes(value.error.code) || typeof value.error.message !== "string" || value.error.message !== evaluatorOutcomeMessage(value.error.code)) {
- return fail("result");
- }
- if (value.error.diagnostic !== undefined && (value.error.code !== "EXECUTION_REJECTED" || value.error.diagnostic !== "UNBOUND_VARIABLE" && value.error.diagnostic !== "GEAR_RADII_ORDER" && value.error.diagnostic !== "ROUNDED_BOX_RADIUS"))
- return fail("result");
- if (value.error.qa !== undefined) {
- if (value.error.code !== "QA_BLOCKED" || !isRecord6(value.error.qa) || !hasExactKeys(value.error.qa, ["report", "stage", "gltfValidation"]) || !validQaReport(value.error.qa.report) || !["scene", "final-glb"].includes(String(value.error.qa.stage)) || value.error.qa.gltfValidation !== undefined && !validGltfValidation(value.error.qa.gltfValidation)) {
- return fail("result");
- }
- } else if (value.error.code === "QA_BLOCKED") {
- return fail("result");
- }
- return value;
- }
- if (value.error !== undefined || !isRecord6(value.render))
- fail("result");
- const renderKeys = [
- "glbBase64",
- "artifactGlbSha256",
- "tris",
- "meta",
- "warnings",
- "diagnosticViews",
- "materialMetrics",
- "materialRecipeApplications",
- "materialResourceProvenance",
- "bakedTextures",
- "integrationManifest"
- ];
- if (!hasExactKeys(value.render, renderKeys) || typeof value.render.glbBase64 !== "string" || !validInteger(value.render.tris, 0, Number.MAX_SAFE_INTEGER) || !isRecord6(value.render.meta) || !Array.isArray(value.render.warnings) || !value.render.warnings.every((warning) => typeof warning === "string") || !isRecord6(value.render.integrationManifest)) {
- fail("result");
- }
- const glb = Buffer.from(value.render.glbBase64, "base64");
- if (glb.byteLength > maxGlbBytes || glb.toString("base64") !== value.render.glbBase64)
- fail("result");
- if (!isSha256(value.render.artifactGlbSha256))
- fail("result");
- const actualHash = `sha256:${createHash6("sha256").update(glb).digest("hex")}`;
- if (actualHash !== value.render.artifactGlbSha256)
- fail("result");
- const diagnosticViews = value.render.diagnosticViews;
- if (diagnosticViews !== undefined && !Array.isArray(diagnosticViews))
- fail("result");
- const decodedViews = diagnosticViews?.map((candidate) => {
- if (!isRecord6(candidate) || typeof candidate.pngBase64 !== "string")
- return fail("result");
- const png = Buffer.from(candidate.pngBase64, "base64");
- if (png.toString("base64") !== candidate.pngBase64)
- return fail("result");
- const { pngBase64: _2, ...view } = candidate;
- return { ...view, png };
- });
- const { glbBase64: _, diagnosticViews: __, ...rest } = value.render;
- return {
- version: EVALUATOR_RESULT_VERSION,
- requestId: value.requestId,
- ok: true,
- render: {
- ...rest,
- glb,
- ...decodedViews ? { diagnosticViews: decodedViews } : {}
- }
- };
-}
-function createEvaluatorPortV1(transport, defaults2 = {}) {
- let sequence = 0;
- return {
- async render(code, options = {}, controls = {}) {
- const signal = controls.signal ?? defaults2.signal;
- if (signal?.aborted)
- throw new EvaluatorPortError("CANCELLED");
- const deadlineMs = boundedControl(controls.deadlineMs ?? defaults2.deadlineMs, DEFAULT_EVALUATOR_DEADLINE_MS, 120000);
- const maxGlbBytes = boundedControl(controls.maxGlbBytes ?? defaults2.maxGlbBytes, DEFAULT_EVALUATOR_MAX_GLB_BYTES, 64 * 1024 * 1024);
- const maxResponseBytes = boundedControl(controls.maxResponseBytes ?? defaults2.maxResponseBytes, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, 96 * 1024 * 1024);
- const requestId = `eval-${++sequence}`;
- const built = createEvaluatorRequestV1({ requestId, code, options, maxGlbBytes });
- let timer;
- let response;
- const transportController = new AbortController;
- let abort;
- try {
- const cancelled = new Promise((_, reject) => {
- abort = () => {
- reject(new EvaluatorPortError("CANCELLED"));
- transportController.abort();
- };
- signal?.addEventListener("abort", abort, { once: true });
- });
- response = await Promise.race([
- transport(built.json, {
- deadlineMs,
- maxResponseBytes,
- signal: transportController.signal
- }),
- cancelled,
- new Promise((_, reject) => {
- timer = setTimeout(() => {
- reject(new EvaluatorPortError("DEADLINE_EXCEEDED"));
- transportController.abort();
- }, deadlineMs);
- })
- ]);
- } catch (error) {
- if (error instanceof EvaluatorPortError)
- throw error;
- throw new EvaluatorPortError("WORKER_FAILED");
- } finally {
- clearTimeout(timer);
- if (abort)
- signal?.removeEventListener("abort", abort);
- }
- if (signal?.aborted)
- throw new EvaluatorPortError("CANCELLED");
- if (typeof response !== "string")
- throw new EvaluatorPortError("PROTOCOL_ERROR");
- if (Buffer.byteLength(response, "utf8") > maxResponseBytes) {
- throw new EvaluatorPortError("OUTPUT_LIMIT_EXCEEDED");
- }
- let result;
- try {
- result = decodeEvaluatorResultV1(response, maxGlbBytes, requestId);
- } catch {
- throw new EvaluatorPortError("PROTOCOL_ERROR");
- }
- if (!result.ok) {
- if (result.error.code === "QA_BLOCKED" && result.error.qa) {
- const { AssetQaBlockedError: AssetQaBlockedError2 } = await Promise.resolve().then(() => (init_run(), exports_run));
- throw new AssetQaBlockedError2(result.error.qa.report, result.error.qa.stage, result.error.qa.gltfValidation);
- }
- throw new EvaluatorPortError(result.error.code, undefined, result.error.diagnostic);
- }
- return result.render;
- }
- };
-}
-var EVALUATOR_REQUEST_VERSION = "kiln.evaluator.request.v1", EVALUATOR_RESULT_VERSION = "kiln.evaluator.result.v1", MAX_EVALUATOR_CODE_BYTES, MAX_EVALUATOR_REQUEST_BYTES, DEFAULT_EVALUATOR_DEADLINE_MS = 60000, DEFAULT_EVALUATOR_MAX_GLB_BYTES, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, EVALUATOR_OUTCOME_MESSAGES, EvaluatorPortError, trustedInProcessEvaluatorPortV1;
-var init_protocol = __esm(() => {
- init_authoring_diagnostic();
- init_contracts();
- init_types();
- MAX_EVALUATOR_CODE_BYTES = 512 * 1024;
- MAX_EVALUATOR_REQUEST_BYTES = 1024 * 1024;
- DEFAULT_EVALUATOR_MAX_GLB_BYTES = 16 * 1024 * 1024;
- DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
- EVALUATOR_OUTCOME_MESSAGES = {
- INPUT_INVALID: "Evaluator request was invalid.",
- EXECUTION_REJECTED: "Generated asset execution was rejected.",
- QA_BLOCKED: "Generated asset did not pass quality checks.",
- DEADLINE_EXCEEDED: "Evaluator deadline exceeded.",
- CANCELLED: "Evaluator request was cancelled.",
- OUTPUT_LIMIT_EXCEEDED: "Evaluator output limit exceeded.",
- ISOLATION_UNAVAILABLE: "Isolated evaluator is unavailable.",
- WORKER_FAILED: "Evaluator worker failed.",
- PROTOCOL_ERROR: "Evaluator returned invalid data."
- };
- EvaluatorPortError = class EvaluatorPortError extends Error {
- code;
- diagnostic;
- constructor(code, message = evaluatorOutcomeMessage(code), diagnostic) {
- super(diagnostic ? `${message} ${authoringDiagnosticAdvice(diagnostic)}` : message);
- this.code = code;
- this.diagnostic = diagnostic;
- this.name = "EvaluatorPortError";
- }
- };
- trustedInProcessEvaluatorPortV1 = {
- async render(code, options = {}, controls = {}) {
- if (controls.signal?.aborted)
- throw new EvaluatorPortError("CANCELLED");
- const { renderGLBInProcess: renderGLBInProcess2 } = await Promise.resolve().then(() => (init_render(), exports_render));
- const result = await renderGLBInProcess2(code, options);
- if (controls.signal?.aborted)
- throw new EvaluatorPortError("CANCELLED");
- return result;
- }
- };
-});
-
-// src/evaluator/subprocess.ts
-var exports_subprocess = {};
-__export(exports_subprocess, {
- sanitizedEvaluatorEnv: () => sanitizedEvaluatorEnv,
- renderGLBViaSubprocess: () => renderGLBViaSubprocess,
- renderGLBViaProcessLaunch: () => renderGLBViaProcessLaunch,
- EvaluatorSubprocessError: () => EvaluatorSubprocessError
-});
-import { spawn as spawn2 } from "node:child_process";
-import { fileURLToPath as fileURLToPath2 } from "node:url";
-function sanitizedEvaluatorEnv(source = process.env) {
- const env = { NODE_ENV: "production", NO_COLOR: "1" };
- for (const key of ["PATH", "Path", "SystemRoot", "SYSTEMROOT", "TEMP", "TMP", "TZ"]) {
- if (source[key] !== undefined)
- env[key] = source[key];
- }
- return env;
-}
-function boundedInteger(value, fallback, max) {
- const resolved2 = value ?? fallback;
- if (!Number.isInteger(resolved2) || resolved2 < 1 || resolved2 > max) {
- throw new EvaluatorSubprocessError("INPUT_INVALID", "Evaluator controls are invalid.");
- }
- return resolved2;
-}
-function terminateProcess(child, detached) {
- if (!child.pid || child.killed)
- return;
- try {
- if (detached && process.platform !== "win32")
- process.kill(-child.pid, "SIGKILL");
- else
- child.kill("SIGKILL");
- } catch (error) {
- if (error.code !== "ESRCH")
- throw error;
- }
-}
-async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, launch) {
- if (controls.signal?.aborted) {
- throw new EvaluatorSubprocessError("CANCELLED", "Evaluator request was cancelled.");
- }
- if (options.textureResolver) {
- throw new EvaluatorSubprocessError("INPUT_INVALID", "Subprocess evaluation does not accept host resolver capabilities.");
- }
- const deadlineMs = boundedInteger(controls.deadlineMs, DEFAULT_DEADLINE_MS, 120000);
- const maxGlbBytes = boundedInteger(controls.maxGlbBytes, DEFAULT_MAX_GLB_BYTES, 64 * 1024 * 1024);
- const maxResponseBytes = boundedInteger(controls.maxResponseBytes, DEFAULT_MAX_RESPONSE_BYTES, 96 * 1024 * 1024);
- const request2 = {
- version: EVALUATOR_REQUEST_VERSION,
- requestId: "render-1",
- operation: "execute-export-glb",
- code,
- options,
- limits: { maxGlbBytes }
- };
- const requestJson = JSON.stringify(request2);
- if (Buffer.byteLength(requestJson, "utf8") > MAX_EVALUATOR_REQUEST_BYTES) {
- throw new EvaluatorSubprocessError("INPUT_INVALID", "Evaluator request exceeds its size limit.");
- }
- const sourceModule = import.meta.url.endsWith(".ts");
- const workerPath = fileURLToPath2(new URL(process.versions.bun && sourceModule ? "./worker.ts" : sourceModule ? "../../dist/evaluator-worker.mjs" : "./evaluator-worker.mjs", import.meta.url));
- const maxHeapMb = boundedInteger(controls.maxHeapMb, 512, 4096);
- if (maxHeapMb < 64 || process.versions.bun && controls.maxHeapMb !== undefined) {
- throw new EvaluatorSubprocessError("INPUT_INVALID", "Heap limits require a Node worker and 64–4096 MiB.");
- }
- const defaultLaunch = {
- command: process.execPath,
- args: process.versions.bun ? [workerPath] : [`--max-old-space-size=${maxHeapMb}`, workerPath],
- env: sanitizedEvaluatorEnv()
- };
- const resolvedLaunch = launch ?? defaultLaunch;
- const detached = resolvedLaunch.detached === true;
- return await new Promise((resolve, reject) => {
- const spawnOptions = {
- env: resolvedLaunch.env,
- windowsHide: true,
- stdio: ["pipe", "ignore", "pipe", "pipe"],
- ...detached ? { detached: true } : {}
- };
- const child = spawn2(resolvedLaunch.command, resolvedLaunch.args, spawnOptions);
- const protocol = child.stdio[3];
- if (!protocol) {
- terminateProcess(child, detached);
- reject(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker did not start."));
- return;
- }
- const chunks = [];
- let responseBytes = 0;
- let stderrBytes = 0;
- let settled = false;
- const finish = (error, result) => {
- if (settled)
- return;
- settled = true;
- clearTimeout(timer);
- controls.signal?.removeEventListener("abort", abort);
- if (error)
- reject(error);
- else
- resolve(result);
- };
- const timer = setTimeout(() => {
- finish(new EvaluatorSubprocessError("DEADLINE_EXCEEDED", "Evaluator deadline exceeded."));
- terminateProcess(child, detached);
- }, deadlineMs);
- const abort = () => {
- finish(new EvaluatorSubprocessError("CANCELLED", "Evaluator request was cancelled."));
- terminateProcess(child, detached);
- };
- const pipeFailed = (error) => {
- if (settled)
- return;
- if (["EPIPE", "ECONNRESET", "ERR_STREAM_DESTROYED", "ERR_STREAM_PREMATURE_CLOSE"].includes(error.code ?? ""))
- return;
- finish(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker pipe failed."));
- terminateProcess(child, detached);
- };
- child.stdin?.on("error", pipeFailed);
- protocol.on("error", (error) => {
- if (process.platform === "win32" && process.versions.bun && error.code === "EBADF")
- return;
- pipeFailed(error);
- });
- child.stderr?.on("error", pipeFailed);
- controls.signal?.addEventListener("abort", abort, { once: true });
- if (controls.signal?.aborted)
- abort();
- protocol.on("data", (chunk2) => {
- responseBytes += chunk2.byteLength;
- if (responseBytes > maxResponseBytes) {
- finish(new EvaluatorSubprocessError("OUTPUT_LIMIT_EXCEEDED", "Evaluator output limit exceeded."));
- terminateProcess(child, detached);
- return;
- }
- chunks.push(Buffer.from(chunk2));
- });
- child.stderr?.on("data", (chunk2) => {
- stderrBytes = Math.min(MAX_STDERR_BYTES, stderrBytes + chunk2.byteLength);
- });
- child.on("error", () => {
- finish(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker failed to start."));
- });
- child.on("close", (exitCode) => {
- if (settled)
- return;
- if (exitCode !== 0 || chunks.length === 0) {
- finish(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker failed."));
- return;
- }
- try {
- const result = decodeEvaluatorResultV1(Buffer.concat(chunks).toString("utf8"), maxGlbBytes);
- if (!result.ok) {
- if (result.error.code === "QA_BLOCKED" && result.error.qa) {
- finish(new AssetQaBlockedError(result.error.qa.report, result.error.qa.stage, result.error.qa.gltfValidation));
- return;
- }
- finish(new EvaluatorSubprocessError(result.error.code, evaluatorOutcomeMessage(result.error.code), result.error.diagnostic));
- return;
- }
- finish(undefined, result.render);
- } catch {
- finish(new EvaluatorSubprocessError("PROTOCOL_ERROR", "Evaluator returned invalid data."));
- }
- });
- if (!settled)
- child.stdin?.end(requestJson);
- });
-}
-async function renderGLBViaSubprocess(code, options = {}, controls = {}) {
- return renderGLBViaProcessLaunch(code, options, controls);
-}
-var DEFAULT_DEADLINE_MS = 60000, DEFAULT_MAX_GLB_BYTES, DEFAULT_MAX_RESPONSE_BYTES, MAX_STDERR_BYTES, EvaluatorSubprocessError;
-var init_subprocess = __esm(() => {
- init_authoring_diagnostic();
- init_run();
- init_protocol();
- DEFAULT_MAX_GLB_BYTES = 16 * 1024 * 1024;
- DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
- MAX_STDERR_BYTES = 16 * 1024;
- EvaluatorSubprocessError = class EvaluatorSubprocessError extends Error {
- diagnostic;
- code;
- constructor(code, message, diagnostic) {
- super(diagnostic ? `${message} ${authoringDiagnosticAdvice(diagnostic)}` : message);
- this.diagnostic = diagnostic;
- this.name = "EvaluatorSubprocessError";
- this.code = code;
- }
- };
-});
-
-// src/program-store.ts
-function assertProgramRef(ref) {
- if (typeof ref !== "string" || !programRefPattern.test(ref))
- throw new Error("Invalid program reference; use a p_ handle or full sha256 reference returned by Kiln.");
-}
-async function retainProgram(store, code) {
- const canonical2 = await store.put(code);
- return store.shortRef ? store.shortRef(canonical2) : canonical2;
-}
-function* shortProgramRefCandidates(canonical2) {
- if (!canonicalProgramRefPattern.test(canonical2) || canonical2.length !== 71)
- throw new Error("Invalid canonical program reference.");
- for (let length3 = 12;length3 <= 64; length3 += 4)
- yield `p_${canonical2.slice(7, 7 + length3)}`;
-}
-async function programReference(code) {
- const bytes = new TextEncoder().encode(code);
- if (bytes.length > MAX_PROGRAM_BYTES)
- throw new Error("Program exceeds the 1 MiB source limit.");
- if (new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes) !== code)
- throw new Error("Program must be valid Unicode.");
- const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
- return `sha256:${Array.from(hash, (b) => b.toString(16).padStart(2, "0")).join("")}`;
-}
-
-class MemoryProgramStore {
- maxBytes;
- programs = new Map;
- handles = new Map;
- constructor(maxBytes = 64 * 1024 * 1024) {
- this.maxBytes = maxBytes;
- }
- bytes = 0;
- async put(code) {
- const ref = await programReference(code);
- if (!this.programs.has(ref)) {
- const size = new TextEncoder().encode(code).length;
- if (this.bytes + size > this.maxBytes)
- throw new Error("Program store is full; export your work and start a new store.");
- this.programs.set(ref, code);
- this.bytes += size;
- }
- return ref;
- }
- async stats() {
- return {
- entries: this.programs.size,
- bytes: this.bytes,
- maxSourceBytes: MAX_PROGRAM_BYTES,
- maxBytes: this.maxBytes,
- eviction: "none"
- };
- }
- async get(ref) {
- assertProgramRef(ref);
- const canonical2 = ref.startsWith("p_") ? this.handles.get(ref) : ref;
- const code = canonical2 === undefined ? undefined : this.programs.get(canonical2);
- if (code === undefined)
- throw new Error(`Program not found: ${ref}. Import the source into this store again.`);
- return code;
- }
- async shortRef(ref) {
- await this.get(ref);
- if (ref.startsWith("p_"))
- return ref;
- for (const handle of shortProgramRefCandidates(ref)) {
- const owner = this.handles.get(handle);
- if (owner === ref)
- return handle;
- if (owner === undefined) {
- this.handles.set(handle, ref);
- return handle;
- }
- }
- throw new Error("Unable to register an immutable program handle.");
- }
-}
-var MAX_PROGRAM_BYTES, canonicalProgramRefPattern, programRefPattern;
-var init_program_store = __esm(() => {
- MAX_PROGRAM_BYTES = 1024 * 1024;
- canonicalProgramRefPattern = /^sha256:[a-f0-9]{64}(?![\s\S])/;
- programRefPattern = /^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\s\S])/;
-});
-
-// src/program-store-node.ts
-import { link, lstat, mkdir, readFile as readFile2, readdir, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
-import { randomUUID } from "node:crypto";
-import { join as join3, resolve } from "node:path";
-
-class FileProgramStore {
- directory;
- constructor(directory) {
- this.directory = directory;
- }
- async stats() {
- let entries = 0;
- let bytes = 0;
- try {
- for (const entry of await readdir(this.directory, { withFileTypes: true })) {
- if (!entry.isFile() || !/^[a-f0-9]{64}\.js$/.test(entry.name))
- continue;
- try {
- bytes += (await stat(join3(this.directory, entry.name))).size;
- entries++;
- } catch (error) {
- if (error.code !== "ENOENT")
- throw error;
- }
- }
- } catch (error) {
- if (error.code !== "ENOENT")
- throw error;
- }
- return { entries, bytes, maxSourceBytes: MAX_PROGRAM_BYTES, eviction: "none" };
- }
- async get(ref) {
- assertProgramRef(ref);
- const canonical2 = ref.startsWith("p_") ? await this.readHandle(ref) : ref;
- if (canonical2 === undefined)
- throw this.notFound(ref);
- const path = join3(this.directory, `${canonical2.slice(7)}.js`);
- let code;
- try {
- if ((await stat(path)).size > MAX_PROGRAM_BYTES)
- throw new Error("Stored program exceeds the 1 MiB source limit.");
- code = await readFile2(path, "utf8");
- } catch (error) {
- if (error.code === "ENOENT")
- throw this.notFound(ref);
- throw error;
- }
- if (await programReference(code) !== canonical2)
- throw new Error(`Program integrity check failed: ${ref}`);
- return code;
- }
- notFound(ref) {
- return new Error(`Program not found: ${ref}. Use the same KILN_PROGRAM_STORE or import the source again.`);
- }
- async readHandle(handle) {
- const path = join3(this.directory, "refs", `${handle}.ref`);
- try {
- const info = await lstat(path);
- if (!info.isFile() || info.size !== 71)
- throw new Error(`Program handle integrity check failed: ${handle}`);
- const canonical2 = await readFile2(path, "utf8");
- if (!canonicalProgramRefPattern.test(canonical2) || !canonical2.slice(7).startsWith(handle.slice(2)))
- throw new Error(`Program handle integrity check failed: ${handle}`);
- return canonical2;
- } catch (error) {
- if (error.code === "ENOENT")
- return;
- throw error;
- }
- }
- async shortRef(ref) {
- await this.get(ref);
- if (ref.startsWith("p_"))
- return ref;
- const directory = join3(this.directory, "refs");
- await mkdir(directory, { recursive: true });
- for (const handle of shortProgramRefCandidates(ref)) {
- const owner = await this.readHandle(handle);
- if (owner === ref)
- return handle;
- if (owner !== undefined)
- continue;
- const temporary = join3(directory, `.write-${randomUUID()}`);
- await writeFile2(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });
- try {
- try {
- await link(temporary, join3(directory, `${handle}.ref`));
- return handle;
- } catch (error) {
- if (error.code !== "EEXIST")
- throw error;
- if (await this.readHandle(handle) === ref)
- return handle;
- }
- } finally {
- await unlink(temporary);
- }
- }
- throw new Error("Unable to register an immutable program handle.");
- }
- async put(code) {
- const ref = await programReference(code);
- await mkdir(this.directory, { recursive: true });
- const target = join3(this.directory, `${ref.slice(7)}.js`);
- const temporary = join3(this.directory, `.write-${randomUUID()}`);
- await writeFile2(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });
- try {
- try {
- await link(temporary, target);
- } catch (error) {
- if (error.code !== "EEXIST")
- throw error;
- await this.get(ref);
- }
- } finally {
- await unlink(temporary);
- }
- return ref;
- }
-}
-function localProgramStore() {
- return new FileProgramStore(resolve(process.env["KILN_PROGRAM_STORE"] ?? ".kiln/programs"));
-}
-var init_program_store_node = __esm(() => {
- init_program_store();
-});
-
-// src/build-cache.ts
-import { createHash as createHash7 } from "node:crypto";
-import * as acorn2 from "acorn";
-import * as walk2 from "acorn-walk";
-function sourceHasAmbientInputs(code) {
- let ambient = false;
- const property = (node) => !node.computed && node.property.type === "Identifier" ? node.property.name : node.computed && node.property.type === "Literal" && typeof node.property.value === "string" ? node.property.value : undefined;
- try {
- const ast = acorn2.parse(code, { ecmaVersion: "latest", sourceType: "script" });
- walk2.ancestor(ast, {
- Identifier(node, _state, ancestors) {
- const parent = ancestors.at(-2);
- if (["Date", "performance", "crypto"].includes(node.name))
- ambient = true;
- if (node.name === "Math") {
- if (parent?.type !== "MemberExpression" || parent.object !== node)
- ambient = true;
- else {
- const name = property(parent);
- if (!name || name === "random")
- ambient = true;
- }
- }
- },
- MemberExpression(node, _state, ancestors) {
- if (node.object.type !== "Identifier" || node.object.name !== "THREE" || property(node) !== "MathUtils")
- return;
- const parent = ancestors.at(-2);
- if (parent?.type !== "MemberExpression" || parent.object !== node) {
- ambient = true;
- return;
- }
- const name = property(parent);
- if (!name || ["randInt", "randFloat", "randFloatSpread", "seededRandom", "generateUUID"].includes(name))
- ambient = true;
- }
- });
- } catch {
- return true;
- }
- return ambient;
-}
-function copy(result) {
- return { ...structuredClone(result), glb: Buffer.from(result.glb) };
-}
-
-class MemoryBuildCache {
- maxBytes;
- entries = new Map;
- bytes = 0;
- constructor(maxBytes = 64 * 1024 * 1024) {
- this.maxBytes = maxBytes;
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 0)
- throw new Error("Build cache size must be a nonnegative integer.");
- }
- async get(key) {
- const entry = this.entries.get(key);
- if (!entry)
- return;
- this.entries.delete(key);
- this.entries.set(key, entry);
- return copy(entry.result);
- }
- async put(key, result) {
- const { glb, ...metadata } = result;
- const size = glb.byteLength + Buffer.byteLength(JSON.stringify(metadata));
- if (size > this.maxBytes)
- return;
- const old = this.entries.get(key);
- if (old) {
- this.bytes -= old.bytes;
- this.entries.delete(key);
- }
- while (this.bytes + size > this.maxBytes) {
- const first = this.entries.keys().next().value;
- if (first === undefined)
- break;
- this.bytes -= this.entries.get(first).bytes;
- this.entries.delete(first);
- }
- this.entries.set(key, { result: copy(result), bytes: size });
- this.bytes += size;
- }
- stats() {
- return { entries: this.entries.size, bytes: this.bytes, maxBytes: this.maxBytes };
- }
-}
-function canonical2(value) {
- if (value === undefined || value === null || typeof value === "string" || typeof value === "boolean")
- return value;
- if (typeof value === "number" && Number.isFinite(value))
- return value;
- if (Array.isArray(value))
- return value.map(canonical2);
- if (typeof value === "object")
- return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([key, v]) => [key, canonical2(v)]));
- throw new Error("Build input contains a non-data dependency.");
-}
-function createCachedEvaluatorPort(evaluator, options) {
- const pending = new Map;
- return {
- async render(code, renderOptions, controls) {
- const signal = controls?.signal;
- const checkCancelled = () => {
- if (signal?.aborted)
- throw new EvaluatorPortError("CANCELLED");
- };
- checkCancelled();
- const identity = options.identity();
- if (!identity || renderOptions?.textureResolver || sourceHasAmbientInputs(code))
- return evaluator.render(code, renderOptions, controls);
- let serialized;
- try {
- renderOptions = structuredClone(renderOptions);
- const { signal: _signal, ...dataControls } = controls ?? {};
- const snapshotControls = structuredClone(dataControls);
- controls = { ...snapshotControls, ...signal ? { signal } : {} };
- serialized = JSON.stringify(canonical2({ identity, code, options: renderOptions ?? {}, controls: snapshotControls }));
- } catch {
- return evaluator.render(code, renderOptions, controls);
- }
- const key = `sha256:${createHash7("sha256").update(serialized).digest("hex")}`;
- const cached = await options.cache.get(key).catch(() => {
- return;
- });
- checkCancelled();
- if (cached)
- return { ...cached, buildCache: { key, hit: true } };
- const existing = signal ? undefined : pending.get(key);
- if (existing) {
- const completed = await existing;
- if (!completed.shareable)
- return evaluator.render(code, renderOptions, controls);
- return { ...copy(completed.result), buildCache: { key, hit: true } };
- }
- const build = (async () => {
- const result = await evaluator.render(code, renderOptions, controls);
- checkCancelled();
- let snapshot;
- try {
- snapshot = copy(result);
- } catch {
- return { result, shareable: false };
- }
- await options.cache.put(key, snapshot).catch(() => {});
- return { result: snapshot, shareable: true };
- })();
- if (!signal)
- pending.set(key, build);
- try {
- const completed = await build;
- checkCancelled();
- return completed.shareable ? { ...copy(completed.result), buildCache: { key, hit: false } } : completed.result;
- } finally {
- if (!signal)
- pending.delete(key);
- }
- }
- };
-}
-var init_build_cache = __esm(() => {
- init_protocol();
-});
-
-// src/build-cache-node.ts
-import { createHash as createHash8, randomUUID as randomUUID2 } from "node:crypto";
-import {
- mkdir as mkdir2,
- readFile as readFile3,
- readdir as readdir2,
- rename,
- stat as stat2,
- unlink as unlink2,
- utimes,
- writeFile as writeFile3
-} from "node:fs/promises";
-import { join as join4, resolve as resolve2 } from "node:path";
-
-class FileBuildCache {
- maxBytes;
- directory;
- constructor(directory, maxBytes = 128 * 1024 * 1024) {
- this.maxBytes = maxBytes;
- this.directory = resolve2(directory);
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || maxBytes > 1024 * 1024 * 1024)
- throw new Error("File build cache size must be 0..1 GiB.");
- }
- path(key) {
- if (!keyPattern.test(key))
- throw new Error("Invalid build cache key.");
- return join4(this.directory, `${key.slice(7)}.json`);
- }
- async get(key) {
- const path = this.path(key);
- try {
- const entry = await stat2(path);
- if (entry.size > this.maxBytes || entry.size > 96 * 1024 * 1024)
- return;
- const envelope = JSON.parse(await readFile3(path, "utf8"));
- if (envelope.version !== 1 || envelope.key !== key || typeof envelope.payload !== "string" || envelope.checksum !== digest2(envelope.payload))
- return;
- const decoded = decodeEvaluatorResultV1(envelope.payload, 64 * 1024 * 1024);
- if (!decoded.ok)
- return;
- const now = new Date;
- await utimes(path, now, now).catch(() => {});
- return decoded.render;
- } catch {
- return;
- }
- }
- async put(key, result) {
- const path = this.path(key);
- const payload = JSON.stringify(encodeRenderResultV1("cached-build", result));
- const bytes = JSON.stringify({ version: 1, key, payload, checksum: digest2(payload) });
- if (Buffer.byteLength(bytes) > Math.min(this.maxBytes, 96 * 1024 * 1024))
- return;
- await mkdir2(this.directory, { recursive: true });
- const temporary = join4(this.directory, `.write-${randomUUID2()}`);
- await writeFile3(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });
- try {
- await rename(temporary, path);
- } finally {
- await unlink2(temporary).catch(() => {});
- }
- await this.trim();
- }
- async trim() {
- const entries = [];
- for (const name of await readdir2(this.directory)) {
- if (!filePattern.test(name))
- continue;
- const path = join4(this.directory, name);
- try {
- const item = await stat2(path);
- entries.push({ path, size: item.size, used: item.mtimeMs });
- } catch {}
- }
- let bytes = entries.reduce((sum, item) => sum + item.size, 0);
- entries.sort((a, b) => a.used - b.used || a.path.localeCompare(b.path));
- for (const entry of entries) {
- if (bytes <= this.maxBytes)
- break;
- await unlink2(entry.path).catch(() => {});
- bytes -= entry.size;
- }
- }
-}
-var keyPattern, filePattern, digest2 = (text2) => createHash8("sha256").update(text2).digest("hex");
-var init_build_cache_node = __esm(() => {
- init_protocol();
- keyPattern = /^sha256:[a-f0-9]{64}$/;
- filePattern = /^[a-f0-9]{64}\.json$/;
-});
-
-// src/runtime-identity.ts
-import { createHash as createHash9 } from "node:crypto";
-import { readFile as readFile4, readdir as readdir3, realpath, stat as stat3 } from "node:fs/promises";
-import { createRequire as createRequire2 } from "node:module";
-import { dirname, join as join5, relative } from "node:path";
-async function installedRuntimeIdentity(root, limits = {}) {
- let bytes = 0;
- let files = 0;
- const maxBytes = limits.maxBytes ?? 512 * 1024 * 1024;
- const maxFiles = limits.maxFiles ?? 40000;
- const manifest = async (directory) => JSON.parse(await readFile4(join5(directory, "package.json"), "utf8"));
- let readers = 0;
- const waiting = [];
- const read = async (path) => {
- if (readers >= 24)
- await new Promise((resolve3) => waiting.push(resolve3));
- else
- readers++;
- try {
- const info = await stat3(path);
- if (++files > maxFiles || bytes + info.size > maxBytes)
- throw new Error("Installed runtime fingerprint exceeds its scan budget.");
- bytes += info.size;
- return await readFile4(path);
- } finally {
- const next = waiting.shift();
- if (next)
- next();
- else
- readers--;
- }
- };
- try {
- const pkg = await manifest(root);
- if (pkg.name !== "@kiln/engine")
- throw new Error("Not a Kiln installation.");
- const build = JSON.parse(await readFile4(join5(root, "dist", "build.json"), "utf8"));
- const worker = build.entries?.worker;
- if (build.schemaVersion !== 1 || worker?.file !== "evaluator-worker.mjs" || !/^sha256:[a-f0-9]{64}$/.test(worker.identity))
- throw new Error("No valid packaged worker identity.");
- const workerHash = `sha256:${digest3(await read(join5(root, "dist", worker.file)))}`;
- if (worker.bundleHash !== workerHash)
- throw new Error("Packaged worker differs from its build manifest.");
- const records = [];
- const visited = new Map;
- async function resolvePackage(parent, name) {
- const require2 = createRequire2(join5(parent, "package.json"));
- let found;
- try {
- found = require2.resolve(`${name}/package.json`);
- } catch {
- try {
- found = require2.resolve(name);
- } catch {
- for (const modules of require2.resolve.paths(name) ?? []) {
- const candidate = join5(modules, name);
- try {
- if ((await manifest(candidate)).name === name)
- return await realpath(candidate);
- } catch {}
- }
- throw new Error(`Cannot resolve installed dependency ${name}.`);
- }
- }
- let directory = dirname(found);
- for (;; ) {
- try {
- if ((await manifest(directory)).name === name)
- return await realpath(directory);
- } catch {}
- const next = dirname(directory);
- if (next === directory)
- throw new Error(`Cannot identify installed dependency ${name}.`);
- directory = next;
- }
- }
- async function tree(directory, base) {
- const entries = (await readdir3(directory, { withFileTypes: true })).sort((a, b) => compare(a.name, b.name));
- return (await Promise.all(entries.map(async (entry) => {
- if (entry.name === "node_modules" || entry.name === ".git")
- return [];
- const path = join5(directory, entry.name);
- if (entry.isSymbolicLink())
- throw new Error("Dependency contains an untracked internal symlink.");
- if (entry.isDirectory())
- return tree(path, base);
- if (entry.isFile())
- return [[relative(base, path).replaceAll("\\", "/"), digest3(await read(path))]];
- throw new Error("Dependency contains a non-file runtime input.");
- }))).flat();
- }
- async function visit(directory, path) {
- const canonical3 = await realpath(directory);
- const previous = visited.get(canonical3);
- if (previous) {
- records.push([path, `same-package:${previous}`]);
- return;
- }
- visited.set(canonical3, path);
- const metadata = await manifest(canonical3);
- records.push([path, digest3(JSON.stringify(await tree(canonical3, canonical3)))]);
- await dependencies(canonical3, metadata, path);
- }
- async function dependencies(directory, metadata, prefix) {
- const names = [
- ...new Set([
- ...Object.keys(metadata.dependencies ?? {}),
- ...Object.keys(metadata.optionalDependencies ?? {}),
- ...Object.keys(metadata.peerDependencies ?? {})
- ])
- ].sort(compare);
- for (const name of names) {
- let child;
- try {
- child = await resolvePackage(directory, name);
- } catch {
- if (name in (metadata.optionalDependencies ?? {}) || metadata.peerDependenciesMeta?.[name]?.optional) {
- records.push([`${prefix}/${name}`, "optional-absent"]);
- continue;
- }
- throw new Error(`Cannot fingerprint missing installed dependency ${name}.`);
- }
- await visit(child, `${prefix}/${name}`);
- }
- }
- await dependencies(root, { ...pkg, peerDependencies: {} }, "dependencies");
- const inputs = {
- version: 1,
- engine: pkg.version,
- workerHash,
- build: worker.identity,
- runtime: {
- node: process.versions.node,
- bun: process.versions.bun,
- modules: process.versions.modules,
- platform: process.platform,
- arch: process.arch
- },
- dependencies: records
- };
- return { identity: `sha256:${digest3(JSON.stringify(inputs))}`, files, bytes };
- } catch (error) {
- return { reason: error instanceof Error ? error.message : String(error), files, bytes };
- }
-}
-var digest3 = (bytes) => createHash9("sha256").update(bytes).digest("hex"), compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
-var init_runtime_identity = () => {};
-
-// src/local-runtime.ts
-import { dirname as dirname2, join as join6, resolve as resolve3 } from "node:path";
-import { fileURLToPath as fileURLToPath3 } from "node:url";
-function integer2(env, name, fallback, min, max) {
- const value = env[name] === undefined ? fallback : Number(env[name]);
- if (!Number.isInteger(value) || value < min || value > max)
- throw new Error(`${name} requires an integer from ${min} to ${max}.`);
- return value;
-}
-function createLocalToolContext(base = {}, env = process.env) {
- const geometryPolicy = base.geometryPolicy ?? env.KILN_GEOMETRY_POLICY ?? "warn";
- if (!["warn", "strict"].includes(geometryPolicy))
- throw new Error("KILN_GEOMETRY_POLICY must be warn or strict.");
- const mode = resolveEvaluatorMode({
- KILN_EVALUATOR_MODE: env.KILN_EVALUATOR_MODE ?? "subprocess"
- });
- const deadlineMs = integer2(env, "KILN_EVALUATOR_TIMEOUT_MS", 60000, 1, 120000);
- const heapMb = integer2(env, "KILN_EVALUATOR_HEAP_MB", 512, 64, 4096);
- if (mode === "subprocess" && process.versions.bun && env.KILN_EVALUATOR_HEAP_MB !== undefined) {
- throw new Error("KILN_EVALUATOR_HEAP_MB requires the packaged Node runtime.");
- }
- if (mode !== "in-process" && ["observe", "off"].includes(env.KILN_QA_MODE ?? "")) {
- throw new Error("KILN_QA_MODE overrides are not transported to the local worker. Remove the override or explicitly select trusted KILN_EVALUATOR_MODE=in-process.");
- }
- const optimize = ["auto", "palette", "full"].includes(env.KILN_BAKE_OPTIMIZE ?? "") ? env.KILN_BAKE_OPTIMIZE : "off";
- const instance2 = ["off", "auto", "on"].includes(env.KILN_BAKE_INSTANCE ?? "") ? env.KILN_BAKE_INSTANCE : "auto";
- const maxGlbBytes = 16 * 1024 * 1024;
- const maxResponseBytes = 32 * 1024 * 1024;
- const evaluatorPort = {
- async render(code, options = {}, controls = {}) {
- if (controls.signal?.aborted) {
- const { EvaluatorPortError: EvaluatorPortError2 } = await Promise.resolve().then(() => (init_protocol(), exports_protocol));
- throw new EvaluatorPortError2("CANCELLED");
- }
- if (options.geometryPolicy !== undefined && !["warn", "strict"].includes(options.geometryPolicy))
- throw new Error("geometryPolicy must be warn or strict");
- const resolved2 = {
- optimize,
- instance: instance2,
- ...options,
- geometryPolicy: geometryPolicy === "strict" ? "strict" : options.geometryPolicy ?? "warn"
- };
- if (mode === "in-process") {
- const result = await renderGLBInProcess(code, resolved2);
- if (controls.signal?.aborted) {
- const { EvaluatorPortError: EvaluatorPortError2 } = await Promise.resolve().then(() => (init_protocol(), exports_protocol));
- throw new EvaluatorPortError2("CANCELLED");
- }
- return result;
- }
- const limits = { deadlineMs, maxGlbBytes, maxResponseBytes, ...controls };
- if (mode === "isolated")
- return renderGLBViaIsolatedEvaluator(code, resolved2, limits);
- return renderGLBViaSubprocess(code, resolved2, {
- ...limits,
- ...!process.versions.bun ? { maxHeapMb: heapMb } : {}
- });
- }
- };
- const localExecution = {
- mode,
- terminable: mode !== "in-process",
- ...mode !== "in-process" ? { deadlineMs } : {},
- ...mode === "subprocess" && !process.versions.bun ? { nodeHeapMb: heapMb } : {},
- ...mode !== "in-process" ? { maxGlbBytes, maxResponseBytes } : {},
- totalMemoryLimited: false,
- cacheScope: "process"
- };
- return {
- ...base,
- geometryPolicy,
- programStore: base.programStore ?? new FileProgramStore(resolve3(env.KILN_PROGRAM_STORE ?? ".kiln/programs")),
- evaluatorPort,
- assetBuildOptions: {
- optimize,
- instance: instance2,
- geometryPolicy,
- qaMode: env.KILN_QA_MODE ?? "enforce",
- evaluatorMode: mode
- },
- buildCache: new MemoryBuildCache,
- evaluatorCacheIdentity: `kiln-local-${process.pid}-${++scope}:${JSON.stringify({ mode, optimize, instance: instance2, geometryPolicy, qa: env.KILN_QA_MODE, deadlineMs, heapMb })}`,
- localExecution
- };
-}
-async function createPackagedLocalToolContext(base = {}, env = process.env, installationRoot = fileURLToPath3(new URL("../", import.meta.url))) {
- const context = createLocalToolContext(base, env);
- const managed = () => {
- const identity2 = context.evaluatorCacheIdentity;
- const cached = createCachedEvaluatorPort(context.evaluatorPort, {
- cache: context.buildCache,
- identity: () => typeof identity2 === "function" ? identity2() : identity2
- });
- context.evaluatorPort = {
- render: (code, options, controls) => cached.render(code, {
- ...options,
- geometryPolicy: context.geometryPolicy === "strict" ? "strict" : options?.geometryPolicy ?? context.geometryPolicy
- }, controls)
- };
- context.evaluatorCacheManaged = true;
- return context;
- };
- const policy = env.KILN_BUILD_CACHE ?? "disk";
- if (!["disk", "memory", "off"].includes(policy))
- throw new Error("KILN_BUILD_CACHE must be disk, memory, or off.");
- if (policy === "off" || base.cacheEvaluations === false) {
- context.cacheEvaluations = false;
- context.localExecution.cacheScope = "disabled";
- return context;
- }
- if (policy === "memory")
- return managed();
- if (process.versions.bun || context.localExecution.mode !== "subprocess") {
- context.localExecution.cacheReason = "Disk reuse requires the packaged Node subprocess evaluator; this host uses process memory.";
- return managed();
- }
- const identity = await installedRuntimeIdentity(installationRoot);
- if (!identity.identity) {
- context.localExecution.cacheReason = identity.reason;
- return managed();
- }
- const cacheBytes = integer2(env, "KILN_BUILD_CACHE_MB", 128, 0, 1024) * 1024 * 1024;
- const store = context.programStore;
- const directory = resolve3(env.KILN_BUILD_CACHE_DIR ?? join6(store instanceof FileProgramStore ? dirname2(store.directory) : ".kiln", "cache", "builds"));
- context.buildCache = new FileBuildCache(directory, cacheBytes);
- context.evaluatorCacheIdentity = `${identity.identity}:${JSON.stringify({
- execution: context.localExecution,
- optimize: env.KILN_BAKE_OPTIMIZE ?? "off",
- instance: env.KILN_BAKE_INSTANCE ?? "auto",
- qa: env.KILN_QA_MODE ?? "enforce",
- geometryPolicy: context.geometryPolicy,
- timezone: env.TZ
- })}`;
- context.localExecution = {
- ...context.localExecution,
- cacheScope: "disk",
- cacheBytes,
- runtimeIdentity: identity.identity
- };
- return managed();
-}
-var scope = 0;
-var init_local_runtime = __esm(() => {
- init_subprocess();
- init_isolation();
- init_render();
- init_program_store_node();
- init_build_cache();
- init_build_cache_node();
- init_runtime_identity();
-});
-
-// src/assets.ts
-import { z } from "zod";
-import { zipSync, unzipSync } from "three/addons/libs/fflate.module.js";
-function validateRecordShape(record5) {
- const manifest = assetManifestSchema.parse(record5.manifest);
- const names = Object.keys(record5.files);
- if (names.length !== Object.keys(manifest.files).length || !names.includes("asset.glb"))
- throw new Error("Asset file inventory mismatch");
- let total = 0;
- for (const name of names) {
- if (!allowedFiles.has(name) || !manifest.files[name] || manifest.files[name].bytes !== record5.files[name].length)
- throw new Error("Invalid asset file inventory");
- total += record5.files[name].length;
- }
- if (total > ASSET_LIMIT || manifest.editable !== names.includes("source.kiln.js"))
- throw new Error("Invalid asset size or source inventory");
- if ((record5.files["source.kiln.js"]?.length ?? 0) > 1024 * 1024)
- throw new Error("Source exceeds 1 MiB");
- validateAssetGlb(record5.files["asset.glb"]);
-}
-function validateAssetGlb(bytes) {
- if (bytes.length < 20 || bytes.length > ASSET_LIMIT)
- throw new Error("Invalid GLB size");
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- if (view.getUint32(0, true) !== 1179937895 || view.getUint32(4, true) !== 2 || view.getUint32(8, true) !== bytes.length || view.getUint32(16, true) !== 1313821514)
- throw new Error("Invalid GLB header");
- const end = 20 + view.getUint32(12, true);
- if (end > bytes.length)
- throw new Error("Invalid GLB JSON length");
- const json = JSON.parse(new TextDecoder().decode(bytes.subarray(20, end)));
- for (const resource of [...json.buffers ?? [], ...json.images ?? []]) {
- if (resource.uri && !String(resource.uri).startsWith("data:"))
- throw new Error("GLB must embed its resources");
- }
-}
-function encodeAssetBundle(records) {
- if (!records.length || records.length > 100)
- throw new Error("Bundle requires 1..100 revisions");
- const files = {};
- let total = 0;
- for (const record5 of records) {
- validateRecordShape(record5);
- const prefix = `${record5.manifest.assetId}/${record5.manifest.revisionId}/`;
- if (files[`${prefix}manifest.json`])
- throw new Error("Duplicate bundle revision");
- files[`${prefix}manifest.json`] = new TextEncoder().encode(JSON.stringify(record5.manifest, null, 2));
- for (const [name, bytes] of Object.entries(record5.files))
- files[prefix + name] = bytes;
- }
- for (const bytes of Object.values(files))
- total += bytes.length;
- if (total > ASSET_LIMIT)
- throw new Error("Bundle exceeds 64 MiB");
- return zipSync(files, { level: 0 });
-}
-function decodeAssetBundle(bytes) {
- if (bytes.length > ASSET_LIMIT + 1024 * 1024)
- throw new Error("Bundle exceeds 64 MiB");
- let total = 0;
- let count = 0;
- const files = unzipSync(bytes, {
- filter: (entry) => {
- total += entry.originalSize;
- count++;
- if (total > ASSET_LIMIT || count > 400 || !/^[a-z][a-z0-9_-]{0,79}\/[a-z][a-z0-9_-]{0,79}\/(manifest\.json|asset\.glb|source\.kiln\.js|preview\.png)$/.test(entry.name))
- throw new Error("Unsafe or oversized asset bundle");
- return true;
- }
- });
- const records = [];
- const used = new Set;
- for (const [path, data] of Object.entries(files)) {
- if (!path.endsWith("/manifest.json"))
- continue;
- if (data.length > 1024 * 1024)
- throw new Error("Manifest exceeds 1 MiB");
- const manifest = assetManifestSchema.parse(JSON.parse(new TextDecoder().decode(data)));
- const prefix = `${manifest.assetId}/${manifest.revisionId}/`;
- if (path !== `${prefix}manifest.json`)
- throw new Error("Bundle identity mismatch");
- const record5 = { manifest, files: {} };
- used.add(path);
- for (const name of Object.keys(manifest.files)) {
- if (!files[prefix + name])
- throw new Error("Bundle file missing");
- record5.files[name] = files[prefix + name];
- used.add(prefix + name);
- }
- validateRecordShape(record5);
- records.push(record5);
- }
- if (!records.length || used.size !== Object.keys(files).length)
- throw new Error("Incomplete asset bundle");
- return records;
-}
-var ASSET_LIMIT, assetIdSchema, hash, assetManifestSchema, allowedFiles;
-var init_assets = __esm(() => {
- ASSET_LIMIT = 64 * 1024 * 1024;
- assetIdSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
- hash = z.string().regex(/^sha256:[a-f0-9]{64}$/);
- assetManifestSchema = z.object({
- version: z.literal("kiln.asset.v1"),
- assetId: assetIdSchema,
- revisionId: assetIdSchema,
- parentRevision: assetIdSchema.optional(),
- name: z.string().min(1).max(200),
- tags: z.array(z.string().max(80)).max(30),
- createdAt: z.string().datetime(),
- description: z.string().max(4000).optional(),
- brief: z.string().max(8000).optional(),
- attribution: z.object({
- model: z.string().max(200).optional(),
- harness: z.string().max(200).optional(),
- author: z.string().max(200).optional()
- }).optional(),
- editable: z.boolean(),
- files: z.record(z.string(), z.object({ sha256: hash, bytes: z.number().int().nonnegative().max(ASSET_LIMIT) })),
- build: z.object({
- engine: z.string(),
- options: z.record(z.string(), z.unknown()),
- warnings: z.array(z.string()),
- integration: z.unknown().optional(),
- qa: z.unknown().optional(),
- dependencies: z.array(z.unknown()).optional(),
- rebuild: z.enum(["engine-required", "external-dependencies-required"])
- }).optional(),
- preview: z.object({ fidelity: z.unknown().optional(), error: z.string().optional() }).optional()
- });
- allowedFiles = new Set(["asset.glb", "source.kiln.js", "preview.png"]);
-});
-
-// src/tools/programs.ts
-import { z as z2 } from "zod";
-function withProgramReferences(def, store) {
- if (!(def.inputSchema instanceof z2.ZodObject))
- throw new Error(`${def.name} must have an object input schema.`);
- const inputSchema = def.inputSchema.extend({
- code: z2.string().optional().describe("New source. Supply code OR programRef."),
- programRef: refInput.optional(),
- ...def.name === "kiln_edit" ? {
- includeCode: z2.boolean().optional().describe("Return the full updated source. Defaults to false with programRef, true with code.")
- } : {}
- }).refine((input) => input.code !== undefined !== (input.programRef !== undefined), {
- message: "Supply exactly one of code or programRef."
- });
- const summaries = {
- kiln_validate: "Check program syntax and sandbox rules before building. Returns validation findings; use kiln_render to evaluate geometry and see the asset.",
- kiln_render: "Build a program and return geometry metrics, exact part paths and images. Omit capture for six views; choose preset/cells for orbit grids or version kiln.capture.v1 plus shots for part-local framing, perspective and separate images. Check viewFidelity before judging materials. Failed builds return errors without an image.",
- kiln_screenshot_animation: "Render sampled animation frames to check motion and attachments. Use shot for the shared camera controls, frameTimes for selected phases, and framing locked (default) or follow. The program must define animate(). Check viewFidelity before judging materials.",
- kiln_view_interior: "Render roof-off floor-plan, dollhouse, and eye-level cutaway views. Optional versioned capture selects custom roof-off shots. Select a roof by nodeName or let Kiln resolve its role/name. Review roofsHidden and warnings for unresolved occlusion.",
- kiln_inspect: "Inspect a part with context or isolation. Use legacy part/orbit controls or shot for exact paths, part-local axes and perspective. Use names from the source or render result; check viewFidelity before judging materials."
- };
- const description = def.name === "kiln_edit" ? "Apply exact-string replacements to a program revision and render the result (render:false skips images). Edits are ordered and atomic: missing or ambiguous matches fail without changing the base. Returns a new programRef, parentRef and diff; untouched text stays identical. Read anchors with kiln_source. Optional capture chooses the same cameras as kiln_render. Use includeCode only when full source is needed." : `${summaries[def.name] ?? def.description} Supply code once or reuse programRef from an earlier result. Returns programRef even for an invalid draft. kiln_source reads that revision.`;
- return {
- ...def,
- inputSchema,
- description,
- run: async (input) => {
- const args = inputSchema.parse(input);
- const code = typeof args.code === "string" ? args.code : await store.get(args.programRef);
- const parentRef = await retainProgram(store, code);
- const output = await def.run({ ...args, code });
- if (def.name !== "kiln_edit" || output.ok !== true || typeof output.code !== "string")
- return { ...output, programRef: parentRef };
- const programRef = await retainProgram(store, output.code);
- const { code: updatedCode, ...rest } = output;
- const includeCode = args.includeCode ?? args.code !== undefined;
- const diff = typeof rest.diff === "string" ? rest.diff : "";
- return {
- ...rest,
- programRef,
- parentRef,
- ...includeCode ? { code: updatedCode } : {
- diff: diff.slice(0, 8000),
- diffTruncated: diff.length > 8000
- }
- };
- }
- };
-}
-function createKilnSourceDef(store) {
- const inputSchema = z2.object({
- programRef: refInput,
- offset: z2.number().int().min(0).default(0).describe("UTF-16 character offset; use nextOffset to continue."),
- limit: z2.number().int().min(1).max(16000).default(8000).describe("Maximum characters returned."),
- query: z2.string().min(1).max(1000).optional().describe("Find literal text at or after offset; return bounded surrounding source.")
- });
- return {
- name: "kiln_source",
- description: "Read a saved program revision without changing it. Returns exact source text in bounded pages, or searches for literal text with surrounding context. Copy edit anchors from code. Follow nextOffset for more; use matchOffset + 1 to find the next match. Offsets count UTF-16 characters, not bytes.",
- inputSchema,
- run: async (input) => {
- const { programRef, offset, limit, query } = inputSchema.parse(input);
- const source = await store.get(programRef);
- const matchOffset = query ? source.indexOf(query, offset) : undefined;
- const start = matchOffset !== undefined && matchOffset >= 0 ? Math.max(offset, matchOffset - Math.floor(limit / 4)) : Math.min(offset, source.length);
- const code = matchOffset === -1 ? "" : source.slice(start, start + limit);
- const end = start + code.length;
- return {
- programRef,
- code,
- offset: start,
- nextOffset: matchOffset === -1 || end >= source.length ? null : end,
- totalCharacters: source.length,
- totalBytes: new TextEncoder().encode(source).length,
- ...matchOffset !== undefined ? { matchOffset, found: matchOffset >= 0 } : {}
- };
- }
- };
-}
-var refInput;
-var init_programs = __esm(() => {
- init_program_store();
- refInput = z2.string().regex(programRefPattern).describe("Returned p_ handle or full sha256 ref.");
-});
-
-// src/geometry-catalog.ts
-var geometryPrimitives;
-var init_geometry_catalog = __esm(() => {
- geometryPrimitives = [
- {
- name: "copyGeometry",
- signature: "copyGeometry(geometry: BufferGeometry)",
- returns: "THREE.BufferGeometry",
- category: "instancing",
- description: "Returns an independent geometry with copied vertex buffers. Use before direct mutation of a cached primitive.",
- example: "const editable = copyGeometry(boxGeo(1, 1, 1)); editable.translate(0, 0.5, 0);"
- },
- {
- name: "copyMaterial",
- signature: "copyMaterial(material: Material)",
- returns: "THREE.Material (same subtype)",
- category: "instancing",
- description: "Copies material properties so edits do not change other parts. Referenced textures remain shared.",
- example: "const red = copyMaterial(steel); red.color.set(0xaa2222);"
- },
- {
- name: "meshGeo",
- signature: "meshGeo({ positions: number[], indices?: number[], normals?: number[], uvs?: number[], tangents?: number[] })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Builds an owned triangle mesh from flat numeric arrays. Validates finite values, attribute lengths and indices; computes normals if absent. Counterclockwise winding.",
- example: "const triangle = meshGeo({ positions: [0,0,0, 1,0,0, 0,1,0], indices: [0,1,2] });"
- },
- {
- name: "parametricSurface",
- signature: "parametricSurface(sample: (u,v) => [x,y,z], opts?: { u?: [0,1], v?: [0,1], uSegments?: 24, vSegments?: 24, periodicU?: false, periodicV?: false, orientation?: 'uv'|'vu' })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Samples an equation into an owned surface with UVs. Periodic endpoints must coincide; UV seams retain matching normals. A surface is not automatically a watertight solid.",
- example: "const canopy = parametricSurface((u,v) => [u, 0.3*Math.sin(u*3)*Math.cos(v*2), v], { u: [-2,2], v: [-1,1] });"
- },
- {
- name: "geometryDiagnostics",
- signature: "geometryDiagnostics(geometry: BufferGeometry, tolerance?: 1e-6)",
- returns: "{ vertices, triangles, boundaryEdges, nonManifoldEdges, orientationConflicts, degenerateTriangles, invalidIndices, nonFiniteVertices }",
- category: "utility",
- description: "Counts mesh topology problems after position-based seam matching. Open boundaries are valid for sheets; closed edges alone do not prove a self-intersection-free solid.",
- example: "const topology = geometryDiagnostics(shell);"
- },
- {
- name: "creaseNormals",
- signature: "creaseNormals(geometry: BufferGeometry, opts?: { angle?: 60, tolerance?: number })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Returns owned geometry with angle-limited smooth normals, preserving UV corners. Angle is degrees. Invalidates tangents; use after shaping for sharp rims and smooth walls.",
- example: "const shell = creaseNormals(cylinderGeo(1,1,2,32), { angle: 45 });"
- },
- {
- name: "bend",
- signature: "bend(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Bends local +Y toward +X through angle degrees. Returns owned geometry and updated normals/bounds; preserves UVs, invalidates tangents. Frame rotation is Euler XYZ degrees.",
- promptNotes: "Deformation interval uses local Y distances; outside vertices stay unchanged. Add enough segments before bending. Falloff returns 0..1; use it to avoid a discontinuity at a selected interval boundary.",
- example: "const arch = bend(planeGeo(1,4,4,32), { angle: 90 });"
- },
- {
- name: "twist",
- signature: "twist(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Rotates the cross-section progressively around local +Y, reaching angle degrees at the end. Returns owned geometry; frame rotation uses Euler XYZ degrees.",
- example: "const spiral = twist(column, { angle: 120 });"
- },
- {
- name: "taper",
- signature: "taper(geometry, { startScale?: [1,1], endScale: [x,z], frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Scales local X/Z across the local Y interval using positive start/end scale pairs. Returns owned geometry; preserves UVs and invalidates tangents.",
- example: "const narrowed = taper(column, { endScale: [0.4,0.7] });"
- },
- {
- name: "displace",
- signature: "displace(geometry, offset: ([x,y,z], t) => [dx,dy,dz], opts?: { frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Adds an authored displacement vector in the chosen local frame. Returns owned geometry; callback coordinates are local and t is normalized along the interval.",
- example: "const rippled = displace(surface, ([x,y,z]) => [0, 0.1*Math.sin(x*8), 0]);"
- },
- {
- name: "sweepProfile",
- signature: "sweepProfile(profile: [x,z][], path: [x,y,z][], opts?: { cap?: true, closed?: false, up?: [x,y,z], twist?: 0, scale?: number | [x,z][] })",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Sweeps a simple noncircular profile along polyline stations using transported frames. Supports total twist in degrees and per-station scales. Generates UVs and optional caps.",
- promptNotes: "First version supports one simple profile without holes. Closed paths omit the repeated endpoint and require twist to be a multiple of 360. up sets the initial profile +Z direction and cannot parallel the path. Tight-turn warnings do not replace visual inspection for self-intersections.",
- example: "const rail = sweepProfile([[-.1,-.2],[.1,-.2],[.1,.2],[-.1,.2]], [[0,0,0],[0,1,0],[1,2,0]]);"
- },
- {
- name: "loftProfiles",
- signature: "loftProfiles(sections: { profile: [x,z][], frame?: { origin, rotation } }[], opts?: { cap?: true })",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Joins corresponding simple profiles in explicit local XZ planes. Each frame uses Euler XYZ degrees and local +Y along the loft. Profiles need equal point counts and corresponding vertices.",
- promptNotes: "No holes or automatic profile correspondence. Opposite winding is normalized while preserving the first point. Caps close boundaries but do not prove the loft has no self-intersections.",
- example: "const hull = loftProfiles([{ profile: wide }, { profile: narrow, frame: { origin: [0,2,0] } }]);"
- },
- {
- name: "implicitSurface",
- signature: "await implicitSurface(sample: ([x,y,z]) => signedValue, { bounds: { min, max }, edgeLength, maxCells?: 1000000, maxEvaluations?: 8000000, level?: 0, tolerance?: -1, smooth?: true })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "geometry",
- description: "Experimental positive-inside implicit field sampled into a solid mesh. Requires explicit bounds and resolution; checks grid size and actual evaluation count. Output has no UVs.",
- promptNotes: "Use async build and await. Smaller edgeLength increases cost sharply. This helper cannot stop a callback that never returns; the host evaluator process provides that boundary. Thin features and geometric accuracy require inspection.",
- example: "const blob = await implicitSurface(([x,y,z]) => 1-Math.hypot(x,y,z), { bounds: { min: [-1.2,-1.2,-1.2], max: [1.2,1.2,1.2] }, edgeLength: 0.15 });"
- }
- ];
-});
-
-// src/list-primitives.ts
-function listPrimitives() {
- return PRIMITIVES.map((p) => ({ ...p }));
-}
-var PRIMITIVES;
-var init_list_primitives = __esm(() => {
- init_geometry_catalog();
- PRIMITIVES = [
- ...geometryPrimitives,
- {
- name: "createRoot",
- signature: "createRoot(name: string)",
- returns: "THREE.Object3D",
- category: "structure",
- description: "Creates the root Object3D for an asset. Call first in build().",
- example: "const root = createRoot('FuelDrum');"
- },
- {
- name: "createPivot",
- signature: "createPivot(name: string, position?: [x, y, z], parent?: Object3D)",
- returns: "THREE.Object3D (prefixed `Joint_`)",
- category: "structure",
- description: "Creates an empty pivot node for skeletal animation. Name is auto-prefixed with `Joint_`.",
- example: "const hip = createPivot('Hip', [0, 1, 0], root);"
- },
- {
- name: "createJointChain",
- signature: "createJointChain(name, segments: { role, offset, aliases?, side?, localForwardAxis?, localBendAxis?, endEffector?, contact? }[], opts?: { parent?, parentRole? })",
- returns: "{ root, end, nodes, byRole, descriptors }",
- category: "structure",
- description: "Creates one body-plan-neutral deterministic Joint_* chain with explicit parent edges, rest frames, local axes, end effectors, contacts, and semantic metadata.",
- example: "const leg = createJointChain('LegL', [{ role: 'hip.left', offset: [0, 1, -0.2], side: 'left' }, { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' }, { role: 'ankle.left', offset: [0, -0.5, 0], side: 'left', endEffector: true, contact: true }], { parent: root });",
- promptNotes: "Use only the resolved body-plan graph. Offsets are local to the previous joint; contact end effectors must land at world Y=0."
- },
- {
- name: "createVehicleFrame",
- signature: "createVehicleFrame(name, opts?: { chassis?, axles?, seats?, contacts?, steering?, propulsion?, parent? })",
- returns: "{ root, chassis, axles, seats, contacts, steering, propulsion }",
- category: "structure",
- description: "Creates a canonical +X-forward/+Y-up/+Z-right vehicle frame with typed semantic sockets for chassis, support, steering, and propulsion.",
- example: "const frame = createVehicleFrame('CarFrame', { axles: [{ id: 'front', position: [1.2, 0.45, 0] }, { id: 'rear', position: [-1.2, 0.45, 0] }], parent: root });",
- promptNotes: "Generated vehicles keep +X as front. Boats and other non-wheeled subtypes use declared support/propulsion sockets, not wheel rules."
- },
- {
- name: "createWheelGeometrySet",
- signature: "createWheelGeometrySet(radius: number, width: number)",
- returns: "{ tire, rim, hub } shared THREE.BufferGeometry set",
- category: "instancing",
- description: "Creates one reusable +Z-axle tire/rim/hub geometry set for instanced wheel assemblies.",
- example: "const wheelGeo = createWheelGeometrySet(0.45, 0.22);"
- },
- {
- name: "createWheelAssembly",
- signature: "createWheelAssembly(name, { tire, rim, hub? }, { radius, width, side, index, position?, rimRadius?, hubRadius?, steering?, loadBearing?, geometries?, parent? })",
- returns: "{ root, steeringPivot?, spinPivot, tire, rim, hub, contact, radius, width, side, index, spinAxis }",
- category: "structure",
- description: "Creates one axle-centered wheel pivot containing concentric tire/rim/hub roles, a contact marker, +Z spin frame, and optional steering pivot.",
- example: "createWheelAssembly('FrontLeft', { tire: rubber, rim: metal }, { radius: 0.45, width: 0.22, side: 'left', index: 'front', position: [1.2, 0.45, -0.9], steering: true, geometries: wheelGeo, parent: frame.root });",
- promptNotes: "Keep tire, rim, and hub descendants concentric at the axle pivot. Reuse one geometry set across matching wheels."
+ {
+ name: "createWheelAssembly",
+ signature: "createWheelAssembly(name, { tire, rim, hub? }, { radius, width, side, index, position?, rimRadius?, hubRadius?, steering?, loadBearing?, geometries?, parent? })",
+ returns: "{ root, steeringPivot?, spinPivot, tire, rim, hub, contact, radius, width, side, index, spinAxis }",
+ category: "structure",
+ description: "Creates one axle-centered wheel pivot containing concentric tire/rim/hub roles, a contact marker, +Z spin frame, and optional steering pivot.",
+ example: "createWheelAssembly('FrontLeft', { tire: rubber, rim: metal }, { radius: 0.45, width: 0.22, side: 'left', index: 'front', position: [1.2, 0.45, -0.9], steering: true, geometries: wheelGeo, parent: frame.root });",
+ promptNotes: "Keep tire, rim, and hub descendants concentric at the axle pivot. Reuse one geometry set across matching wheels."
},
{
name: "createPart",
@@ -27147,332 +18559,9023 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`
example: "return [bobbingAnimation('Joint_Root', 1.5, 0.08)];"
},
{
- name: "spinAnimation",
- signature: "spinAnimation(jointName: string, duration?: 2, axis?: 'x' | 'y' | 'z')",
- returns: "THREE.AnimationClip",
- category: "animation",
- description: "360° rotation over `duration` around `axis`.",
- example: "return [spinAnimation('Joint_Rotor', 0.5, 'y')];"
+ name: "spinAnimation",
+ signature: "spinAnimation(jointName: string, duration?: 2, axis?: 'x' | 'y' | 'z')",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "360° rotation over `duration` around `axis`.",
+ example: "return [spinAnimation('Joint_Rotor', 0.5, 'y')];"
+ },
+ {
+ name: "cloneGeometry",
+ signature: "cloneGeometry(geo: BufferGeometry)",
+ returns: "THREE.BufferGeometry (same ref)",
+ category: "instancing",
+ description: "Deprecated name: returns the SAME geometry, without copying. Use copyGeometry for independent vertex edits, or pass the original geometry directly for intentional sharing.",
+ example: "const wheelGeo = cylinderGeo(0.4, 0.4, 0.2, 12);"
+ },
+ {
+ name: "cloneMaterial",
+ signature: "cloneMaterial(mat: Material)",
+ returns: "THREE.Material (same ref)",
+ category: "instancing",
+ description: "Deprecated name: returns the SAME material. Use copyMaterial for independent property edits, or pass the original for intentional sharing.",
+ example: "const rubberMat = gameMaterial(0x1a1a1a, { roughness: 0.95 });"
+ },
+ {
+ name: "createInstance",
+ signature: "createInstance(name, source, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, parent })",
+ returns: "THREE.Object3D",
+ category: "instancing",
+ description: "Creates a new mesh reusing an existing part's geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows. `rotation` is in DEGREES, like createPart.",
+ example: `const wheelFL = createPart('WheelFL', wheelGeo, rubberMat, { position: [-0.8, 0.3, 1.2], parent: root });
+createInstance('WheelFR', wheelFL, { position: [0.8, 0.3, 1.2], parent: root });
+createInstance('WheelRL', wheelFL, { position: [-0.8, 0.3, -1.2], parent: root });
+createInstance('WheelRR', wheelFL, { position: [0.8, 0.3, -1.2], parent: root });`
+ },
+ {
+ name: "boolUnion",
+ signature: "await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Merges two or more parts into one watertight manifold mesh. Default flat shading (hard edges) — pass { smooth: true } as last arg for averaged normals on organic merges.",
+ example: `const body = new THREE.Mesh(boxGeo(2, 1, 1), steel);
+const turret = new THREE.Mesh(cylinderGeo(0.3, 0.3, 0.4, 16), steel);
+turret.position.y = 0.5;
+const hull = await boolUnion('Hull', body, turret);`
+ },
+ {
+ name: "boolDiff",
+ signature: "await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Subtracts cutters from a body (holes, button recesses, window slots). Default flat shading for sharp mechanical edges.",
+ example: `const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel);
+const teeth = [...]; // 8 radially-arrayed box meshes
+const gear = await boolDiff('Gear', body, ...teeth); // hard-edged`
+ },
+ {
+ name: "roundedBoxGeo",
+ signature: "await roundedBoxGeo(width: number, height: number, depth: number, radius: number, opts?: { style?: 'round' | 'chamfer', segments?: 12, smooth?: boolean })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "csg",
+ description: "A box with all twelve edges rounded (or chamfered) at the EXACT outer size requested — roundedBoxGeo(1, 1, 1, 0.1) measures 1x1x1, it does not grow. Use it anywhere boxGeo reads too sharp: consoles, crates, appliances, handheld props, machined blocks.",
+ promptNotes: "Real objects almost never have perfectly sharp box edges, and a small radius is the single cheapest upgrade to how manufactured an asset looks. Prefer this over boxGeo for anything moulded, cast, or machined. Keep radius small relative to the box (5-10% of the smallest dimension); radius must be less than half the smallest dimension or the call throws. style: 'chamfer' reads as machined metal, 'round' as moulded plastic. This is async — build() must be async and the call must use await.",
+ example: `const geo = await roundedBoxGeo(1.2, 0.6, 0.8, 0.05);
+createPart('Console', geo, plastic, { position: [0, 0.3, 0], parent: root });`
+ },
+ {
+ name: "extrudeProfile",
+ signature: "await extrudeProfile(profile: [number, number][], opts?: { depth?: 1, holes?: [number, number][][], bevel?: 0, bevelStyle?: 'round' | 'chamfer', segments?: 12, twist?: 0, taper?: number | [number, number], divisions?: number, axis?: 'x' | 'y' | 'z', center?: true, smooth?: false })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "csg",
+ description: "Sweeps a closed 2D outline into a watertight solid, with optional holes, corner rounding/chamfering, twist, and taper. The way to build any cross-section that is not a box or a cylinder: L-brackets, I-beams, gaskets, washers, star and gear plates, signage, extruded trim.",
+ promptNotes: "The bevel rounds the edges PARALLEL to the sweep axis (the profile corners) — the two flat caps stay sharp. For a box rounded on all twelve edges use roundedBoxGeo instead. Holes are subtracted, so their winding order does not matter. A bevel larger than half the outline's narrowest feature throws rather than silently returning an empty solid. Output is manifold, so it feeds straight into boolUnion / boolDiff / boolIntersect. Async — await it inside an async build().",
+ example: `// L-bracket, inner AND outer corners filleted
+const outline = [[0, 0], [2, 0], [2, 0.4], [0.4, 0.4], [0.4, 2], [0, 2]];
+const geo = await extrudeProfile(outline, { depth: 0.5, bevel: 0.06 });
+createPart('Bracket', geo, steel, { parent: root });`
+ },
+ {
+ name: "revolveProfile",
+ signature: "await revolveProfile(profile: [number, number][], opts?: { segments?: 24, angle?: 360, bevel?: 0, bevelStyle?: 'round' | 'chamfer', bevelSegments?: 12, axis?: 'x' | 'y' | 'z', smooth?: true })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "csg",
+ description: "Revolves a closed 2D outline around an axis into a watertight SOLID, optionally rounding the profile corners first. Bottles, tanks, pressure vessels, wheels, turned wood, domes, buttons, pills.",
+ promptNotes: "Use this instead of lathe/revolveGeo whenever the result must survive a boolean or needs a rounded rim — lathe and revolveGeo build an open surface, this builds a closed solid. Profile convention matches lathe: x is distance from the axis, y is position along it, and only the x >= 0 side is used. Async — await it inside an async build().",
+ example: `// capsule tank with a rounded rim, then carve a port into it
+const profile = [[0, -0.5], [0.4, -0.5], [0.4, 0.5], [0, 0.5]];
+const body = await revolveProfile(profile, { bevel: 0.08, segments: 32 });
+const tank = await boolDiff('Tank', createPart('B', body, steel), portCutter);`
+ },
+ {
+ name: "circleProfile",
+ signature: "circleProfile(radius: number, segments?: 24, center?: [number, number])",
+ returns: "[number, number][]",
+ category: "csg",
+ description: "Builds a closed circular outline for extrudeProfile / revolveProfile, so you never hand-write the trigonometry. Synchronous.",
+ example: `const washer = await extrudeProfile(circleProfile(1), {
+ depth: 0.1,
+ holes: [circleProfile(0.4), circleProfile(0.1, 16, [0.7, 0])],
+});`
+ },
+ {
+ name: "boolIntersect",
+ signature: "await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Keeps only the volume where both operands overlap. Default flat shading.",
+ example: "const lens = await boolIntersect('Lens', boxMesh, sphereMesh);"
+ },
+ {
+ name: "hull",
+ signature: "await hull(name: string, ...parts: Object3D[], opts?: { smooth?: true })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Tightest convex mesh enclosing all input points. Default smooth shading (rocks, collision volumes). Pass { smooth: false } for a faceted look.",
+ example: `const rockChunks = [...]; // scattered box meshes
+const rock = await hull('Rock', ...rockChunks);`
+ },
+ {
+ name: "arrayLinear",
+ signature: "arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)",
+ returns: "THREE.Object3D[]",
+ category: "arrays",
+ description: "Places N copies of `source` along a constant offset vector. Copies share geometry + material via createInstance.",
+ example: `const post = createPart('Post0', cylinderGeo(0.05,0.05,1.5,6), wood, { position: [0,0.75,0], parent: root });
+arrayLinear('Post', post, 10, [0.5, 0, 0], root);`
+ },
+ {
+ name: "arrayRadial",
+ signature: "arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?)",
+ returns: "THREE.Object3D[]",
+ category: "arrays",
+ description: "Places N copies of `source` around the given axis. Source's local rotation is oriented outward. Perfect for gear teeth, radial bolts, circle of columns.",
+ example: `const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });
+arrayRadial('Bolt', bolt, 8, 'y', root);`
+ },
+ {
+ name: "mirror",
+ signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",
+ returns: "THREE.Object3D",
+ category: "arrays",
+ description: "Reflects source across the plane whose normal is `axis`. Uses negative scale (winding flip handled by viewers).",
+ example: "mirror('WingR', wingL, 'x', root);"
+ },
+ {
+ name: "subdivide",
+ signature: "subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { preserveUV?: boolean, split?: boolean, uvSmooth?: boolean, preserveEdges?: boolean, flatOnly?: boolean, weld?: boolean })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Loop subdivision returns new geometry; each iteration roughly quadruples triangles and smooths the surface. Use preserveUV:true for textured meshes. Legacy position-only welding discards UVs and reports that loss. This smooths shapes, not selected-edge beveling.",
+ example: "const smoothRock = subdivide(boxGeo(1, 1, 1), 2);"
+ },
+ {
+ name: "mergeVertices",
+ signature: "mergeVertices(geometry: BufferGeometry, opts?: { tolerance?: 1e-4, positionOnly?: boolean } | number)",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Returns indexed geometry. Default welding preserves attribute seams, so a textured cube retains separate face corners. positionOnly:true welds coincident positions and discards other attributes; use it explicitly when changing topology and regenerate shading/UVs afterward.",
+ example: `const welded = mergeVertices(boxGeo(1, 1, 1), { positionOnly: true });
+const rock = displace(subdivide(welded, 2), ([x,y,z]) => [0.08*Math.sin(y*7+z*3), 0.04*Math.sin(x*9), 0]);`
+ },
+ {
+ name: "curveToMesh",
+ signature: "curveToMesh(points: [x,y,z][], radius, tubularSegs?: 32, radialSegs?: 8, closed?: false)",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Sweeps a circular profile along a path. Equivalent to Blender's Curve to Mesh node with a circle profile. Use for pipes, cables, tubular frames.",
+ example: "const pipe = curveToMesh([[0,0,0],[0,1,0],[1,1,0],[1,2,0]], 0.1);"
+ },
+ {
+ name: "pipeAlongPath",
+ signature: "pipeAlongPath(points: [x,y,z][], radius: number, opts?: { bendRadius?: 0, closed?: false, tubularSegments?: 32, radialSegments?: 8 })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Path-driven swept circle with optional bend smoothing. Generalises beamBetween (point-to-point) and curveToMesh (raw spline) into one helper. bendRadius>0 inserts interpolated waypoints near interior corners so the spline reads as a rounded turn instead of pinching to the control point.",
+ example: "const cable = pipeAlongPath([[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]], 0.02, { bendRadius: 0.1 });"
+ },
+ {
+ name: "lathe",
+ signature: "lathe(profile: [x,y][], segments?: 12)",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Surface of revolution. Spins a 2D profile around the Y axis. For bottles, vases, wheels, turned wood parts.",
+ example: "const vase = lathe([[0.1,0],[0.3,0.5],[0.2,1],[0.1,1.2]], 16);"
+ },
+ {
+ name: "revolveGeo",
+ signature: "revolveGeo(profile: [x,y][], opts?: { angle?: 2π, axis?: [x,y,z]=[0,1,0], segments?: 12 })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Surface of revolution with explicit axis + sweep angle. Generalises lathe — use it when you need a partial sweep (half-dome, 90° wedge) or revolution around a non-Y axis. Profile convention is identical to lathe: x = radial distance, y = position along the axis.",
+ example: `// Half-dome (180° sweep around +Y):
+const quarter = [...Array(8)].map((_, i) => { const t = (i/7)*Math.PI/2; return [Math.cos(t), Math.sin(t)] as [number, number]; });
+const dome = revolveGeo(quarter, { angle: Math.PI });`
+ },
+ {
+ name: "bezierCurve",
+ signature: "bezierCurve(controlPoints: [x,y,z][], samples?: 32)",
+ returns: "[x,y,z][]",
+ category: "curves",
+ description: "Samples a quadratic (3 ctrl pts) or cubic (4 ctrl pts) Bézier into a point list you can feed into curveToMesh.",
+ example: `const path = bezierCurve([[0,0,0],[1,2,0],[3,2,0],[4,0,0]], 24);
+const geo = curveToMesh(path, 0.1);`
+ },
+ {
+ name: "autoUnwrap",
+ signature: "await autoUnwrap(geometry: BufferGeometry, opts?: { resolution?: 1024, padding?: 2, useNormals?: false })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "uv",
+ description: "xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware unwraps below.",
+ example: `const unwrapped = await autoUnwrap(someCsgResult, { resolution: 1024 });
+const mesh = new THREE.Mesh(unwrapped, bakedPbr);`
+ },
+ {
+ name: "boxUnwrap",
+ signature: "boxUnwrap(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Preserves BoxGeometry's built-in per-face UVs — every face maps [0,1] with consistent orientation. Use for crates/blocks with a tileable texture. Sync; no WASM cost.",
+ example: `const crate = boxUnwrap(boxGeo(1, 1, 1));
+const mesh = new THREE.Mesh(crate, pbrMaterial({ albedo: planksTex }));`
},
{
- name: "cloneGeometry",
- signature: "cloneGeometry(geo: BufferGeometry)",
- returns: "THREE.BufferGeometry (same ref)",
- category: "instancing",
- description: "Deprecated name: returns the SAME geometry, without copying. Use copyGeometry for independent vertex edits, or pass the original geometry directly for intentional sharing.",
- example: "const wheelGeo = cylinderGeo(0.4, 0.4, 0.2, 12);"
+ name: "cylinderUnwrap",
+ signature: "cylinderUnwrap(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Preserves CylinderGeometry's built-in UVs: u wraps around the axis (horizontal texture features ring the cylinder), v runs up the height. Caps use circle-in-square. Sync; no WASM cost.",
+ example: `const barrel = cylinderUnwrap(cylinderGeo(0.5, 0.5, 1.2, 24));
+const mesh = new THREE.Mesh(barrel, pbrMaterial({ albedo: bandsTex }));`
},
{
- name: "cloneMaterial",
- signature: "cloneMaterial(mat: Material)",
- returns: "THREE.Material (same ref)",
- category: "instancing",
- description: "Deprecated name: returns the SAME material. Use copyMaterial for independent property edits, or pass the original for intentional sharing.",
- example: "const rubberMat = gameMaterial(0x1a1a1a, { roughness: 0.95 });"
+ name: "planeUnwrap",
+ signature: "planeUnwrap(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Projects xy-extent of the bbox to [0,1]. Use for signs/decals/posters where you want ONE readable texture and no edge-face bleeding. Sync.",
+ example: `const sign = planeUnwrap(planeGeo(1, 0.6));
+const mesh = new THREE.Mesh(sign, pbrMaterial({ albedo: kilnTextTex }));`
},
{
- name: "createInstance",
- signature: "createInstance(name, source, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, parent })",
- returns: "THREE.Object3D",
- category: "instancing",
- description: "Creates a new mesh reusing an existing part's geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows. `rotation` is in DEGREES, like createPart.",
- example: `const wheelFL = createPart('WheelFL', wheelGeo, rubberMat, { position: [-0.8, 0.3, 1.2], parent: root });
-createInstance('WheelFR', wheelFL, { position: [0.8, 0.3, 1.2], parent: root });
-createInstance('WheelRL', wheelFL, { position: [-0.8, 0.3, -1.2], parent: root });
-createInstance('WheelRR', wheelFL, { position: [0.8, 0.3, -1.2], parent: root });`
+ name: "panelRemapV",
+ signature: "panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Scales an existing UV attribute so a small mesh samples a sub-region of a SHARED texture. Replaces the broken texture.clone() pattern (Three.js Texture.clone() runs JSON.stringify on userData, mangling encoded PNG bytes — panelRemapV avoids that by remapping UVs on the geometry instead). Typical use: multi-zone albedo where v=0..0.30 is plain panel and v=0.30..1 has windows/markings — small parts call panelRemapV(unwrap(geo), 0.30) to sample only the clean strip.",
+ example: `const cowlGeo = panelRemapV(cylinderUnwrap(capsuleXGeo(0.45, 1.0)), 0.30);
+const cowl = new THREE.Mesh(cowlGeo, bodyMat); // SAME bodyMat as fuselage, no clone needed`
},
{
- name: "boolUnion",
- signature: "await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
- returns: "Promise<THREE.Mesh>",
- category: "csg",
- description: "Merges two or more parts into one watertight manifold mesh. Default flat shading (hard edges) — pass { smooth: true } as last arg for averaged normals on organic merges.",
- example: `const body = new THREE.Mesh(boxGeo(2, 1, 1), steel);
-const turret = new THREE.Mesh(cylinderGeo(0.3, 0.3, 0.4, 16), steel);
-turret.position.y = 0.5;
-const hull = await boolUnion('Hull', body, turret);`
+ name: "loadApprovedTexture",
+ signature: "await loadApprovedTexture(resourceId)",
+ returns: "Promise<THREE.DataTexture>",
+ category: "textures",
+ description: "Loads one approved kiln.texture.* resource ID through the host-injected closed resolver. The registry fixes bytes, MIME, usage, dimensions, hash, and deadline; paths, URLs, byte arrays, resolver objects, hashes, and options are rejected.",
+ example: "const bark = await loadApprovedTexture('kiln.texture.bark-brown-01-albedo.v1');",
+ promptNotes: "Use only a concrete resource ID listed in material capabilities; never invent one. Prefer materialRecipe when a recipe already binds the family, or proceduralTexture V2 for authored surfaces. NEVER texture.clone() a loaded texture (clone() corrupts encoded bytes and breaks GLB export)."
},
{
- name: "boolDiff",
- signature: "await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
- returns: "Promise<THREE.Mesh>",
- category: "csg",
- description: "Subtracts cutters from a body (holes, button recesses, window slots). Default flat shading for sharp mechanical edges.",
- example: `const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel);
-const teeth = [...]; // 8 radially-arrayed box meshes
-const gear = await boolDiff('Gear', body, ...teeth); // hard-edged`
+ name: "proceduralTexture",
+ signature: "proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })",
+ returns: "THREE.DataTexture (tiling, sRGB or linear per usage)",
+ category: "textures",
+ description: "Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.",
+ example: "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",
+ promptNotes: "Sync — no await. Strict V2 JSON boundary: unknown/prototype keys, callbacks, paths, URLs, and shader source are rejected. Prefer this over approved resources for describable surfaces. Max 8 layers, power-of-two size up to 1024. Only the six listed ops exist."
},
{
- name: "roundedBoxGeo",
- signature: "await roundedBoxGeo(width: number, height: number, depth: number, radius: number, opts?: { style?: 'round' | 'chamfer', segments?: 12, smooth?: boolean })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "csg",
- description: "A box with all twelve edges rounded (or chamfered) at the EXACT outer size requested — roundedBoxGeo(1, 1, 1, 0.1) measures 1x1x1, it does not grow. Use it anywhere boxGeo reads too sharp: consoles, crates, appliances, handheld props, machined blocks.",
- promptNotes: "Real objects almost never have perfectly sharp box edges, and a small radius is the single cheapest upgrade to how manufactured an asset looks. Prefer this over boxGeo for anything moulded, cast, or machined. Keep radius small relative to the box (5-10% of the smallest dimension); radius must be less than half the smallest dimension or the call throws. style: 'chamfer' reads as machined metal, 'round' as moulded plastic. This is async — build() must be async and the call must use await.",
- example: `const geo = await roundedBoxGeo(1.2, 0.6, 0.8, 0.05);
-createPart('Console', geo, plastic, { position: [0, 0.3, 0], parent: root });`
+ name: "normalMapFromHeight",
+ signature: "normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })",
+ returns: "THREE.DataTexture (linear normal map)",
+ category: "textures",
+ description: "Derives a tangent-space normal map from the source texture's brightness, treating it as height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at the edges, so a tiling source gives a tiling normal map.",
+ example: `const bark = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] });
+const mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });`,
+ promptNotes: "strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always linear data — never assign it to an albedo/emissive slot."
},
{
- name: "extrudeProfile",
- signature: "await extrudeProfile(profile: [number, number][], opts?: { depth?: 1, holes?: [number, number][][], bevel?: 0, bevelStyle?: 'round' | 'chamfer', segments?: 12, twist?: 0, taper?: number | [number, number], divisions?: number, axis?: 'x' | 'y' | 'z', center?: true, smooth?: false })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "csg",
- description: "Sweeps a closed 2D outline into a watertight solid, with optional holes, corner rounding/chamfering, twist, and taper. The way to build any cross-section that is not a box or a cylinder: L-brackets, I-beams, gaskets, washers, star and gear plates, signage, extruded trim.",
- promptNotes: "The bevel rounds the edges PARALLEL to the sweep axis (the profile corners) — the two flat caps stay sharp. For a box rounded on all twelve edges use roundedBoxGeo instead. Holes are subtracted, so their winding order does not matter. A bevel larger than half the outline's narrowest feature throws rather than silently returning an empty solid. Output is manifold, so it feeds straight into boolUnion / boolDiff / boolIntersect. Async — await it inside an async build().",
- example: `// L-bracket, inner AND outer corners filleted
-const outline = [[0, 0], [2, 0], [2, 0.4], [0.4, 0.4], [0.4, 2], [0, 2]];
-const geo = await extrudeProfile(outline, { depth: 0.5, bevel: 0.06 });
-createPart('Bracket', geo, steel, { parent: root });`
+ name: "pbrMaterial",
+ signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, aoMap?, alphaMode?, alphaCutoff?, doubleSided? })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. Supports OPAQUE/MASK/BLEND and double-sided output.",
+ example: `const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });
+const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });`
},
{
- name: "revolveProfile",
- signature: "await revolveProfile(profile: [number, number][], opts?: { segments?: 24, angle?: 360, bevel?: 0, bevelStyle?: 'round' | 'chamfer', bevelSegments?: 12, axis?: 'x' | 'y' | 'z', smooth?: true })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "csg",
- description: "Revolves a closed 2D outline around an axis into a watertight SOLID, optionally rounding the profile corners first. Bottles, tanks, pressure vessels, wheels, turned wood, domes, buttons, pills.",
- promptNotes: "Use this instead of lathe/revolveGeo whenever the result must survive a boolean or needs a rounded rim — lathe and revolveGeo build an open surface, this builds a closed solid. Profile convention matches lathe: x is distance from the axis, y is position along it, and only the x >= 0 side is used. Async — await it inside an async build().",
- example: `// capsule tank with a rounded rim, then carve a port into it
-const profile = [[0, -0.5], [0.4, -0.5], [0.4, 0.5], [0, 0.5]];
-const body = await revolveProfile(profile, { bevel: 0.08, segments: 32 });
-const tank = await boolDiff('Tank', createPart('B', body, steel), portCutter);`
+ name: "foliageMaterial",
+ signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",
+ example: "const mat = await materialRecipe('kiln.material.leaf.v1');"
},
{
- name: "circleProfile",
- signature: "circleProfile(radius: number, segments?: 24, center?: [number, number])",
- returns: "[number, number][]",
- category: "csg",
- description: "Builds a closed circular outline for extrudeProfile / revolveProfile, so you never hand-write the trigonometry. Synchronous.",
- example: `const washer = await extrudeProfile(circleProfile(1), {
- depth: 0.1,
- holes: [circleProfile(0.4), circleProfile(0.1, 16, [0.7, 0])],
-});`
+ name: "countTriangles",
+ signature: "countTriangles(root: Object3D)",
+ returns: "number",
+ category: "utility",
+ description: "Sums triangle count across every mesh in the subtree.",
+ example: "meta.tris = countTriangles(root);"
},
{
- name: "boolIntersect",
- signature: "await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })",
- returns: "Promise<THREE.Mesh>",
- category: "csg",
- description: "Keeps only the volume where both operands overlap. Default flat shading.",
- example: "const lens = await boolIntersect('Lens', boxMesh, sphereMesh);"
+ name: "countMaterials",
+ signature: "countMaterials(root: Object3D)",
+ returns: "number",
+ category: "utility",
+ description: "Unique material count (by reference) across the subtree.",
+ example: "const mats = countMaterials(root);"
},
{
- name: "hull",
- signature: "await hull(name: string, ...parts: Object3D[], opts?: { smooth?: true })",
- returns: "Promise<THREE.Mesh>",
- category: "csg",
- description: "Tightest convex mesh enclosing all input points. Default smooth shading (rocks, collision volumes). Pass { smooth: false } for a faceted look.",
- example: `const rockChunks = [...]; // scattered box meshes
-const rock = await hull('Rock', ...rockChunks);`
+ name: "getJointNames",
+ signature: "getJointNames(root: Object3D)",
+ returns: "string[]",
+ category: "utility",
+ description: "All node names beginning with `Joint_`. Use to sanity-check animation targets.",
+ example: "const joints = getJointNames(root);"
},
{
- name: "arrayLinear",
- signature: "arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)",
- returns: "THREE.Object3D[]",
- category: "arrays",
- description: "Places N copies of `source` along a constant offset vector. Copies share geometry + material via createInstance.",
- example: `const post = createPart('Post0', cylinderGeo(0.05,0.05,1.5,6), wood, { position: [0,0.75,0], parent: root });
-arrayLinear('Post', post, 10, [0.5, 0, 0], root);`
+ name: "validateAsset",
+ signature: "validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture' | 'vegetation' | 'vehicle')",
+ returns: "{ valid, errors, warnings }",
+ category: "utility",
+ description: "Checks geometry and material costs for the selected category. No default triangle limit; choose detail for the intended runtime and inspect measured draw calls.",
+ example: "const v = validateAsset(root, 'prop');"
+ }
+ ];
+});
+
+// src/validation.ts
+import * as acorn from "acorn";
+import * as walk from "acorn-walk";
+function estimateGeometryTris(name, args) {
+ function asNum(node) {
+ if (!node)
+ return null;
+ if (node.type === "Literal" && typeof node.value === "number")
+ return node.value;
+ if (node.type === "UnaryExpression" && node.operator === "-") {
+ const inner = asNum(node.argument);
+ return inner === null ? null : -inner;
+ }
+ return null;
+ }
+ function asObjNum(node, prop) {
+ if (!node || node.type !== "ObjectExpression")
+ return null;
+ for (const p of node.properties) {
+ if (p.type === "Property" && !p.computed && (p.key.type === "Identifier" && p.key.name === prop || p.key.type === "Literal" && p.key.value === prop)) {
+ return asNum(p.value);
+ }
+ }
+ return null;
+ }
+ switch (name) {
+ case "boxGeo":
+ case "decalBox":
+ return 12;
+ case "planeGeo": {
+ const ws = asNum(args[2]) ?? 1;
+ const hs = asNum(args[3]) ?? 1;
+ return Math.max(1, ws * hs) * 2;
+ }
+ case "coneGeo":
+ case "coneXGeo":
+ case "coneYGeo":
+ case "coneZGeo": {
+ const segs = asNum(args[2]) ?? 8;
+ return segs * 2;
+ }
+ case "cylinderGeo":
+ case "cylinderXGeo":
+ case "cylinderYGeo":
+ case "cylinderZGeo": {
+ const segs = asNum(args[3]) ?? 8;
+ return segs * 4;
+ }
+ case "taperConeGeo": {
+ const segs = asNum(args[4]) ?? 8;
+ return segs * 4;
+ }
+ case "sphereGeo": {
+ const w = asNum(args[1]) ?? 8;
+ const h = asNum(args[2]) ?? 6;
+ return w * h * 2;
+ }
+ case "capsuleGeo":
+ case "capsuleXGeo":
+ case "capsuleYGeo":
+ case "capsuleZGeo": {
+ const segs = asNum(args[2]) ?? 6;
+ return segs * 8;
+ }
+ case "torusGeo": {
+ const rad = asNum(args[2]) ?? 8;
+ const tub = asNum(args[3]) ?? 12;
+ return rad * tub * 2;
+ }
+ case "gearGeo": {
+ const teeth = asObjNum(args[0], "teeth") ?? 12;
+ return teeth * 32;
+ }
+ case "bladeGeo":
+ return 36;
+ case "wingGeo":
+ return 24;
+ default:
+ return null;
+ }
+}
+function validate(code, _opts = {}) {
+ const issues = [];
+ const warnings = [];
+ if (!code || typeof code !== "string" || code.trim().length === 0) {
+ issues.push({
+ code: "EMPTY_CODE",
+ message: "Empty or missing code",
+ fixHint: "Provide a non-empty code string from the code generator."
+ });
+ return toResult(issues, warnings);
+ }
+ const normalized = code.replace(/\r\n/g, `
+`);
+ if (/^\s*import\s+/m.test(normalized)) {
+ issues.push({
+ code: "HAS_IMPORT",
+ message: "Contains import statements — code must use sandbox globals only",
+ fixHint: "Remove all `import` lines; primitives like boxGeo are already in scope.",
+ line: findLineOf(normalized, /^\s*import\s+/m)
+ });
+ }
+ if (/^\s*export\s+/m.test(normalized)) {
+ issues.push({
+ code: "HAS_EXPORT",
+ message: "Contains export statements — just define meta, build, animate",
+ fixHint: "Remove `export` keywords; the sandbox evaluator picks up `meta` and `build` by name.",
+ line: findLineOf(normalized, /^\s*export\s+/m)
+ });
+ }
+ const valueMatch = /\{\s*time:\s*[^,]+,\s*value:\s*\[/.exec(normalized);
+ if (valueMatch) {
+ issues.push({
+ code: "KEYFRAME_VALUE_KEY",
+ message: "Uses `value:` in keyframes — must use `rotation:` or `position:` instead",
+ fixHint: "In every `{ time, value: [...] }` change `value:` to `rotation:` (degrees) or `position:`.",
+ line: lineOfIndex(normalized, valueMatch.index)
+ });
+ }
+ let ast;
+ try {
+ ast = acorn.parse(normalized, {
+ ecmaVersion: 2022,
+ sourceType: "script",
+ allowReturnOutsideFunction: false,
+ locations: true
+ });
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ const locMatch = /\((\d+):\d+\)/.exec(msg);
+ issues.push({
+ code: "SYNTAX_ERROR",
+ message: `Syntax error: ${msg}`,
+ fixHint: "Fix the syntax error at the reported line/column.",
+ line: locMatch ? Number(locMatch[1]) : undefined
+ });
+ return toResult(issues, warnings);
+ }
+ issues.push(...analyzeGeneratedSourceSafety(ast));
+ const structure = analyzeTopLevel(ast);
+ if (!structure.hasMetaConst) {
+ issues.push({
+ code: "MISSING_META",
+ message: "Missing `const meta = { ... }` declaration at top level",
+ fixHint: 'Add `const meta = { name: "YourAsset" };` at the top of the file.'
+ });
+ } else if (!structure.metaHasName) {
+ warnings.push({
+ code: "META_MISSING_NAME",
+ message: "`meta` object has no `name` property",
+ fixHint: 'Add `name: "YourAsset"` to the meta object.'
+ });
+ }
+ if (!structure.hasBuildFn) {
+ issues.push({
+ code: "MISSING_BUILD",
+ message: "Missing top-level `function build()` declaration",
+ fixHint: 'Add `function build() { const root = createRoot("..."); ...; return root; }` at top level.'
+ });
+ }
+ const analysis = analyzeBody(ast);
+ if (analysis.infiniteLoops.length > 0) {
+ for (const hit of analysis.infiniteLoops) {
+ issues.push({
+ code: "INFINITE_LOOP",
+ message: `${hit.kind} with no break statement`,
+ fixHint: `Add a break/return condition inside the ${hit.kind} loop, or switch to a bounded for/forEach.`,
+ line: hit.line
+ });
+ }
+ }
+ if (analysis.recursiveBuild) {
+ issues.push({
+ code: "RECURSIVE_BUILD",
+ message: "`build()` calls itself — will blow the stack at render time",
+ fixHint: "Refactor the recursive step into a helper function; keep `build()` non-recursive.",
+ line: analysis.recursiveBuild
+ });
+ }
+ for (const smell of analyzeRotationUnits(ast, normalized)) {
+ warnings.push({
+ code: "ROTATION_RADIANS_SUSPECTED",
+ message: `${smell.fn} rotation ${smell.rendered} looks like RADIANS — the rotation option is DEGREES${smell.suggestion ? `; did you mean ${smell.suggestion}?` : ""}`,
+ fixHint: "createPart/createInstance rotation is degrees ([0,0,90] = quarter turn). Convert: deg = rad * 180 / Math.PI. Direct THREE properties (obj.rotation.z) stay radians.",
+ line: smell.line
+ });
+ }
+ warnings.push(...unknownHelperWarnings(ast));
+ return toResult(issues, warnings, analysis.estimatedTris);
+}
+function unknownHelperWarnings(ast) {
+ const declared = new Set;
+ const bind = (node) => {
+ const target = node;
+ if (!target?.type)
+ return;
+ if (target.type === "Identifier")
+ declared.add(target["name"]);
+ else if (target.type === "ObjectPattern")
+ for (const prop of target["properties"])
+ bind(prop.value ?? prop.argument);
+ else if (target.type === "ArrayPattern")
+ for (const el of target["elements"])
+ bind(el);
+ else if (target.type === "AssignmentPattern")
+ bind(target["left"]);
+ else if (target.type === "RestElement")
+ bind(target["argument"]);
+ };
+ const params = (node) => {
+ const fn = node;
+ if (fn.id?.name)
+ declared.add(fn.id.name);
+ for (const param of fn.params ?? [])
+ bind(param);
+ };
+ walk.simple(ast, {
+ VariableDeclarator(node) {
+ bind(node.id);
},
- {
- name: "arrayRadial",
- signature: "arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?)",
- returns: "THREE.Object3D[]",
- category: "arrays",
- description: "Places N copies of `source` around the given axis. Source's local rotation is oriented outward. Perfect for gear teeth, radial bolts, circle of columns.",
- example: `const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });
-arrayRadial('Bolt', bolt, 8, 'y', root);`
+ FunctionDeclaration(node) {
+ params(node);
},
- {
- name: "mirror",
- signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",
- returns: "THREE.Object3D",
- category: "arrays",
- description: "Reflects source across the plane whose normal is `axis`. Uses negative scale (winding flip handled by viewers).",
- example: "mirror('WingR', wingL, 'x', root);"
+ FunctionExpression(node) {
+ params(node);
},
- {
- name: "subdivide",
- signature: "subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { preserveUV?: boolean, split?: boolean, uvSmooth?: boolean, preserveEdges?: boolean, flatOnly?: boolean, weld?: boolean })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Loop subdivision returns new geometry; each iteration roughly quadruples triangles and smooths the surface. Use preserveUV:true for textured meshes. Legacy position-only welding discards UVs and reports that loss. This smooths shapes, not selected-edge beveling.",
- example: "const smoothRock = subdivide(boxGeo(1, 1, 1), 2);"
+ ArrowFunctionExpression(node) {
+ params(node);
},
- {
- name: "mergeVertices",
- signature: "mergeVertices(geometry: BufferGeometry, opts?: { tolerance?: 1e-4, positionOnly?: boolean } | number)",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Returns indexed geometry. Default welding preserves attribute seams, so a textured cube retains separate face corners. positionOnly:true welds coincident positions and discards other attributes; use it explicitly when changing topology and regenerate shading/UVs afterward.",
- example: `const welded = mergeVertices(boxGeo(1, 1, 1), { positionOnly: true });
-const rock = displace(subdivide(welded, 2), ([x,y,z]) => [0.08*Math.sin(y*7+z*3), 0.04*Math.sin(x*9), 0]);`
+ ClassDeclaration(node) {
+ params(node);
},
- {
- name: "curveToMesh",
- signature: "curveToMesh(points: [x,y,z][], radius, tubularSegs?: 32, radialSegs?: 8, closed?: false)",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Sweeps a circular profile along a path. Equivalent to Blender's Curve to Mesh node with a circle profile. Use for pipes, cables, tubular frames.",
- example: "const pipe = curveToMesh([[0,0,0],[0,1,0],[1,1,0],[1,2,0]], 0.1);"
+ CatchClause(node) {
+ bind(node.param);
+ }
+ });
+ const seen = new Map;
+ walk.simple(ast, {
+ CallExpression(node) {
+ const callee = node.callee;
+ if (callee?.type !== "Identifier" || !callee.name)
+ return;
+ const name = callee.name;
+ if (declared.has(name) || SANDBOX_CALLABLES.has(name) || seen.has(name))
+ return;
+ seen.set(name, node.loc?.start?.line);
+ }
+ });
+ return [...seen].map(([name, line]) => ({
+ code: "UNKNOWN_HELPER",
+ message: `${name}() is not declared in this program and is not a Kiln sandbox global; the build will fail when it runs.`,
+ fixHint: "Call kiln_list_primitives to confirm the helper name and signature, or declare the function in this program.",
+ ...line === undefined ? {} : { line }
+ }));
+}
+function assertGeneratedSourceSafe(code) {
+ let ast;
+ try {
+ ast = acorn.parse(code, {
+ ecmaVersion: 2022,
+ sourceType: "script",
+ allowReturnOutsideFunction: false,
+ locations: true
+ });
+ } catch (error) {
+ const line = error && typeof error === "object" && "loc" in error ? error.loc?.line : undefined;
+ throw new GeneratedSourcePolicyError({
+ code: "SYNTAX_ERROR",
+ message: "Generated source has invalid syntax.",
+ line
+ });
+ }
+ const issue = analyzeGeneratedSourceSafety(ast)[0];
+ if (issue)
+ throw new GeneratedSourcePolicyError(issue);
+}
+function issueKey(issue) {
+ return `${issue.code}:${issue.line ?? 0}:${issue.message}`;
+}
+function analyzeGeneratedSourceSafety(ast) {
+ const issues = [];
+ const seen = new Set;
+ const staticStrings = collectStaticStringBindings(ast);
+ const add2 = (issue) => {
+ const key = issueKey(issue);
+ if (seen.has(key))
+ return;
+ seen.add(key);
+ issues.push(issue);
+ };
+ const ambient = (name, line) => add2({
+ code: "UNSAFE_GLOBAL_ACCESS",
+ message: `Generated code cannot access ambient capability \`${name}\`.`,
+ fixHint: "Use only the documented sandbox globals and approved resource helpers.",
+ line
+ });
+ const dynamicCode = (line) => add2({
+ code: "DYNAMIC_CODE_ACCESS",
+ message: "Generated code cannot access constructor chains or dynamic-code constructors.",
+ fixHint: "Call documented sandbox helpers directly; do not derive constructors at runtime.",
+ line
+ });
+ const unsafeThree = (name, line) => add2({
+ code: "UNSAFE_THREE_CONSTRUCTOR",
+ message: `Generated code cannot access raw THREE constructor \`${name}\`.`,
+ fixHint: "Use approved texture loading, proceduralTexture, pbrMaterial, or materialRecipe instead.",
+ line
+ });
+ const unsafeThreeNamespace = (code, line) => add2({
+ code,
+ message: code === "UNSAFE_THREE_ALIAS" ? "Generated code cannot alias the THREE namespace." : "Generated code cannot use non-static computed access on the THREE namespace.",
+ fixHint: "Use a documented direct THREE constructor or a sandbox material/texture helper.",
+ line
+ });
+ walk.ancestor(ast, {
+ Identifier(node, _state, ancestors) {
+ const parent = ancestors.at(-2);
+ if (identifierIsNonReferenceKey(node, parent))
+ return;
+ if (FORBIDDEN_AMBIENT_IDENTIFIERS.has(node.name)) {
+ ambient(node.name, node.loc?.start.line);
+ }
},
- {
- name: "pipeAlongPath",
- signature: "pipeAlongPath(points: [x,y,z][], radius: number, opts?: { bendRadius?: 0, closed?: false, tubularSegments?: 32, radialSegments?: 8 })",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Path-driven swept circle with optional bend smoothing. Generalises beamBetween (point-to-point) and curveToMesh (raw spline) into one helper. bendRadius>0 inserts interpolated waypoints near interior corners so the spline reads as a rounded turn instead of pinching to the control point.",
- example: "const cable = pipeAlongPath([[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]], 0.02, { bendRadius: 0.1 });"
+ ThisExpression(node) {
+ ambient("this", node.loc?.start.line);
},
- {
- name: "lathe",
- signature: "lathe(profile: [x,y][], segments?: 12)",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Surface of revolution. Spins a 2D profile around the Y axis. For bottles, vases, wheels, turned wood parts.",
- example: "const vase = lathe([[0.1,0],[0.3,0.5],[0.2,1],[0.1,1.2]], 16);"
+ ImportExpression(node) {
+ add2({
+ code: "DYNAMIC_IMPORT",
+ message: "Generated code cannot use dynamic import.",
+ fixHint: "Remove import(); all supported helpers are already sandbox globals.",
+ line: node.loc?.start.line
+ });
},
- {
- name: "revolveGeo",
- signature: "revolveGeo(profile: [x,y][], opts?: { angle?: 2π, axis?: [x,y,z]=[0,1,0], segments?: 12 })",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Surface of revolution with explicit axis + sweep angle. Generalises lathe — use it when you need a partial sweep (half-dome, 90° wedge) or revolution around a non-Y axis. Profile convention is identical to lathe: x = radial distance, y = position along the axis.",
- example: `// Half-dome (180° sweep around +Y):
-const quarter = [...Array(8)].map((_, i) => { const t = (i/7)*Math.PI/2; return [Math.cos(t), Math.sin(t)] as [number, number]; });
-const dome = revolveGeo(quarter, { angle: Math.PI });`
+ MemberExpression(node) {
+ const property = staticPropertyName(node, staticStrings);
+ if (property === "constructor")
+ dynamicCode(node.loc?.start.line);
+ if (property && FORBIDDEN_THREE_CONSTRUCTORS.has(property) && expressionReferencesThree(node.object)) {
+ unsafeThree(property, node.loc?.start.line);
+ }
+ if (node.computed && property === undefined && expressionReferencesThree(node.object)) {
+ unsafeThreeNamespace("UNSAFE_THREE_COMPUTED_ACCESS", node.loc?.start.line);
+ }
},
- {
- name: "bezierCurve",
- signature: "bezierCurve(controlPoints: [x,y,z][], samples?: 32)",
- returns: "[x,y,z][]",
- category: "curves",
- description: "Samples a quadratic (3 ctrl pts) or cubic (4 ctrl pts) Bézier into a point list you can feed into curveToMesh.",
- example: `const path = bezierCurve([[0,0,0],[1,2,0],[3,2,0],[4,0,0]], 24);
-const geo = curveToMesh(path, 0.1);`
+ VariableDeclarator(node) {
+ if (node.id.type === "Identifier" && expressionReferencesThree(node.init)) {
+ unsafeThreeNamespace("UNSAFE_THREE_ALIAS", node.loc?.start.line);
+ }
+ if (node.id.type !== "ObjectPattern")
+ return;
+ analyzeObjectPatternSafety(node.id, node.init?.type === "Identifier" && node.init.name === "THREE", staticStrings, dynamicCode, unsafeThree);
},
- {
- name: "autoUnwrap",
- signature: "await autoUnwrap(geometry: BufferGeometry, opts?: { resolution?: 1024, padding?: 2, useNormals?: false })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "uv",
- description: "xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware unwraps below.",
- example: `const unwrapped = await autoUnwrap(someCsgResult, { resolution: 1024 });
-const mesh = new THREE.Mesh(unwrapped, bakedPbr);`
+ AssignmentExpression(node) {
+ if (node.left.type === "Identifier" && expressionReferencesThree(node.right)) {
+ unsafeThreeNamespace("UNSAFE_THREE_ALIAS", node.loc?.start.line);
+ }
+ if (node.left.type !== "ObjectPattern")
+ return;
+ analyzeObjectPatternSafety(node.left, node.right.type === "Identifier" && node.right.name === "THREE", staticStrings, dynamicCode, unsafeThree);
+ },
+ CallExpression(node) {
+ if (node.callee.type !== "MemberExpression" || node.callee.object.type !== "Identifier") {
+ return;
+ }
+ const owner = node.callee.object.name;
+ const method = staticPropertyName(node.callee, staticStrings);
+ if (!(owner === "Reflect" && method === "get" || owner === "Object" && method === "getOwnPropertyDescriptor")) {
+ return;
+ }
+ const property = staticExpressionString(node.arguments[1], staticStrings);
+ if (property === "constructor")
+ dynamicCode(node.loc?.start.line);
+ if (owner === "Reflect" && property && FORBIDDEN_THREE_CONSTRUCTORS.has(property) && expressionReferencesThree(node.arguments[0])) {
+ unsafeThree(property, node.loc?.start.line);
+ }
+ }
+ });
+ return issues;
+}
+function expressionReferencesThree(node) {
+ if (!node || typeof node !== "object")
+ return false;
+ const expression = node;
+ if (expression.type === "Identifier")
+ return expression.name === "THREE";
+ if (expression.type === "ChainExpression")
+ return expressionReferencesThree(expression.expression);
+ if (expression.type === "SequenceExpression") {
+ return expressionReferencesThree(expression.expressions.at(-1));
+ }
+ return false;
+}
+function identifierIsNonReferenceKey(node, parent) {
+ if (!parent)
+ return false;
+ if (parent.type === "MemberExpression") {
+ const member = parent;
+ if (member.property === node && !member.computed)
+ return true;
+ }
+ if (parent.type === "Property") {
+ const property = parent;
+ if (property.key === node && !property.computed && !property.shorthand)
+ return true;
+ }
+ if (parent.type === "MethodDefinition") {
+ const method = parent;
+ if (method.key === node && !method.computed)
+ return true;
+ }
+ if (parent.type === "LabeledStatement") {
+ if (parent.label === node)
+ return true;
+ }
+ if (parent.type === "BreakStatement" || parent.type === "ContinueStatement") {
+ if (parent.label === node)
+ return true;
+ }
+ return false;
+}
+function analyzeObjectPatternSafety(pattern, fromThree, staticStrings, dynamicCode, unsafeThree) {
+ for (const entry of pattern.properties) {
+ if (entry.type !== "Property")
+ continue;
+ const property = !entry.computed && entry.key.type === "Identifier" ? entry.key.name : staticExpressionString(entry.key, staticStrings);
+ if (property === "constructor")
+ dynamicCode(entry.loc?.start.line);
+ if (fromThree && property && FORBIDDEN_THREE_CONSTRUCTORS.has(property)) {
+ unsafeThree(property, entry.loc?.start.line);
+ }
+ }
+}
+function staticPropertyName(node, staticStrings) {
+ if (!node.computed && node.property.type === "Identifier")
+ return node.property.name;
+ return staticExpressionString(node.property, staticStrings);
+}
+function staticExpressionString(node, staticStrings = new Map) {
+ if (!node || typeof node !== "object")
+ return;
+ const expression = node;
+ if (expression.type === "Literal") {
+ return typeof expression.value === "string" || typeof expression.value === "number" ? String(expression.value) : undefined;
+ }
+ if (expression.type === "Identifier")
+ return staticStrings.get(expression.name);
+ if (expression.type === "TemplateLiteral") {
+ let value = expression.quasis[0]?.value.cooked ?? expression.quasis[0]?.value.raw ?? "";
+ for (let index = 0;index < expression.expressions.length; index++) {
+ const part = staticExpressionString(expression.expressions[index], staticStrings);
+ if (part === undefined)
+ return;
+ const quasi = expression.quasis[index + 1];
+ value += part + (quasi?.value.cooked ?? quasi?.value.raw ?? "");
+ }
+ return value;
+ }
+ if (expression.type === "BinaryExpression" && expression.operator === "+") {
+ const left = staticExpressionString(expression.left, staticStrings);
+ const right = staticExpressionString(expression.right, staticStrings);
+ return left === undefined || right === undefined ? undefined : left + right;
+ }
+ return;
+}
+function collectStaticStringBindings(ast) {
+ const candidates = new Map;
+ const duplicateNames = new Set;
+ walk.simple(ast, {
+ VariableDeclaration(node) {
+ if (node.kind !== "const")
+ return;
+ for (const declaration of node.declarations) {
+ if (declaration.id.type !== "Identifier" || !declaration.init)
+ continue;
+ if (candidates.has(declaration.id.name))
+ duplicateNames.add(declaration.id.name);
+ else
+ candidates.set(declaration.id.name, declaration.init);
+ }
+ }
+ });
+ for (const name of duplicateNames)
+ candidates.delete(name);
+ const values = new Map;
+ for (let pass = 0;pass < candidates.size; pass++) {
+ let changed = false;
+ for (const [name, expression] of candidates) {
+ if (values.has(name))
+ continue;
+ const value = staticExpressionString(expression, values);
+ if (value === undefined)
+ continue;
+ values.set(name, value);
+ changed = true;
+ }
+ if (!changed)
+ break;
+ }
+ return values;
+}
+function toResult(issues, warnings, estimatedTris) {
+ return {
+ valid: issues.length === 0,
+ errors: issues.map((i) => i.message),
+ issues,
+ warnings,
+ ...estimatedTris === undefined ? {} : { estimatedTris }
+ };
+}
+function findLineOf(code, re) {
+ const match = re.exec(code);
+ if (!match)
+ return;
+ return lineOfIndex(code, match.index);
+}
+function lineOfIndex(code, idx) {
+ let line = 1;
+ for (let i = 0;i < idx; i++)
+ if (code.charCodeAt(i) === 10)
+ line++;
+ return line;
+}
+function analyzeRotationUnits(ast, source) {
+ const smells = [];
+ walk.simple(ast, {
+ CallExpression(node) {
+ if (node.callee.type !== "Identifier" || !ROTATION_OPTION_FNS.has(node.callee.name))
+ return;
+ const fn = node.callee.name;
+ for (const arg of node.arguments) {
+ if (arg.type !== "ObjectExpression")
+ continue;
+ for (const prop of arg.properties) {
+ if (prop.type !== "Property" || prop.computed)
+ continue;
+ const key = prop.key.type === "Identifier" ? prop.key.name : prop.key.type === "Literal" ? String(prop.key.value) : "";
+ if (key !== "rotation" || prop.value.type !== "ArrayExpression")
+ continue;
+ const smell = classifyRotationArray(prop.value, fn, source);
+ if (smell)
+ smells.push(smell);
+ }
+ }
+ }
+ });
+ return smells;
+}
+function classifyRotationArray(arr, fn, source) {
+ const rendered = () => {
+ const text = source.slice(arr.start, arr.end).replace(/\s+/g, " ");
+ return text.length > 64 ? `${text.slice(0, 61)}...` : text;
+ };
+ let sawPI = false;
+ let onlyConversions = true;
+ for (const el of arr.elements) {
+ if (!el || el.type === "SpreadElement")
+ continue;
+ if (containsMathPI(el)) {
+ sawPI = true;
+ if (!dividesByMathPI(el))
+ onlyConversions = false;
+ }
+ }
+ if (sawPI) {
+ if (onlyConversions)
+ return null;
+ return { fn, rendered: rendered(), line: arr.loc?.start.line };
+ }
+ const nums = [];
+ for (const el of arr.elements) {
+ if (!el || el.type === "SpreadElement")
+ return null;
+ const n = literalNumber(el);
+ if (n === undefined)
+ return null;
+ nums.push(n);
+ }
+ const nonZero = nums.filter((n) => n !== 0);
+ if (nonZero.length === 0)
+ return null;
+ if (!nonZero.every((n) => Math.abs(n) < 6.3))
+ return null;
+ if (!nonZero.some((n) => !Number.isInteger(n)))
+ return null;
+ const deg = nums.map((n) => n === 0 ? 0 : Math.round(n * 180 / Math.PI));
+ return {
+ fn,
+ rendered: rendered(),
+ suggestion: `[${deg.join(", ")}]`,
+ line: arr.loc?.start.line
+ };
+}
+function literalNumber(el) {
+ if (el.type === "Literal" && typeof el.value === "number")
+ return el.value;
+ if (el.type === "UnaryExpression" && el.operator === "-") {
+ const inner = literalNumber(el.argument);
+ return inner === undefined ? undefined : -inner;
+ }
+ return;
+}
+function containsMathPI(node) {
+ if (!node || typeof node !== "object")
+ return false;
+ const n = node;
+ if (n.type === "MemberExpression") {
+ const obj = n["object"];
+ const prop = n["property"];
+ if (obj?.type === "Identifier" && obj.name === "Math" && prop?.type === "Identifier" && prop.name === "PI") {
+ return true;
+ }
+ }
+ for (const key of Object.keys(n)) {
+ if (key === "loc" || key === "start" || key === "end")
+ continue;
+ const v = n[key];
+ if (Array.isArray(v)) {
+ for (const item of v)
+ if (containsMathPI(item))
+ return true;
+ } else if (v && typeof v === "object" && v.type) {
+ if (containsMathPI(v))
+ return true;
+ }
+ }
+ return false;
+}
+function dividesByMathPI(node) {
+ if (!node || typeof node !== "object")
+ return false;
+ const n = node;
+ if (n.type === "BinaryExpression" && n.operator === "/" && containsMathPI(n.right))
+ return true;
+ if (n.type === "BinaryExpression")
+ return dividesByMathPI(n.left) || dividesByMathPI(n.right);
+ if (n.type === "UnaryExpression")
+ return dividesByMathPI(n.argument);
+ return false;
+}
+function analyzeTopLevel(ast) {
+ const out = {
+ hasMetaConst: false,
+ metaHasName: false,
+ hasBuildFn: false,
+ hasAnimateFn: false
+ };
+ for (const stmt of ast.body) {
+ if (stmt.type === "VariableDeclaration" && (stmt.kind === "const" || stmt.kind === "let")) {
+ for (const decl of stmt.declarations) {
+ if (decl.id.type === "Identifier" && decl.id.name === "meta") {
+ out.hasMetaConst = true;
+ if (decl.init && decl.init.type === "ObjectExpression") {
+ out.metaHasName = decl.init.properties.some((p) => p.type === "Property" && !p.computed && (p.key.type === "Identifier" && p.key.name === "name" || p.key.type === "Literal" && p.key.value === "name"));
+ }
+ }
+ }
+ } else if (stmt.type === "FunctionDeclaration" && stmt.id) {
+ if (stmt.id.name === "build")
+ out.hasBuildFn = true;
+ if (stmt.id.name === "animate")
+ out.hasAnimateFn = true;
+ }
+ }
+ return out;
+}
+function analyzeBody(ast) {
+ const infiniteLoops = [];
+ let recursiveBuild;
+ let estimatedTris = 0;
+ const stack = [];
+ walk.ancestor(ast, {
+ FunctionDeclaration(node, _state, ancestors) {
+ if (node.id?.name)
+ stack.push(node.id.name);
},
- {
- name: "boxUnwrap",
- signature: "boxUnwrap(geometry: BufferGeometry)",
- returns: "THREE.BufferGeometry",
- category: "uv",
- description: "Preserves BoxGeometry's built-in per-face UVs — every face maps [0,1] with consistent orientation. Use for crates/blocks with a tileable texture. Sync; no WASM cost.",
- example: `const crate = boxUnwrap(boxGeo(1, 1, 1));
-const mesh = new THREE.Mesh(crate, pbrMaterial({ albedo: planksTex }));`
+ WhileStatement(node) {
+ if (isConstantTruthy(node.test) && !hasBreak(node.body)) {
+ infiniteLoops.push({ kind: "while(true)", line: node.loc?.start.line });
+ }
},
- {
- name: "cylinderUnwrap",
- signature: "cylinderUnwrap(geometry: BufferGeometry)",
- returns: "THREE.BufferGeometry",
- category: "uv",
- description: "Preserves CylinderGeometry's built-in UVs: u wraps around the axis (horizontal texture features ring the cylinder), v runs up the height. Caps use circle-in-square. Sync; no WASM cost.",
- example: `const barrel = cylinderUnwrap(cylinderGeo(0.5, 0.5, 1.2, 24));
-const mesh = new THREE.Mesh(barrel, pbrMaterial({ albedo: bandsTex }));`
+ ForStatement(node) {
+ if (!node.test && !hasBreak(node.body)) {
+ infiniteLoops.push({ kind: "for(;;)", line: node.loc?.start.line });
+ } else if (node.test && isConstantTruthy(node.test) && !hasBreak(node.body)) {
+ infiniteLoops.push({ kind: "for(;;)", line: node.loc?.start.line });
+ }
},
- {
- name: "planeUnwrap",
- signature: "planeUnwrap(geometry: BufferGeometry)",
- returns: "THREE.BufferGeometry",
- category: "uv",
- description: "Projects xy-extent of the bbox to [0,1]. Use for signs/decals/posters where you want ONE readable texture and no edge-face bleeding. Sync.",
- example: `const sign = planeUnwrap(planeGeo(1, 0.6));
-const mesh = new THREE.Mesh(sign, pbrMaterial({ albedo: kilnTextTex }));`
+ CallExpression(node, _state, ancestors) {
+ if (node.callee.type === "Identifier" && node.callee.name === "build" && insideFunctionNamed(ancestors, "build")) {
+ recursiveBuild ??= node.loc?.start.line;
+ }
+ if (node.callee.type === "Identifier") {
+ let est = estimateGeometryTris(node.callee.name, node.arguments);
+ if (est === null && node.callee.name === "subdivide") {
+ const inner = node.arguments[0];
+ if (inner && inner.type === "CallExpression" && inner.callee.type === "Identifier") {
+ const base = estimateGeometryTris(inner.callee.name, inner.arguments);
+ if (base !== null) {
+ const nArg = node.arguments[1];
+ const n = Math.min(4, nArg && nArg.type === "Literal" && typeof nArg.value === "number" ? nArg.value : 1);
+ est = base * (4 ** Math.max(0, n) - 1);
+ }
+ }
+ }
+ if (est !== null) {
+ estimatedTris += est * loopMultiplier(ancestors);
+ }
+ }
+ }
+ });
+ return { infiniteLoops, recursiveBuild, estimatedTris };
+}
+function loopMultiplier(ancestors) {
+ let mult = 1;
+ for (const node of ancestors) {
+ if (node.type !== "ForStatement")
+ continue;
+ const f = node;
+ if (!f.test || f.test.type !== "BinaryExpression")
+ continue;
+ const { operator, right } = f.test;
+ if (operator !== "<" && operator !== "<=")
+ continue;
+ if (right.type !== "Literal" || typeof right.value !== "number")
+ continue;
+ const n = operator === "<" ? right.value : right.value + 1;
+ if (n > 1 && Number.isFinite(n))
+ mult *= Math.min(n, 256);
+ }
+ return Math.min(mult, 4096);
+}
+function insideFunctionNamed(ancestors, name) {
+ for (let i = ancestors.length - 1;i >= 0; i--) {
+ const node = ancestors[i];
+ if (!node)
+ continue;
+ if (node.type === "FunctionDeclaration" && node.id?.name === name)
+ return true;
+ }
+ return false;
+}
+function isConstantTruthy(node) {
+ if (node.type === "Literal") {
+ return Boolean(node.value);
+ }
+ if (node.type === "Identifier")
+ return false;
+ if (node.type === "UnaryExpression" && node.operator === "!") {
+ if (node.argument.type === "Literal")
+ return !node.argument.value;
+ }
+ return false;
+}
+function hasBreak(body) {
+ let found = false;
+ walk.simple(body, {
+ BreakStatement() {
+ found = true;
},
- {
- name: "panelRemapV",
- signature: "panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)",
- returns: "THREE.BufferGeometry",
- category: "uv",
- description: "Scales an existing UV attribute so a small mesh samples a sub-region of a SHARED texture. Replaces the broken texture.clone() pattern (Three.js Texture.clone() runs JSON.stringify on userData, mangling encoded PNG bytes — panelRemapV avoids that by remapping UVs on the geometry instead). Typical use: multi-zone albedo where v=0..0.30 is plain panel and v=0.30..1 has windows/markings — small parts call panelRemapV(unwrap(geo), 0.30) to sample only the clean strip.",
- example: `const cowlGeo = panelRemapV(cylinderUnwrap(capsuleXGeo(0.45, 1.0)), 0.30);
-const cowl = new THREE.Mesh(cowlGeo, bodyMat); // SAME bodyMat as fuselage, no clone needed`
+ ReturnStatement() {
+ found = true;
},
+ ThrowStatement() {
+ found = true;
+ }
+ });
+ return found;
+}
+var SANDBOX_CALLABLES, GeneratedSourcePolicyError, FORBIDDEN_AMBIENT_IDENTIFIERS, FORBIDDEN_THREE_CONSTRUCTORS, ROTATION_OPTION_FNS;
+var init_validation = __esm(() => {
+ init_list_primitives();
+ SANDBOX_CALLABLES = new Set([
+ ...listPrimitives().map((primitive) => primitive.name),
+ "Array",
+ "BigInt",
+ "Boolean",
+ "Error",
+ "Float32Array",
+ "Float64Array",
+ "Int16Array",
+ "Int32Array",
+ "Int8Array",
+ "Map",
+ "Number",
+ "Object",
+ "Promise",
+ "Proxy",
+ "RangeError",
+ "Reflect",
+ "RegExp",
+ "Set",
+ "String",
+ "Symbol",
+ "TypeError",
+ "Uint16Array",
+ "Uint32Array",
+ "Uint8Array",
+ "WeakMap",
+ "WeakSet",
+ "decodeURIComponent",
+ "encodeURIComponent",
+ "isFinite",
+ "isNaN",
+ "parseFloat",
+ "parseInt",
+ "structuredClone"
+ ]);
+ GeneratedSourcePolicyError = class GeneratedSourcePolicyError extends Error {
+ code;
+ line;
+ constructor(issue) {
+ super(`Generated source rejected by policy (${issue.code})${issue.line ? ` at line ${issue.line}` : ""}.`);
+ this.name = "GeneratedSourcePolicyError";
+ this.code = issue.code;
+ this.line = issue.line;
+ }
+ };
+ FORBIDDEN_AMBIENT_IDENTIFIERS = new Set([
+ "globalThis",
+ "global",
+ "process",
+ "fetch",
+ "XMLHttpRequest",
+ "WebSocket",
+ "Function",
+ "eval",
+ "window",
+ "self",
+ "document",
+ "navigator",
+ "location",
+ "Bun",
+ "Deno",
+ "Reflect",
+ "require",
+ "module"
+ ]);
+ FORBIDDEN_THREE_CONSTRUCTORS = new Set([
+ "DataTexture",
+ "ShaderMaterial",
+ "RawShaderMaterial"
+ ]);
+ ROTATION_OPTION_FNS = new Set(["createPart", "createInstance"]);
+});
+
+// src/kit.ts
+import { execFile } from "node:child_process";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import { KHRMaterialsVariants, KHRTextureBasisu } from "@gltf-transform/extensions";
+async function findKtxEncoder() {
+ if (cachedEncoder !== undefined)
+ return cachedEncoder ?? undefined;
+ for (const candidate of KTX_ENCODER_CANDIDATES) {
+ try {
+ await run(candidate, ["--version"], { timeout: 1e4 });
+ cachedEncoder = candidate;
+ return candidate;
+ } catch {}
+ }
+ cachedEncoder = null;
+ return;
+}
+function disposeIfOrphaned(texture) {
+ const stillUsed = texture.listParents().some((parent) => parent.propertyType !== "Root");
+ if (!stillUsed)
+ texture.dispose();
+}
+async function packOcclusionIntoMetallicRoughness(doc) {
+ const sharp = (await import("sharp")).default;
+ let packed = 0;
+ for (const material of doc.getRoot().listMaterials()) {
+ const occlusion = material.getOcclusionTexture();
+ const metallicRoughness = material.getMetallicRoughnessTexture();
+ if (!occlusion || !metallicRoughness || occlusion === metallicRoughness)
+ continue;
+ if (!isPng(occlusion) || !isPng(metallicRoughness))
+ continue;
+ const occlusionBytes = occlusion.getImage();
+ const mrBytes = metallicRoughness.getImage();
+ if (!occlusionBytes || !mrBytes)
+ continue;
+ try {
+ const [occImage, mrImage] = await Promise.all([
+ sharp(Buffer.from(occlusionBytes)).ensureAlpha().raw().toBuffer({ resolveWithObject: true }),
+ sharp(Buffer.from(mrBytes)).ensureAlpha().raw().toBuffer({ resolveWithObject: true })
+ ]);
+ if (occImage.info.width !== mrImage.info.width || occImage.info.height !== mrImage.info.height) {
+ continue;
+ }
+ const { width, height } = mrImage.info;
+ const merged = Buffer.allocUnsafe(width * height * 3);
+ for (let i = 0, o = 0;o < merged.length; i += 4, o += 3) {
+ merged[o] = occImage.data[i] ?? 255;
+ merged[o + 1] = mrImage.data[i + 1] ?? 255;
+ merged[o + 2] = mrImage.data[i + 2] ?? 255;
+ }
+ const png = await sharp(merged, { raw: { width, height, channels: 3 } }).png({ compressionLevel: 9 }).toBuffer();
+ metallicRoughness.setImage(new Uint8Array(png));
+ material.setOcclusionTexture(metallicRoughness);
+ const info = material.getOcclusionTextureInfo();
+ const mrInfo = material.getMetallicRoughnessTextureInfo();
+ if (info && mrInfo)
+ info.setTexCoord(mrInfo.getTexCoord());
+ disposeIfOrphaned(occlusion);
+ packed += 1;
+ } catch {}
+ }
+ return packed;
+}
+function recolorForPalette(doc, material, slots, variantName) {
+ const clone = doc.createMaterial(`${material.getName()}__${variantName}`).copy(material);
+ if (material.getBaseColorTexture())
+ return { material: clone, changed: false };
+ const index = buildSlotIndex(slots);
+ const base = material.getBaseColorFactor();
+ const emissive = material.getEmissiveFactor();
+ const slot = chooseSlot(index, {
+ baseLinear: [base[0], base[1], base[2]],
+ emissiveLinear: [emissive[0], emissive[1], emissive[2]],
+ transparent: material.getAlphaMode() === "BLEND" || material.getAlpha() < 0.98
+ });
+ if (slot === undefined)
+ return { material: clone, changed: false };
+ const chosen = slots[slot];
+ if (!chosen)
+ return { material: clone, changed: false };
+ const [r, g, b] = hexToLinearRgb(chosen.color);
+ if (chosen.kind === "glow") {
+ clone.setEmissiveFactor([r, g, b]);
+ } else {
+ clone.setBaseColorFactor([r, g, b, base[3]]);
+ if (typeof chosen.roughness === "number")
+ clone.setRoughnessFactor(chosen.roughness);
+ if (typeof chosen.metalness === "number")
+ clone.setMetallicFactor(chosen.metalness);
+ if (chosen.kind === "glass" && typeof chosen.opacity === "number") {
+ clone.setBaseColorFactor([r, g, b, chosen.opacity]);
+ }
+ }
+ return { material: clone, changed: true };
+}
+function addPaletteVariants(doc, specs) {
+ const extension = doc.createExtension(KHRMaterialsVariants);
+ const names = [];
+ let materialsCreated = 0;
+ const variants = specs.map((spec) => {
+ names.push(spec.name);
+ return { spec, variant: extension.createVariant(spec.name) };
+ });
+ for (const mesh of doc.getRoot().listMeshes()) {
+ for (const primitive of mesh.listPrimitives()) {
+ const base = primitive.getMaterial();
+ if (!base)
+ continue;
+ const mappings = variants.map(({ spec, variant }) => {
+ const { material, changed } = recolorForPalette(doc, base, spec.slots, spec.name);
+ if (!changed) {
+ material.dispose();
+ return;
+ }
+ materialsCreated += 1;
+ return extension.createMapping().addVariant(variant).setMaterial(material);
+ }).filter((value) => value !== undefined);
+ if (mappings.length === 0)
+ continue;
+ const list = extension.createMappingList();
+ for (const mapping of mappings)
+ list.addMapping(mapping);
+ primitive.setExtension("KHR_materials_variants", list);
+ }
+ }
+ if (names.length === 0 || materialsCreated === 0)
+ extension.dispose();
+ return { names: materialsCreated > 0 ? names : [], materialsCreated };
+}
+async function encodeTexturesToKtx2(doc, encoder) {
+ const textures = doc.getRoot().listTextures().filter(isPng);
+ if (textures.length === 0)
+ return { encoded: 0, before: 0, after: 0 };
+ const dir = await mkdtemp(join(tmpdir(), "kiln-ktx2-"));
+ const staged = [];
+ let encoded = 0;
+ let before = 0;
+ let after = 0;
+ try {
+ for (const [index, texture] of textures.entries()) {
+ const bytes = texture.getImage();
+ if (!bytes)
+ continue;
+ const src = join(dir, `t${index}.png`);
+ const dst = join(dir, `t${index}.ktx2`);
+ await writeFile(src, bytes);
+ const srgb = doc.getRoot().listMaterials().some((material) => material.getBaseColorTexture() === texture || material.getEmissiveTexture() === texture);
+ await run(encoder, [
+ "create",
+ "--format",
+ srgb ? "R8G8B8A8_SRGB" : "R8G8B8A8_UNORM",
+ "--encode",
+ KTX_ENCODE_MODE,
+ "--generate-mipmap",
+ src,
+ dst
+ ], { timeout: 120000 });
+ const out = await readFile(dst);
+ before += bytes.byteLength;
+ after += out.byteLength;
+ staged.push({ texture, original: bytes, encodedBytes: new Uint8Array(out) });
+ }
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ if (staged.length === 0)
+ return { encoded: 0, before, after };
+ if (after >= before * KTX2_SIZE_ACCEPT_RATIO) {
+ return { encoded: 0, before, after };
+ }
+ for (const entry of staged) {
+ entry.texture.setImage(entry.encodedBytes).setMimeType("image/ktx2");
+ encoded += 1;
+ }
+ doc.createExtension(KHRTextureBasisu).setRequired(true);
+ return { encoded, before, after };
+}
+async function applyKitContract(doc, options = {}) {
+ const ormPacked = options.packOrm === false ? 0 : await packOcclusionIntoMetallicRoughness(doc);
+ const specs = options.variants ?? [];
+ const { names, materialsCreated } = specs.length ? addPaletteVariants(doc, specs) : { names: [], materialsCreated: 0 };
+ let ktx2 = {
+ applied: false,
+ skipped: "disabled by caller",
+ texturesEncoded: 0,
+ bytesBefore: 0,
+ bytesAfter: 0
+ };
+ if (options.ktx2 !== false) {
+ const encoder = await findKtxEncoder();
+ if (!encoder) {
+ ktx2 = {
+ applied: false,
+ skipped: "no KTX-Software encoder on PATH (set KILN_KTX_BIN to override)",
+ texturesEncoded: 0,
+ bytesBefore: 0,
+ bytesAfter: 0
+ };
+ } else {
+ try {
+ const result = await encodeTexturesToKtx2(doc, encoder);
+ ktx2 = {
+ applied: result.encoded > 0,
+ ...result.encoded > 0 ? {} : {
+ skipped: result.before === 0 ? "no PNG textures to encode" : `KTX2 was not smaller (${result.after} vs ${result.before} bytes); kept PNG`
+ },
+ encoder,
+ texturesEncoded: result.encoded,
+ bytesBefore: result.before,
+ bytesAfter: result.after
+ };
+ } catch (error) {
+ ktx2 = {
+ applied: false,
+ skipped: `encoder failed: ${error instanceof Error ? error.message : String(error)}`,
+ encoder,
+ texturesEncoded: 0,
+ bytesBefore: 0,
+ bytesAfter: 0
+ };
+ }
+ }
+ }
+ return { ormPacked, variantsAdded: names, variantMaterialsCreated: materialsCreated, ktx2 };
+}
+var run, KTX_ENCODER_CANDIDATES, KTX_ENCODE_MODE = "basis-lz", KTX2_SIZE_ACCEPT_RATIO = 0.9, cachedEncoder, isPng = (texture) => texture.getMimeType() === "image/png";
+var init_kit = __esm(() => {
+ run = promisify(execFile);
+ KTX_ENCODER_CANDIDATES = Object.freeze([
+ process.env["KILN_KTX_BIN"] ?? "",
+ "ktx",
+ "/usr/bin/ktx",
+ "/usr/local/bin/ktx",
+ "C:/Program Files/KTX-Software/bin/ktx.exe"
+ ].filter((value) => value.length > 0));
+});
+
+// src/texture-bake.ts
+import { createHash as createHash3 } from "node:crypto";
+import * as THREE29 from "three";
+function readPixels(texture) {
+ const image = texture.image;
+ if (!image)
+ return "it has no image data";
+ const { width, height } = image;
+ if (!Number.isFinite(width) || !Number.isFinite(height) || !width || !height) {
+ return "its image has no usable width/height";
+ }
+ const data = image.data;
+ if (!data) {
+ return "its pixels are not readable in Node (only DataTexture-style byte arrays can be baked)";
+ }
+ if (!(data instanceof Uint8Array) && !(data instanceof Uint8ClampedArray)) {
+ return `its pixel data is ${data.constructor?.name ?? "an unknown type"}, not 8-bit bytes (float/half-float textures cannot be baked to PNG)`;
+ }
+ const pixels = width * height;
+ const channels = data.length / pixels;
+ if (channels !== 3 && channels !== 4) {
+ return `its pixel data is ${data.length} bytes for ${width}x${height}, which is neither RGB nor RGBA`;
+ }
+ return {
+ data: data instanceof Uint8Array ? data : new Uint8Array(data),
+ width,
+ height,
+ channels
+ };
+}
+async function encodePngFromRaw(raw) {
+ const sharp = (await import("sharp")).default;
+ const out = await sharp(Buffer.from(raw.data.buffer, raw.data.byteOffset, raw.data.length), {
+ raw: { width: raw.width, height: raw.height, channels: raw.channels }
+ }).png({ compressionLevel: 9, adaptiveFiltering: false, palette: false }).toBuffer();
+ return new Uint8Array(out);
+}
+function hasTranslucentPixel(raw) {
+ if (raw.channels !== 4)
+ return false;
+ for (let i = 3;i < raw.data.length; i += 4) {
+ if ((raw.data[i] ?? 255) < 255)
+ return true;
+ }
+ return false;
+}
+function isTexture2(value) {
+ return value?.isTexture === true;
+}
+async function bakeSceneTextures(root, warnings) {
+ const pending = new Map;
+ root.traverse((node) => {
+ const material = node.material;
+ const materials = Array.isArray(material) ? material : material ? [material] : [];
+ for (const item of materials) {
+ const bag = item;
+ for (const [slot, usage2] of SLOT_USAGE2) {
+ const texture = bag[slot];
+ if (!isTexture2(texture))
+ continue;
+ if (texture.userData["encoded"])
+ continue;
+ const existing = pending.get(texture) ?? { texture, bindings: [] };
+ existing.bindings.push({
+ node: node.name || "(unnamed node)",
+ material: item.name || "(unnamed material)",
+ slot,
+ usage: usage2
+ });
+ pending.set(texture, existing);
+ }
+ }
+ });
+ const baked = [];
+ for (const entry of pending.values()) {
+ const name = entry.texture.name || "(unnamed texture)";
+ const raw = readPixels(entry.texture);
+ const firstBinding = entry.bindings[0];
+ const bindingSummary = `material ${JSON.stringify(firstBinding.material)} (${firstBinding.slot})${entry.bindings.length > 1 ? ` and ${entry.bindings.length - 1} other binding(s)` : ""}`;
+ if (typeof raw === "string") {
+ warnings.push(`Texture ${JSON.stringify(name)} on ${bindingSummary} was dropped from the GLB: ${raw}.`);
+ continue;
+ }
+ let bytes;
+ try {
+ bytes = await encodePngFromRaw(raw);
+ } catch (err) {
+ warnings.push(`Texture ${JSON.stringify(name)} on ${bindingSummary} was dropped from the GLB: PNG encoding failed (${err instanceof Error ? err.message : String(err)}).`);
+ continue;
+ }
+ entry.texture.userData["encoded"] = {
+ mime: "image/png",
+ bytes
+ };
+ const colorSpace = entry.texture.colorSpace === THREE29.SRGBColorSpace ? "srgb" : "linear";
+ const recipe2 = entry.texture.userData["kilnProcedural"];
+ const primaryUsage = recipe2?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");
+ entry.texture.userData["kilnTexture"] = {
+ usage: primaryUsage,
+ colorSpace,
+ width: raw.width,
+ height: raw.height,
+ hasAlpha: hasTranslucentPixel(raw)
+ };
+ const sha1 = createHash3("sha1").update(bytes).digest("hex");
+ const imageSha256 = `sha256:${createHash3("sha256").update(bytes).digest("hex")}`;
+ baked.push({
+ schemaVersion: 1,
+ texture: name,
+ node: firstBinding.node,
+ material: firstBinding.material,
+ slot: firstBinding.slot,
+ usage: primaryUsage,
+ bindings: entry.bindings,
+ width: raw.width,
+ height: raw.height,
+ channels: raw.channels,
+ bytes: bytes.length,
+ mime: "image/png",
+ colorSpace,
+ imageSha256,
+ sha1,
+ ...recipe2 ? { procedural: recipe2 } : {}
+ });
+ }
+ return baked.sort((a, b) => `${a.node}:${a.material}:${a.texture}:${a.slot}`.localeCompare(`${b.node}:${b.material}:${b.texture}:${b.slot}`));
+}
+function computeTangentBasis(geometry2) {
+ const index = geometry2.getIndex();
+ const position = geometry2.getAttribute("position");
+ const normal = geometry2.getAttribute("normal");
+ const uv = geometry2.getAttribute("uv");
+ if (!position || !normal || !uv) {
+ throw new Error("position, normal, and uv are all required");
+ }
+ const vertexCount = position.count;
+ const triangleIndices = index ? index.count : vertexCount;
+ const at = index ? (i) => index.getX(i) : (i) => i;
+ const tan1 = new Float32Array(vertexCount * 3);
+ const tan2 = new Float32Array(vertexCount * 3);
+ for (let i = 0;i + 2 < triangleIndices; i += 3) {
+ const a = at(i);
+ const b = at(i + 1);
+ const c = at(i + 2);
+ const x1 = position.getX(b) - position.getX(a);
+ const y1 = position.getY(b) - position.getY(a);
+ const z1 = position.getZ(b) - position.getZ(a);
+ const x2 = position.getX(c) - position.getX(a);
+ const y2 = position.getY(c) - position.getY(a);
+ const z2 = position.getZ(c) - position.getZ(a);
+ const s1 = uv.getX(b) - uv.getX(a);
+ const t1 = uv.getY(b) - uv.getY(a);
+ const s2 = uv.getX(c) - uv.getX(a);
+ const t2 = uv.getY(c) - uv.getY(a);
+ const det = s1 * t2 - s2 * t1;
+ if (det === 0 || !Number.isFinite(det))
+ continue;
+ const r = 1 / det;
+ const sdx = (t2 * x1 - t1 * x2) * r;
+ const sdy = (t2 * y1 - t1 * y2) * r;
+ const sdz = (t2 * z1 - t1 * z2) * r;
+ const tdx = (s1 * x2 - s2 * x1) * r;
+ const tdy = (s1 * y2 - s2 * y1) * r;
+ const tdz = (s1 * z2 - s2 * z1) * r;
+ for (const v of [a, b, c]) {
+ const o = v * 3;
+ tan1[o] = (tan1[o] ?? 0) + sdx;
+ tan1[o + 1] = (tan1[o + 1] ?? 0) + sdy;
+ tan1[o + 2] = (tan1[o + 2] ?? 0) + sdz;
+ tan2[o] = (tan2[o] ?? 0) + tdx;
+ tan2[o + 1] = (tan2[o + 1] ?? 0) + tdy;
+ tan2[o + 2] = (tan2[o + 2] ?? 0) + tdz;
+ }
+ }
+ const out = new Float32Array(vertexCount * 4);
+ const n = new THREE29.Vector3;
+ const t = new THREE29.Vector3;
+ const tmp = new THREE29.Vector3;
+ const tmp2 = new THREE29.Vector3;
+ for (let v = 0;v < vertexCount; v++) {
+ n.set(normal.getX(v), normal.getY(v), normal.getZ(v));
+ t.set(tan1[v * 3], tan1[v * 3 + 1], tan1[v * 3 + 2]);
+ if (t.lengthSq() === 0) {
+ t.set(1, 0, 0);
+ if (Math.abs(n.x) > 0.9)
+ t.set(0, 1, 0);
+ }
+ tmp.copy(t).sub(tmp2.copy(n).multiplyScalar(n.dot(t)));
+ if (tmp.lengthSq() === 0)
+ tmp.set(1, 0, 0);
+ tmp.normalize();
+ tmp2.set(tan2[v * 3], tan2[v * 3 + 1], tan2[v * 3 + 2]);
+ const w = n.clone().cross(t).dot(tmp2) < 0 ? -1 : 1;
+ out[v * 4] = tmp.x;
+ out[v * 4 + 1] = tmp.y;
+ out[v * 4 + 2] = tmp.z;
+ out[v * 4 + 3] = w;
+ }
+ geometry2.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));
+}
+function ensureNormalMapTangents(root, warnings) {
+ let count = 0;
+ const done = new Set;
+ root.traverse((node) => {
+ const mesh = node;
+ if (!mesh.isMesh)
+ return;
+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
+ const needsTangents = materials.some((m) => m?.normalMap);
+ if (!needsTangents)
+ return;
+ const geometry2 = mesh.geometry;
+ if (!geometry2 || done.has(geometry2) || geometry2.getAttribute("tangent"))
+ return;
+ done.add(geometry2);
+ const name = mesh.name || "(unnamed mesh)";
+ if (!geometry2.getAttribute("uv")) {
+ warnings.push(`Mesh ${JSON.stringify(name)} uses a normal map but has no UV coordinates, so tangents could not be computed — and the normal map cannot be sampled either. Unwrap it first: mesh.geometry = await autoUnwrap(mesh.geometry).`);
+ return;
+ }
+ if (!geometry2.getAttribute("normal"))
+ geometry2.computeVertexNormals();
+ try {
+ computeTangentBasis(geometry2);
+ count++;
+ } catch (err) {
+ warnings.push(`Mesh ${JSON.stringify(name)} uses a normal map but tangents could not be computed (${err instanceof Error ? err.message : String(err)}). Each runtime will generate its own tangent basis.`);
+ }
+ });
+ return count;
+}
+var SLOT_USAGE2;
+var init_texture_bake = __esm(() => {
+ SLOT_USAGE2 = [
+ ["map", "albedo"],
+ ["normalMap", "normal"],
+ ["roughnessMap", "roughness"],
+ ["metalnessMap", "metalness"],
+ ["emissiveMap", "emissive"],
+ ["aoMap", "occlusion"]
+ ];
+});
+
+// src/views/character.ts
+import * as THREE30 from "three";
+function rounded(value) {
+ const result = Math.round(value * 1e9) / 1e9;
+ return Object.is(result, -0) ? 0 : result;
+}
+function tuple2(vector) {
+ return [rounded(vector.x), rounded(vector.y), rounded(vector.z)];
+}
+function chainIdFor(descriptor2, byRole) {
+ if (AXIAL_ROLES.has(descriptor2.role))
+ return "axial";
+ let current = descriptor2;
+ const seen = new Set([current.role]);
+ while (current.parentRole && !AXIAL_ROLES.has(current.parentRole)) {
+ const parent = byRole.get(current.parentRole);
+ if (!parent || seen.has(parent.role))
+ break;
+ seen.add(parent.role);
+ current = parent;
+ }
+ return current.role;
+}
+function colorFor(value) {
+ let hash = 2166136261;
+ for (let index = 0;index < value.length; index++) {
+ hash ^= value.charCodeAt(index);
+ hash = Math.imul(hash, 16777619);
+ }
+ return CHAIN_COLORS[Math.abs(hash) % CHAIN_COLORS.length];
+}
+function buildCharacterDiagnosticDescriptor(root, findings = []) {
+ root.updateMatrixWorld(true);
+ const rootInverse2 = root.matrixWorld.clone().invert();
+ const evidence2 = collectCharacterJointNodes(root);
+ const descriptorByRole = new Map(evidence2.map((joint) => [joint.descriptor.role, joint.descriptor]));
+ const evidenceByRole = new Map(evidence2.map((joint) => [joint.descriptor.role, joint]));
+ const invalidFindingNodePaths = [
+ ...new Set(findings.filter((finding6) => finding6.code === "CHAR_PARENT_EDGE").map((finding6) => finding6.affected?.nodePath).filter((path) => Boolean(path)))
+ ].sort();
+ const invalidPaths = new Set(invalidFindingNodePaths);
+ const joints = evidence2.map((joint) => {
+ const relative = rootInverse2.clone().multiply(joint.node.matrixWorld);
+ const position = new THREE30.Vector3().setFromMatrixPosition(relative);
+ const forward = new THREE30.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const bend2 = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const chainId = chainIdFor(joint.descriptor, descriptorByRole);
+ return {
+ role: joint.descriptor.role,
+ aliases: [...joint.descriptor.aliases],
+ side: joint.descriptor.side,
+ nodeName: joint.node.name,
+ nodePath: joint.nodePath,
+ label: joint.descriptor.role,
+ chainId,
+ color: colorFor(chainId),
+ assetPosition: tuple2(position),
+ forwardAxisEnd: tuple2(forward),
+ bendAxisEnd: tuple2(bend2),
+ endEffector: joint.descriptor.endEffector,
+ contact: joint.descriptor.contact
+ };
+ });
+ const edges = evidence2.filter((joint) => joint.descriptor.parentRole).map((joint) => {
+ const parentRole = joint.descriptor.parentRole;
+ const parent = evidenceByRole.get(parentRole);
+ const chainId = chainIdFor(joint.descriptor, descriptorByRole);
+ return {
+ parentRole,
+ childRole: joint.descriptor.role,
+ ...parent ? { parentNodePath: parent.nodePath } : {},
+ childNodePath: joint.nodePath,
+ valid: Boolean(parent) && !invalidPaths.has(joint.nodePath),
+ color: colorFor(chainId)
+ };
+ }).sort((a, b) => `${a.parentRole}:${a.childRole}`.localeCompare(`${b.parentRole}:${b.childRole}`));
+ return {
+ schemaVersion: 1,
+ joints,
+ edges,
+ contacts: joints.filter((joint) => joint.contact).map((joint) => ({
+ role: joint.role,
+ nodePath: joint.nodePath,
+ assetPosition: joint.assetPosition
+ })),
+ canonicalForwardArrow: { start: [0, 0, 0], end: [1, 0, 0], label: "+X forward" },
+ invalidFindingNodePaths
+ };
+}
+function safeClipId(name) {
+ return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
+}
+function planCharacterDiagnosticRequests(intent) {
+ const requests = [
+ diagnosticRequest({
+ id: "character.skeleton.front",
+ label: "Character skeleton front",
+ cameraId: "front",
+ buffer: "semantic-overlay",
+ variant: "character-skeleton",
+ focusRolePrefixes: ["skeleton.", "joint.", "contact."],
+ automatic: true
+ }),
+ diagnosticRequest({
+ id: "character.skeleton.right",
+ label: "Character skeleton right",
+ cameraId: "right",
+ buffer: "semantic-overlay",
+ variant: "character-skeleton",
+ focusRolePrefixes: ["skeleton.", "joint.", "contact."],
+ automatic: true
+ })
+ ];
+ const locomotion = intent.clips.find((clip) => clip.playback === "loop" && new RegExp(intent.locomotion === "stationary" ? "idle" : intent.locomotion, "i").test(clip.name)) ?? intent.clips.find((clip) => clip.playback === "loop");
+ const action = intent.clips.find((clip) => clip.playback === "oneShot");
+ const selected = [locomotion, action].filter((clip, index, values) => Boolean(clip) && values.findIndex((candidate) => candidate?.name === clip?.name) === index);
+ for (const clip of selected) {
+ for (const cameraId of ["front", "right"]) {
+ requests.push(diagnosticRequest({
+ id: `character.motion-strip.${cameraId}.${safeClipId(clip.name)}`,
+ label: `${clip.name} fixed-phase ${cameraId} strip`,
+ cameraId,
+ buffer: "silhouette-unlit",
+ variant: "character-motion-strip",
+ clipName: clip.name,
+ phaseFractions: CHARACTER_MOTION_DIAGNOSTIC_PHASES,
+ focusRolePrefixes: ["skeleton.", "joint.", "limb.", "held-item"],
+ automatic: true
+ }));
+ }
+ }
+ return Object.freeze(requests);
+}
+var CHAIN_COLORS, AXIAL_ROLES, CHARACTER_MOTION_DIAGNOSTIC_PHASES, diagnosticRequest = (value) => Object.freeze({
+ ...value,
+ focusRolePrefixes: Object.freeze([...value.focusRolePrefixes]),
+ ...value.phaseFractions ? { phaseFractions: Object.freeze([...value.phaseFractions]) } : {}
+});
+var init_character3 = __esm(() => {
+ init_character();
+ CHAIN_COLORS = Object.freeze([
+ "#4fc3f7",
+ "#ff8a65",
+ "#81c784",
+ "#ba68c8",
+ "#ffd54f",
+ "#4db6ac",
+ "#f06292",
+ "#90a4ae"
+ ]);
+ AXIAL_ROLES = new Set(["root", "hips", "spine", "neck", "head"]);
+ CHARACTER_MOTION_DIAGNOSTIC_PHASES = Object.freeze([0, 0.2, 0.4, 0.6, 0.8, 1]);
+});
+
+// src/views/png.ts
+import { deflateSync, inflateSync } from "node:zlib";
+function crc32(buf) {
+ let c = 4294967295;
+ for (let i = 0;i < buf.length; i++) {
+ c = CRC_TABLE[(c ^ buf[i]) & 255] ^ c >>> 8;
+ }
+ return (c ^ 4294967295) >>> 0;
+}
+function chunk(type, data) {
+ const out = Buffer.alloc(8 + data.length + 4);
+ out.writeUInt32BE(data.length, 0);
+ out.write(type, 4, "ascii");
+ out.set(data, 8);
+ const crcInput = out.subarray(4, 8 + data.length);
+ out.writeUInt32BE(crc32(crcInput), 8 + data.length);
+ return out;
+}
+function encodePng(rgb2, width, height) {
+ if (rgb2.length !== width * height * 3) {
+ throw new Error(`encodePng: expected ${width * height * 3} bytes, got ${rgb2.length}`);
+ }
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(width, 0);
+ ihdr.writeUInt32BE(height, 4);
+ ihdr[8] = 8;
+ ihdr[9] = 2;
+ ihdr[10] = 0;
+ ihdr[11] = 0;
+ ihdr[12] = 0;
+ const raw = Buffer.alloc(height * (1 + width * 3));
+ for (let y = 0;y < height; y++) {
+ const rowStart = y * (1 + width * 3);
+ raw[rowStart] = 0;
+ raw.set(rgb2.subarray(y * width * 3, (y + 1) * width * 3), rowStart + 1);
+ }
+ return Buffer.concat([
+ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
+ chunk("IHDR", ihdr),
+ chunk("IDAT", deflateSync(raw)),
+ chunk("IEND", new Uint8Array(0))
+ ]);
+}
+function decodePng(png) {
+ if (png.length < 8 || PNG_SIGNATURE.some((b, i) => png[i] !== b)) {
+ throw new Error("decodePng: not a PNG (bad signature)");
+ }
+ const view = new DataView(png.buffer, png.byteOffset, png.byteLength);
+ let width = 0;
+ let height = 0;
+ let bitDepth = 0;
+ let colorType = 0;
+ let interlace = 0;
+ let sawIhdr = false;
+ const idat = [];
+ let off = 8;
+ while (off + 8 <= png.length) {
+ const len = view.getUint32(off);
+ const type = String.fromCharCode(png[off + 4], png[off + 5], png[off + 6], png[off + 7]);
+ const dataStart = off + 8;
+ if (dataStart + len + 4 > png.length)
+ throw new Error("decodePng: truncated chunk");
+ if (type === "IHDR") {
+ width = view.getUint32(dataStart);
+ height = view.getUint32(dataStart + 4);
+ bitDepth = png[dataStart + 8];
+ colorType = png[dataStart + 9];
+ interlace = png[dataStart + 12];
+ sawIhdr = true;
+ } else if (type === "IDAT") {
+ idat.push(Buffer.from(png.subarray(dataStart, dataStart + len)));
+ } else if (type === "IEND") {
+ break;
+ }
+ off = dataStart + len + 4;
+ }
+ if (!sawIhdr || idat.length === 0)
+ throw new Error("decodePng: missing IHDR or IDAT");
+ if (bitDepth !== 8 || colorType !== 2 && colorType !== 6 || interlace !== 0) {
+ throw new Error(`decodePng: unsupported PNG (bitDepth ${bitDepth}, colorType ${colorType}, interlace ` + `${interlace}); only 8-bit non-interlaced RGB/RGBA is supported`);
+ }
+ if (width <= 0 || height <= 0)
+ throw new Error("decodePng: empty image");
+ const channels = colorType === 6 ? 4 : 3;
+ const stride = width * channels;
+ const raw = inflateSync(idat.length === 1 ? idat[0] : Buffer.concat(idat));
+ if (raw.length !== height * (1 + stride)) {
+ throw new Error(`decodePng: expected ${height * (1 + stride)} raw bytes, got ${raw.length}`);
+ }
+ const rgb2 = new Uint8Array(width * height * 3);
+ const cur = new Uint8Array(stride);
+ const prior = new Uint8Array(stride);
+ for (let y = 0;y < height; y++) {
+ const rowStart = y * (1 + stride);
+ const filter = raw[rowStart];
+ if (filter > 4)
+ throw new Error(`decodePng: unknown filter type ${filter}`);
+ for (let i = 0;i < stride; i++) {
+ const x = raw[rowStart + 1 + i];
+ const a = i >= channels ? cur[i - channels] : 0;
+ const b = prior[i];
+ let value;
+ if (filter === 0)
+ value = x;
+ else if (filter === 1)
+ value = x + a;
+ else if (filter === 2)
+ value = x + b;
+ else if (filter === 3)
+ value = x + (a + b >> 1);
+ else {
+ const c = i >= channels ? prior[i - channels] : 0;
+ const p = a + b - c;
+ const pa = Math.abs(p - a);
+ const pb = Math.abs(p - b);
+ const pc = Math.abs(p - c);
+ value = x + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c);
+ }
+ cur[i] = value & 255;
+ }
+ for (let px = 0;px < width; px++) {
+ const src = px * channels;
+ const dst = (y * width + px) * 3;
+ rgb2[dst] = cur[src];
+ rgb2[dst + 1] = cur[src + 1];
+ rgb2[dst + 2] = cur[src + 2];
+ }
+ prior.set(cur);
+ }
+ return { rgb: rgb2, width, height };
+}
+var CRC_TABLE, PNG_SIGNATURE;
+var init_png = __esm(() => {
+ CRC_TABLE = (() => {
+ const table = new Uint32Array(256);
+ for (let n = 0;n < 256; n++) {
+ let c = n;
+ for (let k = 0;k < 8; k++) {
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
+ }
+ table[n] = c >>> 0;
+ }
+ return table;
+ })();
+ PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
+});
+
+// src/views/diagnostic.ts
+function architectureDiagnosticRequests(intent) {
+ const architecture = intent.architecture;
+ if (!architecture)
+ return [];
+ const requests = [];
+ const buildingProfile = architecture.roof.type === "gable" || /(?:building|house|cottage|barn|hut|gable)/i.test(architecture.subtype);
+ if (buildingProfile) {
+ const ridgeX = architecture.roof.ridgeAxis === "x";
+ requests.push(request({
+ id: "architecture.gable.positive",
+ label: "Architecture positive gable elevation",
+ cameraId: ridgeX ? "front" : "right",
+ buffer: "semantic-overlay",
+ scope: "category",
+ variant: "architecture-gable-elevation",
+ focusRolePrefixes: ["roof.gable.positive", "roof.slope.", "wall."]
+ }), request({
+ id: "architecture.gable.negative",
+ label: "Architecture negative gable elevation",
+ cameraId: ridgeX ? "back" : "left",
+ buffer: "semantic-overlay",
+ scope: "category",
+ variant: "architecture-gable-elevation",
+ focusRolePrefixes: ["roof.gable.negative", "roof.slope.", "wall."]
+ }));
+ }
+ requests.push(request({
+ id: "architecture.cutaway.plan",
+ label: "Architecture roof-off plan",
+ cameraId: "top",
+ buffer: "semantic-overlay",
+ scope: "category",
+ variant: "architecture-cutaway",
+ omitRolePrefixes: ["roof."]
+ }), request({
+ id: "architecture.cutaway.dollhouse",
+ label: "Architecture roof-off dollhouse",
+ cameraId: "three-quarter",
+ buffer: "semantic-overlay",
+ scope: "category",
+ variant: "architecture-cutaway",
+ omitRolePrefixes: ["roof."]
+ }));
+ if (architecture.enterable) {
+ requests.push(request({
+ id: "architecture.portal.eye",
+ label: "Architecture portal eye view",
+ cameraId: "front",
+ buffer: "depth-contact",
+ scope: "category",
+ variant: "architecture-portal-eye",
+ focusRolePrefixes: ["opening.", "wall.", "floor"]
+ }));
+ }
+ return Object.freeze(requests);
+}
+function characterDiagnosticRequests(intent) {
+ if (!intent.character)
+ return [];
+ return Object.freeze(planCharacterDiagnosticRequests(intent.character).map((value) => request({
+ id: value.id,
+ label: value.label,
+ cameraId: value.cameraId,
+ buffer: value.buffer,
+ scope: "category",
+ variant: value.variant,
+ focusRolePrefixes: value.focusRolePrefixes,
+ ...value.phaseFractions ? { phaseFractions: value.phaseFractions } : {},
+ ...value.clipName ? { clipName: value.clipName } : {}
+ })));
+}
+function planDiagnosticViews(intent) {
+ const categoryRequests = intent.category === "architecture" ? architectureDiagnosticRequests(intent) : intent.category === "character" ? characterDiagnosticRequests(intent) : CATEGORY_REQUESTS[intent.category];
+ const includeGrazing = intent.material.mode !== "flatOptimized";
+ return {
+ schemaVersion: 1,
+ category: intent.category,
+ qaProfile: intent.qaProfile,
+ genericCameraIds: Object.freeze(GENERIC_DIAGNOSTIC_CAMERAS.map((camera) => camera.id)),
+ generic: GENERIC_DIAGNOSTIC_REQUESTS,
+ extra: includeGrazing ? Object.freeze([...categoryRequests, MATERIAL_GRAZING_REQUEST]) : categoryRequests
+ };
+}
+function multiplyMatrices(a, b) {
+ const out = new Float64Array(16);
+ for (let column = 0;column < 4; column++) {
+ for (let row = 0;row < 4; row++) {
+ let value = 0;
+ for (let k = 0;k < 4; k++)
+ value += a[k * 4 + row] * b[column * 4 + k];
+ out[column * 4 + row] = value;
+ }
+ }
+ return out;
+}
+function composeLocalMatrix(node) {
+ if (node.matrixAutoUpdate === false && node.matrix?.elements) {
+ return new Float64Array(Array.from(node.matrix.elements));
+ }
+ const p = node.position;
+ const q = node.quaternion;
+ const s = node.scale;
+ if (!p || !q || !s) {
+ return node.matrix?.elements ? new Float64Array(Array.from(node.matrix.elements)) : new Float64Array(IDENTITY);
+ }
+ const x2 = q.x + q.x;
+ const y2 = q.y + q.y;
+ const z2 = q.z + q.z;
+ const xx = q.x * x2;
+ const xy = q.x * y2;
+ const xz = q.x * z2;
+ const yy = q.y * y2;
+ const yz = q.y * z2;
+ const zz = q.z * z2;
+ const wx = q.w * x2;
+ const wy = q.w * y2;
+ const wz = q.w * z2;
+ return new Float64Array([
+ (1 - (yy + zz)) * s.x,
+ (xy + wz) * s.x,
+ (xz - wy) * s.x,
+ 0,
+ (xy - wz) * s.y,
+ (1 - (xx + zz)) * s.y,
+ (yz + wx) * s.y,
+ 0,
+ (xz + wy) * s.z,
+ (yz - wx) * s.z,
+ (1 - (xx + yy)) * s.z,
+ 0,
+ p.x,
+ p.y,
+ p.z,
+ 1
+ ]);
+}
+function transformPoint2(matrix, x, y, z) {
+ return [
+ matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12],
+ matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13],
+ matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]
+ ];
+}
+function matchesRole(roles2, prefixes) {
+ return Boolean(prefixes?.some((prefix) => roles2.some((role) => role.startsWith(prefix))));
+}
+function semanticRoles2(node) {
+ const metadata = readSemanticMetadataV1FromExtras(node.userData ?? {});
+ if (metadata)
+ return metadata.roles;
+ const geometryRole = node.geometry?.userData?.["kilnGeometryRole"];
+ return typeof geometryRole === "string" ? [geometryRole] : [];
+}
+function clamp01(value) {
+ return value < 0 ? 0 : value > 1 ? 1 : value;
+}
+function collectScene(root, requestValue) {
+ const triangles = [];
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ const focusMin = [Infinity, Infinity, Infinity];
+ const focusMax = [-Infinity, -Infinity, -Infinity];
+ const visit = (node, parentMatrix, parentPath, siblingIndex, ancestorVisible, inheritedRoles) => {
+ const local = composeLocalMatrix(node);
+ const world = multiplyMatrices(parentMatrix, local);
+ const visible = ancestorVisible && node.visible !== false;
+ const segment = `${node.name?.trim() || node.type || "Node"}[${siblingIndex}]`;
+ const nodePath5 = parentPath ? `${parentPath}/${segment}` : segment;
+ const roles2 = [...new Set([...inheritedRoles, ...semanticRoles2(node)])];
+ const omitted = matchesRole(roles2, requestValue.omitRolePrefixes);
+ if (visible && !omitted && node.isMesh && node.geometry) {
+ const materials = Array.isArray(node.material) ? node.material : [node.material];
+ const material = materials[0];
+ if (material?.visible !== false) {
+ const position = node.geometry.getAttribute?.("position");
+ if (position?.itemSize === 3) {
+ const worldPositions = [];
+ for (let index2 = 0;index2 < position.count; index2++) {
+ const point = transformPoint2(world, position.array[index2 * 3], position.array[index2 * 3 + 1], position.array[index2 * 3 + 2]);
+ worldPositions.push(point);
+ }
+ const materialColor = material?.color;
+ const color2 = materialColor ? [clamp01(materialColor.r), clamp01(materialColor.g), clamp01(materialColor.b)] : [0.7, 0.7, 0.7];
+ const focused = matchesRole(roles2, requestValue.focusRolePrefixes);
+ const addTriangle = (a, b, c) => {
+ const points = [worldPositions[a], worldPositions[b], worldPositions[c]];
+ if (points.some((point) => !point || point.some((value) => !Number.isFinite(value)))) {
+ return;
+ }
+ const vertices = new Float64Array(9);
+ points.forEach((point, pointIndex) => {
+ for (let axis = 0;axis < 3; axis++) {
+ const value = point[axis];
+ vertices[pointIndex * 3 + axis] = value;
+ min[axis] = Math.min(min[axis], value);
+ max[axis] = Math.max(max[axis], value);
+ if (focused) {
+ focusMin[axis] = Math.min(focusMin[axis], value);
+ focusMax[axis] = Math.max(focusMax[axis], value);
+ }
+ }
+ });
+ triangles.push({
+ vertices,
+ color: color2,
+ nodeName: node.name ?? "",
+ nodePath: nodePath5,
+ semanticRoles: roles2
+ });
+ };
+ const index = node.geometry.index;
+ if (index) {
+ for (let i = 0;i + 2 < index.count; i += 3) {
+ addTriangle(index.array[i], index.array[i + 1], index.array[i + 2]);
+ }
+ } else {
+ for (let i = 0;i + 2 < position.count; i += 3)
+ addTriangle(i, i + 1, i + 2);
+ }
+ }
+ }
+ }
+ (node.children ?? []).forEach((child, index) => {
+ visit(child, world, nodePath5, index, visible && !omitted, roles2);
+ });
+ };
+ visit(root, IDENTITY, "", 0, true, []);
+ const empty = !Number.isFinite(min[0]);
+ const focusEmpty = !Number.isFinite(focusMin[0]);
+ return {
+ triangles,
+ bounds: empty ? { min: [0, 0, 0], max: [0, 0, 0] } : { min, max },
+ ...!focusEmpty ? { focusBounds: { min: focusMin, max: focusMax } } : {}
+ };
+}
+function normalize2(vector) {
+ const length3 = Math.hypot(...vector) || 1;
+ return [vector[0] / length3, vector[1] / length3, vector[2] / length3];
+}
+function cross2(a, b) {
+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+}
+function dot3(a, b) {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+}
+function stableColor(key) {
+ let hash = 2166136261;
+ for (let index = 0;index < key.length; index++) {
+ hash ^= key.charCodeAt(index);
+ hash = Math.imul(hash, 16777619);
+ }
+ return [96 + (hash & 127), 96 + (hash >>> 8 & 127), 96 + (hash >>> 16 & 127)];
+}
+function projectScene(scene, camera, size) {
+ const zAxis = normalize2(camera.dir);
+ const upHint = Math.abs(zAxis[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];
+ const xAxis = normalize2(cross2(upHint, zAxis));
+ const yAxis = cross2(zAxis, xAxis);
+ const frame = scene.focusBounds ?? scene.bounds;
+ const center = [
+ (frame.min[0] + frame.max[0]) / 2,
+ (frame.min[1] + frame.max[1]) / 2,
+ (frame.min[2] + frame.max[2]) / 2
+ ];
+ let extent2 = 0.000001;
+ for (let corner = 0;corner < 8; corner++) {
+ const point = [
+ (corner & 1 ? frame.max[0] : frame.min[0]) - center[0],
+ (corner & 2 ? frame.max[1] : frame.min[1]) - center[1],
+ (corner & 4 ? frame.max[2] : frame.min[2]) - center[2]
+ ];
+ extent2 = Math.max(extent2, Math.abs(dot3(point, xAxis)), Math.abs(dot3(point, yAxis)));
+ }
+ const scale2 = size * 0.45 / extent2;
+ const half = size / 2;
+ return scene.triangles.flatMap((triangle) => {
+ const v = triangle.vertices;
+ const edgeA = [v[3] - v[0], v[4] - v[1], v[5] - v[2]];
+ const edgeB = [v[6] - v[0], v[7] - v[1], v[8] - v[2]];
+ const normalRaw = cross2(edgeA, edgeB);
+ const length3 = Math.hypot(...normalRaw);
+ if (length3 < 0.000000000001)
+ return [];
+ const normal = normalRaw.map((component) => component / length3);
+ const xs = [];
+ const ys = [];
+ const zs = [];
+ const worldY = [];
+ for (let index = 0;index < 3; index++) {
+ const point = [
+ v[index * 3] - center[0],
+ v[index * 3 + 1] - center[1],
+ v[index * 3 + 2] - center[2]
+ ];
+ xs.push(half + dot3(point, xAxis) * scale2);
+ ys.push(half - dot3(point, yAxis) * scale2);
+ zs.push(dot3(point, zAxis));
+ worldY.push(v[index * 3 + 1]);
+ }
+ return [
+ {
+ source: triangle,
+ x: xs,
+ y: ys,
+ z: zs,
+ worldY,
+ normal,
+ frontFacing: dot3(normal, zAxis) > 0
+ }
+ ];
+ });
+}
+function drawLine(rgb2, size, from, to, color2) {
+ let x0 = Math.round(from[0]);
+ let y0 = Math.round(from[1]);
+ const x1 = Math.round(to[0]);
+ const y1 = Math.round(to[1]);
+ const dx = Math.abs(x1 - x0);
+ const sx = x0 < x1 ? 1 : -1;
+ const dy = -Math.abs(y1 - y0);
+ const sy = y0 < y1 ? 1 : -1;
+ let error = dx + dy;
+ while (true) {
+ if (x0 >= 0 && x0 < size && y0 >= 0 && y0 < size) {
+ const offset = (y0 * size + x0) * 3;
+ rgb2[offset] = color2[0];
+ rgb2[offset + 1] = color2[1];
+ rgb2[offset + 2] = color2[2];
+ }
+ if (x0 === x1 && y0 === y1)
+ break;
+ const doubled = 2 * error;
+ if (doubled >= dy) {
+ error += dy;
+ x0 += sx;
+ }
+ if (doubled <= dx) {
+ error += dx;
+ y0 += sy;
+ }
+ }
+}
+function drawRegionBox(rgb2, size, region) {
+ const [minX, minY, maxX, maxY] = region.pixelBounds;
+ drawLine(rgb2, size, [minX, minY], [maxX, minY], region.color);
+ drawLine(rgb2, size, [maxX, minY], [maxX, maxY], region.color);
+ drawLine(rgb2, size, [maxX, maxY], [minX, maxY], region.color);
+ drawLine(rgb2, size, [minX, maxY], [minX, minY], region.color);
+}
+function renderDiagnosticView(root, requestValue, options = {}) {
+ const camera = cameraById.get(requestValue.cameraId);
+ if (!camera)
+ throw new TypeError(`Unknown diagnostic camera ${JSON.stringify(requestValue.cameraId)}.`);
+ const size = Math.max(16, Math.min(1024, Math.round(options.size ?? 256)));
+ const groundY = options.groundY ?? 0;
+ const scene = collectScene(root, requestValue);
+ const triangles = projectScene(scene, camera, size);
+ const background = [18, 20, 24];
+ const rgb2 = new Uint8Array(size * size * 3);
+ for (let pixel = 0;pixel < size * size; pixel++) {
+ rgb2[pixel * 3] = background[0];
+ rgb2[pixel * 3 + 1] = background[1];
+ rgb2[pixel * 3 + 2] = background[2];
+ }
+ const depth = new Float64Array(size * size).fill(-Infinity);
+ const depths = triangles.flatMap((triangle) => triangle.z);
+ const minDepth = depths.length > 0 ? Math.min(...depths) : 0;
+ const maxDepth = depths.length > 0 ? Math.max(...depths) : 1;
+ const depthRange = Math.max(0.000000001, maxDepth - minDepth);
+ const contactTolerance = Math.max(0.0001, (scene.bounds.max[1] - scene.bounds.min[1]) * 0.015);
+ const regionMap = new Map;
+ for (const triangle of triangles) {
+ const minX = Math.max(0, Math.floor(Math.min(...triangle.x)));
+ const maxX = Math.min(size - 1, Math.ceil(Math.max(...triangle.x)));
+ const minY = Math.max(0, Math.floor(Math.min(...triangle.y)));
+ const maxY = Math.min(size - 1, Math.ceil(Math.max(...triangle.y)));
+ if (minX > maxX || minY > maxY)
+ continue;
+ const key = triangle.source.semanticRoles.at(-1) ?? triangle.source.nodePath;
+ const regionColor = stableColor(key);
+ const existing = regionMap.get(triangle.source.nodePath);
+ if (existing) {
+ existing.pixelBounds[0] = Math.min(existing.pixelBounds[0], minX);
+ existing.pixelBounds[1] = Math.min(existing.pixelBounds[1], minY);
+ existing.pixelBounds[2] = Math.max(existing.pixelBounds[2], maxX);
+ existing.pixelBounds[3] = Math.max(existing.pixelBounds[3], maxY);
+ existing.triangleCount++;
+ } else {
+ regionMap.set(triangle.source.nodePath, {
+ nodeName: triangle.source.nodeName,
+ nodePath: triangle.source.nodePath,
+ semanticRoles: [...triangle.source.semanticRoles],
+ pixelBounds: [minX, minY, maxX, maxY],
+ color: regionColor,
+ triangleCount: 1
+ });
+ }
+ if (requestValue.buffer === "wireframe")
+ continue;
+ const ax = triangle.x[0];
+ const ay = triangle.y[0];
+ const bx = triangle.x[1];
+ const by = triangle.y[1];
+ const cx = triangle.x[2];
+ const cy = triangle.y[2];
+ const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
+ if (Math.abs(area) < 0.000000001)
+ continue;
+ const inverseArea = 1 / area;
+ for (let py = minY;py <= maxY; py++) {
+ for (let px = minX;px <= maxX; px++) {
+ const sampleX = px + 0.5;
+ const sampleY = py + 0.5;
+ const w0 = ((bx - ax) * (sampleY - ay) - (by - ay) * (sampleX - ax)) * inverseArea;
+ const w1 = ((cx - bx) * (sampleY - by) - (cy - by) * (sampleX - bx)) * inverseArea;
+ const w2 = 1 - w0 - w1;
+ if (w0 < 0 || w1 < 0 || w2 < 0)
+ continue;
+ const pixelDepth = w1 * triangle.z[0] + w2 * triangle.z[1] + w0 * triangle.z[2];
+ const pixel = py * size + px;
+ if (pixelDepth <= depth[pixel])
+ continue;
+ depth[pixel] = pixelDepth;
+ const offset = pixel * 3;
+ let color2;
+ if (requestValue.variant === "material-grazing-light") {
+ const grazingDirection = normalize2([0.25, 0.08, 1]);
+ const light = 0.08 + 0.92 * Math.max(0, dot3(triangle.normal, grazingDirection));
+ color2 = triangle.source.color.map((value) => Math.round(clamp01(value * light) * 255));
+ } else if (requestValue.buffer === "silhouette-unlit") {
+ color2 = [235, 238, 242];
+ } else if (requestValue.buffer === "normals-backface") {
+ color2 = triangle.frontFacing ? triangle.normal.map((value) => Math.round((value * 0.5 + 0.5) * 255)) : [238, 48, 64];
+ } else if (requestValue.buffer === "depth-contact") {
+ const worldY = w1 * triangle.worldY[0] + w2 * triangle.worldY[1] + w0 * triangle.worldY[2];
+ if (Math.abs(worldY - groundY) <= contactTolerance)
+ color2 = [58, 220, 126];
+ else if (worldY < groundY - contactTolerance)
+ color2 = [245, 94, 72];
+ else {
+ const value = Math.round(48 + 190 * ((pixelDepth - minDepth) / depthRange));
+ color2 = [value, value, value];
+ }
+ } else {
+ color2 = regionColor;
+ }
+ rgb2[offset] = color2[0];
+ rgb2[offset + 1] = color2[1];
+ rgb2[offset + 2] = color2[2];
+ }
+ }
+ }
+ if (requestValue.buffer === "wireframe") {
+ for (const triangle of triangles) {
+ const color2 = triangle.frontFacing ? [225, 235, 245] : [230, 72, 84];
+ for (const [a, b] of [
+ [0, 1],
+ [1, 2],
+ [2, 0]
+ ]) {
+ drawLine(rgb2, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color2);
+ }
+ }
+ }
+ const regions = [...regionMap.values()].sort((a, b) => a.nodePath.localeCompare(b.nodePath));
+ if (requestValue.buffer === "semantic-overlay") {
+ for (const region of regions)
+ drawRegionBox(rgb2, size, region);
+ }
+ return {
+ id: requestValue.id,
+ label: requestValue.label,
+ camera,
+ buffer: requestValue.buffer,
+ ...requestValue.variant ? { variant: requestValue.variant } : {},
+ width: size,
+ height: size,
+ rgb: rgb2,
+ png: encodePng(rgb2, size, size),
+ regions,
+ ...requestValue.phaseFractions ? { phaseFractions: requestValue.phaseFractions } : {}
+ };
+}
+function renderDiagnosticViews(root, requests, options = {}) {
+ return requests.map((viewRequest) => renderDiagnosticView(root, viewRequest, options));
+}
+var GENERIC_DIAGNOSTIC_BUFFER_IDS, frozenCamera = (id, name, dir) => Object.freeze({ id, name, dir: Object.freeze([...dir]) }), GENERIC_DIAGNOSTIC_CAMERAS, EXTRA_CAMERAS, cameraById, request = (value) => Object.freeze({
+ ...value,
+ ...value.omitRolePrefixes ? { omitRolePrefixes: Object.freeze([...value.omitRolePrefixes]) } : {},
+ ...value.focusRolePrefixes ? { focusRolePrefixes: Object.freeze([...value.focusRolePrefixes]) } : {},
+ ...value.phaseFractions ? { phaseFractions: Object.freeze([...value.phaseFractions]) } : {}
+}), GENERIC_DIAGNOSTIC_REQUESTS, CATEGORY_REQUESTS, MATERIAL_GRAZING_REQUEST, IDENTITY;
+var init_diagnostic = __esm(() => {
+ init_contracts();
+ init_character3();
+ init_png();
+ GENERIC_DIAGNOSTIC_BUFFER_IDS = [
+ "silhouette-unlit",
+ "wireframe",
+ "normals-backface",
+ "depth-contact",
+ "semantic-overlay"
+ ];
+ GENERIC_DIAGNOSTIC_CAMERAS = Object.freeze([
+ frozenCamera("front", "Front", [1, 0, 0]),
+ frozenCamera("right", "Right", [0, 0, 1]),
+ frozenCamera("back", "Back", [-1, 0, 0]),
+ frozenCamera("left", "Left", [0, 0, -1]),
+ frozenCamera("top", "Top", [0, 1, 0.0001]),
+ frozenCamera("three-quarter", "3/4", [0.7, 0.5, 0.7])
+ ]);
+ EXTRA_CAMERAS = Object.freeze({
+ underside: frozenCamera("underside", "Canopy underside", [0.15, -0.85, 0.5]),
+ grazing: frozenCamera("grazing", "Material grazing light", [0.08, 0.12, 1])
+ });
+ cameraById = new Map([...GENERIC_DIAGNOSTIC_CAMERAS, ...Object.values(EXTRA_CAMERAS)].map((camera) => [
+ camera.id,
+ camera
+ ]));
+ GENERIC_DIAGNOSTIC_REQUESTS = Object.freeze(GENERIC_DIAGNOSTIC_CAMERAS.flatMap((camera) => GENERIC_DIAGNOSTIC_BUFFER_IDS.map((buffer) => request({
+ id: `generic.${camera.id}.${buffer}`,
+ label: `${camera.name} ${buffer}`,
+ cameraId: camera.id,
+ buffer,
+ scope: "generic"
+ }))));
+ CATEGORY_REQUESTS = Object.freeze({
+ prop: Object.freeze([]),
+ vfx: Object.freeze([]),
+ environment: Object.freeze([]),
+ architecture: Object.freeze([]),
+ character: Object.freeze([]),
+ vehicle: Object.freeze([
+ request({
+ id: "vehicle.underbody",
+ label: "Vehicle underbody and support plane",
+ cameraId: "underside",
+ buffer: "semantic-overlay",
+ scope: "category",
+ variant: "vehicle-underbody",
+ focusRolePrefixes: [
+ "chassis.",
+ "wheel.",
+ "axle.",
+ "support.",
+ "contact.",
+ "diagnostic.vehicle."
+ ]
+ }),
+ request({
+ id: "vehicle.wheel-section.right",
+ label: "Vehicle wheel section",
+ cameraId: "right",
+ buffer: "semantic-overlay",
+ scope: "category",
+ variant: "vehicle-wheel-section",
+ focusRolePrefixes: ["wheel.", "axle.", "hub.", "tire."]
+ })
+ ]),
+ vegetation: Object.freeze([
+ request({
+ id: "vegetation.canopy-underside",
+ label: "Vegetation canopy underside",
+ cameraId: "underside",
+ buffer: "normals-backface",
+ scope: "category",
+ variant: "vegetation-canopy-underside",
+ focusRolePrefixes: ["canopy.", "foliage.", "leaf."]
+ })
+ ])
+ });
+ MATERIAL_GRAZING_REQUEST = request({
+ id: "material.grazing-light",
+ label: "Material grazing light",
+ cameraId: "grazing",
+ buffer: "silhouette-unlit",
+ scope: "material",
+ variant: "material-grazing-light"
+ });
+ IDENTITY = new Float64Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+});
+
+// src/views/pose.ts
+function findClip(clips, name) {
+ const q = name.trim().toLowerCase();
+ const named = clips.filter((c) => typeof c.name === "string");
+ return named.find((c) => c.name.toLowerCase() === q) ?? named.find((c) => c.name.toLowerCase().includes(q)) ?? undefined;
+}
+function clipNames(clips) {
+ return clips.map((c) => typeof c.name === "string" ? c.name : "(unnamed)");
+}
+function prepareClip(root, clip) {
+ const nodeNames = new Set;
+ root.traverse?.((obj) => {
+ const n = obj.name;
+ if (n)
+ nodeNames.add(n);
+ });
+ const tracks = [];
+ const unresolved = [];
+ let maxTime = 0;
+ for (const track of clip.tracks ?? []) {
+ const raw = track.name;
+ if (!raw)
+ continue;
+ const dot4 = raw.lastIndexOf(".");
+ if (dot4 === -1)
+ continue;
+ const nodeName2 = raw.slice(0, dot4);
+ const property = raw.slice(dot4 + 1);
+ if (property !== "position" && property !== "quaternion" && property !== "scale")
+ continue;
+ const times = track.times ? Array.from(track.times) : [];
+ const values = track.values ? Array.from(track.values) : [];
+ if (times.length === 0 || values.length === 0)
+ continue;
+ if (!nodeNames.has(nodeName2))
+ unresolved.push(raw);
+ if (times[times.length - 1] > maxTime)
+ maxTime = times[times.length - 1];
+ tracks.push({ nodeName: nodeName2, prop: property, stride: PROP_STRIDE[property], times, values });
+ }
+ const duration = clip.duration && clip.duration > 0 ? clip.duration : maxTime;
+ return { name: clip.name ?? "(unnamed)", duration, tracks, unresolved };
+}
+function keyframeIndexAtOrBefore(times, t) {
+ let i = -1;
+ for (let k = 0;k < times.length; k++) {
+ if (times[k] <= t)
+ i = k;
+ else
+ break;
+ }
+ return i;
+}
+function slerpFlat(out, src0, o0, src1, o1, t) {
+ const x0 = src0[o0], y0 = src0[o0 + 1], z0 = src0[o0 + 2], w0 = src0[o0 + 3];
+ const x1 = src1[o1], y1 = src1[o1 + 1], z1 = src1[o1 + 2], w1 = src1[o1 + 3];
+ let cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
+ let bx = x1, by = y1, bz = z1, bw = w1;
+ if (cos < 0) {
+ cos = -cos;
+ bx = -x1;
+ by = -y1;
+ bz = -z1;
+ bw = -w1;
+ }
+ let s0, s1;
+ if (cos > 0.9995) {
+ s0 = 1 - t;
+ s1 = t;
+ } else {
+ const theta = Math.acos(cos);
+ const sin = Math.sin(theta);
+ s0 = Math.sin((1 - t) * theta) / sin;
+ s1 = Math.sin(t * theta) / sin;
+ }
+ const rx = s0 * x0 + s1 * bx;
+ const ry = s0 * y0 + s1 * by;
+ const rz = s0 * z0 + s1 * bz;
+ const rw = s0 * w0 + s1 * bw;
+ const len = Math.hypot(rx, ry, rz, rw) || 1;
+ out[0] = rx / len;
+ out[1] = ry / len;
+ out[2] = rz / len;
+ out[3] = rw / len;
+}
+function sampleTrack(track, t, out) {
+ const { times, values, stride } = track;
+ const i = keyframeIndexAtOrBefore(times, t);
+ if (i < 0) {
+ for (let s = 0;s < stride; s++)
+ out[s] = values[s];
+ return;
+ }
+ if (i >= times.length - 1) {
+ const base = (times.length - 1) * stride;
+ for (let s = 0;s < stride; s++)
+ out[s] = values[base + s];
+ return;
+ }
+ const t0 = times[i];
+ const t1 = times[i + 1];
+ const span = t1 - t0;
+ const a = span > 0.000000001 ? (t - t0) / span : 0;
+ const o0 = i * stride;
+ const o1 = (i + 1) * stride;
+ if (stride === 4) {
+ slerpFlat(quatTmp, values, o0, values, o1, a);
+ out[0] = quatTmp[0];
+ out[1] = quatTmp[1];
+ out[2] = quatTmp[2];
+ out[3] = quatTmp[3];
+ } else {
+ for (let s = 0;s < stride; s++)
+ out[s] = values[o0 + s] + (values[o1 + s] - values[o0 + s]) * a;
+ }
+}
+function poseSceneAtTime(root, prepared, t) {
+ const byName = new Map;
+ root.traverse?.((obj) => {
+ const node = obj;
+ if (node.name && !byName.has(node.name))
+ byName.set(node.name, node);
+ });
+ const buf = [0, 0, 0, 0];
+ for (const track of prepared.tracks) {
+ const node = byName.get(track.nodeName);
+ if (!node)
+ continue;
+ sampleTrack(track, t, buf);
+ if (track.prop === "position")
+ node.position?.set(buf[0], buf[1], buf[2]);
+ else if (track.prop === "scale")
+ node.scale?.set(buf[0], buf[1], buf[2]);
+ else
+ node.quaternion?.set(buf[0], buf[1], buf[2], buf[3]);
+ }
+ root.updateMatrixWorld?.(true);
+}
+function planFrameTimes(duration, count) {
+ if (count <= 1 || duration <= 0)
+ return new Array(Math.max(1, count)).fill(0);
+ const out = [];
+ for (let i = 0;i < count; i++)
+ out.push(duration * i / (count - 1));
+ return out;
+}
+function stampLabel(rgb2, width, height, x0, y0, text, scale2 = 3) {
+ const gw = 3 * scale2;
+ const gh = 5 * scale2;
+ const gap = scale2;
+ const pad = scale2;
+ const totalW = text.length * gw + (text.length - 1) * gap + pad * 2;
+ const totalH = gh + pad * 2;
+ for (let y = y0;y < y0 + totalH; y++) {
+ for (let x = x0;x < x0 + totalW; x++) {
+ if (x < 0 || y < 0 || x >= width || y >= height)
+ continue;
+ const p = (y * width + x) * 3;
+ rgb2[p] = LABEL_BG[0];
+ rgb2[p + 1] = LABEL_BG[1];
+ rgb2[p + 2] = LABEL_BG[2];
+ }
+ }
+ let cx = x0 + pad;
+ const cy = y0 + pad;
+ for (const ch of text.toUpperCase()) {
+ const glyph = GLYPHS[ch] ?? GLYPHS[" "];
+ for (let row = 0;row < 5; row++) {
+ const bits = glyph[row];
+ for (let col = 0;col < 3; col++) {
+ if (!(bits & 1 << 2 - col))
+ continue;
+ for (let sy = 0;sy < scale2; sy++) {
+ for (let sx = 0;sx < scale2; sx++) {
+ const x = cx + col * scale2 + sx;
+ const y = cy + row * scale2 + sy;
+ if (x < 0 || y < 0 || x >= width || y >= height)
+ continue;
+ const p = (y * width + x) * 3;
+ rgb2[p] = LABEL_FG[0];
+ rgb2[p + 1] = LABEL_FG[1];
+ rgb2[p + 2] = LABEL_FG[2];
+ }
+ }
+ }
+ }
+ cx += gw + gap;
+ }
+}
+var PROP_STRIDE, quatTmp, GLYPHS, LABEL_FG, LABEL_BG;
+var init_pose = __esm(() => {
+ PROP_STRIDE = { position: 3, quaternion: 4, scale: 3 };
+ quatTmp = [0, 0, 0, 1];
+ GLYPHS = {
+ "0": [7, 5, 5, 5, 7],
+ "1": [2, 6, 2, 2, 7],
+ "2": [7, 1, 7, 4, 7],
+ "3": [7, 1, 7, 1, 7],
+ "4": [5, 5, 7, 1, 1],
+ "5": [7, 4, 7, 1, 7],
+ "6": [7, 4, 7, 5, 7],
+ "7": [7, 1, 2, 2, 2],
+ "8": [7, 5, 7, 5, 7],
+ "9": [7, 5, 7, 1, 7],
+ "%": [5, 1, 2, 4, 5],
+ " ": [0, 0, 0, 0, 0],
+ A: [2, 5, 7, 5, 5],
+ B: [6, 5, 6, 5, 6],
+ C: [3, 4, 4, 4, 3],
+ D: [6, 5, 5, 5, 6],
+ E: [7, 4, 6, 4, 7],
+ F: [7, 4, 6, 4, 4],
+ G: [3, 4, 5, 5, 3],
+ H: [5, 5, 7, 5, 5],
+ I: [7, 2, 2, 2, 7],
+ J: [1, 1, 1, 5, 2],
+ K: [5, 5, 6, 5, 5],
+ L: [4, 4, 4, 4, 7],
+ M: [5, 7, 7, 5, 5],
+ N: [5, 7, 7, 7, 5],
+ O: [2, 5, 5, 5, 2],
+ P: [6, 5, 6, 4, 4],
+ Q: [2, 5, 5, 2, 1],
+ R: [6, 5, 6, 5, 5],
+ S: [3, 4, 2, 1, 6],
+ T: [7, 2, 2, 2, 2],
+ U: [5, 5, 5, 5, 7],
+ V: [5, 5, 5, 5, 2],
+ W: [5, 5, 5, 7, 5],
+ X: [5, 5, 2, 5, 5],
+ Y: [5, 5, 2, 2, 2],
+ Z: [7, 1, 2, 4, 7],
+ "/": [1, 1, 2, 4, 4],
+ "-": [0, 0, 7, 0, 0],
+ ".": [0, 0, 0, 0, 2]
+ };
+ LABEL_FG = [255, 224, 64];
+ LABEL_BG = [12, 12, 14];
+});
+
+// src/views/annotate.ts
+function stampAxisGnomon(rgb2, size, viewDir) {
+ const zl = Math.hypot(viewDir[0], viewDir[1], viewDir[2]) || 1;
+ const z = [viewDir[0] / zl, viewDir[1] / zl, viewDir[2] / zl];
+ const up = Math.abs(z[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];
+ const cx = [
+ up[1] * z[2] - up[2] * z[1],
+ up[2] * z[0] - up[0] * z[2],
+ up[0] * z[1] - up[1] * z[0]
+ ];
+ const xl = Math.hypot(cx[0], cx[1], cx[2]) || 1;
+ const bx = [cx[0] / xl, cx[1] / xl, cx[2] / xl];
+ const by = [
+ z[1] * bx[2] - z[2] * bx[1],
+ z[2] * bx[0] - z[0] * bx[2],
+ z[0] * bx[1] - z[1] * bx[0]
+ ];
+ const len = Math.max(12, Math.round(size * 0.055));
+ const ox = len + 10;
+ const oy = size - len - 10;
+ for (const { label, axis, color: color2 } of GNOMON_AXES) {
+ const dx = axis[0] * bx[0] + axis[1] * bx[1] + axis[2] * bx[2];
+ const dy = axis[0] * by[0] + axis[1] * by[1] + axis[2] * by[2];
+ if (Math.hypot(dx, dy) < 0.25)
+ continue;
+ const ex = ox + dx * len;
+ const ey = oy - dy * len;
+ const steps = Math.ceil(Math.hypot(ex - ox, ey - oy));
+ for (let s = 0;s <= steps; s++) {
+ const px = Math.round(ox + (ex - ox) * s / steps);
+ const py = Math.round(oy + (ey - oy) * s / steps);
+ for (let ty = 0;ty < 2; ty++) {
+ for (let tx = 0;tx < 2; tx++) {
+ const x = px + tx;
+ const y = py + ty;
+ if (x < 0 || y < 0 || x >= size || y >= size)
+ continue;
+ const p = (y * size + x) * 3;
+ rgb2[p] = color2[0];
+ rgb2[p + 1] = color2[1];
+ rgb2[p + 2] = color2[2];
+ }
+ }
+ }
+ stampLabel(rgb2, size, size, Math.round(ex) + 2, Math.round(ey) - 6, label, 1);
+ }
+}
+function annotateViewCell(rgb2, size, view) {
+ const inset = Math.max(2, Math.round(size / 96));
+ const width = size - inset * 2;
+ if (width < 7 || (4 * view.name.length + 1) * inset <= width) {
+ stampLabel(rgb2, size, size, inset, inset, view.name, inset);
+ } else {
+ const minimumScale = size >= 128 ? 2 : 1;
+ const scale2 = Math.max(minimumScale, Math.floor(width / (4 * view.name.length + 1)));
+ const columns = Math.max(1, Math.floor((width / scale2 - 1) / 4));
+ const rows = Math.min(3, Math.floor((size - inset * 2) / (7 * scale2)));
+ let remaining = view.name.toUpperCase();
+ for (let row = 0;row < rows && remaining; row++) {
+ let line = remaining;
+ if (remaining.length > columns) {
+ if (row === rows - 1) {
+ line = `${remaining.slice(0, Math.max(0, columns - 3)).trimEnd()}${".".repeat(Math.min(3, columns))}`;
+ remaining = "";
+ } else {
+ const space = remaining.lastIndexOf(" ", columns);
+ const end = space > 0 ? space : columns;
+ line = remaining.slice(0, end);
+ remaining = remaining.slice(end).trimStart();
+ }
+ } else
+ remaining = "";
+ stampLabel(rgb2, size, size, inset, inset + row * 7 * scale2, line, scale2);
+ }
+ }
+ stampAxisGnomon(rgb2, size, view.dir);
+}
+var GNOMON_AXES;
+var init_annotate = __esm(() => {
+ init_pose();
+ GNOMON_AXES = [
+ { label: "X", axis: [1, 0, 0], color: [235, 80, 70] },
+ { label: "Y", axis: [0, 1, 0], color: [90, 205, 90] },
+ { label: "Z", axis: [0, 0, 1], color: [90, 145, 245] }
+ ];
+});
+
+// src/views/grid.ts
+function compositeCellGrid(cells, size, cols = GRID_COLS) {
+ if (cells.length === 0)
+ throw new Error("compositeCellGrid: no cells to composite");
+ const rows = Math.ceil(cells.length / cols);
+ const width = cols * size + (cols + 1) * PAD;
+ const height = rows * size + (rows + 1) * PAD;
+ const grid = new Uint8Array(width * height * 3);
+ for (let p = 0;p < width * height; p++) {
+ grid[p * 3] = PAD_COLOR[0];
+ grid[p * 3 + 1] = PAD_COLOR[1];
+ grid[p * 3 + 2] = PAD_COLOR[2];
+ }
+ for (let i = 0;i < cells.length; i++) {
+ const cell = cells[i];
+ if (cell.length !== size * size * 3) {
+ throw new Error(`compositeCellGrid: cell ${i} must be ${size * size * 3} bytes (size ${size}), got ${cell.length}`);
+ }
+ const col = i % cols;
+ const row = Math.floor(i / cols);
+ const x0 = PAD + col * (size + PAD);
+ const y0 = PAD + row * (size + PAD);
+ for (let y = 0;y < size; y++) {
+ const src = y * size * 3;
+ const dst = ((y0 + y) * width + x0) * 3;
+ grid.set(cell.subarray(src, src + size * 3), dst);
+ }
+ }
+ return { rgb: grid, width, height };
+}
+function compositeViewPngGrid(pngs, cols = GRID_COLS, views) {
+ if (pngs.length === 0)
+ throw new Error("compositeViewPngGrid: no views to composite");
+ if (views && views.length !== pngs.length) {
+ throw new Error(`compositeViewPngGrid: ${views.length} view specs for ${pngs.length} PNGs — they must align 1:1`);
+ }
+ const decoded = pngs.map((png) => decodePng(png));
+ const size = decoded[0].width;
+ for (const d of decoded) {
+ if (d.width !== size || d.height !== size) {
+ throw new Error(`compositeViewPngGrid: every view must be a ${size}x${size} square; got ${d.width}x${d.height}`);
+ }
+ }
+ if (views) {
+ for (let i = 0;i < decoded.length; i++)
+ annotateViewCell(decoded[i].rgb, size, views[i]);
+ }
+ const { rgb: rgb2, width, height } = compositeCellGrid(decoded.map((d) => d.rgb), size, cols);
+ return { png: encodePng(rgb2, width, height), width, height, cellSize: size };
+}
+var PAD = 4, PAD_COLOR, GRID_COLS = 3;
+var init_grid = __esm(() => {
+ init_annotate();
+ init_png();
+ PAD_COLOR = [10, 11, 13];
+});
+
+// src/views/capture-limits.ts
+var exports_capture_limits = {};
+__export(exports_capture_limits, {
+ resolveCaptureLimits: () => resolveCaptureLimits,
+ enforcePngCaptureBudget: () => enforcePngCaptureBudget,
+ enforceCapturePixels: () => enforceCapturePixels,
+ enforceCaptureBytes: () => enforceCaptureBytes,
+ DEFAULT_CAPTURE_LIMITS: () => DEFAULT_CAPTURE_LIMITS
+});
+function resolveCaptureLimits(limits = {}) {
+ const result = { ...DEFAULT_CAPTURE_LIMITS };
+ for (const key of ["maxTotalPixels", "maxOutputBytes"]) {
+ const value = limits[key];
+ if (value !== undefined) {
+ if (!Number.isSafeInteger(value) || value < 1)
+ throw new Error(`capture limit ${key} must be a positive integer`);
+ result[key] = Math.min(value, result[key]);
+ }
+ }
+ return result;
+}
+function enforceCapturePixels(cells, size, cols, limits, compose = true) {
+ if (!Number.isSafeInteger(cells) || cells < 1 || !Number.isSafeInteger(size) || size < 1 || !Number.isSafeInteger(cols) || cols < 1)
+ throw new Error("invalid capture dimensions");
+ const pixels = cells * size * size + (compose ? (cols * size + (cols + 1) * PAD) * (Math.ceil(cells / cols) * size + (Math.ceil(cells / cols) + 1) * PAD) : 0);
+ if (pixels > resolveCaptureLimits(limits).maxTotalPixels)
+ throw new Error(`capture pixel budget exceeded: ${pixels}`);
+ return pixels;
+}
+function enforceCaptureBytes(images, limits) {
+ const bytes = images.reduce((sum, image) => sum + image.byteLength, 0);
+ if (bytes > resolveCaptureLimits(limits).maxOutputBytes)
+ throw new Error(`capture byte budget exceeded: ${bytes}`);
+ return bytes;
+}
+function enforcePngCaptureBudget(images, limits) {
+ enforceCaptureBytes(images, limits);
+ let pixels = 0;
+ for (const png of images) {
+ if (png.byteLength < 24)
+ throw new Error("invalid PNG header");
+ const view = new DataView(png.buffer, png.byteOffset, png.byteLength);
+ if (view.getUint32(0) !== 2303741511 || view.getUint32(12) !== 1229472850)
+ throw new Error("invalid PNG header");
+ pixels += view.getUint32(16) * view.getUint32(20);
+ }
+ if (pixels > resolveCaptureLimits(limits).maxTotalPixels)
+ throw new Error(`capture pixel budget exceeded: ${pixels}`);
+}
+var DEFAULT_CAPTURE_LIMITS;
+var init_capture_limits = __esm(() => {
+ init_grid();
+ DEFAULT_CAPTURE_LIMITS = Object.freeze({
+ maxTotalPixels: 24000000,
+ maxOutputBytes: 32 * 1024 * 1024
+ });
+});
+
+// src/views/background.ts
+var GRID_BACKGROUND_RGB, GRID_BACKGROUND_HEX = "#1a1a1a";
+var init_background = __esm(() => {
+ GRID_BACKGROUND_RGB = [26, 26, 26];
+});
+
+// src/views/raster.ts
+function orbitDir(azimuthDeg, elevationDeg) {
+ const el = Math.min(MAX_ELEVATION_DEG, Math.max(MIN_ELEVATION_DEG, elevationDeg)) * Math.PI / 180;
+ const az = azimuthDeg * Math.PI / 180;
+ const cosEl = Math.cos(el);
+ return [cosEl * Math.cos(az), Math.sin(el), cosEl * Math.sin(az)];
+}
+function orbitAnglesOf(dir) {
+ const [x, y, z] = normalize3(dir);
+ const azimuthDeg = (Math.atan2(z, x) * 180 / Math.PI % 360 + 360) % 360;
+ return {
+ azimuthDeg: +azimuthDeg.toFixed(2),
+ elevationDeg: +(Math.asin(Math.min(1, Math.max(-1, y))) * 180 / Math.PI).toFixed(2)
+ };
+}
+function resolveGridViews(variant) {
+ return variant?.trim().toLowerCase() === "rear-quarter" ? SIX_VIEWS_REAR_QUARTER : SIX_VIEWS;
+}
+function normalize3(v) {
+ const len = Math.hypot(v[0], v[1], v[2]) || 1;
+ return [v[0] / len, v[1] / len, v[2] / len];
+}
+function cross3(a, b) {
+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+}
+function dot4(a, b) {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+}
+function collectTriangles(root) {
+ root.updateMatrixWorld?.(true);
+ const tris = [];
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ root.traverse?.((obj) => {
+ const mesh = obj;
+ if (!mesh.isMesh || mesh.visible === false)
+ return;
+ const geo = mesh.geometry;
+ const pos = geo?.getAttribute?.("position");
+ if (!geo || !pos || pos.itemSize !== 3)
+ return;
+ const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
+ const colorOf = (mat) => {
+ const c = mat?.color;
+ return c ? [clamp012(c.r), clamp012(c.g), clamp012(c.b)] : [0.7, 0.7, 0.7];
+ };
+ const groups = mats.length > 1 && geo.groups?.length ? geo.groups : undefined;
+ const materialAt = (bufferPos) => {
+ if (!groups)
+ return mats[0];
+ for (const g of groups) {
+ if (bufferPos >= g.start && bufferPos < g.start + g.count) {
+ return mats[g.materialIndex ?? 0];
+ }
+ }
+ return mats[0];
+ };
+ const m = mesh.matrixWorld?.elements;
+ if (!m)
+ return;
+ const arr = pos.array;
+ const world = new Float64Array(pos.count * 3);
+ for (let i = 0;i < pos.count; i++) {
+ const x = arr[i * 3];
+ const y = arr[i * 3 + 1];
+ const z = arr[i * 3 + 2];
+ const wx = m[0] * x + m[4] * y + m[8] * z + m[12];
+ const wy = m[1] * x + m[5] * y + m[9] * z + m[13];
+ const wz = m[2] * x + m[6] * y + m[10] * z + m[14];
+ world[i * 3] = wx;
+ world[i * 3 + 1] = wy;
+ world[i * 3 + 2] = wz;
+ if (wx < min[0])
+ min[0] = wx;
+ if (wy < min[1])
+ min[1] = wy;
+ if (wz < min[2])
+ min[2] = wz;
+ if (wx > max[0])
+ max[0] = wx;
+ if (wy > max[1])
+ max[1] = wy;
+ if (wz > max[2])
+ max[2] = wz;
+ }
+ const pushTri = (a, b, c2, material) => {
+ const v = new Float64Array(9);
+ v[0] = world[a * 3];
+ v[1] = world[a * 3 + 1];
+ v[2] = world[a * 3 + 2];
+ v[3] = world[b * 3];
+ v[4] = world[b * 3 + 1];
+ v[5] = world[b * 3 + 2];
+ v[6] = world[c2 * 3];
+ v[7] = world[c2 * 3 + 1];
+ v[8] = world[c2 * 3 + 2];
+ tris.push({
+ v,
+ color: colorOf(material),
+ alpha: clamp012(material?.opacity ?? 1),
+ doubleSided: material?.doubleSided === true
+ });
+ };
+ const index = geo.index;
+ if (index) {
+ const ia = index.array;
+ for (let i = 0;i + 2 < index.count; i += 3) {
+ pushTri(ia[i], ia[i + 1], ia[i + 2], materialAt(i));
+ }
+ } else {
+ for (let i = 0;i + 2 < pos.count; i += 3) {
+ pushTri(i, i + 1, i + 2, materialAt(i));
+ }
+ }
+ });
+ if (!Number.isFinite(min[0])) {
+ return { tris, bbox: { min: [0, 0, 0], max: [0, 0, 0] } };
+ }
+ return { tris, bbox: { min, max } };
+}
+function clamp012(n) {
+ return n < 0 ? 0 : n > 1 ? 1 : n;
+}
+function linearToSrgb(c) {
+ const v = clamp012(c);
+ return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
+}
+function rasterizeView(root, dir, opts = {}) {
+ const size = opts.size ?? 256;
+ const cull = opts.backfaceCull ?? true;
+ const { tris, bbox } = collectTriangles(root);
+ const out = new Uint8Array(size * size * 3);
+ for (let i = 0;i < size * size; i++) {
+ out[i * 3] = BG[0];
+ out[i * 3 + 1] = BG[1];
+ out[i * 3 + 2] = BG[2];
+ }
+ if (tris.length === 0)
+ return out;
+ const z = normalize3(dir);
+ const upHint = Math.abs(z[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];
+ const x = normalize3(cross3(upHint, z));
+ const y = cross3(z, x);
+ const frameMin = opts.frameBounds ? opts.frameBounds.min : bbox.min;
+ const frameMax = opts.frameBounds ? opts.frameBounds.max : bbox.max;
+ const center = [
+ (frameMin[0] + frameMax[0]) / 2,
+ (frameMin[1] + frameMax[1]) / 2,
+ (frameMin[2] + frameMax[2]) / 2
+ ];
+ let ext = 0.000001;
+ for (let ci = 0;ci < 8; ci++) {
+ const px = (ci & 1 ? frameMax[0] : frameMin[0]) - center[0];
+ const py = (ci & 2 ? frameMax[1] : frameMin[1]) - center[1];
+ const pz = (ci & 4 ? frameMax[2] : frameMin[2]) - center[2];
+ const p = [px, py, pz];
+ ext = Math.max(ext, Math.abs(dot4(p, x)), Math.abs(dot4(p, y)));
+ }
+ const scale2 = size * 0.45 / ext;
+ const half = size / 2;
+ const zbuf = new Float64Array(size * size).fill(-Infinity);
+ const sx = new Float64Array(3);
+ const sy = new Float64Array(3);
+ const sz = new Float64Array(3);
+ for (const tri of tris) {
+ const e1 = [tri.v[3] - tri.v[0], tri.v[4] - tri.v[1], tri.v[5] - tri.v[2]];
+ const e2 = [tri.v[6] - tri.v[0], tri.v[7] - tri.v[1], tri.v[8] - tri.v[2]];
+ const n = cross3(e1, e2);
+ const nLen = Math.hypot(n[0], n[1], n[2]);
+ if (nLen < 0.000000000001)
+ continue;
+ const N = [n[0] / nLen, n[1] / nLen, n[2] / nLen];
+ const facing = dot4(N, z);
+ if (cull && facing <= 0 && !tri.doubleSided)
+ continue;
+ if (tri.alpha <= 0)
+ continue;
+ for (let i = 0;i < 3; i++) {
+ const px = tri.v[i * 3] - center[0];
+ const py = tri.v[i * 3 + 1] - center[1];
+ const pz = tri.v[i * 3 + 2] - center[2];
+ const p = [px, py, pz];
+ sx[i] = half + dot4(p, x) * scale2;
+ sy[i] = half - dot4(p, y) * scale2;
+ sz[i] = dot4(p, z);
+ }
+ const lambert = Math.max(0, dot4(N, KEY_DIR));
+ const lit = Math.min(1, AMBIENT + KEY_INTENSITY * lambert);
+ const r = Math.round(linearToSrgb(tri.color[0] * lit) * 255);
+ const g = Math.round(linearToSrgb(tri.color[1] * lit) * 255);
+ const b = Math.round(linearToSrgb(tri.color[2] * lit) * 255);
+ const minX = Math.max(0, Math.floor(Math.min(sx[0], sx[1], sx[2])));
+ const maxX = Math.min(size - 1, Math.ceil(Math.max(sx[0], sx[1], sx[2])));
+ const minY = Math.max(0, Math.floor(Math.min(sy[0], sy[1], sy[2])));
+ const maxY = Math.min(size - 1, Math.ceil(Math.max(sy[0], sy[1], sy[2])));
+ if (minX > maxX || minY > maxY)
+ continue;
+ const ax = sx[0], ay = sy[0], bx2 = sx[1], by = sy[1], cx = sx[2], cy = sy[2];
+ const area = (bx2 - ax) * (cy - ay) - (by - ay) * (cx - ax);
+ if (Math.abs(area) < 0.000000001)
+ continue;
+ const invArea = 1 / area;
+ for (let py = minY;py <= maxY; py++) {
+ for (let px = minX;px <= maxX; px++) {
+ const cxp = px + 0.5;
+ const cyp = py + 0.5;
+ const w0 = ((bx2 - ax) * (cyp - ay) - (by - ay) * (cxp - ax)) * invArea;
+ const w1 = ((cx - bx2) * (cyp - by) - (cy - by) * (cxp - bx2)) * invArea;
+ const w2 = 1 - w0 - w1;
+ if (w0 < 0 || w1 < 0 || w2 < 0)
+ continue;
+ const depth = w1 * sz[0] + w2 * sz[1] + w0 * sz[2];
+ const pi = py * size + px;
+ if (depth <= zbuf[pi])
+ continue;
+ zbuf[pi] = depth;
+ if (tri.alpha >= 1) {
+ out[pi * 3] = r;
+ out[pi * 3 + 1] = g;
+ out[pi * 3 + 2] = b;
+ } else {
+ const inverse = 1 - tri.alpha;
+ out[pi * 3] = Math.round(r * tri.alpha + out[pi * 3] * inverse);
+ out[pi * 3 + 1] = Math.round(g * tri.alpha + out[pi * 3 + 1] * inverse);
+ out[pi * 3 + 2] = Math.round(b * tri.alpha + out[pi * 3 + 2] * inverse);
+ }
+ }
+ }
+ }
+ return out;
+}
+function measureBounds(root) {
+ const { bbox } = collectTriangles(root);
+ return { min: [...bbox.min], max: [...bbox.max] };
+}
+function coverage(rgb2, size) {
+ let filled = 0;
+ for (let i = 0;i < size * size; i++) {
+ if (rgb2[i * 3] !== BG[0] || rgb2[i * 3 + 1] !== BG[1] || rgb2[i * 3 + 2] !== BG[2])
+ filled++;
+ }
+ return filled / (size * size);
+}
+function hideNodeInScene(root, match) {
+ const test = typeof match === "function" ? match : (name) => {
+ const t = match.toLowerCase();
+ const n = name.toLowerCase();
+ return n === t || n.startsWith(t);
+ };
+ let hidden = 0;
+ const r = root;
+ r.traverse?.((obj) => {
+ const node = obj;
+ if (!node.name || !test(node.name))
+ return;
+ hidden++;
+ node.traverse?.((d) => {
+ d.visible = false;
+ });
+ });
+ return hidden;
+}
+var SIX_VIEWS, SIX_VIEWS_REAR_QUARTER, MIN_ELEVATION_DEG = -89, MAX_ELEVATION_DEG = 89, BG, AMBIENT = 0.25, KEY_INTENSITY = 1.1, KEY_DIR;
+var init_raster = __esm(() => {
+ init_background();
+ SIX_VIEWS = [
+ { name: "Front", dir: [1, 0, 0] },
+ { name: "Right", dir: [0, 0, 1] },
+ { name: "Back", dir: [-1, 0, 0] },
+ { name: "Left", dir: [0, 0, -1] },
+ { name: "Top", dir: [0, 1, 0.0001] },
+ { name: "3/4", dir: [0.7, 0.5, 0.7] }
+ ];
+ SIX_VIEWS_REAR_QUARTER = [
+ ...SIX_VIEWS.slice(0, 5),
+ { name: "3/4 Rear", dir: [-0.7, 0.5, -0.7] }
+ ];
+ BG = GRID_BACKGROUND_RGB;
+ KEY_DIR = normalize3([1.5, 2, 1]);
+});
+
+// src/views/camera.ts
+import { Vector3 as Vector325, Matrix4 as Matrix46, Euler as Euler4 } from "three";
+function strict(value, keys, label) {
+ for (const key of Object.keys(value))
+ if (!keys.includes(key))
+ throw new Error(`${label}.${key} is unknown`);
+}
+function finite2(n, label) {
+ if (!Number.isFinite(n))
+ throw new Error(`${label} must be finite`);
+ return n;
+}
+function triple(v, label) {
+ if (!Array.isArray(v) || v.length !== 3 || v.some((n) => !Number.isFinite(n)))
+ throw new Error(`${label} must contain three finite numbers`);
+ return [...v];
+}
+function listCameraSubjects(root) {
+ const result = [];
+ const visit = (node2, path) => {
+ result.push({ node: node2, path, name: node2.name });
+ const counts = new Map;
+ for (const child of node2.children ?? []) {
+ const count = counts.get(child.name) ?? 0;
+ counts.set(child.name, count + 1);
+ visit(child, `${path}/${encodeURIComponent(child.name)}[${count}]`);
+ }
+ };
+ const node = root;
+ visit(node, `/${encodeURIComponent(node.name)}[0]`);
+ return result;
+}
+function selectCameraSubject(root, subject) {
+ if (subject) {
+ strict(subject, ["path", "name"], "subject");
+ if (subject.path === undefined === (subject.name === undefined))
+ throw new Error("subject requires exactly one of path or name");
+ }
+ const all = listCameraSubjects(root);
+ const matches = !subject ? [all[0]] : all.filter((n) => subject.path !== undefined ? n.path === subject.path : n.name === subject.name);
+ if (matches.length !== 1)
+ throw new Error(`${matches.length ? "ambiguous" : "missing"} camera subject; choose an exact path: ${all.slice(0, 40).map((n) => n.path).join(", ")}`);
+ return matches[0];
+}
+function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {
+ if (!Number.isFinite(padding) || padding <= 0 || padding > 100)
+ throw new Error("padding must be in (0,100]");
+ const target = vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);
+ const z = vec(dir).normalize();
+ if (!z.length())
+ throw new Error("camera direction must be non-zero");
+ const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector325(0, 0, -1) : new Vector325(0, 1, 0);
+ const x = hint.clone().cross(z).normalize();
+ if (x.length() < 0.000000001)
+ throw new Error("camera up must not be collinear with view");
+ const y = z.clone().cross(x);
+ let extent2 = 0.000001;
+ for (let i = 0;i < 8; i++) {
+ const p = new Vector325((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);
+ extent2 = Math.max(extent2, Math.abs(p.dot(x)), Math.abs(p.dot(y)));
+ }
+ const depthMin = bounds.min.map((v, i) => Math.min(v, sceneBounds.min[i]));
+ const depthMax = bounds.max.map((v, i) => Math.max(v, sceneBounds.max[i]));
+ const radius = Math.max(vec(depthMax).distanceTo(target), vec(depthMin).distanceTo(target)) * 2;
+ const distance = Math.max(radius * 2, 1);
+ return {
+ version: "kiln.camera.v1",
+ projection: "orthographic",
+ position: tuple5(target.clone().addScaledVector(z, distance)),
+ target: tuple5(target),
+ up: tuple5(y),
+ aspect: 1,
+ near: Math.max(0.000001, distance - radius),
+ far: distance + radius + 1,
+ halfHeight: extent2 * padding / 0.9
+ };
+}
+function validateResolvedAssetCamera(value) {
+ strict(value, [
+ "version",
+ "projection",
+ "position",
+ "target",
+ "up",
+ "aspect",
+ "near",
+ "far",
+ "halfHeight",
+ "fovDeg"
+ ], "camera");
+ if (value.version !== "kiln.camera.v1")
+ throw new Error("camera.version must be kiln.camera.v1");
+ const camera = {
+ ...value,
+ position: triple(value.position, "position"),
+ target: triple(value.target, "target"),
+ up: triple(value.up, "up")
+ };
+ const view = vec(camera.target).sub(vec(camera.position));
+ const up = vec(camera.up);
+ if (view.length() < 0.000000001)
+ throw new Error("camera target must differ from position");
+ if (up.length() < 0.000000001 || view.clone().cross(up).length() <= view.length() * up.length() * 0.000000001)
+ throw new Error("camera up must be non-zero and not collinear with view");
+ if (finite2(camera.aspect, "aspect") <= 0 || finite2(camera.near, "near") <= 0 || finite2(camera.far, "far") <= camera.near)
+ throw new Error("camera requires positive aspect and 0 < near < far");
+ if (camera.projection === "orthographic") {
+ if (!Number.isFinite(camera.halfHeight) || camera.halfHeight <= 0 || camera.fovDeg !== undefined)
+ throw new Error("orthographic camera requires positive halfHeight and no fovDeg");
+ } else if (camera.projection === "perspective") {
+ if (!Number.isFinite(camera.fovDeg) || camera.fovDeg <= 0 || camera.fovDeg >= 180 || camera.halfHeight !== undefined)
+ throw new Error("perspective camera requires 0 < fovDeg < 180 and no halfHeight");
+ } else
+ throw new Error("unknown camera projection");
+ return camera;
+}
+function resolveAssetCamera(root, shot = {}) {
+ strict(shot, ["name", "subject", "visibility", "camera"], "shot");
+ const rootNode = root;
+ rootNode.updateMatrixWorld(true);
+ const selected = selectCameraSubject(root, shot.subject);
+ const bounds = measureBounds(selected.node);
+ if (!collectTriangles(selected.node).tris.length)
+ throw new Error(`subject ${selected.path} has no visible geometry`);
+ const request2 = shot.camera ?? { type: "orbit" };
+ let camera;
+ if (request2.type === "orbit") {
+ strict(request2, ["type", "azimuthDeg", "elevationDeg", "relativeTo", "padding"], "camera");
+ const relative = request2.relativeTo ?? "world";
+ if (!["world", "asset", "part"].includes(relative))
+ throw new Error("invalid relativeTo");
+ const dir = vec(orbitDir(finite2(request2.azimuthDeg ?? 45, "azimuthDeg"), finite2(request2.elevationDeg ?? 25, "elevationDeg")));
+ let up;
+ if (relative !== "world") {
+ const node = relative === "part" ? selected.node : rootNode;
+ dir.transformDirection(node.matrixWorld);
+ up = tuple5(new Vector325(0, 1, 0).transformDirection(node.matrixWorld));
+ }
+ camera = cameraFromBounds(bounds, tuple5(dir), request2.padding ?? 1.2, up, measureBounds(root));
+ } else if (request2.type === "explicit") {
+ strict(request2, [
+ "type",
+ "projection",
+ "position",
+ "target",
+ "up",
+ "halfHeight",
+ "fovDeg",
+ "near",
+ "far",
+ "relativeTo",
+ "frame",
+ "framing",
+ "padding",
+ "targetOffset"
+ ], "camera");
+ if (request2.projection === "orthographic" && request2.fovDeg !== undefined || request2.projection === "perspective" && request2.halfHeight !== undefined)
+ throw new Error("projection and lens fields conflict");
+ const relative = request2.relativeTo ?? "world";
+ if (!["world", "asset", "part", "local"].includes(relative))
+ throw new Error("invalid relativeTo");
+ if (relative === "local" !== Boolean(request2.frame))
+ throw new Error("local coordinates require frame; frame is only valid for local coordinates");
+ if (request2.framing !== undefined && !["explicit", "bounds"].includes(request2.framing))
+ throw new Error("invalid framing");
+ if (request2.target === undefined && request2.framing !== "bounds")
+ throw new Error("explicit framing requires target");
+ if (request2.padding !== undefined && request2.framing !== "bounds")
+ throw new Error("padding requires bounds framing");
+ if (request2.framing === "bounds" && request2.halfHeight !== undefined)
+ throw new Error("bounds framing derives halfHeight");
+ let matrix = new Matrix46;
+ if (relative === "asset" || relative === "part")
+ matrix = (relative === "asset" ? rootNode : selected.node).matrixWorld;
+ if (request2.frame) {
+ strict(request2.frame, ["origin", "rotation"], "frame");
+ const rotation = triple(request2.frame.rotation ?? [0, 0, 0], "frame.rotation");
+ matrix.makeRotationFromEuler(new Euler4(...rotation.map((n) => n * Math.PI / 180), "XYZ"));
+ matrix.setPosition(...triple(request2.frame.origin ?? [0, 0, 0], "frame.origin"));
+ }
+ const position = vec(triple(request2.position, "position")).applyMatrix4(matrix);
+ const target = request2.target ? vec(triple(request2.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);
+ const up = vec(triple(request2.up ?? [0, 1, 0], "up")).transformDirection(matrix);
+ const offset = vec(triple(request2.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector325().setFromMatrixPosition(matrix));
+ const radius = vec(bounds.max).sub(vec(bounds.min)).length();
+ camera = {
+ version: "kiln.camera.v1",
+ projection: request2.projection,
+ position: tuple5(position),
+ target: tuple5(target.clone().add(offset)),
+ up: tuple5(up),
+ aspect: 1,
+ near: request2.near ?? 0.001,
+ far: request2.far ?? Math.max(100, position.distanceTo(target) + radius * 4),
+ ...request2.projection === "orthographic" ? { halfHeight: request2.halfHeight ?? Math.max(radius / 2, 0.000001) } : { fovDeg: request2.fovDeg ?? 50 }
+ };
+ if (request2.framing === "bounds") {
+ const direction = position.clone().sub(target);
+ if (direction.lengthSq() < 0.00000000000000000001)
+ throw new Error("bounds framing position and target must differ");
+ const padding = request2.padding ?? 1.2;
+ const fit = cameraFromBounds(bounds, tuple5(direction), padding, tuple5(up), measureBounds(root));
+ if (request2.projection === "orthographic")
+ camera = { ...fit, near: request2.near ?? fit.near, far: request2.far ?? fit.far };
+ else {
+ const fov = finite2(request2.fovDeg ?? 50, "fovDeg");
+ if (fov <= 0 || fov >= 180)
+ throw new Error("invalid fovDeg");
+ const distance = Math.max(radius / 2, 0.000001) * padding / Math.sin(fov * Math.PI / 360);
+ const center = vec(fit.target);
+ camera = {
+ ...camera,
+ position: tuple5(center.clone().add(direction.normalize().multiplyScalar(distance))),
+ target: tuple5(center),
+ far: request2.far ?? Math.max(100, distance + radius * 4)
+ };
+ }
+ camera.position = tuple5(vec(camera.position).add(offset));
+ camera.target = tuple5(vec(camera.target).add(offset));
+ }
+ } else
+ throw new Error("unknown camera type");
+ if (shot.visibility !== undefined && !["context", "isolate"].includes(shot.visibility))
+ throw new Error("invalid visibility");
+ return {
+ name: shot.name ?? selected.name ?? "VIEW",
+ camera: validateResolvedAssetCamera(camera),
+ subject: { path: selected.path, name: selected.name, bounds },
+ visibility: shot.visibility ?? "context"
+ };
+}
+async function withCameraVisibility(root, shot, run2) {
+ if (shot.visibility === "context")
+ return run2();
+ const keep = new Set;
+ selectCameraSubject(root, { path: shot.subject.path }).node.traverse((n) => keep.add(n));
+ const restore = [];
+ root.traverse((n) => {
+ if (n.isMesh && !keep.has(n)) {
+ restore.push([n, n.visible]);
+ n.visible = false;
+ }
+ });
+ try {
+ return await run2();
+ } finally {
+ for (const [node, visible] of restore)
+ node.visible = visible;
+ }
+}
+function rasterizeCamera(root, input, size = 384, backfaceCull = true) {
+ const camera = validateResolvedAssetCamera(input);
+ if (!Number.isInteger(size) || size < 1 || size > 2048)
+ throw new Error("camera size must be an integer in 1..2048");
+ const z = vec(camera.position).sub(vec(camera.target)).normalize(), x = vec(camera.up).cross(z).normalize(), y = z.clone().cross(x), position = vec(camera.position);
+ const out = new Uint8Array(size * size * 3);
+ for (let i = 0;i < size * size; i++)
+ out.set(GRID_BACKGROUND_RGB, i * 3);
+ const depth = new Float64Array(size * size).fill(Infinity);
+ const clip = (points, plane, near) => {
+ const result = [];
+ for (let i = 0;i < points.length; i++) {
+ const a = points[i], b = points[(i + 1) % points.length];
+ const insideA = near ? a.z >= plane : a.z <= plane, insideB = near ? b.z >= plane : b.z <= plane;
+ if (insideA)
+ result.push(a);
+ if (insideA !== insideB)
+ result.push(a.clone().lerp(b, (plane - a.z) / (b.z - a.z)));
+ }
+ return result;
+ };
+ const key = new Vector325(1.5, 2, 1).normalize();
+ const srgb = (n) => n <= 0.0031308 ? n * 12.92 : 1.055 * n ** (1 / 2.4) - 0.055;
+ for (const tri of collectTriangles(root).tris) {
+ const world = [0, 1, 2].map((i) => new Vector325(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));
+ const normal = world[1].clone().sub(world[0]).cross(world[2].clone().sub(world[0])).normalize();
+ if (backfaceCull && !tri.doubleSided && normal.dot(camera.projection === "perspective" ? position.clone().sub(world[0]) : z) <= 0)
+ continue;
+ if (tri.alpha <= 0)
+ continue;
+ const light = Math.min(1, 0.25 + 1.1 * Math.max(0, normal.dot(key)));
+ const color2 = tri.color.map((c) => Math.round(srgb(c * light) * 255));
+ let polygon = world.map((p) => {
+ const d = p.clone().sub(position);
+ return new Vector325(d.dot(x), d.dot(y), -d.dot(z));
+ });
+ polygon = clip(clip(polygon, camera.near, true), camera.far, false);
+ for (let t = 1;t < polygon.length - 1; t++) {
+ const p = [polygon[0], polygon[t], polygon[t + 1]];
+ const screen = p.map((v) => {
+ const half = camera.projection === "orthographic" ? camera.halfHeight : v.z * Math.tan(camera.fovDeg * Math.PI / 360);
+ return [
+ size / 2 + v.x * size / (2 * half * camera.aspect),
+ size / 2 - v.y * size / (2 * half)
+ ];
+ });
+ const [a, b, c] = screen;
+ const area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
+ if (Math.abs(area) < 0.000000001)
+ continue;
+ for (let py = Math.max(0, Math.floor(Math.min(...screen.map((s) => s[1]))));py <= Math.min(size - 1, Math.ceil(Math.max(...screen.map((s) => s[1])))); py++)
+ for (let px = Math.max(0, Math.floor(Math.min(...screen.map((s) => s[0]))));px <= Math.min(size - 1, Math.ceil(Math.max(...screen.map((s) => s[0])))); px++) {
+ const w0 = ((b[0] - a[0]) * (py + 0.5 - a[1]) - (b[1] - a[1]) * (px + 0.5 - a[0])) / area, w1 = ((c[0] - b[0]) * (py + 0.5 - b[1]) - (c[1] - b[1]) * (px + 0.5 - b[0])) / area, w2 = 1 - w0 - w1;
+ if (w0 < 0 || w1 < 0 || w2 < 0)
+ continue;
+ const d = camera.projection === "perspective" ? 1 / (w1 / p[0].z + w2 / p[1].z + w0 / p[2].z) : w1 * p[0].z + w2 * p[1].z + w0 * p[2].z;
+ const index = py * size + px;
+ if (d >= depth[index])
+ continue;
+ depth[index] = d;
+ for (let channel = 0;channel < 3; channel++)
+ out[index * 3 + channel] = Math.round(color2[channel] * tri.alpha + out[index * 3 + channel] * (1 - tri.alpha));
+ }
+ }
+ }
+ return out;
+}
+var vec = (a) => new Vector325(...a), tuple5 = (v) => [v.x || 0, v.y || 0, v.z || 0];
+var init_camera = __esm(() => {
+ init_raster();
+ init_background();
+});
+
+// src/composer/render-port.ts
+function finiteTuple3(value, path) {
+ if (!Array.isArray(value) || value.length !== 3 || value.some((entry) => typeof entry !== "number" || !Number.isFinite(entry)))
+ throw new TypeError(`${path} must be a finite [x,y,z] tuple`);
+ return [value[0], value[1], value[2]];
+}
+function boundedPixelSize(value, path) {
+ if (!Number.isInteger(value) || value < 1 || value > 4096) {
+ throw new TypeError(`${path} must be an integer in [1,4096]`);
+ }
+ return value;
+}
+function validatePbrRenderRequest(input) {
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
+ throw new TypeError("PbrRenderRequest must be an object");
+ }
+ const source = input;
+ for (const key of Object.keys(source)) {
+ if (!PBR_REQUEST_KEYS.has(key))
+ throw new TypeError(`PbrRenderRequest.${key} is unknown`);
+ }
+ if (!(source.glb instanceof Uint8Array) || source.glb.byteLength === 0) {
+ throw new TypeError("PbrRenderRequest.glb must be a non-empty Uint8Array");
+ }
+ const result = { glb: source.glb };
+ if (source.viewDirs !== undefined) {
+ if (!Array.isArray(source.viewDirs) || source.viewDirs.length < 1 || source.viewDirs.length > 12) {
+ throw new TypeError("PbrRenderRequest.viewDirs must contain 1..12 directions");
+ }
+ result.viewDirs = source.viewDirs.map((value, index) => {
+ const direction = finiteTuple3(value, `PbrRenderRequest.viewDirs[${index}]`);
+ if (Math.hypot(...direction) === 0) {
+ throw new TypeError(`PbrRenderRequest.viewDirs[${index}] must be non-zero`);
+ }
+ return direction;
+ });
+ }
+ if (source.size !== undefined)
+ result.size = boundedPixelSize(source.size, "PbrRenderRequest.size");
+ if (source.beautySize !== undefined) {
+ result.beautySize = boundedPixelSize(source.beautySize, "PbrRenderRequest.beautySize");
+ }
+ const hasWidth = source.width !== undefined;
+ const hasHeight = source.height !== undefined;
+ if (hasWidth !== hasHeight) {
+ throw new TypeError("PbrRenderRequest.width and height must be provided together");
+ }
+ if (hasWidth) {
+ result.width = boundedPixelSize(source.width, "PbrRenderRequest.width");
+ result.height = boundedPixelSize(source.height, "PbrRenderRequest.height");
+ }
+ if (source.cameras !== undefined) {
+ if (source.viewDirs !== undefined) {
+ throw new TypeError("PbrRenderRequest.cameras and viewDirs are mutually exclusive");
+ }
+ if (source.size !== undefined || source.beautySize !== undefined) {
+ throw new TypeError("PbrRenderRequest camera mode cannot use legacy size or beautySize");
+ }
+ if (result.width === undefined || result.height === undefined) {
+ throw new TypeError("PbrRenderRequest camera mode requires width and height");
+ }
+ if (!Array.isArray(source.cameras) || source.cameras.length < 1 || source.cameras.length > 12) {
+ throw new TypeError("PbrRenderRequest.cameras must contain 1..12 cameras");
+ }
+ result.cameras = source.cameras.map((value, index) => {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ throw new TypeError(`PbrRenderRequest.cameras[${index}] must be an object`);
+ }
+ const camera = value;
+ if (camera.version !== undefined || camera.projection !== undefined) {
+ const parsed = validateResolvedAssetCamera(camera);
+ if (Math.abs(parsed.aspect - result.width / result.height) > 0.000000001)
+ throw new TypeError("camera aspect must equal width/height");
+ return parsed;
+ }
+ const expected = new Set(["position", "target", "up", "fovDeg", "aspect", "near", "far"]);
+ for (const key of Object.keys(camera)) {
+ if (!expected.has(key))
+ throw new TypeError(`PbrRenderRequest.cameras[${index}].${key} is unknown`);
+ }
+ const position = finiteTuple3(camera.position, `PbrRenderRequest.cameras[${index}].position`);
+ const target = finiteTuple3(camera.target, `PbrRenderRequest.cameras[${index}].target`);
+ const up = finiteTuple3(camera.up, `PbrRenderRequest.cameras[${index}].up`);
+ if (Math.hypot(position[0] - target[0], position[1] - target[1], position[2] - target[2]) === 0) {
+ throw new TypeError(`PbrRenderRequest.cameras[${index}].target must differ from position`);
+ }
+ if (Math.hypot(...up) === 0) {
+ throw new TypeError(`PbrRenderRequest.cameras[${index}].up must be non-zero`);
+ }
+ const view = [
+ target[0] - position[0],
+ target[1] - position[1],
+ target[2] - position[2]
+ ];
+ const cross4 = [
+ view[1] * up[2] - view[2] * up[1],
+ view[2] * up[0] - view[0] * up[2],
+ view[0] * up[1] - view[1] * up[0]
+ ];
+ if (Math.hypot(...cross4) <= Math.hypot(...view) * Math.hypot(...up) * 0.000000001) {
+ throw new TypeError(`PbrRenderRequest.cameras[${index}].up must not be collinear with view`);
+ }
+ const number = (key) => {
+ const parsed = camera[key];
+ if (typeof parsed !== "number" || !Number.isFinite(parsed)) {
+ throw new TypeError(`PbrRenderRequest.cameras[${index}].${key} must be finite`);
+ }
+ return parsed;
+ };
+ const fovDeg = number("fovDeg");
+ const aspect = number("aspect");
+ const near = number("near");
+ const far = number("far");
+ if (fovDeg <= 0 || fovDeg >= 180) {
+ throw new TypeError(`PbrRenderRequest.cameras[${index}].fovDeg must be in (0,180)`);
+ }
+ if (aspect <= 0)
+ throw new TypeError(`PbrRenderRequest.cameras[${index}].aspect must be positive`);
+ if (near <= 0)
+ throw new TypeError(`PbrRenderRequest.cameras[${index}].near must be positive`);
+ if (far <= near)
+ throw new TypeError(`PbrRenderRequest.cameras[${index}].far must exceed near`);
+ const targetAspect = result.width / result.height;
+ if (Math.abs(aspect - targetAspect) > Math.max(1, targetAspect) * 0.000000001) {
+ throw new TypeError(`PbrRenderRequest.cameras[${index}].aspect must equal width/height`);
+ }
+ return { position, target, up, fovDeg, aspect, near, far };
+ });
+ } else if (hasWidth) {
+ throw new TypeError("PbrRenderRequest width and height require camera mode");
+ }
+ if (source.lightingPresetId !== undefined) {
+ if (typeof source.lightingPresetId !== "string" || !source.lightingPresetId.trim() || source.lightingPresetId !== source.lightingPresetId.trim() || source.lightingPresetId.length > 128) {
+ throw new TypeError("PbrRenderRequest.lightingPresetId must be a non-empty string");
+ }
+ result.lightingPresetId = source.lightingPresetId;
+ }
+ return result;
+}
+var PBR_REQUEST_KEYS;
+var init_render_port = __esm(() => {
+ init_camera();
+ init_background();
+ PBR_REQUEST_KEYS = new Set([
+ "glb",
+ "viewDirs",
+ "size",
+ "beautySize",
+ "cameras",
+ "width",
+ "height",
+ "lightingPresetId"
+ ]);
+});
+
+// src/views/capture-cache.ts
+var exports_capture_cache = {};
+__export(exports_capture_cache, {
+ createCachedRenderPort: () => createCachedRenderPort,
+ captureCpuCell: () => captureCpuCell,
+ MemoryCaptureCache: () => MemoryCaptureCache
+});
+import { createHash as createHash4 } from "node:crypto";
+function clone(entry) {
+ const result = structuredClone(entry);
+ if (result.kind === "cpu")
+ result.result.png = Buffer.from(result.result.png);
+ return result;
+}
+
+class MemoryCaptureCache {
+ maxBytes;
+ entries = new Map;
+ bytes = 0;
+ constructor(maxBytes = 64 * 1024 * 1024) {
+ this.maxBytes = maxBytes;
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0)
+ throw new Error("Capture cache bytes must be a nonnegative integer");
+ }
+ async get(key) {
+ const value = this.entries.get(key);
+ if (!value)
+ return;
+ this.entries.delete(key);
+ this.entries.set(key, value);
+ return clone(value.entry);
+ }
+ async put(key, value) {
+ const entry = clone(value);
+ let bytes;
+ if (entry.kind === "gpu") {
+ const { viewsPng, beautyPng, ...metadata } = entry.result;
+ bytes = (viewsPng ?? []).reduce((sum, png) => sum + png.byteLength, 0) + (beautyPng?.byteLength ?? 0) + Buffer.byteLength(JSON.stringify(metadata));
+ } else {
+ const { png, ...metadata } = entry.result;
+ bytes = png.byteLength + Buffer.byteLength(JSON.stringify(metadata));
+ }
+ if (bytes > this.maxBytes)
+ return;
+ const old = this.entries.get(key);
+ if (old) {
+ this.bytes -= old.bytes;
+ this.entries.delete(key);
+ }
+ while (this.bytes + bytes > this.maxBytes) {
+ const first = this.entries.keys().next().value;
+ if (first === undefined)
+ break;
+ this.bytes -= this.entries.get(first).bytes;
+ this.entries.delete(first);
+ }
+ this.entries.set(key, { entry, bytes });
+ this.bytes += bytes;
+ }
+ stats() {
+ return { entries: this.entries.size, bytes: this.bytes, maxBytes: this.maxBytes };
+ }
+}
+function canonical(value) {
+ if (Array.isArray(value))
+ return value.map(canonical);
+ if (value && typeof value === "object")
+ return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, canonical(v)]));
+ if (typeof value === "number" && !Number.isFinite(value))
+ throw new Error("Non-finite capture identity");
+ if (value === undefined || value === null || ["string", "number", "boolean"].includes(typeof value))
+ return value;
+ throw new Error("Capture identity must be data");
+}
+function usable(result, request2, hash) {
+ try {
+ if (!result.ok || !result.rendererId?.trim() || result.derivativeFidelity?.materialFaithful !== true || result.derivativeFidelity.inputGlbSha256 !== hash)
+ return false;
+ const count = (request2.cameras ?? request2.viewDirs).length;
+ if (result.viewsPng?.length !== count)
+ return false;
+ if (request2.cameras && (result.width !== request2.width || result.height !== request2.height || text(result.cameras) !== text(request2.cameras)))
+ return false;
+ enforcePngCaptureBudget(result.viewsPng);
+ for (const png of result.viewsPng) {
+ const image = decodePng(png);
+ if (image.width !== image.height || request2.cameras && (image.width !== request2.width || image.height !== request2.height))
+ return false;
+ }
+ return true;
+ } catch {
+ return false;
+ }
+}
+function createCachedRenderPort(port, options) {
+ return async (input) => {
+ const identity = await Promise.resolve().then(() => options.identity()).catch(() => {
+ return;
+ });
+ if (!identity || input.beautySize !== undefined || !(input.cameras ?? input.viewDirs)?.length)
+ return port(input);
+ const validated = validatePbrRenderRequest(input);
+ const request2 = { ...validated, glb: Uint8Array.from(validated.glb) };
+ const hash = digest(request2.glb);
+ const selectors = request2.cameras ?? request2.viewDirs;
+ const keys = selectors.map((selector) => digest(text({
+ version: "kiln.capture-cache.v1",
+ kind: "gpu",
+ identity,
+ artifact: hash,
+ selector,
+ size: request2.size,
+ width: request2.width,
+ height: request2.height,
+ lighting: request2.lightingPresetId
+ })));
+ const cells = [];
+ const missing = [];
+ for (let i = 0;i < keys.length; i++) {
+ const cached = await options.cache.get(keys[i]).catch(() => {
+ return;
+ });
+ const single = {
+ ...request2,
+ ...request2.cameras ? { cameras: [request2.cameras[i]] } : { viewDirs: [request2.viewDirs[i]] }
+ };
+ if (cached?.kind === "gpu" && usable(cached.result, single, hash))
+ cells[i] = cached.result;
+ else
+ missing.push(i);
+ }
+ if (missing.length) {
+ const subrequest = {
+ ...request2,
+ ...request2.cameras ? { cameras: missing.map((i) => request2.cameras[i]) } : { viewDirs: missing.map((i) => request2.viewDirs[i]) }
+ };
+ const produced = await port(subrequest);
+ const afterIdentity = await Promise.resolve().then(() => options.identity()).catch(() => {
+ return;
+ });
+ if (afterIdentity !== identity)
+ return missing.length === selectors.length ? produced : {
+ ok: false,
+ rendererId: produced.rendererId,
+ error: "capture producer changed during render"
+ };
+ if (!usable(produced, subrequest, hash)) {
+ return missing.length === selectors.length ? produced : {
+ ok: false,
+ rendererId: produced.rendererId,
+ error: produced.error ?? "uncacheable partial camera response"
+ };
+ }
+ for (let j = 0;j < missing.length; j++) {
+ const i = missing[j];
+ const cell = {
+ ...produced,
+ viewsPng: [Uint8Array.from(produced.viewsPng[j])],
+ ...produced.cameras ? { cameras: [produced.cameras[j]] } : {}
+ };
+ cells[i] = cell;
+ await options.cache.put(keys[i], { kind: "gpu", result: cell }).catch(() => {});
+ }
+ }
+ const first = cells[0];
+ if (cells.some((c) => c.rendererId !== first.rendererId))
+ return {
+ ok: false,
+ rendererId: first.rendererId,
+ error: "capture producer changed; refresh host cache identity"
+ };
+ return {
+ ...first,
+ viewsPng: cells.map((c) => Uint8Array.from(c.viewsPng[0])),
+ ...request2.cameras ? { cameras: structuredClone(request2.cameras) } : {},
+ captureCache: {
+ hit: missing.length === 0,
+ reused: selectors.length - missing.length,
+ total: selectors.length
+ }
+ };
+ };
+}
+async function captureCpuCell(cache, identity, produce) {
+ const snapshot = structuredClone(identity);
+ const key = digest(text({ version: "kiln.capture-cache.v1", kind: "cpu", ...snapshot }));
+ const valid = (result2) => {
+ try {
+ enforcePngCaptureBudget([result2.png]);
+ const image = decodePng(result2.png);
+ return result2.inputGlbSha256 === snapshot.artifactGlbSha256 && image.width === snapshot.size && image.height === snapshot.size && result2.width === snapshot.size && result2.height === snapshot.size;
+ } catch {
+ return false;
+ }
+ };
+ const cached = await cache.get(key).catch(() => {
+ return;
+ });
+ if (cached?.kind === "cpu" && valid(cached.result))
+ return { ...cached.result, png: Buffer.from(cached.result.png), captureCache: { hit: true } };
+ const result = await produce();
+ if (!valid(result))
+ return result;
+ await cache.put(key, { kind: "cpu", result }).catch(() => {});
+ return { ...result, png: Buffer.from(result.png), captureCache: { hit: false } };
+}
+var text = (value) => JSON.stringify(canonical(value)), digest = (value) => `sha256:${createHash4("sha256").update(value).digest("hex")}`;
+var init_capture_cache = __esm(() => {
+ init_render_port();
+ init_png();
+ init_capture_limits();
+});
+
+// src/views/camera-capture.ts
+var exports_camera_capture = {};
+__export(exports_camera_capture, {
+ validateAdvancedCapture: () => validateAdvancedCapture,
+ renderCaptureGrid: () => renderCaptureGrid
+});
+function validateAdvancedCapture(config) {
+ for (const key of Object.keys(config))
+ if (!["version", "shots", "cols", "size", "output"].includes(key))
+ throw new Error(`capture.${key} is unknown or incompatible with shots`);
+ if (config.version !== "kiln.capture.v1")
+ throw new Error("advanced capture requires version kiln.capture.v1");
+ if (!Array.isArray(config.shots) || config.shots.length < 1 || config.shots.length > 9)
+ throw new Error("capture.shots must contain 1..9 shots");
+ if (config.cols !== undefined && (!Number.isInteger(config.cols) || config.cols < 1 || config.cols > 3))
+ throw new Error("capture.cols must be 1..3");
+ if (config.size !== undefined && (!Number.isInteger(config.size) || config.size < 128 || config.size > 1024))
+ throw new Error("capture.size must be 128..1024");
+ if (config.output !== undefined && !["grid", "separate"].includes(config.output))
+ throw new Error("capture.output must be grid or separate");
+}
+async function renderCaptureGrid(root, config, render, limits) {
+ validateAdvancedCapture(config);
+ const shots = config.shots.map((s) => resolveAssetCamera(root, s));
+ const size = config.size ?? 384;
+ const cols = config.cols ?? Math.min(3, shots.length);
+ enforceCapturePixels(shots.length, size, cols, limits);
+ const cells = [];
+ const perFramePngs = [];
+ const derivativeReceipts = [];
+ for (const shot of shots) {
+ const dir = shot.camera.position.map((n, i) => n - shot.camera.target[i]);
+ const view = { name: shot.name, dir };
+ const png2 = await withCameraVisibility(root, shot, async () => {
+ if (render) {
+ const result = await render({ root, label: shot.name, view, size, camera: shot.camera });
+ derivativeReceipts.push(result.receipt);
+ return result.png;
+ }
+ return encodePng(rasterizeCamera(root, shot.camera, size), size, size);
+ });
+ const decoded = decodePng(png2);
+ if (decoded.width !== size || decoded.height !== size)
+ throw new Error("capture cell dimensions do not match request");
+ annotateViewCell(decoded.rgb, size, view);
+ cells.push(decoded.rgb);
+ perFramePngs.push(encodePng(decoded.rgb, size, size));
+ }
+ const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, cols);
+ const png = encodePng(rgb2, width, height);
+ enforceCaptureBytes(config.output === "separate" ? perFramePngs : [png], limits);
+ return {
+ png,
+ width,
+ height,
+ views: shots.map((s) => s.name),
+ capture: { preset: `${cols}x${Math.ceil(shots.length / cols)}`, cols, cells: shots.length },
+ cameraShots: shots,
+ perFramePngs,
+ derivativeReceipts,
+ ...derivativeReceipts.length ? {
+ captureCache: {
+ hit: derivativeReceipts.every((r) => r.captureCache?.hit),
+ reused: derivativeReceipts.filter((r) => r.captureCache?.hit).length,
+ total: derivativeReceipts.length
+ }
+ } : {}
+ };
+}
+var init_camera_capture = __esm(() => {
+ init_capture_limits();
+ init_camera();
+ init_png();
+ init_grid();
+ init_annotate();
+});
+
+// src/views/capture.ts
+var exports_capture = {};
+__export(exports_capture, {
+ resolveGridCapture: () => resolveGridCapture,
+ resolveCapture: () => resolveCapture,
+ describeCapture: () => describeCapture,
+ captureCellLabel: () => captureCellLabel,
+ MAX_CAPTURE_CELLS: () => MAX_CAPTURE_CELLS,
+ DEFAULT_CAPTURE_PRESET: () => DEFAULT_CAPTURE_PRESET,
+ CaptureConfigError: () => CaptureConfigError,
+ CAPTURE_PRESETS: () => CAPTURE_PRESETS
+});
+function captureCellLabel(azimuthDeg, elevationDeg) {
+ const az = Math.round((azimuthDeg % 360 + 360) % 360);
+ const el = Math.round(elevationDeg);
+ return `A${az} ${el < 0 ? "D" : "U"}${Math.abs(el)}`;
+}
+function resolveCapture(config) {
+ if (!config || config.preset === undefined && config.cells === undefined) {
+ return {
+ preset: DEFAULT_CAPTURE_PRESET,
+ views: PRESET_VIEWS[DEFAULT_CAPTURE_PRESET],
+ cols: PRESET_COLS[DEFAULT_CAPTURE_PRESET],
+ zooms: new Array(PRESET_CAPACITY[DEFAULT_CAPTURE_PRESET]).fill(undefined),
+ isDefault: true
+ };
+ }
+ const cells = config.cells;
+ let preset = config.preset;
+ if (preset !== undefined && !CAPTURE_PRESETS.includes(preset)) {
+ throw new CaptureConfigError(`capture.preset must be one of ${CAPTURE_PRESETS.join(", ")} (got ${JSON.stringify(preset)}).`);
+ }
+ if (cells !== undefined) {
+ if (!Array.isArray(cells) || cells.length === 0) {
+ throw new CaptureConfigError("capture.cells must be a non-empty array of camera angles.");
+ }
+ if (cells.length > MAX_CAPTURE_CELLS) {
+ throw new CaptureConfigError(`capture.cells has ${cells.length} entries; the maximum is ${MAX_CAPTURE_CELLS}.`);
+ }
+ for (let i = 0;i < cells.length; i++) {
+ const c = cells[i];
+ if (!Number.isFinite(c?.azimuthDeg) || !Number.isFinite(c?.elevationDeg)) {
+ throw new CaptureConfigError(`capture.cells[${i}] needs finite azimuthDeg and elevationDeg (got ${JSON.stringify(c)}).`);
+ }
+ if (c.zoom !== undefined && (!Number.isFinite(c.zoom) || c.zoom <= 0)) {
+ throw new CaptureConfigError(`capture.cells[${i}].zoom must be a positive number (got ${c.zoom}).`);
+ }
+ }
+ if (preset === undefined) {
+ preset = CAPTURE_PRESETS.find((p) => PRESET_CAPACITY[p] >= cells.length);
+ } else if (cells.length > PRESET_CAPACITY[preset]) {
+ throw new CaptureConfigError(`capture.preset ${preset} holds ${PRESET_CAPACITY[preset]} cells but ${cells.length} were given. ` + `Use a larger preset or fewer cells.`);
+ }
+ return {
+ preset,
+ views: cells.map((c) => ({
+ name: c.name?.trim().toUpperCase() || captureCellLabel(c.azimuthDeg, c.elevationDeg),
+ dir: orbitDir(c.azimuthDeg, c.elevationDeg)
+ })),
+ cols: PRESET_COLS[preset],
+ zooms: cells.map((c) => c.zoom),
+ isDefault: false
+ };
+ }
+ const chosen = preset;
+ return {
+ preset: chosen,
+ views: PRESET_VIEWS[chosen],
+ cols: PRESET_COLS[chosen],
+ zooms: new Array(PRESET_VIEWS[chosen].length).fill(undefined),
+ isDefault: chosen === DEFAULT_CAPTURE_PRESET
+ };
+}
+function resolveGridCapture(config, envVariant) {
+ const resolved2 = resolveCapture(config);
+ if (config)
+ return resolved2;
+ const views = resolveGridViews(envVariant);
+ return views === resolved2.views ? resolved2 : { ...resolved2, views };
+}
+function describeCapture(resolved2) {
+ const angles = resolved2.views.map((v) => {
+ const { azimuthDeg, elevationDeg } = orbitAnglesOf(v.dir);
+ return `${v.name} (az ${azimuthDeg}, el ${elevationDeg})`;
+ }).join("; ");
+ return `${resolved2.preset} grid, ${resolved2.views.length} cell${resolved2.views.length === 1 ? "" : "s"}: ${angles}`;
+}
+var CAPTURE_PRESETS, DEFAULT_CAPTURE_PRESET = "3x2", MAX_CAPTURE_CELLS = 9, PRESET_COLS, PRESET_CAPACITY, BOTTOM, THREE_QUARTER_REAR, THREE_QUARTER_LOW, PRESET_VIEWS, CaptureConfigError;
+var init_capture = __esm(() => {
+ init_raster();
+ CAPTURE_PRESETS = [
+ "1x1",
+ "1x2",
+ "2x1",
+ "3x1",
+ "2x2",
+ "3x2",
+ "3x3"
+ ];
+ PRESET_COLS = {
+ "1x1": 1,
+ "1x2": 1,
+ "2x1": 2,
+ "3x1": 3,
+ "2x2": 2,
+ "3x2": 3,
+ "3x3": 3
+ };
+ PRESET_CAPACITY = {
+ "1x1": 1,
+ "1x2": 2,
+ "2x1": 2,
+ "3x1": 3,
+ "2x2": 4,
+ "3x2": 6,
+ "3x3": 9
+ };
+ BOTTOM = { name: "BOTTOM", dir: [0, -1, 0.0001] };
+ THREE_QUARTER_REAR = { name: "REAR 34", dir: [-0.7, 0.5, -0.7] };
+ THREE_QUARTER_LOW = { name: "LOW 34", dir: [0.7, -0.35, 0.7] };
+ PRESET_VIEWS = {
+ "1x1": [SIX_VIEWS[5]],
+ "1x2": [SIX_VIEWS[0], SIX_VIEWS[5]],
+ "2x1": [SIX_VIEWS[0], SIX_VIEWS[5]],
+ "3x1": [SIX_VIEWS[0], SIX_VIEWS[1], SIX_VIEWS[5]],
+ "2x2": [SIX_VIEWS[0], SIX_VIEWS[1], SIX_VIEWS[4], SIX_VIEWS[5]],
+ "3x2": SIX_VIEWS,
+ "3x3": [...SIX_VIEWS, BOTTOM, THREE_QUARTER_REAR, THREE_QUARTER_LOW]
+ };
+ CaptureConfigError = class CaptureConfigError extends Error {
+ };
+});
+
+// src/views/architecture.ts
+function nodeRoles(node) {
+ return readSemanticMetadataV1FromExtras(node.userData ?? {})?.roles ?? [];
+}
+function hasArchitectureRoofRole(node) {
+ return nodeRoles(node).some((role) => ARCHITECTURE_ROOF_ROLE_PREFIXES.some((prefix) => role.startsWith(prefix)));
+}
+function legacyRoofName(name) {
+ if (!name)
+ return false;
+ return /^roof(?:$|[_. -]|(?:slope|panel|gable|ridge)|[ab](?:$|[_. -]))/i.test(name.trim());
+}
+function minimalMatches(root, predicate) {
+ const matches = [];
+ const visit = (node, ancestorMatched) => {
+ const matched = predicate(node);
+ if (matched && !ancestorMatched)
+ matches.push(node);
+ for (const child of node.children ?? [])
+ visit(child, ancestorMatched || matched);
+ };
+ visit(root, false);
+ return matches;
+}
+function selectArchitectureRoofNodes(root) {
+ const candidate = root;
+ const semantic3 = minimalMatches(candidate, hasArchitectureRoofRole);
+ if (semantic3.length > 0)
+ return { mode: "semantic", nodes: semantic3 };
+ const legacy = minimalMatches(candidate, (node) => legacyRoofName(node.name));
+ return legacy.length > 0 ? { mode: "legacy-name", nodes: legacy } : { mode: "none", nodes: [] };
+}
+function setSubtreeVisibility(node, visible) {
+ node.visible = visible;
+ for (const child of node.children ?? [])
+ setSubtreeVisibility(child, visible);
+}
+function hideArchitectureRoofInScene(root) {
+ const selection = selectArchitectureRoofNodes(root);
+ for (const node of selection.nodes)
+ setSubtreeVisibility(node, false);
+ return selection;
+}
+var ARCHITECTURE_ROOF_ROLE_PREFIXES;
+var init_architecture3 = __esm(() => {
+ init_contracts();
+ ARCHITECTURE_ROOF_ROLE_PREFIXES = Object.freeze([
+ `${KILN_SEMANTIC_ROLES.roof}.`,
+ `${KILN_SEMANTIC_ROLES.architectureRoof}.`
+ ]);
+});
+
+// src/views/glb.ts
+import {
+ Primitive,
+ WebIO as WebIO2
+} from "@gltf-transform/core";
+import {
+ EXTMeshGPUInstancing as EXTMeshGPUInstancing2,
+ KHRMaterialsVariants as KHRMaterialsVariants2,
+ KHRTextureBasisu as KHRTextureBasisu2
+} from "@gltf-transform/extensions";
+import {
+ BufferAttribute as BufferAttribute8,
+ BufferGeometry as BufferGeometry14,
+ Group,
+ Matrix4 as Matrix47,
+ Mesh as Mesh10,
+ MeshStandardMaterial as MeshStandardMaterial5,
+ NoColorSpace as NoColorSpace4,
+ SRGBColorSpace as SRGBColorSpace5,
+ Texture,
+ AnimationClip as AnimationClip3,
+ QuaternionKeyframeTrack as QuaternionKeyframeTrack2,
+ VectorKeyframeTrack as VectorKeyframeTrack2,
+ Quaternion as Quaternion14,
+ Vector3 as Vector326
+} from "three";
+function record4(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function reviewClipsFromExtras(extras) {
+ if (!record4(extras))
+ return;
+ const envelope = extras[REVIEW_CLIPS_EXTRAS_KEY];
+ if (!record4(envelope) || envelope.version !== 1 || !Array.isArray(envelope.clips)) {
+ return;
+ }
+ if (envelope.clips.length > REVIEW_CLIP_LIMITS.clips) {
+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Animation review clip limit exceeded.");
+ }
+ let trackCount = 0;
+ return envelope.clips.map((candidate) => {
+ if (!record4(candidate) || typeof candidate.name !== "string" || candidate.name.length > 256 || typeof candidate.duration !== "number" || !Number.isFinite(candidate.duration) || candidate.duration < 0 || !Array.isArray(candidate.tracks)) {
+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Invalid animation review clip.");
+ }
+ const tracks = candidate.tracks.map((track) => {
+ trackCount++;
+ if (trackCount > REVIEW_CLIP_LIMITS.tracks || !record4(track) || typeof track.name !== "string" || track.name.length > 512 || !Array.isArray(track.times) || !Array.isArray(track.values) || track.times.length > REVIEW_CLIP_LIMITS.samplesPerTrack || track.values.length > REVIEW_CLIP_LIMITS.valuesPerTrack || !track.times.every((value) => typeof value === "number" && Number.isFinite(value)) || !track.values.every((value) => typeof value === "number" && Number.isFinite(value))) {
+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Invalid animation review track.");
+ }
+ const property = track.name.slice(track.name.lastIndexOf(".") + 1);
+ const Track = property === "quaternion" ? QuaternionKeyframeTrack2 : VectorKeyframeTrack2;
+ return new Track(track.name, track.times, track.values);
+ });
+ return new AnimationClip3(candidate.name, candidate.duration, tracks);
+ });
+}
+function geometryFlatTextureReasonCode(mimeType) {
+ return mimeType === "image/ktx2" ? GLB_GEOMETRY_FLAT_REASON.KTX2_SAMPLING_UNSUPPORTED : GLB_GEOMETRY_FLAT_REASON.TEXTURE_SAMPLING_UNSUPPORTED;
+}
+function decodedAccessor(accessor) {
+ const itemSize = accessor.getElementSize();
+ const output = new Float64Array(accessor.getCount() * itemSize);
+ const element = [];
+ for (let index = 0;index < accessor.getCount(); index++) {
+ accessor.getElement(index, element);
+ for (let component = 0;component < itemSize; component++) {
+ output[index * itemSize + component] = element[component];
+ }
+ }
+ return output;
+}
+function triangleIndices(primitive, vertexCount) {
+ const sourceAccessor = primitive.getIndices();
+ const source = sourceAccessor ? Array.from(decodedAccessor(sourceAccessor), (value) => Math.trunc(value)) : Array.from({ length: vertexCount }, (_, index) => index);
+ switch (primitive.getMode()) {
+ case Primitive.Mode.TRIANGLES:
+ return Uint32Array.from(source);
+ case Primitive.Mode.TRIANGLE_STRIP: {
+ const triangles = [];
+ for (let index = 0;index + 2 < source.length; index++) {
+ triangles.push(source[index], source[index + 1 + index % 2], source[index + 2 - index % 2]);
+ }
+ return Uint32Array.from(triangles);
+ }
+ case Primitive.Mode.TRIANGLE_FAN: {
+ const triangles = [];
+ for (let index = 1;index + 1 < source.length; index++) {
+ triangles.push(source[index], source[index + 1], source[0]);
+ }
+ return Uint32Array.from(triangles);
+ }
+ default:
+ return;
+ }
+}
+function flatMaterial(material) {
+ if (!material) {
+ return {
+ color: { r: 0.7, g: 0.7, b: 0.7 },
+ opacity: 1,
+ doubleSided: false,
+ metalness: 0,
+ roughness: 1,
+ alphaMode: "OPAQUE",
+ alphaCutoff: 0.5,
+ emissive: [0, 0, 0]
+ };
+ }
+ const [r, g, b, factorAlpha] = material.getBaseColorFactor();
+ const alphaMode2 = material.getAlphaMode();
+ const opacity = alphaMode2 === "BLEND" ? factorAlpha : alphaMode2 === "MASK" && factorAlpha < material.getAlphaCutoff() ? 0 : 1;
+ return {
+ color: { r, g, b },
+ opacity,
+ doubleSided: material.getDoubleSided(),
+ metalness: material.getMetallicFactor(),
+ roughness: material.getRoughnessFactor(),
+ alphaMode: alphaMode2,
+ alphaCutoff: material.getAlphaCutoff(),
+ emissive: material.getEmissiveFactor()
+ };
+}
+function preserveTexture(source, usage2, cache) {
+ if (!source)
+ return null;
+ const encoded = source.getImage();
+ const mime = source.getMimeType();
+ if (!encoded || !mime)
+ return null;
+ let byUsage = cache.get(source);
+ if (!byUsage) {
+ byUsage = new Map;
+ cache.set(source, byUsage);
+ }
+ const existing = byUsage.get(usage2);
+ if (existing)
+ return existing;
+ const texture = new Texture;
+ texture.name = source.getName();
+ texture.colorSpace = usage2 === "color" ? SRGBColorSpace5 : NoColorSpace4;
+ texture.userData.encoded = { mime, bytes: Uint8Array.from(encoded) };
+ byUsage.set(usage2, texture);
+ return texture;
+}
+function noteMaterialTextures(material, reasons) {
+ if (!material)
+ return;
+ const textures = [
+ material.getBaseColorTexture(),
+ material.getNormalTexture(),
+ material.getMetallicRoughnessTexture(),
+ material.getEmissiveTexture(),
+ material.getOcclusionTexture()
+ ];
+ for (const texture of textures) {
+ if (texture)
+ reasons.add(geometryFlatTextureReasonCode(texture.getMimeType()));
+ }
+}
+function instanceMatrices(node) {
+ const world = new Matrix47().fromArray(node.getWorldMatrix());
+ const extension = node.getExtension("EXT_mesh_gpu_instancing");
+ if (!extension)
+ return { matrices: [world], count: 1 };
+ const attributes = extension.listAttributes();
+ if (attributes.length === 0) {
+ throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", `Node ${JSON.stringify(node.getName())} has EXT_mesh_gpu_instancing with no attributes.`);
+ }
+ const count = attributes[0].getCount();
+ if (attributes.some((attribute) => attribute.getCount() !== count)) {
+ throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", `Node ${JSON.stringify(node.getName())} has mismatched EXT_mesh_gpu_instancing counts.`);
+ }
+ const translations = extension.getAttribute("TRANSLATION");
+ const rotations = extension.getAttribute("ROTATION");
+ const scales = extension.getAttribute("SCALE");
+ const translation = [];
+ const rotation = [];
+ const scale2 = [];
+ const matrices = [];
+ for (let index = 0;index < count; index++) {
+ translations?.getElement(index, translation);
+ rotations?.getElement(index, rotation);
+ scales?.getElement(index, scale2);
+ const local = new Matrix47().compose(new Vector326(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion14(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector326(scales ? scale2[0] : 1, scales ? scale2[1] : 1, scales ? scale2[2] : 1));
+ matrices.push(world.clone().multiply(local));
+ }
+ return { matrices, count };
+}
+async function loadGlbGeometryFlatScene(bytes) {
+ let document;
+ try {
+ document = await glbIO().readBinary(Uint8Array.from(bytes));
+ } catch (error) {
+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Could not parse final GLB bytes: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ const scene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];
+ if (!scene)
+ throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");
+ const reasons = new Set;
+ const meshes = [];
+ let instanceCount = 0;
+ const sceneNodes2 = new Set;
+ const visit = (node) => {
+ if (sceneNodes2.has(node))
+ return;
+ sceneNodes2.add(node);
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const child of scene.listChildren())
+ visit(child);
+ for (const node of sceneNodes2) {
+ const mesh = node.getMesh();
+ if (!mesh)
+ continue;
+ if (node.getSkin())
+ reasons.add(GLB_GEOMETRY_FLAT_REASON.SKIN_DEFORMATION_UNSUPPORTED);
+ const instances = instanceMatrices(node);
+ instanceCount += instances.count;
+ for (const primitive of mesh.listPrimitives()) {
+ if (primitive.listTargets().length > 0) {
+ reasons.add(GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED);
+ }
+ const positionAccessor = primitive.getAttribute("POSITION");
+ if (positionAccessor?.getElementSize() !== 3)
+ continue;
+ const positions = decodedAccessor(positionAccessor);
+ const indices = triangleIndices(primitive, positionAccessor.getCount());
+ if (!indices) {
+ reasons.add(GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED);
+ continue;
+ }
+ const material = primitive.getMaterial();
+ noteMaterialTextures(material, reasons);
+ const geometry2 = {
+ getAttribute(name) {
+ return name === "position" ? { array: positions, itemSize: 3, count: positionAccessor.getCount() } : undefined;
+ },
+ index: { array: indices, itemSize: 1, count: indices.length }
+ };
+ for (const matrix of instances.matrices) {
+ meshes.push({
+ isMesh: true,
+ visible: true,
+ geometry: geometry2,
+ material: flatMaterial(material),
+ matrixWorld: { elements: [...matrix.elements] }
+ });
+ }
+ }
+ }
+ if (meshes.length === 0) {
+ throw new GlbGeometryFlatError("GLB_FLAT_NO_RENDERABLE_GEOMETRY", "Final GLB contains no triangle geometry supported by the CPU fallback.");
+ }
+ const root = {
+ updateMatrixWorld() {},
+ traverse(callback) {
+ for (const mesh of meshes)
+ callback(mesh);
+ }
+ };
+ return {
+ root,
+ reasonCodes: REASON_ORDER.filter((reason) => reasons.has(reason)),
+ meshCount: meshes.length,
+ instanceCount
+ };
+}
+function localInstanceMatrices(node) {
+ const extension = node.getExtension("EXT_mesh_gpu_instancing");
+ if (!extension)
+ return [new Matrix47];
+ const attributes = extension.listAttributes();
+ if (attributes.length === 0) {
+ throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", "Invalid empty instancing data.");
+ }
+ const count = attributes[0].getCount();
+ if (attributes.some((attribute) => attribute.getCount() !== count)) {
+ throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", "Mismatched instancing data.");
+ }
+ const translations = extension.getAttribute("TRANSLATION");
+ const rotations = extension.getAttribute("ROTATION");
+ const scales = extension.getAttribute("SCALE");
+ const translation = [];
+ const rotation = [];
+ const scale2 = [];
+ return Array.from({ length: count }, (_, index) => {
+ translations?.getElement(index, translation);
+ rotations?.getElement(index, rotation);
+ scales?.getElement(index, scale2);
+ return new Matrix47().compose(new Vector326(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion14(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector326(...scales ? scale2.slice(0, 3) : [1, 1, 1]));
+ });
+}
+async function loadGlbReviewScene(bytes) {
+ let document;
+ try {
+ document = await glbIO().readBinary(Uint8Array.from(bytes));
+ } catch {
+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Could not parse final GLB bytes.");
+ }
+ const sourceScene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];
+ if (!sourceScene)
+ throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");
+ const reasons = new Set;
+ const root = new Group;
+ root.name = sourceScene.getName() || "Scene";
+ const nodeMap = new Map;
+ const textureCache = new Map;
+ let meshCount = 0;
+ let instanceCount = 0;
+ const buildNode = (source) => {
+ const existing = nodeMap.get(source);
+ if (existing)
+ return existing;
+ const target = new Group;
+ target.name = source.getName();
+ target.position.fromArray(source.getTranslation());
+ target.quaternion.fromArray(source.getRotation());
+ target.scale.fromArray(source.getScale());
+ target.userData = { ...source.getExtras() };
+ nodeMap.set(source, target);
+ const sourceMesh = source.getMesh();
+ if (sourceMesh) {
+ target.userData.kilnGlbMeshNode = true;
+ if (source.getSkin())
+ reasons.add(GLB_GEOMETRY_FLAT_REASON.SKIN_DEFORMATION_UNSUPPORTED);
+ const matrices = localInstanceMatrices(source);
+ instanceCount += matrices.length;
+ for (const [primitiveIndex, primitive] of sourceMesh.listPrimitives().entries()) {
+ if (primitive.listTargets().length)
+ reasons.add(GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED);
+ const position = primitive.getAttribute("POSITION");
+ if (position?.getElementSize() !== 3)
+ continue;
+ const indices = triangleIndices(primitive, position.getCount());
+ if (!indices) {
+ reasons.add(GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED);
+ continue;
+ }
+ const material = primitive.getMaterial();
+ noteMaterialTextures(material, reasons);
+ const flat = flatMaterial(material);
+ const geometry2 = new BufferGeometry14;
+ geometry2.setAttribute("position", new BufferAttribute8(Float32Array.from(decodedAccessor(position)), 3));
+ const normal = primitive.getAttribute("NORMAL");
+ if (normal) {
+ geometry2.setAttribute("normal", new BufferAttribute8(Float32Array.from(decodedAccessor(normal)), 3));
+ }
+ const uv = primitive.getAttribute("TEXCOORD_0");
+ if (uv) {
+ geometry2.setAttribute("uv", new BufferAttribute8(Float32Array.from(decodedAccessor(uv)), 2));
+ }
+ const tangent = primitive.getAttribute("TANGENT");
+ if (tangent) {
+ geometry2.setAttribute("tangent", new BufferAttribute8(Float32Array.from(decodedAccessor(tangent)), 4));
+ }
+ geometry2.setIndex(new BufferAttribute8(indices, 1));
+ const threeMaterial = new MeshStandardMaterial5({
+ opacity: flat.opacity,
+ transparent: flat.alphaMode === "BLEND",
+ alphaTest: flat.alphaMode === "MASK" ? flat.alphaCutoff : 0,
+ side: flat.doubleSided ? 2 : 0,
+ metalness: flat.metalness,
+ roughness: flat.roughness
+ });
+ threeMaterial.color.setRGB(flat.color.r, flat.color.g, flat.color.b);
+ threeMaterial.emissive.fromArray(flat.emissive);
+ if (material) {
+ threeMaterial.map = preserveTexture(material.getBaseColorTexture(), "color", textureCache);
+ threeMaterial.normalMap = preserveTexture(material.getNormalTexture(), "data", textureCache);
+ threeMaterial.normalScale.setScalar(material.getNormalScale());
+ const metallicRoughness = preserveTexture(material.getMetallicRoughnessTexture(), "data", textureCache);
+ threeMaterial.metalnessMap = metallicRoughness;
+ threeMaterial.roughnessMap = metallicRoughness;
+ threeMaterial.emissiveMap = preserveTexture(material.getEmissiveTexture(), "color", textureCache);
+ threeMaterial.aoMap = preserveTexture(material.getOcclusionTexture(), "data", textureCache);
+ threeMaterial.aoMapIntensity = material.getOcclusionStrength();
+ }
+ for (const [index, matrix] of matrices.entries()) {
+ const mesh = new Mesh10(geometry2, threeMaterial);
+ const baseName = source.getName() || sourceMesh.getName() || "Mesh";
+ mesh.name = `${baseName}:primitive-${primitiveIndex}${matrices.length === 1 ? "" : `:instance-${index}`}`;
+ mesh.matrixAutoUpdate = false;
+ mesh.matrix.copy(matrix);
+ target.add(mesh);
+ meshCount++;
+ }
+ }
+ }
+ for (const child of source.listChildren())
+ target.add(buildNode(child));
+ return target;
+ };
+ for (const child of sourceScene.listChildren())
+ root.add(buildNode(child));
+ root.updateMatrixWorld(true);
+ if (meshCount === 0)
+ throw new GlbGeometryFlatError("GLB_FLAT_NO_RENDERABLE_GEOMETRY", "Final GLB contains no renderable geometry.");
+ const nativeClips = document.getRoot().listAnimations().map((animation) => new AnimationClip3(animation.getName(), -1, animation.listChannels().flatMap((channel) => {
+ const node = channel.getTargetNode();
+ const path = channel.getTargetPath();
+ const sampler = channel.getSampler();
+ const input = sampler?.getInput()?.getArray();
+ const output = sampler?.getOutput()?.getArray();
+ const property = path === "translation" ? "position" : path === "rotation" ? "quaternion" : path;
+ if (!node || !property || property === "weights" || !input || !output)
+ return [];
+ const Track = path === "rotation" ? QuaternionKeyframeTrack2 : VectorKeyframeTrack2;
+ return [new Track(`${node.getName()}.${property}`, input, output)];
+ })));
+ const clips = reviewClipsFromExtras(sourceScene.getExtras()) ?? nativeClips;
+ return {
+ root,
+ clips,
+ reasonCodes: REASON_ORDER.filter((reason) => reasons.has(reason)),
+ meshCount,
+ instanceCount
+ };
+}
+var GLB_GEOMETRY_FLAT_REASON, REASON_ORDER, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, GlbGeometryFlatError, glbIO = () => new WebIO2().registerExtensions([EXTMeshGPUInstancing2, KHRMaterialsVariants2, KHRTextureBasisu2]);
+var init_glb = __esm(() => {
+ GLB_GEOMETRY_FLAT_REASON = {
+ TEXTURE_SAMPLING_UNSUPPORTED: "GLB_FLAT_TEXTURE_SAMPLING_UNSUPPORTED",
+ KTX2_SAMPLING_UNSUPPORTED: "GLB_FLAT_KTX2_SAMPLING_UNSUPPORTED",
+ NON_TRIANGLE_PRIMITIVE_UNSUPPORTED: "GLB_FLAT_NON_TRIANGLE_PRIMITIVE_UNSUPPORTED",
+ SKIN_DEFORMATION_UNSUPPORTED: "GLB_FLAT_SKIN_DEFORMATION_UNSUPPORTED",
+ MORPH_TARGETS_UNSUPPORTED: "GLB_FLAT_MORPH_TARGETS_UNSUPPORTED"
+ };
+ REASON_ORDER = [
+ GLB_GEOMETRY_FLAT_REASON.KTX2_SAMPLING_UNSUPPORTED,
+ GLB_GEOMETRY_FLAT_REASON.TEXTURE_SAMPLING_UNSUPPORTED,
+ GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED,
+ GLB_GEOMETRY_FLAT_REASON.SKIN_DEFORMATION_UNSUPPORTED,
+ GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED
+ ];
+ REVIEW_CLIP_LIMITS = {
+ clips: 32,
+ tracks: 256,
+ samplesPerTrack: 4096,
+ valuesPerTrack: 16384
+ };
+ GlbGeometryFlatError = class GlbGeometryFlatError extends Error {
+ code;
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ this.name = "GlbGeometryFlatError";
+ }
+ };
+});
+
+// src/evaluator/handler.ts
+var init_handler = __esm(() => {
+ init_authoring_diagnostic();
+ init_render();
+ init_run();
+ init_protocol();
+});
+
+// src/evaluator/isolation.ts
+var exports_isolation = {};
+__export(exports_isolation, {
+ renderGLBViaIsolatedEvaluator: () => renderGLBViaIsolatedEvaluator,
+ isolationReadinessFailureCode: () => isolationReadinessFailureCode,
+ isolatedEvaluatorLaunch: () => isolatedEvaluatorLaunch,
+ decodeEvaluatorIsolationTransport: () => decodeEvaluatorIsolationTransport,
+ decodeEvaluatorIsolationReadiness: () => decodeEvaluatorIsolationReadiness,
+ assertIsolatedEvaluatorReady: () => assertIsolatedEvaluatorReady,
+ EvaluatorIsolationReadinessError: () => EvaluatorIsolationReadinessError
+});
+import { spawn } from "node:child_process";
+import { existsSync } from "node:fs";
+import { posix } from "node:path";
+import { fileURLToPath } from "node:url";
+function isolationReadinessFailureCode(error) {
+ if (!(error instanceof EvaluatorIsolationReadinessError))
+ return;
+ return READINESS_FAILURE_CODES.includes(error.readinessCode) ? error.readinessCode : undefined;
+}
+function isolationUnavailable() {
+ throw new EvaluatorSubprocessError("ISOLATION_UNAVAILABLE", "Isolated evaluator is unavailable.");
+}
+function requiredAbsolutePath(value) {
+ if (!posix.isAbsolute(value) || posix.normalize(value) !== value)
+ isolationUnavailable();
+ return value;
+}
+function requiredRuntimeRoot(value) {
+ const root = requiredAbsolutePath(value);
+ if (root !== DEFAULT_RUNTIME_ROOT)
+ isolationUnavailable();
+ return root;
+}
+function workerInsideRuntime(workerPath, runtimeRoot) {
+ const normalized = requiredAbsolutePath(workerPath);
+ const packageRoot = posix.join(runtimeRoot, "node_modules") + posix.sep;
+ if (!normalized.startsWith(packageRoot))
+ isolationUnavailable();
+ return normalized;
+}
+function runtimeMounts(runtimeRoot, pathExists) {
+ const mounts = ["/usr", "/lib", "/lib64", posix.join(runtimeRoot, "node_modules")];
+ const existing = mounts.filter((path) => pathExists(path));
+ if (!existing.includes("/usr") || !existing.includes(posix.join(runtimeRoot, "node_modules"))) {
+ isolationUnavailable();
+ }
+ return existing;
+}
+function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx") {
+ const platform = host.platform ?? process.platform;
+ if (platform !== "linux")
+ isolationUnavailable();
+ const runtimeRoot = requiredRuntimeRoot(host.runtimeRoot ?? DEFAULT_RUNTIME_ROOT);
+ const pathExists = host.pathExists ?? existsSync;
+ const bwrapPath = requiredAbsolutePath(host.bwrapPath ?? DEFAULT_BWRAP_PATH);
+ const setprivPath = requiredAbsolutePath(host.setprivPath ?? DEFAULT_SETPRIV_PATH);
+ const prlimitPath = requiredAbsolutePath(host.prlimitPath ?? DEFAULT_PRLIMIT_PATH);
+ const nodePath5 = requiredAbsolutePath(host.nodePath ?? DEFAULT_NODE_PATH);
+ for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath5]) {
+ if (!pathExists(executable))
+ isolationUnavailable();
+ }
+ const resolvedWorkerPath = workerInsideRuntime(workerPath, runtimeRoot);
+ if (!pathExists(resolvedWorkerPath))
+ isolationUnavailable();
+ const bwrapArgs = [
+ "--unshare-all",
+ "--die-with-parent",
+ "--new-session",
+ "--disable-userns",
+ "--cap-drop",
+ "ALL",
+ "--clearenv",
+ "--setenv",
+ "NODE_ENV",
+ "production",
+ "--setenv",
+ "NO_COLOR",
+ "1",
+ "--proc",
+ "/proc",
+ "--dev",
+ "/dev",
+ "--tmpfs",
+ "/tmp",
+ "--dir",
+ runtimeRoot,
+ "--dir",
+ posix.join(runtimeRoot, "node_modules")
+ ];
+ for (const mount of runtimeMounts(runtimeRoot, pathExists)) {
+ bwrapArgs.push("--ro-bind", mount, mount);
+ }
+ const nodeArgs = [nodePath5, "--max-old-space-size=512", "--disable-proto=throw"];
+ if (loader === "tsx")
+ nodeArgs.push("--import", "tsx");
+ nodeArgs.push(resolvedWorkerPath);
+ bwrapArgs.push("--chdir", runtimeRoot, "--preserve-fds", "1", "--", prlimitPath, "--cpu=65:65", "--as=6442450944:6442450944", "--fsize=100663296:100663296", "--nofile=64:64", "--nproc=64:64", "--", ...nodeArgs);
+ return {
+ command: setprivPath,
+ args: [
+ "--no-new-privs",
+ "--inh-caps=-all",
+ "--ambient-caps=-all",
+ "--",
+ bwrapPath,
+ ...bwrapArgs
+ ],
+ env: sanitizedEvaluatorEnv({}),
+ detached: true
+ };
+}
+function isolatedEvaluatorLaunch(workerPath, host = {}) {
+ return isolatedEvaluatorLaunchWithLoader(workerPath, host, "tsx");
+}
+async function renderGLBViaIsolatedEvaluator(code, options = {}, controls = {}) {
+ const workerPath = fileURLToPath(new URL("./worker.ts", import.meta.url));
+ const launch = isolatedEvaluatorLaunch(workerPath, controls.host);
+ const { host: _, ...processControls } = controls;
+ return renderGLBViaProcessLaunch(code, options, processControls, launch);
+}
+function decodeEvaluatorIsolationReadiness(value) {
+ if (typeof value !== "object" || value === null || Array.isArray(value))
+ isolationUnavailable();
+ const record5 = value;
+ if (Object.keys(record5).sort().join(",") === "failure,mode,version" && record5.version === READINESS_VERSION && record5.mode === "isolated" && [
+ "loader-probe-boot",
+ "invariant-namespace",
+ "invariant-environment",
+ "invariant-filesystem",
+ "invariant-network",
+ "invariant-generated-policy"
+ ].includes(String(record5.failure))) {
+ return record5;
+ }
+ if (Object.keys(record5).sort().join(",") !== "checks,mode,version" || record5.version !== READINESS_VERSION || record5.mode !== "isolated" || !Array.isArray(record5.checks) || record5.checks.length !== READINESS_CHECKS.length || record5.checks.join(",") !== READINESS_CHECKS.join(",")) {
+ isolationUnavailable();
+ }
+ return record5;
+}
+function decodeEvaluatorIsolationTransport(value) {
+ if (typeof value !== "object" || value === null || Array.isArray(value) || Object.keys(value).sort().join(",") !== "transport,version") {
+ isolationUnavailable();
+ }
+ const record5 = value;
+ if (record5.version !== TRANSPORT_VERSION || record5.transport !== "fd3")
+ isolationUnavailable();
+ return record5;
+}
+function terminateReadinessChild(child) {
+ try {
+ if (child.pid)
+ process.kill(-child.pid, "SIGKILL");
+ } catch {}
+}
+async function assertIsolationTransport(launch) {
+ return await new Promise((resolve, reject) => {
+ const child = spawn(launch.command, launch.args, {
+ env: launch.env,
+ windowsHide: true,
+ detached: true,
+ stdio: ["ignore", "pipe", "ignore", "pipe"]
+ });
+ const stdoutChunks = [];
+ const protocolChunks = [];
+ let stdoutBytes = 0;
+ let protocolBytes = 0;
+ let settled = false;
+ const fail = (readinessCode) => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ reject(new EvaluatorIsolationReadinessError(readinessCode));
+ };
+ const timer = setTimeout(() => {
+ terminateReadinessChild(child);
+ fail("deadline");
+ }, PROBE_DEADLINE_MS);
+ child.stdout?.on("data", (chunk2) => {
+ stdoutBytes += chunk2.byteLength;
+ if (stdoutBytes > MAX_TRANSPORT_STDOUT_BYTES) {
+ terminateReadinessChild(child);
+ fail("wrapper-launch");
+ return;
+ }
+ stdoutChunks.push(Buffer.from(chunk2));
+ });
+ const protocol = child.stdio[3];
+ if (!protocol) {
+ terminateReadinessChild(child);
+ fail("fd3-transport");
+ return;
+ }
+ protocol.on("data", (chunk2) => {
+ protocolBytes += chunk2.byteLength;
+ if (protocolBytes > MAX_READINESS_PROTOCOL_BYTES) {
+ terminateReadinessChild(child);
+ fail("fd3-transport");
+ return;
+ }
+ protocolChunks.push(Buffer.from(chunk2));
+ });
+ child.once("error", () => fail("wrapper-launch"));
+ child.once("close", (code) => {
+ if (settled)
+ return;
+ const stdout = Buffer.concat(stdoutChunks).toString("utf8");
+ if (stdout !== TRANSPORT_STDOUT_MARKER)
+ return fail("wrapper-launch");
+ if (code !== 0 || protocolChunks.length === 0)
+ return fail("fd3-transport");
+ try {
+ decodeEvaluatorIsolationTransport(JSON.parse(Buffer.concat(protocolChunks).toString("utf8")));
+ settled = true;
+ clearTimeout(timer);
+ resolve();
+ } catch {
+ fail("fd3-transport");
+ }
+ });
+ });
+}
+async function runIsolationProbe(launch) {
+ return await new Promise((resolve, reject) => {
+ const child = spawn(launch.command, launch.args, {
+ env: launch.env,
+ windowsHide: true,
+ detached: true,
+ stdio: ["ignore", "ignore", "ignore", "pipe"]
+ });
+ const protocol = child.stdio[3];
+ const chunks = [];
+ let bytes = 0;
+ let settled = false;
+ const fail = (readinessCode) => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ reject(new EvaluatorIsolationReadinessError(readinessCode));
+ };
+ const timer = setTimeout(() => {
+ terminateReadinessChild(child);
+ fail("deadline");
+ }, PROBE_DEADLINE_MS);
+ if (!protocol) {
+ terminateReadinessChild(child);
+ fail("fd3-transport");
+ return;
+ }
+ protocol.on("data", (chunk2) => {
+ bytes += chunk2.byteLength;
+ if (bytes > MAX_READINESS_PROTOCOL_BYTES) {
+ terminateReadinessChild(child);
+ fail("loader-probe-boot");
+ return;
+ }
+ chunks.push(Buffer.from(chunk2));
+ });
+ child.once("error", () => fail("wrapper-launch"));
+ child.once("close", (code) => {
+ if (settled)
+ return;
+ if (chunks.length === 0)
+ return fail("loader-probe-boot");
+ try {
+ const result = decodeEvaluatorIsolationReadiness(JSON.parse(Buffer.concat(chunks).toString("utf8")));
+ if ("failure" in result)
+ return fail(result.failure);
+ if (code !== 0)
+ return fail("loader-probe-boot");
+ settled = true;
+ clearTimeout(timer);
+ resolve(result);
+ } catch {
+ fail("loader-probe-boot");
+ }
+ });
+ });
+}
+async function assertIsolatedEvaluatorReady(host = {}) {
+ if (typeof process.getuid !== "function" || process.getuid() === 0) {
+ throw new EvaluatorIsolationReadinessError("invariant-namespace");
+ }
+ const transportPath = fileURLToPath(new URL("./transport-worker.mjs", import.meta.url));
+ const probePath = fileURLToPath(new URL("./probe-worker.ts", import.meta.url));
+ let transportLaunch;
+ let probeLaunch;
+ try {
+ transportLaunch = isolatedEvaluatorLaunchWithLoader(transportPath, host, "module");
+ probeLaunch = isolatedEvaluatorLaunch(probePath, host);
+ } catch {
+ throw new EvaluatorIsolationReadinessError("wrapper-launch");
+ }
+ await assertIsolationTransport(transportLaunch);
+ return await runIsolationProbe(probeLaunch);
+}
+var DEFAULT_RUNTIME_ROOT = "/app", DEFAULT_BWRAP_PATH = "/usr/local/bin/bwrap", DEFAULT_SETPRIV_PATH = "/usr/bin/setpriv", DEFAULT_PRLIMIT_PATH = "/usr/bin/prlimit", DEFAULT_NODE_PATH = "/usr/local/bin/node", READINESS_VERSION = "kiln.evaluator.isolation-readiness.v1", TRANSPORT_VERSION = "kiln.evaluator.isolation-transport.v1", TRANSPORT_STDOUT_MARKER = `kiln-evaluator-transport-boot-v1
+`, PROBE_DEADLINE_MS = 8000, MAX_READINESS_PROTOCOL_BYTES, MAX_TRANSPORT_STDOUT_BYTES = 256, READINESS_FAILURE_CODES, READINESS_CHECKS, EvaluatorIsolationReadinessError;
+var init_isolation = __esm(() => {
+ init_subprocess();
+ MAX_READINESS_PROTOCOL_BYTES = 16 * 1024;
+ READINESS_FAILURE_CODES = [
+ "wrapper-launch",
+ "fd3-transport",
+ "loader-probe-boot",
+ "invariant-namespace",
+ "invariant-environment",
+ "invariant-filesystem",
+ "invariant-network",
+ "invariant-generated-policy",
+ "deadline"
+ ];
+ READINESS_CHECKS = [
+ "user-namespace",
+ "no-new-privileges",
+ "capabilities-empty",
+ "environment-exact",
+ "product-filesystem-denied",
+ "host-filesystem-denied",
+ "runtime-filesystem-read-only",
+ "network-namespace-empty",
+ "metadata-and-local-network-denied",
+ "generated-capabilities-denied"
+ ];
+ EvaluatorIsolationReadinessError = class EvaluatorIsolationReadinessError extends EvaluatorSubprocessError {
+ readinessCode;
+ constructor(readinessCode) {
+ super("ISOLATION_UNAVAILABLE", "Isolated evaluator readiness check failed.");
+ this.name = "EvaluatorIsolationReadinessError";
+ this.readinessCode = readinessCode;
+ }
+ };
+});
+
+// src/evaluator/index.ts
+var init_evaluator = __esm(() => {
+ init_protocol();
+ init_handler();
+ init_subprocess();
+ init_isolation();
+});
+
+// src/views/evidence-history.ts
+function unique(values) {
+ return [...new Set(values)];
+}
+function cloneReference(reference) {
+ return {
+ ...reference,
+ inputGlbSha256: [...reference.inputGlbSha256],
+ rendererIds: [...reference.rendererIds]
+ };
+}
+function currentEvidence(sequence, surface, fidelity) {
+ if (fidelity.version === "kiln.view-fidelity.v1") {
+ const valid2 = SHA256.test(fidelity.inputGlbSha256) && fidelity.rendererId.trim().length > 0 && (!fidelity.materialFaithful || fidelity.delivered === "full-material" && !fidelity.degraded);
+ if (!valid2) {
+ return {
+ sequence,
+ surface,
+ delivered: "none",
+ materialFaithful: false,
+ exactArtifact: false,
+ degraded: true,
+ inputGlbSha256: [],
+ rendererIds: [],
+ reasonCodes: ["DERIVATIVE_RECEIPT_INVALID"]
+ };
+ }
+ return {
+ sequence,
+ surface,
+ delivered: fidelity.delivered,
+ materialFaithful: fidelity.materialFaithful,
+ exactArtifact: fidelity.exactArtifact,
+ degraded: fidelity.degraded,
+ inputGlbSha256: [fidelity.inputGlbSha256],
+ rendererIds: [fidelity.rendererId],
+ ...fidelity.reasonCodes?.length ? { reasonCodes: [...fidelity.reasonCodes] } : {}
+ };
+ }
+ const valid = fidelity.exactArtifact === false && fidelity.receipts.length > 0 && fidelity.receipts.every((receipt) => receipt.exactArtifact === false && receipt.derivativeLabel.trim().length > 0 && receipt.rendererId.trim().length > 0 && SHA256.test(receipt.inputGlbSha256)) && (!fidelity.materialFaithful || fidelity.delivered === "full-material" && !fidelity.degraded && fidelity.receipts.every((receipt) => receipt.materialFaithful && receipt.delivered === "full-material" && !receipt.degraded));
+ if (!valid) {
+ return {
+ sequence,
+ surface,
+ delivered: "none",
+ materialFaithful: false,
+ exactArtifact: false,
+ degraded: true,
+ inputGlbSha256: [],
+ rendererIds: [],
+ reasonCodes: ["DERIVATIVE_RECEIPT_INVALID"]
+ };
+ }
+ const reasonCodes = unique(fidelity.receipts.flatMap((receipt) => receipt.reasonCodes ?? []).concat(fidelity.reasonCodes ?? []));
+ return {
+ sequence,
+ surface,
+ delivered: fidelity.delivered,
+ materialFaithful: fidelity.materialFaithful,
+ exactArtifact: false,
+ degraded: fidelity.degraded,
+ inputGlbSha256: fidelity.receipts.map((receipt) => receipt.inputGlbSha256),
+ rendererIds: unique(fidelity.receipts.map((receipt) => receipt.rendererId)),
+ ...reasonCodes.length ? { reasonCodes } : {}
+ };
+}
+
+class ViewEvidenceHistoryStore {
+ limit;
+ sequence = 0;
+ current;
+ faithful = [];
+ constructor(limit = DEFAULT_LIMIT) {
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
+ throw new RangeError(`view evidence history limit must be an integer in [1,${MAX_LIMIT}]`);
+ }
+ this.limit = limit;
+ }
+ record(surface, fidelity) {
+ this.sequence++;
+ this.current = currentEvidence(this.sequence, surface, fidelity);
+ if (this.current.materialFaithful) {
+ this.faithful.push({
+ version: "kiln.faithful-view-evidence-ref.v1",
+ sequence: this.current.sequence,
+ surface,
+ materialFaithful: true,
+ exactArtifact: this.current.exactArtifact,
+ inputGlbSha256: [...this.current.inputGlbSha256],
+ rendererIds: [...this.current.rendererIds]
+ });
+ if (this.faithful.length > this.limit)
+ this.faithful.splice(0, this.faithful.length - this.limit);
+ }
+ return this.snapshot();
+ }
+ snapshot() {
+ if (!this.current)
+ return;
+ const faithfulHistory = this.faithful.map(cloneReference);
+ return {
+ version: "kiln.view-evidence-history.v1",
+ current: {
+ ...this.current,
+ inputGlbSha256: [...this.current.inputGlbSha256],
+ rendererIds: [...this.current.rendererIds],
+ ...this.current.reasonCodes ? { reasonCodes: [...this.current.reasonCodes] } : {}
+ },
+ ...faithfulHistory.length ? { lastFaithful: cloneReference(faithfulHistory[faithfulHistory.length - 1]) } : {},
+ faithfulHistory
+ };
+ }
+}
+var SHA256, DEFAULT_LIMIT = 4, MAX_LIMIT = 8;
+var init_evidence_history = __esm(() => {
+ SHA256 = /^sha256:[0-9a-f]{64}$/;
+});
+
+// src/views/renderer-id.ts
+var exports_renderer_id = {};
+__export(exports_renderer_id, {
+ CPU_RASTER_RENDERER_ID: () => CPU_RASTER_RENDERER_ID
+});
+import { readFileSync } from "node:fs";
+function engineVersion() {
+ for (const path of ["../package.json", "../../package.json"]) {
+ try {
+ const raw = readFileSync(new URL(path, import.meta.url), "utf8");
+ const pkg = JSON.parse(raw);
+ if (pkg.name === "@kiln/engine" && typeof pkg.version === "string" && pkg.version) {
+ return pkg.version;
+ }
+ } catch {}
+ }
+ return "unknown";
+}
+var CPU_RASTER_RENDERER_ID;
+var init_renderer_id = __esm(() => {
+ CPU_RASTER_RENDERER_ID = `cpu-raster:${engineVersion()}`;
+});
+
+// src/views/scene-raster.ts
+import * as THREE31 from "three";
+async function rasterizeComposedScene(parts, opts = {}) {
+ const views = opts.views?.length ? opts.views : SCENE_VIEWS;
+ const size = opts.size ?? 320;
+ const group = new THREE31.Group;
+ const baseByInput = new Map;
+ for (const part of parts) {
+ if (part.code === undefined === (part.glb === undefined)) {
+ throw new TypeError("Composed part must provide exactly one of code or glb.");
+ }
+ const key = part.glb ?? part.code;
+ let base = baseByInput.get(key);
+ if (!base) {
+ const glb = part.glb ? Uint8Array.from(part.glb) : (await resolveEvaluatorPortV1(opts.evaluatorPort, opts.evaluatorProfile ?? "trusted-local").render(part.code)).glb;
+ base = (await loadGlbReviewScene(glb)).root;
+ baseByInput.set(key, base);
+ }
+ const inst = base.clone(true);
+ inst.position.set(part.pos[0], part.pos[1], part.pos[2]);
+ inst.rotation.set(0, part.rotYDeg * DEG2, 0);
+ inst.scale.setScalar(part.scale);
+ group.add(inst);
+ }
+ group.updateMatrixWorld(true);
+ const cols = Math.min(Math.max(views.length, 1), 3);
+ const rows = Math.ceil(views.length / cols);
+ const width = cols * size + (cols + 1) * PAD2;
+ const height = rows * size + (rows + 1) * PAD2;
+ const grid = new Uint8Array(width * height * 3);
+ for (let i = 0;i < width * height; i++) {
+ grid[i * 3] = PAD_COLOR2[0];
+ grid[i * 3 + 1] = PAD_COLOR2[1];
+ grid[i * 3 + 2] = PAD_COLOR2[2];
+ }
+ for (let vi = 0;vi < views.length; vi++) {
+ const cell = rasterizeView(group, views[vi].dir, { size });
+ const col = vi % cols;
+ const row = Math.floor(vi / cols);
+ const x0 = PAD2 + col * (size + PAD2);
+ const y0 = PAD2 + row * (size + PAD2);
+ for (let y = 0;y < size; y++) {
+ const src = y * size * 3;
+ const dst = ((y0 + y) * width + x0) * 3;
+ grid.set(cell.subarray(src, src + size * 3), dst);
+ }
+ }
+ return { png: encodePng(grid, width, height), width, height, views: views.map((v) => v.name) };
+}
+var DEG2, PAD2 = 4, PAD_COLOR2, SCENE_VIEWS;
+var init_scene_raster = __esm(() => {
+ init_evaluator();
+ init_glb();
+ init_png();
+ init_raster();
+ DEG2 = Math.PI / 180;
+ PAD_COLOR2 = [10, 11, 13];
+ SCENE_VIEWS = [
+ { name: "Hero 3/4", dir: [0.7, 0.45, 0.7] },
+ { name: "Reverse 3/4", dir: [-0.7, 0.45, -0.7] },
+ { name: "Top", dir: [0, 1, 0.0001] }
+ ];
+});
+
+// src/views/vehicle.ts
+import * as THREE32 from "three";
+function hasRole2(node, prefix) {
+ return readSemanticMetadataV1(node)?.roles.some((role) => role === prefix || role.startsWith(`${prefix}.`)) ?? false;
+}
+function chassisBounds(root, inverse) {
+ const bounds = new THREE32.Box3;
+ let found = false;
+ root.traverse((node) => {
+ if (!hasRole2(node, "chassis"))
+ return;
+ node.traverse((part) => {
+ if (!(part instanceof THREE32.Mesh) || !(part.geometry instanceof THREE32.BufferGeometry))
+ return;
+ part.geometry.computeBoundingBox();
+ const box = part.geometry.boundingBox;
+ if (!box)
+ return;
+ const matrix = inverse.clone().multiply(part.matrixWorld);
+ for (const x of [box.min.x, box.max.x])
+ for (const y of [box.min.y, box.max.y])
+ for (const z of [box.min.z, box.max.z]) {
+ bounds.expandByPoint(new THREE32.Vector3(x, y, z).applyMatrix4(matrix));
+ found = true;
+ }
+ });
+ });
+ return found ? bounds : undefined;
+}
+function describeVehicleDiagnostics(root) {
+ root.updateWorldMatrix(true, true);
+ const inverse = root.matrixWorld.clone().invert();
+ const assemblies = resolveVehicleWheelAssemblies(root);
+ const wheels = assemblies.map((wheel) => ({
+ id: wheel.id,
+ center: tuple7(wheel.centerWorld.clone().applyMatrix4(inverse)),
+ radius: wheel.radius ?? 0,
+ width: wheel.width ?? 0,
+ axle: tuple7(wheel.spinAxisWorld.clone().transformDirection(inverse)),
+ loadBearing: wheel.loadBearing
+ }));
+ const byAxle = new Map;
+ for (let index = 0;index < assemblies.length; index++) {
+ const key = assemblies[index].index ?? assemblies[index].id;
+ const group = byAxle.get(key) ?? [];
+ group.push(wheels[index]);
+ byAxle.set(key, group);
+ }
+ const axles = [...byAxle].flatMap(([id, members]) => {
+ if (members.length < 2)
+ return [];
+ const sorted = [...members].sort((a, b) => a.center[2] - b.center[2]);
+ return [{ id, start: sorted[0].center, end: sorted.at(-1).center }];
+ });
+ const contacts = wheels.filter((wheel) => wheel.loadBearing && wheel.radius > 0).map((wheel) => wheel.center[1] - wheel.radius);
+ const supportPlaneY = contacts.length > 0 ? contacts.reduce((sum, value) => sum + value, 0) / contacts.length : undefined;
+ const chassis = chassisBounds(root, inverse);
+ const views = [
+ { id: "vehicle.front-direction", label: "+X front and chassis", cameraDirection: [1, 0.15, 0] },
{
- name: "loadApprovedTexture",
- signature: "await loadApprovedTexture(resourceId)",
- returns: "Promise<THREE.DataTexture>",
- category: "textures",
- description: "Loads one approved kiln.texture.* resource ID through the host-injected closed resolver. The registry fixes bytes, MIME, usage, dimensions, hash, and deadline; paths, URLs, byte arrays, resolver objects, hashes, and options are rejected.",
- example: "const bark = await loadApprovedTexture('kiln.texture.bark-brown-01-albedo.v1');",
- promptNotes: "Use only a concrete resource ID listed in material capabilities; never invent one. Prefer materialRecipe when a recipe already binds the family, or proceduralTexture V2 for authored surfaces. NEVER texture.clone() a loaded texture (clone() corrupts encoded bytes and breaks GLB export)."
+ id: "vehicle.axles.top",
+ label: "Chassis and axle projection",
+ cameraDirection: [0.001, 1, 0]
},
{
- name: "proceduralTexture",
- signature: "proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })",
- returns: "THREE.DataTexture (tiling, sRGB or linear per usage)",
- category: "textures",
- description: "Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.",
- example: "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",
- promptNotes: "Sync — no await. Strict V2 JSON boundary: unknown/prototype keys, callbacks, paths, URLs, and shader source are rejected. Prefer this over approved resources for describable surfaces. Max 8 layers, power-of-two size up to 1024. Only the six listed ops exist."
+ id: "vehicle.underbody",
+ label: "Underbody support plane",
+ cameraDirection: [-0.3, -0.8, 0.5]
},
- {
- name: "normalMapFromHeight",
- signature: "normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })",
- returns: "THREE.DataTexture (linear normal map)",
- category: "textures",
- description: "Derives a tangent-space normal map from the source texture's brightness, treating it as height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at the edges, so a tiling source gives a tiling normal map.",
- example: `const bark = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] });
-const mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });`,
- promptNotes: "strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always linear data — never assign it to an albedo/emissive slot."
+ ...wheels.slice(0, 2).map((wheel) => ({
+ id: `vehicle.wheel-section.${wheel.id.replace(/[^a-zA-Z0-9.-]/g, "-")}`,
+ label: `Wheel section ${wheel.id}`,
+ cameraDirection: [0, 0, wheel.center[2] < 0 ? -1 : 1],
+ focus: wheel.id
+ }))
+ ];
+ return {
+ schemaVersion: 1,
+ forwardArrow: { start: [0, 0, 0], end: [1, 0, 0] },
+ ...chassis ? { chassisBox: { min: tuple7(chassis.min), max: tuple7(chassis.max) } } : {},
+ axles,
+ wheels,
+ ...supportPlaneY !== undefined ? { supportPlaneY } : {},
+ views
+ };
+}
+function tagDiagnostic(node, role) {
+ stampSemanticMetadataV1(node, { roles: [role] });
+}
+function rod(name, start, end, radius, color2, role) {
+ const from = new THREE32.Vector3(...start);
+ const to = new THREE32.Vector3(...end);
+ const direction = to.clone().sub(from);
+ const length3 = direction.length();
+ const geometry2 = length3 > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length3, 8) : new THREE32.SphereGeometry(radius, 8, 6);
+ const result = new THREE32.Mesh(geometry2, new THREE32.MeshBasicMaterial({ color: color2 }));
+ result.name = name;
+ result.position.copy(from).add(to).multiplyScalar(0.5);
+ if (length3 > 0.000000001) {
+ result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length3));
+ }
+ tagDiagnostic(result, role);
+ return result;
+}
+function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagnostics(root)) {
+ const overlay = new THREE32.Group;
+ overlay.name = "VehicleDiagnosticOverlay";
+ const chassisSpan = descriptor2.chassisBox ? Math.max(descriptor2.chassisBox.max[0] - descriptor2.chassisBox.min[0], descriptor2.chassisBox.max[1] - descriptor2.chassisBox.min[1], descriptor2.chassisBox.max[2] - descriptor2.chassisBox.min[2]) : 1;
+ const thickness = Math.max(0.01, chassisSpan * 0.008);
+ const arrow = new THREE32.Group;
+ arrow.name = "Diagnostic_Forward_+X";
+ tagDiagnostic(arrow, "diagnostic.vehicle.forward");
+ arrow.add(rod("Diagnostic_Forward_Shaft", descriptor2.forwardArrow.start, [descriptor2.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));
+ const arrowHead = new THREE32.Mesh(new THREE32.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE32.MeshBasicMaterial({ color: 16724804 }));
+ arrowHead.name = "Diagnostic_Forward_Head";
+ arrowHead.position.set(descriptor2.forwardArrow.end[0] - 0.12, 0, 0);
+ arrowHead.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), new THREE32.Vector3(1, 0, 0));
+ tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");
+ arrow.add(arrowHead);
+ overlay.add(arrow);
+ for (const axle of descriptor2.axles) {
+ overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));
+ }
+ for (const wheel of descriptor2.wheels) {
+ const ring = new THREE32.Mesh(new THREE32.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE32.MeshBasicMaterial({ color: 16763955 }));
+ ring.name = `Diagnostic_Wheel_${wheel.id}`;
+ ring.position.set(...wheel.center);
+ const axle = new THREE32.Vector3(...wheel.axle);
+ if (axle.lengthSq() > 0.000000000001) {
+ ring.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 0, 1), axle.normalize());
+ }
+ tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);
+ overlay.add(ring);
+ }
+ if (descriptor2.chassisBox) {
+ const chassis = new THREE32.Group;
+ chassis.name = "Diagnostic_ChassisBox";
+ tagDiagnostic(chassis, "diagnostic.vehicle.chassis");
+ const { min, max } = descriptor2.chassisBox;
+ const corners = [
+ [min[0], min[1], min[2]],
+ [max[0], min[1], min[2]],
+ [max[0], max[1], min[2]],
+ [min[0], max[1], min[2]],
+ [min[0], min[1], max[2]],
+ [max[0], min[1], max[2]],
+ [max[0], max[1], max[2]],
+ [min[0], max[1], max[2]]
+ ];
+ const edges = [
+ [0, 1],
+ [1, 2],
+ [2, 3],
+ [3, 0],
+ [4, 5],
+ [5, 6],
+ [6, 7],
+ [7, 4],
+ [0, 4],
+ [1, 5],
+ [2, 6],
+ [3, 7]
+ ];
+ for (const [index, edge] of edges.entries()) {
+ chassis.add(rod(`Diagnostic_ChassisEdge_${index}`, corners[edge[0]], corners[edge[1]], thickness, 5635959, "diagnostic.vehicle.chassis"));
+ }
+ overlay.add(chassis);
+ }
+ if (descriptor2.supportPlaneY !== undefined) {
+ const plane = new THREE32.Group;
+ plane.name = "Diagnostic_SupportPlane";
+ tagDiagnostic(plane, "diagnostic.vehicle.support-plane");
+ const halfX = Math.max(1, ...descriptor2.chassisBox ? [Math.abs(descriptor2.chassisBox.min[0]), Math.abs(descriptor2.chassisBox.max[0])] : [], ...descriptor2.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;
+ const halfZ = Math.max(0.8, ...descriptor2.chassisBox ? [Math.abs(descriptor2.chassisBox.min[2]), Math.abs(descriptor2.chassisBox.max[2])] : [], ...descriptor2.wheels.map((wheel) => Math.abs(wheel.center[2]) + wheel.width / 2)) + 0.2;
+ const y = descriptor2.supportPlaneY;
+ const planeLines = [
+ [
+ [-halfX, y, -halfZ],
+ [halfX, y, -halfZ]
+ ],
+ [
+ [halfX, y, -halfZ],
+ [halfX, y, halfZ]
+ ],
+ [
+ [halfX, y, halfZ],
+ [-halfX, y, halfZ]
+ ],
+ [
+ [-halfX, y, halfZ],
+ [-halfX, y, -halfZ]
+ ],
+ [
+ [-halfX, y, 0],
+ [halfX, y, 0]
+ ],
+ [
+ [0, y, -halfZ],
+ [0, y, halfZ]
+ ]
+ ];
+ for (const [index, [start, end]] of planeLines.entries()) {
+ plane.add(rod(`Diagnostic_SupportLine_${index}`, start, end, thickness * 0.7, 6750207, "diagnostic.vehicle.support-plane"));
+ }
+ overlay.add(plane);
+ }
+ return overlay;
+}
+function compositeForCapture(root, overlay) {
+ if (root.matrixAutoUpdate === false) {
+ overlay.matrix.copy(root.matrix);
+ overlay.matrixAutoUpdate = false;
+ } else {
+ overlay.position.copy(root.position);
+ overlay.quaternion.copy(root.quaternion);
+ overlay.scale.copy(root.scale);
+ }
+ return {
+ name: "VehicleDiagnosticCaptureRoot",
+ type: "Group",
+ visible: true,
+ position: { x: 0, y: 0, z: 0 },
+ quaternion: { x: 0, y: 0, z: 0, w: 1 },
+ scale: { x: 1, y: 1, z: 1 },
+ children: [root, overlay]
+ };
+}
+function selectWheelSectionRequest(requestValue, descriptor2) {
+ const target = descriptor2.wheels.find((wheel) => /right.*front|front.*right/i.test(wheel.id)) ?? descriptor2.wheels.find((wheel) => /right/i.test(wheel.id)) ?? descriptor2.wheels[0];
+ if (!target?.id.startsWith("wheel.assembly."))
+ return requestValue;
+ const suffix = target.id.replace(/[^a-zA-Z0-9.-]/g, "-");
+ return {
+ ...requestValue,
+ id: `vehicle.wheel-section.${suffix}`,
+ label: `Vehicle wheel section ${target.id}`,
+ focusRolePrefixes: [target.id]
+ };
+}
+function captureVehicleDiagnosticViews(root, intent, size = 256) {
+ if (intent.category !== "vehicle")
+ return [];
+ const descriptor2 = describeVehicleDiagnostics(root);
+ const overlay = createVehicleDiagnosticOverlay(root, descriptor2);
+ const composite = compositeForCapture(root, overlay);
+ const requests = planDiagnosticViews(intent).extra.filter((value) => value.variant === "vehicle-underbody" || value.variant === "vehicle-wheel-section");
+ return requests.map((baseRequest) => {
+ const requestValue = baseRequest.variant === "vehicle-wheel-section" ? selectWheelSectionRequest(baseRequest, descriptor2) : baseRequest;
+ const frame = renderDiagnosticView(composite, requestValue, { size });
+ return {
+ id: frame.id,
+ label: frame.label,
+ cameraId: frame.camera.id,
+ kind: requestValue.variant === "vehicle-underbody" ? "underbody" : "wheel-section",
+ buffer: "semantic-overlay",
+ width: frame.width,
+ height: frame.height,
+ png: frame.png,
+ regions: frame.regions,
+ descriptor: descriptor2
+ };
+ });
+}
+var tuple7 = (value) => [value.x, value.y, value.z];
+var init_vehicle3 = __esm(() => {
+ init_contracts();
+ init_vehicle();
+ init_diagnostic();
+});
+
+// src/views/index.ts
+var exports_views = {};
+__export(exports_views, {
+ withCameraVisibility: () => withCameraVisibility,
+ validateResolvedAssetCamera: () => validateResolvedAssetCamera,
+ validateAdvancedCapture: () => validateAdvancedCapture,
+ stampAxisGnomon: () => stampAxisGnomon,
+ snapSceneToPalette: () => snapSceneToPalette,
+ selectCameraSubject: () => selectCameraSubject,
+ selectArchitectureRoofNodes: () => selectArchitectureRoofNodes,
+ resolveGridViews: () => resolveGridViews,
+ resolveGridCapture: () => resolveGridCapture,
+ resolveCaptureLimits: () => resolveCaptureLimits,
+ resolveCapture: () => resolveCapture,
+ resolveAssetCamera: () => resolveAssetCamera,
+ renderViewGrid: () => renderViewGrid,
+ renderInteriorGrid: () => renderInteriorGrid,
+ renderGlbViewGrid: () => renderGlbViewGrid,
+ renderGlbViewCell: () => renderGlbViewCell,
+ renderDiagnosticViews: () => renderDiagnosticViews,
+ renderDiagnosticView: () => renderDiagnosticView,
+ renderCodeViewGrid: () => renderCodeViewGrid,
+ renderClipAnimation: () => renderClipAnimation,
+ renderCaptureGrid: () => renderCaptureGrid,
+ rasterizeView: () => rasterizeView,
+ rasterizeComposedScene: () => rasterizeComposedScene,
+ rasterizeCamera: () => rasterizeCamera,
+ prepareClip: () => prepareClip,
+ poseSceneAtTime: () => poseSceneAtTime,
+ planFrameTimes: () => planFrameTimes,
+ planDiagnosticViews: () => planDiagnosticViews,
+ planCharacterDiagnosticRequests: () => planCharacterDiagnosticRequests,
+ orbitDir: () => orbitDir,
+ orbitAnglesOf: () => orbitAnglesOf,
+ measureBounds: () => measureBounds,
+ loadGlbReviewScene: () => loadGlbReviewScene,
+ loadGlbGeometryFlatScene: () => loadGlbGeometryFlatScene,
+ listCameraSubjects: () => listCameraSubjects,
+ hideNodeInScene: () => hideNodeInScene,
+ hideArchitectureRoofInScene: () => hideArchitectureRoofInScene,
+ hasArchitectureRoofRole: () => hasArchitectureRoofRole,
+ geometryFlatTextureReasonCode: () => geometryFlatTextureReasonCode,
+ findClip: () => findClip,
+ encodePng: () => encodePng,
+ describeVehicleDiagnostics: () => describeVehicleDiagnostics,
+ describeCapture: () => describeCapture,
+ decodePng: () => decodePng,
+ createVehicleDiagnosticOverlay: () => createVehicleDiagnosticOverlay,
+ createCachedRenderPort: () => createCachedRenderPort,
+ coverage: () => coverage,
+ compositeViewPngGrid: () => compositeViewPngGrid,
+ compositeCellGrid: () => compositeCellGrid,
+ clipNames: () => clipNames,
+ captureVehicleDiagnosticViews: () => captureVehicleDiagnosticViews,
+ captureCpuCell: () => captureCpuCell,
+ captureCellLabel: () => captureCellLabel,
+ cameraFromBounds: () => cameraFromBounds,
+ buildCharacterDiagnosticDescriptor: () => buildCharacterDiagnosticDescriptor,
+ annotateViewCell: () => annotateViewCell,
+ ViewEvidenceHistoryStore: () => ViewEvidenceHistoryStore,
+ SIX_VIEWS_REAR_QUARTER: () => SIX_VIEWS_REAR_QUARTER,
+ SIX_VIEWS: () => SIX_VIEWS,
+ SCENE_VIEWS: () => SCENE_VIEWS,
+ MemoryCaptureCache: () => MemoryCaptureCache,
+ MIN_ELEVATION_DEG: () => MIN_ELEVATION_DEG,
+ MAX_ELEVATION_DEG: () => MAX_ELEVATION_DEG,
+ MAX_CAPTURE_CELLS: () => MAX_CAPTURE_CELLS,
+ INTERIOR_VIEWS: () => INTERIOR_VIEWS,
+ GlbGeometryFlatError: () => GlbGeometryFlatError,
+ GRID_COLS: () => GRID_COLS,
+ GRID_BACKGROUND_RGB: () => GRID_BACKGROUND_RGB,
+ GRID_BACKGROUND_HEX: () => GRID_BACKGROUND_HEX,
+ GLB_GEOMETRY_FLAT_REASON: () => GLB_GEOMETRY_FLAT_REASON,
+ GENERIC_DIAGNOSTIC_REQUESTS: () => GENERIC_DIAGNOSTIC_REQUESTS,
+ GENERIC_DIAGNOSTIC_CAMERAS: () => GENERIC_DIAGNOSTIC_CAMERAS,
+ GENERIC_DIAGNOSTIC_BUFFER_IDS: () => GENERIC_DIAGNOSTIC_BUFFER_IDS,
+ DEFAULT_CAPTURE_PRESET: () => DEFAULT_CAPTURE_PRESET,
+ DEFAULT_CAPTURE_LIMITS: () => DEFAULT_CAPTURE_LIMITS,
+ CaptureConfigError: () => CaptureConfigError,
+ CPU_RASTER_RENDERER_ID: () => CPU_RASTER_RENDERER_ID,
+ CHARACTER_MOTION_DIAGNOSTIC_PHASES: () => CHARACTER_MOTION_DIAGNOSTIC_PHASES,
+ CAPTURE_PRESETS: () => CAPTURE_PRESETS,
+ ARCHITECTURE_ROOF_ROLE_PREFIXES: () => ARCHITECTURE_ROOF_ROLE_PREFIXES
+});
+function setLinearColor(color2, rgb2) {
+ if (!color2)
+ return;
+ color2.r = rgb2[0];
+ color2.g = rgb2[1];
+ color2.b = rgb2[2];
+}
+function snapMaterialToPalette(mat, slots, idx) {
+ if (!mat.color)
+ return;
+ if (mat.map || mat.vertexColors)
+ return false;
+ const emissive = mat.emissive && (mat.emissiveIntensity ?? 1) > 0 ? [
+ mat.emissive.r * (mat.emissiveIntensity ?? 1),
+ mat.emissive.g * (mat.emissiveIntensity ?? 1),
+ mat.emissive.b * (mat.emissiveIntensity ?? 1)
+ ] : undefined;
+ const slotI = chooseSlot(idx, {
+ baseLinear: [mat.color.r, mat.color.g, mat.color.b],
+ ...emissive ? { emissiveLinear: emissive } : {},
+ transparent: mat.transparent === true || mat.opacity !== undefined && mat.opacity < 0.98
+ });
+ if (slotI === undefined)
+ return false;
+ const slot = slots[slotI];
+ const kind = slot.kind ?? "opaque";
+ const rgb2 = hexToLinearRgb(slot.color);
+ setLinearColor(mat.color, rgb2);
+ if (mat.metalness !== undefined)
+ mat.metalness = slot.metalness ?? 0;
+ if (mat.roughness !== undefined)
+ mat.roughness = slot.roughness ?? (kind === "glass" ? 0.1 : 0.85);
+ if (kind === "glass") {
+ mat.transparent = true;
+ mat.opacity = slot.opacity ?? 0.4;
+ } else {
+ if (mat.transparent !== undefined)
+ mat.transparent = false;
+ if (mat.opacity !== undefined)
+ mat.opacity = 1;
+ }
+ if (mat.emissive) {
+ if (kind === "glow") {
+ setLinearColor(mat.emissive, rgb2);
+ mat.emissiveIntensity = Math.max(mat.emissiveIntensity ?? 1, 1);
+ } else {
+ setLinearColor(mat.emissive, [0, 0, 0]);
+ if (mat.emissiveIntensity !== undefined)
+ mat.emissiveIntensity = 0;
+ }
+ }
+ return true;
+}
+function snapSceneToPalette(root, slots) {
+ if (slots.length === 0)
+ return { snapped: 0, skipped: 0 };
+ const traverse = root?.traverse;
+ if (!traverse)
+ return { snapped: 0, skipped: 0 };
+ const idx = buildSlotIndex(slots);
+ let snapped = 0;
+ let skipped = 0;
+ traverse.call(root, (obj) => {
+ if (!obj.isMesh || !obj.material)
+ return;
+ const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
+ for (const mat of materials) {
+ const didSnap = snapMaterialToPalette(mat, slots, idx);
+ if (didSnap === true)
+ snapped++;
+ else if (didSnap === false)
+ skipped++;
+ }
+ });
+ return { snapped, skipped };
+}
+async function renderViewGrid(root, opts = {}) {
+ if (opts.capture?.shots || opts.capture?.version)
+ return renderCaptureGrid(root, opts.capture, undefined, opts.captureLimits);
+ const size = opts.size ?? 384;
+ const resolved2 = resolveGridCapture(opts.capture, process.env["KILN_GRID_VARIANT"]);
+ const views = opts.views ?? resolved2.views;
+ const cols = opts.cols ?? resolved2.cols;
+ enforceCapturePixels(views.length, size, cols, opts.captureLimits);
+ if (opts.snapPalette?.length)
+ snapSceneToPalette(root, opts.snapPalette);
+ const wantsZoom = resolved2.zooms.some((z) => z !== undefined);
+ const sceneBounds = wantsZoom ? measureBounds(root) : undefined;
+ const cache = opts.snapPalette?.length ? undefined : opts.captureCache;
+ let reused = 0;
+ const cells = [];
+ for (let vi = 0;vi < views.length; vi++) {
+ const zoom = resolved2.zooms[vi];
+ const rasterOptions = {
+ size,
+ backfaceCull: opts.backfaceCull,
+ ...opts.frameBounds ? { frameBounds: opts.frameBounds } : {},
+ ...sceneBounds && zoom !== undefined ? { frameBounds: expandFrameBounds(sceneBounds, zoom) } : {}
+ };
+ let cell;
+ if (cache && opts.artifactGlbSha256) {
+ const { CPU_RASTER_RENDERER_ID: CPU_RASTER_RENDERER_ID2 } = await Promise.resolve().then(() => (init_renderer_id(), exports_renderer_id));
+ const camera2 = cameraFromBounds(rasterOptions.frameBounds ?? measureBounds(root), views[vi].dir);
+ const result = await captureCpuCell(cache, {
+ artifactGlbSha256: opts.artifactGlbSha256,
+ rendererId: `${CPU_RASTER_RENDERER_ID2}/legacy-fit`,
+ camera: camera2,
+ size,
+ backfaceCull: opts.backfaceCull ?? true
+ }, async () => ({
+ png: encodePng(rasterizeView(root, views[vi].dir, rasterOptions), size, size),
+ width: size,
+ height: size,
+ inputGlbSha256: opts.artifactGlbSha256,
+ reasonCodes: [],
+ meshCount: 0,
+ instanceCount: 0
+ }));
+ if (result.captureCache?.hit)
+ reused++;
+ cell = decodePng(result.png).rgb;
+ } else
+ cell = rasterizeView(root, views[vi].dir, rasterOptions);
+ annotateViewCell(cell, size, views[vi]);
+ cells.push(cell);
+ }
+ const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, cols);
+ const png = encodePng(rgb2, width, height);
+ enforceCaptureBytes([png], opts.captureLimits);
+ return {
+ png,
+ width,
+ height,
+ views: views.map((v) => v.name),
+ capture: { preset: resolved2.preset, cols, cells: views.length },
+ ...cache && opts.artifactGlbSha256 ? { captureCache: { hit: reused === views.length, reused, total: views.length } } : {}
+ };
+}
+async function hashGlbViewInput(bytes) {
+ const copy = Uint8Array.from(bytes);
+ const digest2 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", copy));
+ return `sha256:${[...digest2].map((value) => value.toString(16).padStart(2, "0")).join("")}`;
+}
+async function renderGlbViewCell(bytes, view, options = {}) {
+ const exactBytes = Uint8Array.from(bytes);
+ const loaded = await loadGlbGeometryFlatScene(exactBytes);
+ const size = options.size ?? 256;
+ const rgb2 = options.camera ? rasterizeCamera(loaded.root, options.camera, size, options.backfaceCull) : rasterizeView(loaded.root, view.dir, {
+ size,
+ ...options.backfaceCull !== undefined ? { backfaceCull: options.backfaceCull } : {},
+ ...options.frameBounds ? { frameBounds: options.frameBounds } : {}
+ });
+ return {
+ png: encodePng(rgb2, size, size),
+ width: size,
+ height: size,
+ inputGlbSha256: await hashGlbViewInput(exactBytes),
+ reasonCodes: loaded.reasonCodes,
+ meshCount: loaded.meshCount,
+ instanceCount: loaded.instanceCount
+ };
+}
+async function renderGlbViewGrid(bytes, options = {}) {
+ const exactBytes = Uint8Array.from(bytes);
+ const loaded = await loadGlbGeometryFlatScene(exactBytes);
+ const artifactGlbSha256 = await hashGlbViewInput(exactBytes);
+ const grid = await renderViewGrid(loaded.root, { ...options, artifactGlbSha256 });
+ return {
+ ...grid,
+ inputGlbSha256: await hashGlbViewInput(exactBytes),
+ reasonCodes: loaded.reasonCodes,
+ meshCount: loaded.meshCount,
+ instanceCount: loaded.instanceCount
+ };
+}
+function expandFrameBounds(b, factor) {
+ const min = [0, 0, 0];
+ const max = [0, 0, 0];
+ for (let a = 0;a < 3; a++) {
+ const center = (b.min[a] + b.max[a]) / 2;
+ const half = (b.max[a] - b.min[a]) / 2 * factor;
+ min[a] = center - half;
+ max[a] = center + half;
+ }
+ return { min, max };
+}
+async function renderCodeViewGrid(code, opts = {}) {
+ const { evaluatorPort, evaluatorProfile, ...viewOptions } = opts;
+ const rendered = await resolveEvaluatorPortV1(evaluatorPort, evaluatorProfile ?? "trusted-local").render(code);
+ return renderGlbViewGrid(rendered.glb, viewOptions);
+}
+function resolveCamera(name) {
+ const key = (name ?? "right").trim().toLowerCase().replace(/[_\s]+/g, "-");
+ return ANIM_CAMERAS[key] ?? ANIM_CAMERAS[ANIM_CAMERA_ALIASES[key] ?? ""] ?? ANIM_CAMERAS["right"];
+}
+async function renderClipAnimation(root, clips, opts = {}) {
+ const size = opts.size ?? 256;
+ const frameCount = Math.max(2, Math.min(opts.frames ?? 6, 6));
+ const cam = resolveCamera(opts.camera);
+ if (!clips || clips.length === 0) {
+ return {
+ ok: false,
+ frames: 0,
+ frameTimes: [],
+ error: "this asset has no animation clips",
+ availableClips: []
+ };
+ }
+ const requested = opts.clip?.trim();
+ const chosen = requested ? findClip(clips, requested) : clips[0];
+ if (!chosen) {
+ return {
+ ok: false,
+ frames: 0,
+ frameTimes: [],
+ ...requested ? { clip: requested } : {},
+ error: `clip "${requested}" not found in this asset`,
+ availableClips: clipNames(clips)
+ };
+ }
+ const prepared = prepareClip(root, chosen);
+ if (opts.frameTimes && opts.frames !== undefined)
+ throw new Error("frameTimes and frames are mutually exclusive");
+ if (opts.shot && opts.camera)
+ throw new Error("shot and camera are mutually exclusive");
+ if (opts.frameTimes && (opts.frameTimes.length < 1 || opts.frameTimes.length > 9 || opts.frameTimes.some((v, i) => !Number.isFinite(v) || v < 0 || v > 1 || i > 0 && v <= opts.frameTimes[i - 1])))
+ throw new Error("frameTimes must contain 1..9 strictly increasing phases in 0..1");
+ const times = opts.frameTimes ? opts.frameTimes.map((t) => t * prepared.duration) : planFrameTimes(prepared.duration, frameCount);
+ const frameTimes = times.map((t) => prepared.duration > 0 ? t / prepared.duration : 0);
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ for (const t of times) {
+ poseSceneAtTime(root, prepared, t);
+ const b = measureBounds(opts.shot?.subject ? selectCameraSubject(root, opts.shot.subject).node : root);
+ for (let a = 0;a < 3; a++) {
+ const lo = b.min[a];
+ const hi = b.max[a];
+ if (lo < min[a])
+ min[a] = lo;
+ if (hi > max[a])
+ max[a] = hi;
+ }
+ }
+ const frameBounds = Number.isFinite(min[0]) ? { min, max } : undefined;
+ poseSceneAtTime(root, prepared, times[0]);
+ const initialShot = opts.shot ? resolveAssetCamera(root, opts.shot) : undefined;
+ let lockedCamera = initialShot?.camera;
+ if (initialShot && opts.shot?.camera?.type !== "explicit" && frameBounds) {
+ const dir = initialShot.camera.position.map((v, i) => v - initialShot.camera.target[i]);
+ lockedCamera = cameraFromBounds(frameBounds, dir, opts.shot?.camera?.type === "orbit" ? opts.shot.camera.padding ?? 1.2 : 1.2, initialShot.camera.up);
+ }
+ const cameraShots = [];
+ const labelScale = Math.max(2, Math.round(size / 80));
+ const cells = [];
+ const derivativeReceipts = [];
+ for (let i = 0;i < times.length; i++) {
+ poseSceneAtTime(root, prepared, times[i]);
+ const resolvedShot = opts.shot ? resolveAssetCamera(root, opts.shot) : undefined;
+ if (resolvedShot) {
+ if (opts.framing !== "follow")
+ resolvedShot.camera = lockedCamera;
+ cameraShots.push(resolvedShot);
+ }
+ let cell;
+ if (opts.renderDerivativeCell) {
+ const produce = () => opts.renderDerivativeCell({
+ root,
+ ...resolvedShot ? { camera: resolvedShot.camera } : {},
+ label: `${Math.round(frameTimes[i] * 100)}%`,
+ view: cam,
+ size,
+ ...opts.backfaceCull !== undefined ? { backfaceCull: opts.backfaceCull } : {},
+ ...frameBounds ? { frameBounds } : {}
+ });
+ const rendered = resolvedShot ? await withCameraVisibility(root, resolvedShot, produce) : await produce();
+ const decoded = decodePng(rendered.png);
+ if (decoded.width !== size || decoded.height !== size) {
+ throw new Error(`derivative animation cell must be ${size}x${size}; got ${decoded.width}x${decoded.height}`);
+ }
+ cell = decoded.rgb;
+ derivativeReceipts.push(rendered.receipt);
+ } else {
+ cell = resolvedShot ? await withCameraVisibility(root, resolvedShot, async () => rasterizeCamera(root, resolvedShot.camera, size)) : rasterizeView(root, cam.dir, {
+ size,
+ ...opts.backfaceCull !== undefined ? { backfaceCull: opts.backfaceCull } : {},
+ ...frameBounds ? { frameBounds } : {}
+ });
+ }
+ stampLabel(cell, size, size, labelScale, labelScale, `${Math.round(frameTimes[i] * 100)}%`, labelScale);
+ cells.push(cell);
+ }
+ const baseMeta = {
+ ok: true,
+ clip: prepared.name,
+ camera: cam.name,
+ frames: times.length,
+ frameTimes,
+ ...cameraShots.length ? { cameraShots } : {},
+ duration: prepared.duration,
+ ...prepared.unresolved.length ? { unresolvedTracks: prepared.unresolved } : {},
+ ...derivativeReceipts.length ? { derivativeReceipts } : {}
+ };
+ if (opts.perFrame) {
+ return {
+ ...baseMeta,
+ width: size,
+ height: size,
+ pngs: cells.map((c) => encodePng(c, size, size))
+ };
+ }
+ const { rgb: rgb2, width, height } = compositeCellGrid(cells, size);
+ return { ...baseMeta, width, height, png: encodePng(rgb2, width, height) };
+}
+function normalizeVec(v) {
+ const len = Math.hypot(v[0], v[1], v[2]) || 1;
+ return [v[0] / len, v[1] / len, v[2] / len];
+}
+function dotVec(a, b) {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+}
+async function renderInteriorGrid(root, opts = {}) {
+ const size = opts.size ?? 256;
+ const labelScale = Math.max(2, Math.round(size / 80));
+ const roofsHidden = opts.nodeName ? hideNodeInScene(root, opts.nodeName) : hideArchitectureRoofInScene(root).nodes.length;
+ if (opts.capture) {
+ const grid = await renderCaptureGrid(root, opts.capture, opts.renderDerivativeCell);
+ return { ...grid, roofsHidden, wallsHidden: 0 };
+ }
+ let wallsHidden = 0;
+ const cells = [];
+ const derivativeReceipts = [];
+ for (const view of INTERIOR_VIEWS) {
+ if (view.name === "Eye-level") {
+ const d = normalizeVec(view.dir);
+ wallsHidden = hideNodeInScene(root, (name) => {
+ const lower = name.toLowerCase();
+ for (const w of ROOM_WALL_NORMALS) {
+ if (lower.endsWith(w.suffix) && dotVec(w.n, d) > 0.2)
+ return true;
+ }
+ return false;
+ });
+ }
+ let cell;
+ if (opts.renderDerivativeCell) {
+ const rendered = await opts.renderDerivativeCell({
+ root,
+ label: view.name,
+ view,
+ size,
+ backfaceCull: false
+ });
+ const decoded = decodePng(rendered.png);
+ if (decoded.width !== size || decoded.height !== size) {
+ throw new Error(`derivative interior cell must be ${size}x${size}; got ${decoded.width}x${decoded.height}`);
+ }
+ cell = decoded.rgb;
+ derivativeReceipts.push(rendered.receipt);
+ } else {
+ cell = rasterizeView(root, view.dir, { size, backfaceCull: false });
+ }
+ stampLabel(cell, size, size, labelScale, labelScale, view.name, labelScale);
+ cells.push(cell);
+ }
+ const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, INTERIOR_VIEWS.length);
+ return {
+ png: encodePng(rgb2, width, height),
+ width,
+ height,
+ views: INTERIOR_VIEWS.map((v) => v.name),
+ roofsHidden,
+ wallsHidden,
+ ...derivativeReceipts.length ? { derivativeReceipts } : {}
+ };
+}
+var ANIM_CAMERAS, ANIM_CAMERA_ALIASES, ROOM_WALL_NORMALS, INTERIOR_VIEWS;
+var init_views = __esm(() => {
+ init_capture_limits();
+ init_capture_limits();
+ init_capture_cache();
+ init_camera();
+ init_camera_capture();
+ init_raster();
+ init_png();
+ init_png();
+ init_grid();
+ init_annotate();
+ init_capture();
+ init_pose();
+ init_architecture3();
+ init_glb();
+ init_evaluator();
+ init_raster();
+ init_annotate();
+ init_background();
+ init_png();
+ init_capture();
+ init_grid();
+ init_evidence_history();
+ init_renderer_id();
+ init_glb();
+ init_architecture3();
+ init_scene_raster();
+ init_diagnostic();
+ init_character3();
+ init_vehicle3();
+ init_pose();
+ init_capture_cache();
+ init_camera();
+ init_camera_capture();
+ ANIM_CAMERAS = {
+ front: { name: "Front", dir: [1, 0, 0] },
+ right: { name: "Right", dir: [0, 0, 1] },
+ back: { name: "Back", dir: [-1, 0, 0] },
+ left: { name: "Left", dir: [0, 0, -1] },
+ top: { name: "Top", dir: [0, 1, 0.0001] },
+ "three-quarter": { name: "3/4", dir: [0.7, 0.5, 0.7] }
+ };
+ ANIM_CAMERA_ALIASES = {
+ "3/4": "three-quarter",
+ "34": "three-quarter",
+ threequarter: "three-quarter",
+ quarter: "three-quarter",
+ perspective: "three-quarter",
+ side: "right",
+ profile: "right"
+ };
+ ROOM_WALL_NORMALS = [
+ { suffix: "wallfront", n: [1, 0, 0] },
+ { suffix: "wallback", n: [-1, 0, 0] },
+ { suffix: "wallleft", n: [0, 0, -1] },
+ { suffix: "wallright", n: [0, 0, 1] }
+ ];
+ INTERIOR_VIEWS = [
+ { name: "Floor plan", dir: [0, 1, 0.0001] },
+ { name: "Dollhouse", dir: [0.7, 0.5, 0.7] },
+ { name: "Eye-level", dir: [0.55, 0.35, 0.45] }
+ ];
+});
+
+// src/views/character-capture.ts
+import * as THREE33 from "three";
+function drawLine2(rgb2, width, height, from, to, color2) {
+ let x0 = Math.round(from[0]);
+ let y0 = Math.round(from[1]);
+ const x1 = Math.round(to[0]);
+ const y1 = Math.round(to[1]);
+ const dx = Math.abs(x1 - x0);
+ const sx = x0 < x1 ? 1 : -1;
+ const dy = -Math.abs(y1 - y0);
+ const sy = y0 < y1 ? 1 : -1;
+ let error = dx + dy;
+ while (true) {
+ if (x0 >= 0 && x0 < width && y0 >= 0 && y0 < height) {
+ const offset = (y0 * width + x0) * 3;
+ rgb2[offset] = color2[0];
+ rgb2[offset + 1] = color2[1];
+ rgb2[offset + 2] = color2[2];
+ }
+ if (x0 === x1 && y0 === y1)
+ break;
+ const doubled = 2 * error;
+ if (doubled >= dy) {
+ error += dy;
+ x0 += sx;
+ }
+ if (doubled <= dx) {
+ error += dx;
+ y0 += sy;
+ }
+ }
+}
+function drawCross(rgb2, width, height, point, color2, radius = 3) {
+ drawLine2(rgb2, width, height, [point[0] - radius, point[1]], [point[0] + radius, point[1]], color2);
+ drawLine2(rgb2, width, height, [point[0], point[1] - radius], [point[0], point[1] + radius], color2);
+}
+function projector(root, cameraId, size) {
+ root.updateMatrixWorld(true);
+ const bounds = new THREE33.Box3().setFromObject(root);
+ if (bounds.isEmpty())
+ bounds.set(new THREE33.Vector3(-0.5, 0, -0.5), new THREE33.Vector3(0.5, 1, 0.5));
+ const center = bounds.getCenter(new THREE33.Vector3);
+ const camera2 = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);
+ const upHint = new THREE33.Vector3(0, 1, 0);
+ const xAxis = new THREE33.Vector3().crossVectors(upHint, camera2).normalize();
+ const yAxis = new THREE33.Vector3().crossVectors(camera2, xAxis).normalize();
+ let extent2 = 0.000001;
+ for (let corner = 0;corner < 8; corner++) {
+ const point = new THREE33.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);
+ extent2 = Math.max(extent2, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));
+ }
+ const scale2 = size * 0.45 / extent2;
+ return (assetPoint) => {
+ const world = new THREE33.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
+ return [size / 2 + world.dot(xAxis) * scale2, size / 2 - world.dot(yAxis) * scale2];
+ };
+}
+function skeletonCapture(root, request2, findings, size) {
+ const baseRequest = {
+ id: request2.id,
+ label: request2.label,
+ cameraId: request2.cameraId,
+ buffer: "semantic-overlay",
+ scope: "category",
+ variant: "character-skeleton",
+ focusRolePrefixes: request2.focusRolePrefixes
+ };
+ const frame = renderDiagnosticView(root, baseRequest, { size });
+ const descriptor2 = buildCharacterDiagnosticDescriptor(root, findings);
+ const project2 = projector(root, request2.cameraId, size);
+ const byRole = new Map(descriptor2.joints.map((joint) => [joint.role, joint]));
+ for (const edge of descriptor2.edges) {
+ const parent = byRole.get(edge.parentRole);
+ const child = byRole.get(edge.childRole);
+ if (!parent || !child)
+ continue;
+ drawLine2(frame.rgb, frame.width, frame.height, project2(parent.assetPosition), project2(child.assetPosition), edge.valid ? rgbFromHex(edge.color) : [255, 62, 72]);
+ }
+ for (const joint of descriptor2.joints) {
+ const point = project2(joint.assetPosition);
+ const color2 = rgbFromHex(joint.color);
+ drawCross(frame.rgb, frame.width, frame.height, point, joint.contact ? [55, 235, 130] : color2);
+ drawLine2(frame.rgb, frame.width, frame.height, point, project2(joint.forwardAxisEnd), [64, 220, 255]);
+ drawLine2(frame.rgb, frame.width, frame.height, point, project2(joint.bendAxisEnd), [255, 105, 210]);
+ stampLabel(frame.rgb, frame.width, frame.height, Math.max(0, Math.min(frame.width - 2, Math.round(point[0] + 3))), Math.max(0, Math.min(frame.height - 7, Math.round(point[1] - 6))), joint.label.toUpperCase().replace(/[^A-Z0-9]+/g, " ").slice(0, 18), 1);
+ frame.regions.push({
+ nodeName: joint.nodeName,
+ nodePath: joint.nodePath,
+ semanticRoles: [`joint.${joint.role}`, ...joint.contact ? ["contact.character"] : []],
+ pixelBounds: [
+ Math.max(0, Math.round(point[0]) - 4),
+ Math.max(0, Math.round(point[1]) - 4),
+ Math.min(frame.width - 1, Math.round(point[0]) + 4),
+ Math.min(frame.height - 1, Math.round(point[1]) + 4)
+ ],
+ color: color2,
+ triangleCount: 0
+ });
+ }
+ const arrow = descriptor2.canonicalForwardArrow;
+ drawLine2(frame.rgb, frame.width, frame.height, project2(arrow.start), project2(arrow.end), [255, 220, 64]);
+ frame.regions.sort((a, b) => a.nodePath.localeCompare(b.nodePath));
+ return {
+ id: frame.id,
+ label: frame.label,
+ cameraId: request2.cameraId,
+ kind: "skeleton",
+ width: frame.width,
+ height: frame.height,
+ png: encodePng(frame.rgb, frame.width, frame.height),
+ regions: frame.regions
+ };
+}
+async function captureCharacterDiagnosticViews(root, clips, intent, findings = [], size = 256) {
+ const transforms = [];
+ root.traverse((node) => {
+ transforms.push({
+ node,
+ position: node.position.clone(),
+ quaternion: node.quaternion.clone(),
+ scale: node.scale.clone()
+ });
+ });
+ const requests = planCharacterDiagnosticRequests(intent);
+ const captures = [];
+ try {
+ for (const request2 of requests) {
+ if (request2.variant === "character-skeleton") {
+ captures.push(skeletonCapture(root, request2, findings, size));
+ continue;
+ }
+ if (!request2.clipName)
+ continue;
+ const strip = await renderClipAnimation(root, clips, {
+ clip: request2.clipName,
+ camera: request2.cameraId,
+ frames: request2.phaseFractions?.length ?? 6,
+ size
+ });
+ if (!strip.ok || !strip.png || !strip.width || !strip.height)
+ continue;
+ captures.push({
+ id: request2.id,
+ label: request2.label,
+ cameraId: request2.cameraId,
+ kind: "motion-strip",
+ width: strip.width,
+ height: strip.height,
+ png: strip.png,
+ regions: [],
+ clipName: request2.clipName,
+ phaseFractions: request2.phaseFractions
+ });
+ }
+ } finally {
+ for (const saved of transforms) {
+ saved.node.position.copy(saved.position);
+ saved.node.quaternion.copy(saved.quaternion);
+ saved.node.scale.copy(saved.scale);
+ }
+ root.updateMatrixWorld(true);
+ }
+ return captures;
+}
+var rgbFromHex = (value) => {
+ const parsed = Number.parseInt(value.replace(/^#/, ""), 16);
+ return [parsed >>> 16 & 255, parsed >>> 8 & 255, parsed & 255];
+};
+var init_character_capture = __esm(() => {
+ init_character3();
+ init_diagnostic();
+ init_png();
+ init_views();
+ init_pose();
+});
+
+// src/render.ts
+var exports_render = {};
+__export(exports_render, {
+ snapGlbToPalette: () => snapGlbToPalette,
+ settleContacts: () => settleContacts,
+ resolveEvaluatorMode: () => resolveEvaluatorMode,
+ renderSceneToGLB: () => renderSceneToGLB,
+ renderGLBInProcess: () => renderGLBInProcess,
+ renderGLB: () => renderGLB,
+ packKitGlb: () => packKitGlb,
+ optimizeGlbBytes: () => optimizeGlbBytes,
+ measureGlbBounds: () => measureGlbBounds,
+ inspectSceneStructure: () => inspectSceneStructure,
+ inspectGlbIntegration: () => inspectGlbIntegration,
+ inspectGeneratedAnimation: () => inspectGeneratedAnimation,
+ gradeGlbBytes: () => gradeGlbBytes,
+ executeKilnCode: () => executeKilnCode,
+ composeSceneGLB: () => composeSceneGLB,
+ bindBakedTextureProvenanceToFinalGlb: () => bindBakedTextureProvenanceToFinalGlb
+});
+import * as THREE34 from "three";
+import { createHash as createHash5 } from "node:crypto";
+import { Document, WebIO as WebIO3, getBounds } from "@gltf-transform/core";
+import {
+ EXTMeshGPUInstancing as EXTMeshGPUInstancing3,
+ KHRMaterialsVariants as KHRMaterialsVariants3,
+ KHRTextureBasisu as KHRTextureBasisu3
+} from "@gltf-transform/extensions";
+import {
+ dedup,
+ instance,
+ palette,
+ flatten,
+ join as join2,
+ weld,
+ prune,
+ mergeDocuments
+} from "@gltf-transform/functions";
+async function measureGlbBounds(bytes) {
+ const doc = await engineIO().readBinary(bytes);
+ const root = doc.getRoot();
+ const scene = root.getDefaultScene() ?? root.listScenes()[0];
+ if (!scene)
+ return;
+ const { min, max } = getBounds(scene);
+ if (!min.every(Number.isFinite) || !max.every(Number.isFinite))
+ return;
+ return {
+ min: [min[0], min[1], min[2]],
+ max: [max[0], max[1], max[2]]
+ };
+}
+function ensureDefaultScene(doc) {
+ const root = doc.getRoot();
+ const scene = root.getDefaultScene() ?? root.listScenes()[0];
+ if (scene && !root.getDefaultScene())
+ root.setDefaultScene(scene);
+ return scene;
+}
+async function sha256Hex2(bytes) {
+ const digest2 = await globalThis.crypto.subtle.digest("SHA-256", new Uint8Array(bytes).buffer);
+ return [...new Uint8Array(digest2)].map((value) => value.toString(16).padStart(2, "0")).join("");
+}
+async function inspectGlbIntegration(bytes, opts = {}) {
+ const doc = await engineIO().readBinary(bytes);
+ const root = doc.getRoot();
+ const explicitDefault = root.getDefaultScene();
+ const scene = explicitDefault ?? root.listScenes()[0];
+ if (!scene)
+ return;
+ const { min, max } = getBounds(scene);
+ const finiteBounds = min.every(Number.isFinite) && max.every(Number.isFinite);
+ if (!finiteBounds)
+ return;
+ const metrics = collectGlbMetrics(doc);
+ const validation = opts.validation ?? await validateFinalGlbBytes(bytes);
+ const scenes = root.listScenes();
+ const minTuple = [min[0], min[1], min[2]];
+ const maxTuple = [max[0], max[1], max[2]];
+ const minY = minTuple[1];
+ return {
+ schemaVersion: "kiln.integration-manifest.v1",
+ analyzerVersion: 1,
+ artifactSha256: await sha256Hex2(bytes),
+ units: "m",
+ axes: { forward: "+X", up: "+Y", right: "+Z" },
+ bounds: {
+ min: minTuple,
+ max: maxTuple,
+ size: [maxTuple[0] - minTuple[0], maxTuple[1] - minTuple[1], maxTuple[2] - minTuple[2]],
+ center: [
+ (minTuple[0] + maxTuple[0]) / 2,
+ (minTuple[1] + maxTuple[1]) / 2,
+ (minTuple[2] + maxTuple[2]) / 2
+ ]
},
- {
- name: "pbrMaterial",
- signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, aoMap?, alphaMode?, alphaCutoff?, doubleSided? })",
- returns: "THREE.MeshStandardMaterial",
- category: "material",
- description: "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. Supports OPAQUE/MASK/BLEND and double-sided output.",
- example: `const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });
-const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });`
+ pivot: { convention: "author-origin", position: [0, 0, 0] },
+ ground: {
+ groundY: 0,
+ contactTolerance: GROUND_CONTACT_TOLERANCE,
+ minY,
+ offsetToGround: -minY,
+ grounded: Math.abs(minY) <= GROUND_CONTACT_TOLERANCE
},
- {
- name: "foliageMaterial",
- signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",
- returns: "THREE.MeshStandardMaterial",
- category: "material",
- description: "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",
- example: "const mat = await materialRecipe('kiln.material.leaf.v1');"
+ defaultScene: { index: scenes.indexOf(scene), name: scene.getName() },
+ ...opts.requestedRole ? { requestedRole: opts.requestedRole } : {},
+ ...opts.assessedRole ? { assessedRole: opts.assessedRole } : {},
+ renderMetrics: {
+ triangles: metrics.triangles,
+ drawCalls: metrics.drawCalls,
+ uniqueGeometries: metrics.uniqueGeometries,
+ uniqueMaterials: metrics.uniqueMaterials,
+ textureCount: metrics.textureCount,
+ transparentMaterials: metrics.transparentMaterials,
+ skinned: metrics.skinned
},
- {
- name: "countTriangles",
- signature: "countTriangles(root: Object3D)",
- returns: "number",
- category: "utility",
- description: "Sums triangle count across every mesh in the subtree.",
- example: "meta.tris = countTriangles(root);"
+ structuralQa: {
+ hasDefaultScene: explicitDefault !== null,
+ finiteBounds,
+ validatorErrors: validation.issues.numErrors,
+ validatorWarnings: validation.issues.numWarnings
},
- {
- name: "countMaterials",
- signature: "countMaterials(root: Object3D)",
- returns: "number",
- category: "utility",
- description: "Unique material count (by reference) across the subtree.",
- example: "const mats = countMaterials(root);"
+ visualQa: "not_assessed"
+ };
+}
+async function executeKilnCode(code, options = {}) {
+ if (!code || typeof code !== "string") {
+ throw new Error("executeKilnCode: code must be a non-empty string");
+ }
+ const normalized = code.replace(/\r\n/g, `
+`);
+ assertGeneratedSourceSafe(normalized);
+ try {
+ const primitiveUsage = {};
+ const globals = buildSandboxGlobals(primitiveUsage, {
+ textureResolver: options.textureResolver ?? DEFAULT_TEXTURE_RESOLVER
+ });
+ const globalNames = Object.keys(globals);
+ const globalValues = Object.values(globals);
+ const fn = new Function(...globalNames, `${normalized}
+return { meta: typeof meta !== 'undefined' ? meta : {}, build, animate: typeof animate !== 'undefined' ? animate : null };`);
+ const { meta, build, animate } = fn(...globalValues);
+ if (typeof build !== "function") {
+ throw new Error("executeKilnCode: generated code did not define `build`");
+ }
+ const root = await build();
+ if (!root?.isObject3D) {
+ throw new Error("executeKilnCode: build() did not return a THREE.Object3D");
+ }
+ const clips = animate ? await animate(root) ?? [] : [];
+ return { meta: meta ?? {}, root, clips, primitiveUsage };
+ } catch (error) {
+ rethrowAuthoringError(error);
+ }
+}
+function bridgeMaterial(doc, threeMat, cache, textureCache) {
+ const cached = cache.get(threeMat);
+ if (cached)
+ return cached;
+ const mat = doc.createMaterial(threeMat.name || undefined);
+ const matFlags = threeMat;
+ if (matFlags.isMeshStandardMaterial) {
+ const stdMat = threeMat;
+ mat.setBaseColorFactor([stdMat.color.r, stdMat.color.g, stdMat.color.b, stdMat.opacity]);
+ mat.setRoughnessFactor(stdMat.roughness);
+ mat.setMetallicFactor(stdMat.metalness);
+ if (stdMat.emissive) {
+ mat.setEmissiveFactor([stdMat.emissive.r, stdMat.emissive.g, stdMat.emissive.b]);
+ }
+ if (stdMat.alphaTest > 0) {
+ mat.setAlphaMode("MASK");
+ mat.setAlphaCutoff(stdMat.alphaTest);
+ } else if (stdMat.transparent) {
+ mat.setAlphaMode("BLEND");
+ }
+ if (stdMat.side === THREE34.DoubleSide) {
+ mat.setDoubleSided(true);
+ }
+ if (stdMat.map) {
+ const t = bridgeTexture(doc, stdMat.map, textureCache);
+ if (t)
+ mat.setBaseColorTexture(t);
+ }
+ if (stdMat.normalMap) {
+ const t = bridgeTexture(doc, stdMat.normalMap, textureCache);
+ if (t)
+ mat.setNormalTexture(t);
+ }
+ if (stdMat.roughnessMap && stdMat.metalnessMap && stdMat.roughnessMap !== stdMat.metalnessMap) {
+ throw new TypeError(`Material ${JSON.stringify(threeMat.name || "(unnamed)")} uses separate roughness/metalness textures. Pack G=roughness/B=metalness before export.`);
+ }
+ const mrSource = stdMat.roughnessMap ?? stdMat.metalnessMap;
+ if (mrSource) {
+ const t = bridgeTexture(doc, mrSource, textureCache);
+ if (t)
+ mat.setMetallicRoughnessTexture(t);
+ }
+ if (stdMat.emissiveMap) {
+ const t = bridgeTexture(doc, stdMat.emissiveMap, textureCache);
+ if (t)
+ mat.setEmissiveTexture(t);
+ }
+ if (stdMat.aoMap) {
+ const t = bridgeTexture(doc, stdMat.aoMap, textureCache);
+ if (t)
+ mat.setOcclusionTexture(t);
+ mat.setOcclusionStrength(stdMat.aoMapIntensity ?? 1);
+ }
+ } else if (matFlags.isMeshLambertMaterial) {
+ const lambMat = threeMat;
+ mat.setBaseColorFactor([lambMat.color.r, lambMat.color.g, lambMat.color.b, lambMat.opacity]);
+ mat.setRoughnessFactor(1);
+ mat.setMetallicFactor(0);
+ if (lambMat.emissive) {
+ mat.setEmissiveFactor([lambMat.emissive.r, lambMat.emissive.g, lambMat.emissive.b]);
+ }
+ } else if (matFlags.isMeshBasicMaterial) {
+ const basicMat = threeMat;
+ mat.setBaseColorFactor([
+ basicMat.color.r,
+ basicMat.color.g,
+ basicMat.color.b,
+ basicMat.opacity
+ ]);
+ mat.setRoughnessFactor(1);
+ mat.setMetallicFactor(0);
+ } else if (matFlags.isSpriteMaterial) {
+ const spriteMat = threeMat;
+ mat.setBaseColorFactor([
+ spriteMat.color.r,
+ spriteMat.color.g,
+ spriteMat.color.b,
+ spriteMat.opacity
+ ]);
+ mat.setRoughnessFactor(1);
+ mat.setMetallicFactor(0);
+ }
+ const common = threeMat;
+ if ((common.alphaTest ?? 0) > 0) {
+ mat.setAlphaMode("MASK");
+ mat.setAlphaCutoff(common.alphaTest ?? 0.5);
+ } else if (common.transparent || (common.opacity ?? 1) < 1) {
+ mat.setAlphaMode("BLEND");
+ }
+ if (threeMat.side === THREE34.DoubleSide)
+ mat.setDoubleSided(true);
+ if (common.map && !mat.getBaseColorTexture()) {
+ const texture = bridgeTexture(doc, common.map, textureCache);
+ if (texture)
+ mat.setBaseColorTexture(texture);
+ }
+ cache.set(threeMat, mat);
+ return mat;
+}
+function bridgeTexture(doc, threeTex, cache) {
+ const cached = cache.get(threeTex);
+ if (cached)
+ return cached;
+ const encoded = threeTex.userData["encoded"];
+ if (!encoded)
+ return null;
+ const t = doc.createTexture(threeTex.name || "texture");
+ t.setMimeType(encoded.mime);
+ t.setImage(encoded.bytes);
+ cache.set(threeTex, t);
+ return t;
+}
+function bridgeGeometry(doc, buf, geometry2, material, meshName) {
+ if (!geometry2.getAttribute("normal")) {
+ geometry2.computeVertexNormals();
+ }
+ const prim = doc.createPrimitive().setMaterial(Array.isArray(material) ? material[0] : material);
+ const posAttr = geometry2.getAttribute("position");
+ if (posAttr) {
+ prim.setAttribute("POSITION", doc.createAccessor(meshName + "_pos").setArray(geometryAttributeValues(posAttr)).setType(TYPE_VEC3).setBuffer(buf));
+ }
+ const normAttr = geometry2.getAttribute("normal");
+ if (normAttr) {
+ prim.setAttribute("NORMAL", doc.createAccessor(meshName + "_norm").setArray(geometryAttributeValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));
+ }
+ const uvAttr = geometry2.getAttribute("uv");
+ if (uvAttr) {
+ prim.setAttribute("TEXCOORD_0", doc.createAccessor(meshName + "_uv").setArray(geometryAttributeValues(uvAttr)).setType(TYPE_VEC2).setBuffer(buf));
+ }
+ const tangentAttr = geometry2.getAttribute("tangent");
+ if (tangentAttr?.itemSize === 4) {
+ prim.setAttribute("TANGENT", doc.createAccessor(meshName + "_tangent").setArray(geometryAttributeValues(tangentAttr)).setType(TYPE_VEC4).setBuffer(buf));
+ }
+ const indexAttr = geometry2.getIndex();
+ if (indexAttr) {
+ const IndexArray = posAttr && posAttr.count > 65535 ? Uint32Array : Uint16Array;
+ prim.setIndices(doc.createAccessor(meshName + "_idx").setArray(new IndexArray(indexAttr.array)).setType(TYPE_SCALAR).setBuffer(buf));
+ }
+ const mesh = doc.createMesh(meshName);
+ if (!Array.isArray(material))
+ return mesh.addPrimitive(prim);
+ const indexValues = indexAttr ? Array.from(indexAttr.array) : Array.from({ length: posAttr.count }, (_, i) => i);
+ const groups = [...geometry2.groups].sort((a, b) => a.start - b.start);
+ let covered = 0;
+ for (const group of groups) {
+ if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > indexValues.length || !material[group.materialIndex ?? 0]) {
+ throw new TypeError(`${meshName}: material groups must cover every triangle exactly once with valid material indices.`);
+ }
+ const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]);
+ for (const semantic3 of prim.listSemantics())
+ part.setAttribute(semantic3, prim.getAttribute(semantic3));
+ const IndexArray = posAttr.count > 65535 ? Uint32Array : Uint16Array;
+ part.setIndices(doc.createAccessor(meshName + "_group_indices").setArray(new IndexArray(indexValues.slice(group.start, group.start + group.count))).setType(TYPE_SCALAR).setBuffer(buf));
+ mesh.addPrimitive(part);
+ covered += group.count;
+ }
+ if (covered !== indexValues.length)
+ throw new TypeError(`${meshName}: material groups do not cover every triangle.`);
+ prim.dispose();
+ return mesh;
+}
+function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache) {
+ const gtNode = doc.createNode(threeObj.name || undefined);
+ const semanticValue = threeObj.userData[KILN_SEMANTIC_EXTRAS_KEY];
+ let semanticForExport = semanticValue;
+ if (threeObj.isSprite) {
+ if (semanticValue === undefined) {
+ semanticForExport = createSemanticMetadataV1({
+ roles: ["vfx.facing.camera-spherical", "vfx.effect.surface.card"]
+ });
+ } else {
+ const existing = validateSemanticMetadataV1(semanticValue);
+ if (existing.valid && existing.value) {
+ semanticForExport = {
+ ...cloneSemanticMetadataV1(existing.value),
+ roles: [
+ ...existing.value.roles.filter((role) => !role.startsWith("vfx.facing.")),
+ "vfx.facing.camera-spherical",
+ ...existing.value.roles.some((role) => role.startsWith("vfx.effect.surface")) ? [] : ["vfx.effect.surface.card"]
+ ]
+ };
+ }
+ }
+ }
+ if (semanticForExport !== undefined) {
+ const semantic3 = validateSemanticMetadataV1(semanticForExport);
+ if (!semantic3.valid || !semantic3.value) {
+ const detail = semantic3.issues.map((issue) => `${issue.path || "<root>"}: ${issue.message}`).join("; ");
+ throw new TypeError(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY} on node ${threeObj.name || "<unnamed>"}: ${detail}`);
+ }
+ gtNode.setExtras({
+ [KILN_SEMANTIC_EXTRAS_KEY]: cloneSemanticMetadataV1(semantic3.value)
+ });
+ }
+ gtNode.setTranslation([threeObj.position.x, threeObj.position.y, threeObj.position.z]);
+ gtNode.setRotation([
+ threeObj.quaternion.x,
+ threeObj.quaternion.y,
+ threeObj.quaternion.z,
+ threeObj.quaternion.w
+ ]);
+ gtNode.setScale([threeObj.scale.x, threeObj.scale.y, threeObj.scale.z]);
+ if (threeObj.isMesh) {
+ const threeMesh = threeObj;
+ const threeMats = Array.isArray(threeMesh.material) ? threeMesh.material : [threeMesh.material];
+ const gtMats = threeMats.map((material) => bridgeMaterial(doc, material, matCache, texCache));
+ const gtMat = Array.isArray(threeMesh.material) ? gtMats : gtMats[0];
+ const cacheKey = `${threeMesh.geometry.uuid}__${threeMats.map((material) => material.uuid).join("_")}`;
+ let gtMesh = meshCache.get(cacheKey);
+ if (!gtMesh) {
+ gtMesh = bridgeGeometry(doc, buf, threeMesh.geometry, gtMat, threeMesh.name || "mesh");
+ meshCache.set(cacheKey, gtMesh);
+ }
+ gtNode.setMesh(gtMesh);
+ } else if (threeObj.isSprite) {
+ const sprite = threeObj;
+ const threeMat = sprite.material;
+ const gtMat = bridgeMaterial(doc, threeMat, matCache, texCache);
+ const centerX = sprite.center?.x ?? 0.5;
+ const centerY = sprite.center?.y ?? 0.5;
+ const rotation = sprite.material.rotation ?? 0;
+ const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;
+ let gtMesh = meshCache.get(cacheKey);
+ if (!gtMesh) {
+ const geometry2 = new THREE34.PlaneGeometry(1, 1);
+ if (centerX !== 0.5 || centerY !== 0.5) {
+ geometry2.translate(0.5 - centerX, 0.5 - centerY, 0);
+ }
+ if (rotation !== 0)
+ geometry2.rotateZ(rotation);
+ gtMesh = bridgeGeometry(doc, buf, geometry2, gtMat, sprite.name || "sprite-quad");
+ meshCache.set(cacheKey, gtMesh);
+ }
+ gtNode.setMesh(gtMesh);
+ }
+ if (threeObj.name) {
+ nodeMap.set(threeObj.name, gtNode);
+ }
+ for (const child of threeObj.children) {
+ const childNode = bridgeNode(doc, buf, child, matCache, nodeMap, meshCache, texCache);
+ gtNode.addChild(childNode);
+ }
+ return gtNode;
+}
+function bridgeAnimations(doc, buf, clips, nodeMap, warnings) {
+ for (const clip of clips) {
+ const anim = doc.createAnimation(clip.name);
+ for (const track of clip.tracks) {
+ const dotIdx = track.name.lastIndexOf(".");
+ const nodeName2 = track.name.substring(0, dotIdx);
+ const property = track.name.substring(dotIdx + 1);
+ const targetNode = nodeMap.get(nodeName2);
+ if (!targetNode) {
+ warnings.push(`Animation target "${nodeName2}" not found - skipped`);
+ continue;
+ }
+ let targetPath;
+ let valueType;
+ if (property === "position") {
+ targetPath = "translation";
+ valueType = TYPE_VEC3;
+ } else if (property === "quaternion") {
+ targetPath = "rotation";
+ valueType = TYPE_VEC4;
+ } else if (property === "scale") {
+ targetPath = "scale";
+ valueType = TYPE_VEC3;
+ } else {
+ warnings.push(`Unsupported animation property "${property}" on "${nodeName2}" - skipped`);
+ continue;
+ }
+ const inputAcc = doc.createAccessor(clip.name + "_" + nodeName2 + "_input").setArray(new Float32Array(track.times)).setType(TYPE_SCALAR).setBuffer(buf);
+ const outputAcc = doc.createAccessor(clip.name + "_" + nodeName2 + "_output").setArray(new Float32Array(track.values)).setType(valueType).setBuffer(buf);
+ const sampler = doc.createAnimationSampler().setInput(inputAcc).setOutput(outputAcc).setInterpolation("LINEAR");
+ const channel = doc.createAnimationChannel().setTargetNode(targetNode).setTargetPath(targetPath).setSampler(sampler);
+ anim.addSampler(sampler);
+ anim.addChannel(channel);
+ }
+ if (anim.listChannels().length === 0)
+ anim.dispose();
+ }
+}
+function reviewClipExtras(clips) {
+ if (clips.length > REVIEW_CLIP_LIMITS2.clips) {
+ throw new Error(`Animation review clip limit exceeded (${REVIEW_CLIP_LIMITS2.clips}).`);
+ }
+ let trackCount = 0;
+ return {
+ version: 1,
+ clips: clips.map((clip) => ({
+ name: clip.name,
+ duration: clip.duration,
+ tracks: clip.tracks.map((track) => {
+ trackCount++;
+ if (trackCount > REVIEW_CLIP_LIMITS2.tracks) {
+ throw new Error(`Animation review track limit exceeded (${REVIEW_CLIP_LIMITS2.tracks}).`);
+ }
+ if (track.times.length > REVIEW_CLIP_LIMITS2.samplesPerTrack || track.values.length > REVIEW_CLIP_LIMITS2.valuesPerTrack) {
+ throw new Error("Animation review sample limit exceeded.");
+ }
+ const times = Array.from(track.times);
+ const values = Array.from(track.values);
+ if (!times.every(Number.isFinite) || !values.every(Number.isFinite)) {
+ throw new Error("Animation review tracks must contain only finite values.");
+ }
+ return { name: track.name, times, values };
+ })
+ }))
+ };
+}
+function finalTextureForSlot(material, slot) {
+ switch (slot) {
+ case "map":
+ return material.getBaseColorTexture();
+ case "normalMap":
+ return material.getNormalTexture();
+ case "roughnessMap":
+ case "metalnessMap":
+ return material.getMetallicRoughnessTexture();
+ case "emissiveMap":
+ return material.getEmissiveTexture();
+ case "aoMap":
+ return material.getOcclusionTexture();
+ default:
+ return null;
+ }
+}
+async function bindBakedTextureProvenanceToFinalGlb(baked, finalGlb) {
+ if (baked.length === 0)
+ return [];
+ const doc = await engineIO().readBinary(finalGlb);
+ const root = doc.getRoot();
+ const byMaterialName = new Map;
+ for (const material of root.listMaterials()) {
+ const name = material.getName() || "(unnamed material)";
+ const list = byMaterialName.get(name) ?? [];
+ list.push(material);
+ byMaterialName.set(name, list);
+ }
+ const nodesByName = new Map;
+ for (const node of root.listNodes()) {
+ const list = nodesByName.get(node.getName()) ?? [];
+ list.push(node);
+ nodesByName.set(node.getName(), list);
+ }
+ const artifactGlbSha256 = `sha256:${await sha256Hex2(finalGlb)}`;
+ return baked.flatMap((entry) => {
+ const resolved2 = new Set;
+ for (const binding of entry.bindings) {
+ const nodeMaterials = (nodesByName.get(binding.node) ?? []).flatMap((node) => node.getMesh()?.listPrimitives().flatMap((primitive) => {
+ const material = primitive.getMaterial();
+ return material ? [material] : [];
+ }) ?? []);
+ const materials = nodeMaterials.filter((material) => (material.getName() || "(unnamed material)") === binding.material);
+ const candidates = materials.length ? materials : byMaterialName.get(binding.material) ?? [];
+ for (const material of candidates) {
+ const texture2 = finalTextureForSlot(material, binding.slot);
+ if (texture2)
+ resolved2.add(texture2);
+ }
+ }
+ if (resolved2.size === 0 && entry.texture !== "(unnamed texture)") {
+ for (const texture2 of root.listTextures()) {
+ if (texture2.getName() === entry.texture)
+ resolved2.add(texture2);
+ }
+ }
+ if (resolved2.size !== 1)
+ return [];
+ const texture = [...resolved2][0];
+ const image = texture.getImage();
+ const mime = texture.getMimeType();
+ if (!image || !mime)
+ return [];
+ return [
+ {
+ ...entry,
+ artifactGlbSha256,
+ finalMime: mime,
+ finalImageSha256: `sha256:${createHash5("sha256").update(image).digest("hex")}`
+ }
+ ];
+ });
+}
+function resolveOptimize(opt) {
+ if (opt)
+ return opt;
+ const env = process.env["KILN_BAKE_OPTIMIZE"];
+ return env === "auto" || env === "palette" || env === "full" ? env : "off";
+}
+function resolveInstance(opt) {
+ if (opt)
+ return opt;
+ const env = process.env["KILN_BAKE_INSTANCE"];
+ return env === "off" || env === "auto" || env === "on" ? env : "auto";
+}
+function hasJointPivots(doc) {
+ return doc.getRoot().listNodes().some((n) => /^joint[_-]/i.test(n.getName()));
+}
+async function applyGpuInstancing(doc, mode, role) {
+ if (mode === "off")
+ return;
+ if (mode === "auto" && role !== "fill")
+ return;
+ const root = doc.getRoot();
+ if (root.listAnimations().length > 0 || root.listSkins().length > 0)
+ return;
+ if (hasJointPivots(doc))
+ return;
+ const before = collectGlbMetrics(doc);
+ await doc.transform(instance({ min: INSTANCE_MIN }));
+ let batches = 0;
+ let instances = 0;
+ for (const node of root.listNodes()) {
+ const ext = node.getExtension("EXT_mesh_gpu_instancing");
+ if (!ext)
+ continue;
+ batches += 1;
+ instances += ext.getAttribute?.("TRANSLATION")?.getCount() ?? ext.getAttribute?.("ROTATION")?.getCount() ?? ext.getAttribute?.("SCALE")?.getCount() ?? 0;
+ }
+ if (batches === 0)
+ return;
+ const after = collectGlbMetrics(doc);
+ return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };
+}
+async function consolidateMaterials(doc, mode) {
+ const before = collectGlbMetrics(doc);
+ const root = doc.getRoot();
+ const animatedOrSkinned = root.listAnimations().length > 0 || root.listSkins().length > 0;
+ const semanticGraph = root.listNodes().some((node) => node.getExtras()[KILN_SEMANTIC_EXTRAS_KEY] !== undefined);
+ const effective = mode === "full" && (animatedOrSkinned || semanticGraph) ? "palette" : mode;
+ const steps = [palette({ min: PALETTE_MIN })];
+ if (effective === "full") {
+ steps.push(flatten(), join2({ keepNamed: true }));
+ }
+ steps.push(weld(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));
+ await doc.transform(...steps);
+ const after = collectGlbMetrics(doc);
+ return {
+ mode: effective,
+ materialsBefore: before.uniqueMaterials,
+ materialsAfter: after.uniqueMaterials,
+ drawsBefore: before.drawCalls,
+ drawsAfter: after.drawCalls
+ };
+}
+async function renderSceneToGLB(root, opts = {}) {
+ const clips = opts.clips ?? [];
+ if (opts.geometryPolicy !== undefined && !["warn", "strict"].includes(opts.geometryPolicy))
+ throw new Error("geometryPolicy must be warn or strict");
+ const warnings = inspectGeometryExport(root, opts.geometryPolicy);
+ const tris = countTriangles(root);
+ const intent = opts.intent ?? createAssetIntentV1({
+ category: isAssetCategory(opts.category) ? opts.category : "prop"
+ });
+ const trustedCategory = intent.category;
+ const materialRecipeApplications = collectMaterialRecipeApplications(root);
+ const materialResourceProvenance = collectMaterialResourceProvenance(root);
+ for (const w of inspectGeneratedAnimation(root, clips))
+ warnings.push(w);
+ for (const w of inspectSceneStructure(root, { category: trustedCategory }))
+ warnings.push(w);
+ const bakedTextures = await bakeSceneTextures(root, warnings);
+ ensureNormalMapTangents(root, warnings);
+ let partPenetration;
+ try {
+ partPenetration = await analyzePartPenetration(root);
+ } catch (err) {
+ warnings.push(`self-intersection analysis failed: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ const sceneQaReport = runDeterministicSceneQa({
+ intent,
+ scene: root,
+ clips,
+ ...partPenetration ? { derivedEvidence: { source: "engine-scene-analysis", partPenetration } } : {}
+ }, qaPolicyFromEnv());
+ const qaBlocks = qaBlockingEnabled() && opts.derivative !== true;
+ const qaSuppressedBy = opts.derivative === true ? "derivative re-serialization" : "KILN_QA_MODE";
+ if (sceneQaReport.disposition === "block") {
+ const blocked = new AssetQaBlockedError(sceneQaReport, "scene");
+ if (qaBlocks)
+ throw blocked;
+ warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);
+ }
+ const doc = new Document;
+ const buf = doc.createBuffer();
+ const matCache = new Map;
+ const meshCache = new Map;
+ const texCache = new Map;
+ const nodeMap = new Map;
+ const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
+ const gltfScene = doc.createScene(opts.sceneName ?? "Scene").addChild(rootNode);
+ doc.getRoot().setDefaultScene(gltfScene);
+ if (clips.length > 0) {
+ gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: reviewClipExtras(clips) });
+ bridgeAnimations(doc, buf, clips, nodeMap, warnings);
+ }
+ if (opts.dedup !== false) {
+ try {
+ await doc.transform(dedup());
+ } catch (err) {
+ warnings.push(`dedup transform failed: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+ let instancing;
+ try {
+ instancing = await applyGpuInstancing(doc, resolveInstance(opts.instance), opts.role);
+ } catch (err) {
+ warnings.push(`instance transform failed: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ const optimizeMode = resolveOptimize(opts.optimize);
+ let effectiveOptimize = optimizeMode === "auto" ? "off" : optimizeMode;
+ if (optimizeMode === "auto" && collectGlbMetrics(doc, tris).uniqueMaterials >= PALETTE_MIN) {
+ effectiveOptimize = "palette";
+ }
+ let optimize;
+ if (effectiveOptimize !== "off") {
+ try {
+ optimize = await consolidateMaterials(doc, effectiveOptimize);
+ } catch (err) {
+ warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+ let instanceability;
+ let metricsError;
+ try {
+ const metrics = collectGlbMetrics(doc, optimize || instancing ? undefined : tris);
+ instanceability = gradeInstanceability(metrics, { category: trustedCategory });
+ } catch (err) {
+ metricsError = err instanceof Error ? err.message : String(err);
+ }
+ let materialMetrics;
+ let materialBudgetWarnings = [];
+ try {
+ materialMetrics = collectMaterialMetricsV1(doc);
+ const tier = /(?:^|\.)hero(?:\.|$)/i.test(intent.qaProfile) ? "hero" : /(?:^|\.)background(?:\.|$)/i.test(intent.qaProfile) ? "background" : "standard";
+ materialBudgetWarnings = evaluateMaterialBudgetV1(materialMetrics, {
+ profile: materialBudgetProfileForQaProfile(intent.qaProfile),
+ tier
+ });
+ } catch (error) {
+ warnings.push(`material metrics failed: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ const io = engineIO();
+ ensureDefaultScene(doc);
+ const bytes = await io.writeBinary(doc);
+ const artifactGlbSha256 = `sha256:${await sha256Hex2(bytes)}`;
+ const boundBakedTextures = bakedTextures.map((entry) => ({
+ ...entry,
+ artifactGlbSha256
+ }));
+ const gltfValidation = await validateFinalGlbBytes(bytes);
+ const finalGltfReport = appendFinalGltfQa(intent, sceneQaReport, gltfValidation);
+ const runtimeQaReport = appendRuntimeCostQa(intent, finalGltfReport, instanceability, metricsError);
+ const materialQaReport = materialMetrics ? appendMaterialMetricsQa(intent, runtimeQaReport, materialMetrics, materialBudgetWarnings) : runtimeQaReport;
+ const qaReport = await appendFinalVfxGlbQa(intent, materialQaReport, bytes);
+ if (qaReport.disposition === "block") {
+ const blocked = new AssetQaBlockedError(qaReport, "final-glb", gltfValidation);
+ if (qaBlocks)
+ throw blocked;
+ warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);
+ }
+ for (const issue of gltfValidation.issues.messages) {
+ if (issue.severity !== 1)
+ continue;
+ warnings.push(`glTF ${issue.code}${issue.pointer ? ` at ${issue.pointer}` : ""}: ${issue.message}`);
+ }
+ const integrationManifest = await inspectGlbIntegration(bytes, {
+ ...opts.role ? { requestedRole: opts.role } : {},
+ validation: gltfValidation
+ });
+ if (!integrationManifest)
+ throw new Error("renderSceneToGLB: final GLB has no measurable scene");
+ let diagnosticViews;
+ if (intent.category === "character" && intent.character) {
+ try {
+ const findings = Object.values(qaReport.dimensions).flatMap((dimension) => dimension.findings);
+ diagnosticViews = await captureCharacterDiagnosticViews(root, clips, intent.character, findings);
+ } catch (error) {
+ warnings.push(`character diagnostic capture failed: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ } else if (intent.category === "vehicle" && intent.vehicle) {
+ try {
+ diagnosticViews = captureVehicleDiagnosticViews(root, intent);
+ } catch (error) {
+ warnings.push(`vehicle diagnostic capture failed: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+ return {
+ bytes,
+ artifactGlbSha256,
+ tris,
+ warnings,
+ gltfValidation,
+ qaReport,
+ instanceability,
+ metricsError,
+ ...optimize ? { optimize } : {},
+ ...instancing ? { instancing } : {},
+ ...diagnosticViews ? { diagnosticViews } : {},
+ ...materialMetrics ? { materialMetrics } : {},
+ ...materialRecipeApplications.length ? { materialRecipeApplications } : {},
+ ...materialResourceProvenance.length ? { materialResourceProvenance } : {},
+ ...boundBakedTextures.length ? { bakedTextures: boundBakedTextures } : {},
+ integrationManifest
+ };
+}
+async function renderGLBInProcess(code, opts = {}) {
+ if (opts.geometryPolicy !== undefined && !["warn", "strict"].includes(opts.geometryPolicy))
+ throw new Error("geometryPolicy must be warn or strict");
+ const { meta, root, clips, primitiveUsage } = await executeKilnCode(code, {
+ textureResolver: opts.textureResolver ?? DEFAULT_TEXTURE_RESOLVER
+ });
+ const requestedCategory = opts.intent?.category ?? opts.category;
+ const scene = await renderSceneToGLB(root, {
+ sceneName: meta.name || "Scene",
+ geometryPolicy: opts.geometryPolicy,
+ clips,
+ ...requestedCategory ? { category: requestedCategory } : {},
+ ...opts.intent ? { intent: opts.intent } : {},
+ role: meta.role,
+ ...opts.optimize ? { optimize: opts.optimize } : {},
+ ...opts.instance ? { instance: opts.instance } : {}
+ });
+ const { category: modelCategory, ...modelMeta } = meta;
+ return {
+ glb: Buffer.from(scene.bytes),
+ artifactGlbSha256: scene.artifactGlbSha256,
+ tris: scene.tris,
+ meta: {
+ ...modelMeta,
+ ...modelCategory !== undefined ? { modelCategory } : {},
+ ...requestedCategory ? { category: requestedCategory } : {},
+ tris: scene.tris,
+ primitiveUsage,
+ ...scene.instanceability ? { instanceability: scene.instanceability, tier: scene.instanceability.grade } : {},
+ ...scene.metricsError ? { metricsError: scene.metricsError } : {},
+ ...scene.optimize ? { optimize: scene.optimize } : {},
+ ...scene.instancing ? { instancing: scene.instancing } : {},
+ gltfValidation: scene.gltfValidation,
+ qaReport: scene.qaReport
},
- {
- name: "getJointNames",
- signature: "getJointNames(root: Object3D)",
- returns: "string[]",
- category: "utility",
- description: "All node names beginning with `Joint_`. Use to sanity-check animation targets.",
- example: "const joints = getJointNames(root);"
+ warnings: scene.warnings,
+ ...scene.diagnosticViews ? { diagnosticViews: scene.diagnosticViews } : {},
+ ...scene.materialMetrics ? { materialMetrics: scene.materialMetrics } : {},
+ ...scene.materialRecipeApplications ? { materialRecipeApplications: scene.materialRecipeApplications } : {},
+ ...scene.materialResourceProvenance ? { materialResourceProvenance: scene.materialResourceProvenance } : {},
+ ...scene.bakedTextures ? { bakedTextures: scene.bakedTextures } : {},
+ integrationManifest: scene.integrationManifest
+ };
+}
+function resolveEvaluatorMode(env = process.env) {
+ const value = env["KILN_EVALUATOR_MODE"];
+ if (value === undefined || value === "" || value === "in-process")
+ return "in-process";
+ if (value === "subprocess")
+ return "subprocess";
+ if (value === "isolated")
+ return "isolated";
+ throw new Error("Invalid KILN_EVALUATOR_MODE.");
+}
+async function renderGLB(code, opts = {}) {
+ const mode = resolveEvaluatorMode();
+ if (mode === "in-process")
+ return renderGLBInProcess(code, opts);
+ if (mode === "subprocess") {
+ const { renderGLBViaSubprocess: renderGLBViaSubprocess2 } = await Promise.resolve().then(() => (init_subprocess(), exports_subprocess));
+ return renderGLBViaSubprocess2(code, opts);
+ }
+ const { renderGLBViaIsolatedEvaluator: renderGLBViaIsolatedEvaluator2 } = await Promise.resolve().then(() => (init_isolation(), exports_isolation));
+ return renderGLBViaIsolatedEvaluator2(code, opts);
+}
+async function gradeGlbBytes(bytes, opts = {}) {
+ try {
+ const doc = await engineIO().readBinary(bytes);
+ return gradeInstanceability(collectGlbMetrics(doc), opts);
+ } catch {
+ return;
+ }
+}
+async function optimizeGlbBytes(bytes, opts = {}) {
+ const requested = opts.mode ?? "palette";
+ try {
+ const io = engineIO();
+ const doc = await io.readBinary(bytes);
+ let instancing;
+ if (opts.instance && opts.instance !== "off") {
+ instancing = await applyGpuInstancing(doc, opts.instance, opts.role);
+ }
+ let summary;
+ let mode;
+ if (requested !== "off") {
+ if (requested === "auto") {
+ if (collectGlbMetrics(doc).uniqueMaterials >= PALETTE_MIN)
+ mode = "palette";
+ } else {
+ mode = requested;
+ }
+ }
+ if (mode)
+ summary = await consolidateMaterials(doc, mode);
+ if (!summary && !instancing)
+ return;
+ ensureDefaultScene(doc);
+ const outBytes = await io.writeBinary(doc);
+ const gltfValidation = await assertFinalGlbValid(outBytes);
+ let report;
+ try {
+ report = gradeInstanceability(collectGlbMetrics(doc), { category: opts.category });
+ } catch {
+ report = undefined;
+ }
+ return {
+ bytes: outBytes,
+ gltfValidation,
+ ...report ? { report } : {},
+ ...summary ? { summary } : {},
+ ...instancing ? { instancing } : {}
+ };
+ } catch (error) {
+ if (error instanceof GltfValidationError)
+ throw error;
+ return;
+ }
+}
+async function packKitGlb(bytes, opts = {}) {
+ let doc;
+ try {
+ doc = await engineIO().readBinary(bytes);
+ } catch {
+ return;
+ }
+ const summary = await applyKitContract(doc, opts);
+ const changed = summary.ormPacked > 0 || summary.variantsAdded.length > 0 || summary.ktx2.applied;
+ if (!changed)
+ return;
+ ensureDefaultScene(doc);
+ const outBytes = await engineIO().writeBinary(doc);
+ const gltfValidation = await assertFinalGlbValid(outBytes);
+ return { bytes: outBytes, summary, gltfValidation };
+}
+async function snapGlbToPalette(bytes, slots, opts = {}) {
+ if (slots.length === 0)
+ return;
+ try {
+ const io = engineIO();
+ const doc = await io.readBinary(bytes);
+ const before = collectGlbMetrics(doc);
+ const idx = buildSlotIndex(slots);
+ let snapped = 0;
+ let skipped = 0;
+ for (const mat of doc.getRoot().listMaterials()) {
+ if (mat.getBaseColorTexture()) {
+ skipped++;
+ continue;
+ }
+ const base = mat.getBaseColorFactor();
+ const emissive = mat.getEmissiveFactor();
+ const transparent = mat.getAlphaMode() === "BLEND" || mat.getAlpha() < 0.98;
+ const slotI = chooseSlot(idx, {
+ baseLinear: [base[0], base[1], base[2]],
+ emissiveLinear: [emissive[0], emissive[1], emissive[2]],
+ transparent
+ });
+ if (slotI === undefined) {
+ skipped++;
+ continue;
+ }
+ const slot = slots[slotI];
+ const kind = slot.kind ?? "opaque";
+ const [lr, lg, lb] = hexToLinearRgb(slot.color);
+ const alpha = kind === "glass" ? slot.opacity ?? 0.4 : 1;
+ mat.setBaseColorFactor([lr, lg, lb, alpha]);
+ mat.setMetallicFactor(slot.metalness ?? 0);
+ mat.setRoughnessFactor(slot.roughness ?? (kind === "glass" ? 0.1 : 0.85));
+ if (kind === "glass")
+ mat.setAlphaMode("BLEND");
+ else if (mat.getAlphaMode() === "BLEND")
+ mat.setAlphaMode("OPAQUE");
+ mat.setEmissiveFactor(kind === "glow" ? [lr, lg, lb] : [0, 0, 0]);
+ snapped++;
+ }
+ await doc.transform(dedup());
+ await consolidateMaterials(doc, "palette");
+ const after = collectGlbMetrics(doc);
+ const summary = {
+ mode: "palette",
+ materialsBefore: before.uniqueMaterials,
+ materialsAfter: after.uniqueMaterials,
+ drawsBefore: before.drawCalls,
+ drawsAfter: after.drawCalls
+ };
+ ensureDefaultScene(doc);
+ const outBytes = await io.writeBinary(doc);
+ const gltfValidation = await assertFinalGlbValid(outBytes);
+ let report;
+ try {
+ report = gradeInstanceability(after, { category: opts.category });
+ } catch {
+ report = undefined;
+ }
+ return {
+ bytes: outBytes,
+ ...report ? { report } : {},
+ summary,
+ snapped,
+ skipped,
+ gltfValidation
+ };
+ } catch (error) {
+ if (error instanceof GltfValidationError)
+ throw error;
+ return;
+ }
+}
+function eulerDegToQuat(deg) {
+ const e = new THREE34.Euler(THREE34.MathUtils.degToRad(deg[0]), THREE34.MathUtils.degToRad(deg[1]), THREE34.MathUtils.degToRad(deg[2]), "XYZ");
+ const q = new THREE34.Quaternion().setFromEuler(e);
+ return [q.x, q.y, q.z, q.w];
+}
+async function composeSceneGLB(parts, opts = {}) {
+ const warnings = [];
+ const io = engineIO();
+ const master = new Document;
+ const masterScene = master.createScene(opts.sceneName ?? "Scene");
+ master.getRoot().setDefaultScene(masterScene);
+ let composed = 0;
+ for (let i = 0;i < parts.length; i++) {
+ const part = parts[i];
+ try {
+ const src = await io.readBinary(part.bytes);
+ const srcScene = src.getRoot().listScenes()[0];
+ const map = mergeDocuments(master, src);
+ const wrap = master.createNode(part.name ?? `part_${i}`).setTranslation([part.transform.pos[0], part.transform.pos[1], part.transform.pos[2]]).setRotation(eulerDegToQuat(part.transform.rotDeg)).setScale([part.transform.scale[0], part.transform.scale[1], part.transform.scale[2]]);
+ const mergedScene = srcScene ? map.get(srcScene) : undefined;
+ if (mergedScene) {
+ for (const child of mergedScene.listChildren())
+ wrap.addChild(child);
+ mergedScene.dispose();
+ }
+ masterScene.addChild(wrap);
+ composed++;
+ } catch (err) {
+ warnings.push(`part ${i} (${part.name ?? ""}) skipped: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+ if (composed === 0)
+ throw new Error("composeSceneGLB: no parts could be merged");
+ if (!opts.keepAnimations) {
+ for (const anim of master.getRoot().listAnimations())
+ anim.dispose();
+ }
+ try {
+ await master.transform(dedup());
+ } catch (err) {
+ warnings.push(`dedup failed: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ const optimizeMode = opts.optimize ?? "palette";
+ let effectiveOptimize = optimizeMode === "auto" ? "off" : optimizeMode;
+ if (optimizeMode === "auto" && collectGlbMetrics(master).uniqueMaterials >= PALETTE_MIN) {
+ effectiveOptimize = "palette";
+ }
+ if (effectiveOptimize !== "off") {
+ try {
+ await consolidateMaterials(master, effectiveOptimize);
+ } catch (err) {
+ warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+ const rootBuffers = master.getRoot().listBuffers();
+ if (rootBuffers.length > 1) {
+ const main = rootBuffers[0];
+ for (const acc of master.getRoot().listAccessors())
+ acc.setBuffer(main);
+ for (let i = 1;i < rootBuffers.length; i++)
+ rootBuffers[i].dispose();
+ }
+ const metrics = collectGlbMetrics(master);
+ ensureDefaultScene(master);
+ const bytes = await io.writeBinary(master);
+ const gltfValidation = await assertFinalGlbValid(bytes, "scene.glb");
+ for (const issue of gltfValidation.issues.messages) {
+ if (issue.severity !== 1)
+ continue;
+ warnings.push(`glTF ${issue.code}${issue.pointer ? ` at ${issue.pointer}` : ""}: ${issue.message}`);
+ }
+ return {
+ bytes,
+ tris: metrics.triangles,
+ draws: metrics.drawCalls,
+ materials: metrics.uniqueMaterials,
+ warnings,
+ gltfValidation
+ };
+}
+function inspectGeneratedAnimation(root, clips) {
+ const warnings = [];
+ if (clips.length === 0)
+ return warnings;
+ const nodeNames = new Set;
+ root.traverse((obj) => {
+ if (obj.name)
+ nodeNames.add(obj.name);
+ });
+ for (const clip of clips) {
+ for (const track of clip.tracks) {
+ const dotIdx = track.name.lastIndexOf(".");
+ if (dotIdx === -1) {
+ warnings.push(`Track "${track.name}" is missing a node.property separator`);
+ continue;
+ }
+ const nodeName2 = track.name.substring(0, dotIdx);
+ const property = track.name.substring(dotIdx + 1);
+ if (!nodeNames.has(nodeName2)) {
+ warnings.push(`Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName2}" — rename the pivot or fix the track`);
+ }
+ if (!["position", "quaternion", "scale"].includes(property)) {
+ warnings.push(`Animation track "${clip.name}:${track.name}" uses unsupported property "${property}"`);
+ }
+ }
+ }
+ return warnings;
+}
+function collectMeshStats(root) {
+ root.updateMatrixWorld(true);
+ const out = [];
+ root.traverse((obj) => {
+ if (!obj.isMesh)
+ return;
+ const meshObj = obj;
+ const geo = meshObj.geometry;
+ if (!geo)
+ return;
+ const idx = geo.getIndex();
+ const tri = idx ? idx.count / 3 : (geo.getAttribute("position")?.count ?? 0) / 3;
+ const box = new THREE34.Box3().setFromObject(obj);
+ if (!isFinite(box.min.x) || !isFinite(box.max.x)) {
+ return;
+ }
+ const center = new THREE34.Vector3;
+ const size = new THREE34.Vector3;
+ box.getCenter(center);
+ box.getSize(size);
+ out.push({
+ name: obj.name || "(unnamed)",
+ triCount: Math.floor(tri),
+ isPlaneGeo: geo.type === "PlaneGeometry",
+ center,
+ size,
+ box
+ });
+ });
+ return out;
+}
+function minimalGapVector(a, b) {
+ const v = new THREE34.Vector3;
+ for (const axis of ["x", "y", "z"]) {
+ if (a.min[axis] > b.max[axis])
+ v[axis] = b.max[axis] - a.min[axis];
+ else if (a.max[axis] < b.min[axis])
+ v[axis] = b.min[axis] - a.max[axis];
+ else
+ v[axis] = 0;
+ }
+ return v;
+}
+function inspectSceneStructure(root, opts = {}) {
+ const warnings = [];
+ const meshes = collectMeshStats(root);
+ if (meshes.length === 0)
+ return warnings;
+ const cat = opts.category?.toLowerCase();
+ if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {
+ const all = new THREE34.Box3;
+ for (const m of meshes)
+ all.union(m.box);
+ const size = new THREE34.Vector3;
+ all.getSize(size);
+ if (cat === "aircraft") {
+ if (size.y > size.x * 1.2) {
+ warnings.push(`Orientation: this aircraft is ${size.y.toFixed(2)} tall but only ${size.x.toFixed(2)} long along +X (the nose axis). Kiln aircraft fly nose-first along +X — it may be built vertically or sideways.`);
+ }
+ } else if (size.z > size.x * 1.3) {
+ warnings.push(`Orientation: this ${cat} spans ${size.z.toFixed(2)} along Z but only ${size.x.toFixed(2)} along +X. Kiln ${cat}s face +X (forward/muzzle/bow) — it looks built sideways; rebuild the long axis along X.`);
+ }
+ }
+ const STRAY_CENTROID_TOL = 0.02;
+ const FLOATING_EXPAND = 0.02;
+ const DECAL_EXTENT_MAX = 0.5;
+ for (const m of meshes) {
+ if (!m.isPlaneGeo)
+ continue;
+ if (m.triCount > 2)
+ continue;
+ if (m.size.length() > DECAL_EXTENT_MAX)
+ continue;
+ if (m.center.length() < STRAY_CENTROID_TOL) {
+ warnings.push(`Stray plane "${m.name}" at world origin (centroid ≈ [0,0,0]). Replace planeGeo with decalBox and position on a host surface, or move this mesh into place.`);
+ }
+ }
+ if (meshes.length > 1) {
+ const floaters = [];
+ for (let i = 0;i < meshes.length; i++) {
+ const a = meshes[i];
+ const ax = a.box.clone().expandByScalar(FLOATING_EXPAND);
+ let overlapsAny = false;
+ for (let j = 0;j < meshes.length; j++) {
+ if (i === j)
+ continue;
+ const b = meshes[j];
+ if (ax.intersectsBox(b.box)) {
+ overlapsAny = true;
+ break;
+ }
+ }
+ if (overlapsAny)
+ continue;
+ let nearest;
+ let nearestGap;
+ for (let j = 0;j < meshes.length; j++) {
+ if (i === j)
+ continue;
+ const gap = minimalGapVector(a.box, meshes[j].box);
+ if (!nearestGap || gap.length() < nearestGap.length()) {
+ nearest = meshes[j];
+ nearestGap = gap;
+ }
+ }
+ const fix = nearest && nearestGap ? ` Fix: shift "${a.name}" by [${nearestGap.x.toFixed(3)}, ${nearestGap.y.toFixed(3)}, ${nearestGap.z.toFixed(3)}] toward "${nearest.name}", or call snapTo(part, hostPart) to do it automatically.` : "";
+ floaters.push(`${a.name}${fix ? " —" + fix : ""}`);
+ }
+ if (floaters.length > 0) {
+ warnings.push(`Floating parts (no mesh overlap with any sibling, 2cm tol): ${floaters.join(" | ")}`);
+ }
+ }
+ return warnings;
+}
+function settleContacts(root, opts = {}) {
+ const maxGap = opts.maxGap ?? 0.05;
+ const overlap = opts.overlap ?? 0.01;
+ const settled = [];
+ for (let pass = 0;pass < 8; pass++) {
+ const meshes = collectMeshStats(root);
+ if (meshes.length < 2)
+ return settled;
+ let pick;
+ for (let i = 0;i < meshes.length; i++) {
+ const a = meshes[i];
+ const ax = a.box.clone().expandByScalar(0.02);
+ if (meshes.some((b, j) => j !== i && ax.intersectsBox(b.box)))
+ continue;
+ let nearestGap;
+ for (let j = 0;j < meshes.length; j++) {
+ if (i === j)
+ continue;
+ const gap = minimalGapVector(a.box, meshes[j].box);
+ if (!nearestGap || gap.length() < nearestGap.length())
+ nearestGap = gap;
+ }
+ if (!nearestGap || nearestGap.length() === 0 || nearestGap.length() > maxGap)
+ continue;
+ const volume = a.size.x * a.size.y * a.size.z;
+ if (!pick || volume < pick.volume)
+ pick = { stats: a, gap: nearestGap, volume };
+ }
+ if (!pick)
+ break;
+ const delta = pick.gap.clone();
+ const dominant = ["x", "y", "z"].reduce((d, axis) => Math.abs(delta[axis]) > Math.abs(delta[d]) ? axis : d, "x");
+ delta[dominant] += Math.sign(delta[dominant]) * overlap;
+ let target;
+ root.traverse((obj) => {
+ if (!target && obj.name === pick.stats.name && obj.isMesh)
+ target = obj;
+ });
+ if (!target)
+ break;
+ const parent = target.parent ?? root;
+ const p0 = new THREE34.Vector3;
+ target.getWorldPosition(p0);
+ const p1 = p0.clone().add(delta);
+ const l0 = parent.worldToLocal(p0.clone());
+ const l1 = parent.worldToLocal(p1.clone());
+ target.position.add(l1.sub(l0));
+ target.updateMatrixWorld(true);
+ settled.push(pick.stats.name);
+ }
+ return settled;
+}
+var engineIO = () => new WebIO3().registerExtensions([EXTMeshGPUInstancing3, KHRMaterialsVariants3, KHRTextureBasisu3]), TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5;
+var init_render = __esm(() => {
+ init_authoring_diagnostic();
+ init_geometry_export();
+ init_primitives();
+ init_contracts();
+ init_gltf();
+ init_run();
+ init_breadth_final();
+ init_material_metrics();
+ init_material_recipe_runtime();
+ init_material_resources();
+ init_texture_resolver();
+ init_validation();
+ init_self_intersection();
+ init_kit();
+ init_texture_bake();
+ init_character_capture();
+ init_vehicle3();
+ REVIEW_CLIP_LIMITS2 = {
+ clips: 32,
+ tracks: 256,
+ samplesPerTrack: 4096,
+ valuesPerTrack: 16384
+ };
+});
+
+// src/evaluator/protocol.ts
+var exports_protocol = {};
+__export(exports_protocol, {
+ trustedInProcessEvaluatorPortV1: () => trustedInProcessEvaluatorPortV1,
+ resolveEvaluatorPortV1: () => resolveEvaluatorPortV1,
+ evaluatorOutcomeMessage: () => evaluatorOutcomeMessage,
+ encodeRenderResultV1: () => encodeRenderResultV1,
+ decodeEvaluatorResultV1: () => decodeEvaluatorResultV1,
+ decodeEvaluatorRequestV1: () => decodeEvaluatorRequestV1,
+ createEvaluatorRequestV1: () => createEvaluatorRequestV1,
+ createEvaluatorPortV1: () => createEvaluatorPortV1,
+ MAX_EVALUATOR_REQUEST_BYTES: () => MAX_EVALUATOR_REQUEST_BYTES,
+ MAX_EVALUATOR_CODE_BYTES: () => MAX_EVALUATOR_CODE_BYTES,
+ EvaluatorPortError: () => EvaluatorPortError,
+ EVALUATOR_RESULT_VERSION: () => EVALUATOR_RESULT_VERSION,
+ EVALUATOR_REQUEST_VERSION: () => EVALUATOR_REQUEST_VERSION,
+ DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES: () => DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES,
+ DEFAULT_EVALUATOR_MAX_GLB_BYTES: () => DEFAULT_EVALUATOR_MAX_GLB_BYTES,
+ DEFAULT_EVALUATOR_DEADLINE_MS: () => DEFAULT_EVALUATOR_DEADLINE_MS
+});
+import { createHash as createHash6 } from "node:crypto";
+function evaluatorOutcomeMessage(code) {
+ return EVALUATOR_OUTCOME_MESSAGES[code];
+}
+function resolveEvaluatorPortV1(port, profile) {
+ if (port)
+ return port;
+ if (profile === "evaluator-required") {
+ throw new EvaluatorPortError("ISOLATION_UNAVAILABLE", "Evaluator port is required.");
+ }
+ return trustedInProcessEvaluatorPortV1;
+}
+function isRecord6(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function hasExactKeys(value, allowed) {
+ return Object.keys(value).every((key) => allowed.includes(key));
+}
+function fail(kind) {
+ throw new Error(`invalid evaluator ${kind}`);
+}
+function validRequestId(value) {
+ return typeof value === "string" && /^[A-Za-z0-9._-]{1,64}$/.test(value);
+}
+function validInteger(value, min, max) {
+ return Number.isInteger(value) && Number(value) >= min && Number(value) <= max;
+}
+function validQaReport(value) {
+ const dimensions2 = isRecord6(value) && isRecord6(value.dimensions) ? value.dimensions : undefined;
+ if (!isRecord6(value) || !hasExactKeys(value, ["schemaVersion", "category", "qaProfile", "disposition", "dimensions"]) || value.schemaVersion !== 1 || !isAssetCategory(value.category) || typeof value.qaProfile !== "string" || value.qaProfile.length < 1 || value.qaProfile.length > 128 || !["pass", "warn", "block", "notEvaluated", "legacy-unassessed"].includes(String(value.disposition)) || !dimensions2 || !hasExactKeys(dimensions2, QA_DIMENSIONS) || !QA_DIMENSIONS.every((dimension) => (dimension in dimensions2))) {
+ return false;
+ }
+ return QA_DIMENSIONS.every((dimension) => {
+ const result = dimensions2[dimension];
+ return isRecord6(result) && hasExactKeys(result, ["status", "findings", "metrics"]) && ["pass", "warn", "block", "notEvaluated"].includes(String(result.status)) && Array.isArray(result.findings) && result.findings.length <= 1000 && result.findings.every(isQaFinding) && (result.metrics === undefined || isRecord6(result.metrics));
+ });
+}
+function validGltfValidation(value) {
+ const issues = isRecord6(value) && isRecord6(value.issues) ? value.issues : undefined;
+ if (!issues || !Array.isArray(issues.messages)) {
+ return false;
+ }
+ return ["numErrors", "numWarnings", "numInfos", "numHints"].every((key) => validInteger(issues[key], 0, Number.MAX_SAFE_INTEGER)) && issues.messages.length <= 1000 && issues.messages.every((issue) => isRecord6(issue) && typeof issue.code === "string" && typeof issue.message === "string" && typeof issue.severity === "number" && Number.isFinite(issue.severity));
+}
+function boundedControl(value, fallback, max) {
+ const resolved2 = value ?? fallback;
+ if (!validInteger(resolved2, 1, max)) {
+ throw new EvaluatorPortError("INPUT_INVALID");
+ }
+ return resolved2;
+}
+function createEvaluatorRequestV1(input) {
+ if (input.options?.textureResolver) {
+ throw new EvaluatorPortError("INPUT_INVALID", "Evaluator requests do not accept a host resolver capability.");
+ }
+ const maxGlbBytes = boundedControl(input.maxGlbBytes, DEFAULT_EVALUATOR_MAX_GLB_BYTES, 64 * 1024 * 1024);
+ const { textureResolver: _, ...options } = input.options ?? {};
+ const request2 = {
+ version: EVALUATOR_REQUEST_VERSION,
+ requestId: input.requestId,
+ operation: "execute-export-glb",
+ code: input.code,
+ options,
+ limits: { maxGlbBytes }
+ };
+ const json = JSON.stringify(request2);
+ const decoded = decodeEvaluatorRequestV1(json);
+ return { request: decoded, json };
+}
+function parseOptions(value) {
+ if (!isRecord6(value) || !hasExactKeys(value, ["optimize", "instance", "intent", "category", "geometryPolicy"])) {
+ return fail("request");
+ }
+ const options = {};
+ if (value.geometryPolicy !== undefined) {
+ if (!["warn", "strict"].includes(String(value.geometryPolicy)))
+ fail("request");
+ options.geometryPolicy = value.geometryPolicy;
+ }
+ if (value.optimize !== undefined) {
+ if (!["off", "auto", "palette", "full"].includes(String(value.optimize)))
+ fail("request");
+ options.optimize = value.optimize;
+ }
+ if (value.instance !== undefined) {
+ if (!["off", "auto", "on"].includes(String(value.instance)))
+ fail("request");
+ options.instance = value.instance;
+ }
+ if (value.category !== undefined) {
+ if (!isAssetCategory(value.category))
+ fail("request");
+ options.category = value.category;
+ }
+ if (value.intent !== undefined) {
+ const result = validateAssetIntentV1(value.intent);
+ if (!result.valid)
+ fail("request");
+ options.intent = result.value;
+ }
+ return options;
+}
+function decodeEvaluatorRequestV1(json) {
+ if (Buffer.byteLength(json, "utf8") > MAX_EVALUATOR_REQUEST_BYTES)
+ fail("request");
+ let value;
+ try {
+ value = JSON.parse(json);
+ } catch {
+ return fail("request");
+ }
+ if (!isRecord6(value) || !hasExactKeys(value, ["version", "requestId", "operation", "code", "options", "limits"]) || value.version !== EVALUATOR_REQUEST_VERSION || !validRequestId(value.requestId) || value.operation !== "execute-export-glb" || typeof value.code !== "string" || Buffer.byteLength(value.code, "utf8") > MAX_EVALUATOR_CODE_BYTES || !isRecord6(value.limits) || !hasExactKeys(value.limits, ["maxGlbBytes"]) || !validInteger(value.limits.maxGlbBytes, 1, 64 * 1024 * 1024)) {
+ return fail("request");
+ }
+ return {
+ version: EVALUATOR_REQUEST_VERSION,
+ requestId: value.requestId,
+ operation: "execute-export-glb",
+ code: value.code,
+ options: parseOptions(value.options),
+ limits: { maxGlbBytes: value.limits.maxGlbBytes }
+ };
+}
+function encodeRenderResultV1(requestId, render) {
+ const { glb, diagnosticViews, buildCache: _hostCacheReceipt, ...rest } = render;
+ return {
+ version: EVALUATOR_RESULT_VERSION,
+ requestId,
+ ok: true,
+ render: {
+ ...rest,
+ glbBase64: glb.toString("base64"),
+ ...diagnosticViews ? {
+ diagnosticViews: diagnosticViews.map(({ png, ...view }) => ({
+ ...view,
+ pngBase64: Buffer.from(png).toString("base64")
+ }))
+ } : {}
+ }
+ };
+}
+function isSha256(value) {
+ return typeof value === "string" && /^sha256:[a-f0-9]{64}$/.test(value);
+}
+function decodeEvaluatorResultV1(json, maxGlbBytes, expectedRequestId) {
+ let value;
+ try {
+ value = JSON.parse(json);
+ } catch {
+ return fail("result");
+ }
+ if (!isRecord6(value) || !hasExactKeys(value, ["version", "requestId", "ok", "render", "error"]) || value.version !== EVALUATOR_RESULT_VERSION || !validRequestId(value.requestId) || typeof value.ok !== "boolean") {
+ return fail("result");
+ }
+ if (expectedRequestId !== undefined && value.requestId !== expectedRequestId)
+ fail("result");
+ if (!value.ok) {
+ if (value.render !== undefined)
+ return fail("result");
+ if (!isRecord6(value.error) || !hasExactKeys(value.error, ["code", "message", "qa", "diagnostic"])) {
+ return fail("result");
+ }
+ const codes = [
+ "INPUT_INVALID",
+ "EXECUTION_REJECTED",
+ "QA_BLOCKED",
+ "DEADLINE_EXCEEDED",
+ "CANCELLED",
+ "OUTPUT_LIMIT_EXCEEDED",
+ "ISOLATION_UNAVAILABLE",
+ "WORKER_FAILED",
+ "PROTOCOL_ERROR"
+ ];
+ if (!codes.includes(value.error.code) || typeof value.error.message !== "string" || value.error.message !== evaluatorOutcomeMessage(value.error.code)) {
+ return fail("result");
+ }
+ if (value.error.diagnostic !== undefined && (value.error.code !== "EXECUTION_REJECTED" || value.error.diagnostic !== "UNBOUND_VARIABLE" && value.error.diagnostic !== "GEAR_RADII_ORDER" && value.error.diagnostic !== "ROUNDED_BOX_RADIUS"))
+ return fail("result");
+ if (value.error.qa !== undefined) {
+ if (value.error.code !== "QA_BLOCKED" || !isRecord6(value.error.qa) || !hasExactKeys(value.error.qa, ["report", "stage", "gltfValidation"]) || !validQaReport(value.error.qa.report) || !["scene", "final-glb"].includes(String(value.error.qa.stage)) || value.error.qa.gltfValidation !== undefined && !validGltfValidation(value.error.qa.gltfValidation)) {
+ return fail("result");
+ }
+ } else if (value.error.code === "QA_BLOCKED") {
+ return fail("result");
+ }
+ return value;
+ }
+ if (value.error !== undefined || !isRecord6(value.render))
+ fail("result");
+ const renderKeys = [
+ "glbBase64",
+ "artifactGlbSha256",
+ "tris",
+ "meta",
+ "warnings",
+ "diagnosticViews",
+ "materialMetrics",
+ "materialRecipeApplications",
+ "materialResourceProvenance",
+ "bakedTextures",
+ "integrationManifest"
+ ];
+ if (!hasExactKeys(value.render, renderKeys) || typeof value.render.glbBase64 !== "string" || !validInteger(value.render.tris, 0, Number.MAX_SAFE_INTEGER) || !isRecord6(value.render.meta) || !Array.isArray(value.render.warnings) || !value.render.warnings.every((warning) => typeof warning === "string") || !isRecord6(value.render.integrationManifest)) {
+ fail("result");
+ }
+ const glb = Buffer.from(value.render.glbBase64, "base64");
+ if (glb.byteLength > maxGlbBytes || glb.toString("base64") !== value.render.glbBase64)
+ fail("result");
+ if (!isSha256(value.render.artifactGlbSha256))
+ fail("result");
+ const actualHash = `sha256:${createHash6("sha256").update(glb).digest("hex")}`;
+ if (actualHash !== value.render.artifactGlbSha256)
+ fail("result");
+ const diagnosticViews = value.render.diagnosticViews;
+ if (diagnosticViews !== undefined && !Array.isArray(diagnosticViews))
+ fail("result");
+ const decodedViews = diagnosticViews?.map((candidate) => {
+ if (!isRecord6(candidate) || typeof candidate.pngBase64 !== "string")
+ return fail("result");
+ const png = Buffer.from(candidate.pngBase64, "base64");
+ if (png.toString("base64") !== candidate.pngBase64)
+ return fail("result");
+ const { pngBase64: _2, ...view } = candidate;
+ return { ...view, png };
+ });
+ const { glbBase64: _, diagnosticViews: __, ...rest } = value.render;
+ return {
+ version: EVALUATOR_RESULT_VERSION,
+ requestId: value.requestId,
+ ok: true,
+ render: {
+ ...rest,
+ glb,
+ ...decodedViews ? { diagnosticViews: decodedViews } : {}
+ }
+ };
+}
+function createEvaluatorPortV1(transport, defaults2 = {}) {
+ let sequence = 0;
+ return {
+ async render(code, options = {}, controls = {}) {
+ const signal = controls.signal ?? defaults2.signal;
+ if (signal?.aborted)
+ throw new EvaluatorPortError("CANCELLED");
+ const deadlineMs = boundedControl(controls.deadlineMs ?? defaults2.deadlineMs, DEFAULT_EVALUATOR_DEADLINE_MS, 120000);
+ const maxGlbBytes = boundedControl(controls.maxGlbBytes ?? defaults2.maxGlbBytes, DEFAULT_EVALUATOR_MAX_GLB_BYTES, 64 * 1024 * 1024);
+ const maxResponseBytes = boundedControl(controls.maxResponseBytes ?? defaults2.maxResponseBytes, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, 96 * 1024 * 1024);
+ const requestId = `eval-${++sequence}`;
+ const built = createEvaluatorRequestV1({ requestId, code, options, maxGlbBytes });
+ let timer;
+ let response;
+ const transportController = new AbortController;
+ let abort;
+ try {
+ const cancelled = new Promise((_, reject) => {
+ abort = () => {
+ reject(new EvaluatorPortError("CANCELLED"));
+ transportController.abort();
+ };
+ signal?.addEventListener("abort", abort, { once: true });
+ });
+ response = await Promise.race([
+ transport(built.json, {
+ deadlineMs,
+ maxResponseBytes,
+ signal: transportController.signal
+ }),
+ cancelled,
+ new Promise((_, reject) => {
+ timer = setTimeout(() => {
+ reject(new EvaluatorPortError("DEADLINE_EXCEEDED"));
+ transportController.abort();
+ }, deadlineMs);
+ })
+ ]);
+ } catch (error) {
+ if (error instanceof EvaluatorPortError)
+ throw error;
+ throw new EvaluatorPortError("WORKER_FAILED");
+ } finally {
+ clearTimeout(timer);
+ if (abort)
+ signal?.removeEventListener("abort", abort);
+ }
+ if (signal?.aborted)
+ throw new EvaluatorPortError("CANCELLED");
+ if (typeof response !== "string")
+ throw new EvaluatorPortError("PROTOCOL_ERROR");
+ if (Buffer.byteLength(response, "utf8") > maxResponseBytes) {
+ throw new EvaluatorPortError("OUTPUT_LIMIT_EXCEEDED");
+ }
+ let result;
+ try {
+ result = decodeEvaluatorResultV1(response, maxGlbBytes, requestId);
+ } catch {
+ throw new EvaluatorPortError("PROTOCOL_ERROR");
+ }
+ if (!result.ok) {
+ if (result.error.code === "QA_BLOCKED" && result.error.qa) {
+ const { AssetQaBlockedError: AssetQaBlockedError2 } = await Promise.resolve().then(() => (init_run(), exports_run));
+ throw new AssetQaBlockedError2(result.error.qa.report, result.error.qa.stage, result.error.qa.gltfValidation);
+ }
+ throw new EvaluatorPortError(result.error.code, undefined, result.error.diagnostic);
+ }
+ return result.render;
+ }
+ };
+}
+var EVALUATOR_REQUEST_VERSION = "kiln.evaluator.request.v1", EVALUATOR_RESULT_VERSION = "kiln.evaluator.result.v1", MAX_EVALUATOR_CODE_BYTES, MAX_EVALUATOR_REQUEST_BYTES, DEFAULT_EVALUATOR_DEADLINE_MS = 60000, DEFAULT_EVALUATOR_MAX_GLB_BYTES, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, EVALUATOR_OUTCOME_MESSAGES, EvaluatorPortError, trustedInProcessEvaluatorPortV1;
+var init_protocol = __esm(() => {
+ init_authoring_diagnostic();
+ init_contracts();
+ init_types();
+ MAX_EVALUATOR_CODE_BYTES = 512 * 1024;
+ MAX_EVALUATOR_REQUEST_BYTES = 1024 * 1024;
+ DEFAULT_EVALUATOR_MAX_GLB_BYTES = 16 * 1024 * 1024;
+ DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
+ EVALUATOR_OUTCOME_MESSAGES = {
+ INPUT_INVALID: "Evaluator request was invalid.",
+ EXECUTION_REJECTED: "Generated asset execution was rejected.",
+ QA_BLOCKED: "Generated asset did not pass quality checks.",
+ DEADLINE_EXCEEDED: "Evaluator deadline exceeded.",
+ CANCELLED: "Evaluator request was cancelled.",
+ OUTPUT_LIMIT_EXCEEDED: "Evaluator output limit exceeded.",
+ ISOLATION_UNAVAILABLE: "Isolated evaluator is unavailable.",
+ WORKER_FAILED: "Evaluator worker failed.",
+ PROTOCOL_ERROR: "Evaluator returned invalid data."
+ };
+ EvaluatorPortError = class EvaluatorPortError extends Error {
+ code;
+ diagnostic;
+ constructor(code, message = evaluatorOutcomeMessage(code), diagnostic) {
+ super(diagnostic ? `${message} ${authoringDiagnosticAdvice(diagnostic)}` : message);
+ this.code = code;
+ this.diagnostic = diagnostic;
+ this.name = "EvaluatorPortError";
+ }
+ };
+ trustedInProcessEvaluatorPortV1 = {
+ async render(code, options = {}, controls = {}) {
+ if (controls.signal?.aborted)
+ throw new EvaluatorPortError("CANCELLED");
+ const { renderGLBInProcess: renderGLBInProcess2 } = await Promise.resolve().then(() => (init_render(), exports_render));
+ const result = await renderGLBInProcess2(code, options);
+ if (controls.signal?.aborted)
+ throw new EvaluatorPortError("CANCELLED");
+ return result;
+ }
+ };
+});
+
+// src/evaluator/subprocess.ts
+var exports_subprocess = {};
+__export(exports_subprocess, {
+ sanitizedEvaluatorEnv: () => sanitizedEvaluatorEnv,
+ renderGLBViaSubprocess: () => renderGLBViaSubprocess,
+ renderGLBViaProcessLaunch: () => renderGLBViaProcessLaunch,
+ EvaluatorSubprocessError: () => EvaluatorSubprocessError
+});
+import { spawn as spawn2 } from "node:child_process";
+import { fileURLToPath as fileURLToPath2 } from "node:url";
+function sanitizedEvaluatorEnv(source = process.env) {
+ const env = { NODE_ENV: "production", NO_COLOR: "1" };
+ for (const key of ["PATH", "Path", "SystemRoot", "SYSTEMROOT", "TEMP", "TMP", "TZ"]) {
+ if (source[key] !== undefined)
+ env[key] = source[key];
+ }
+ return env;
+}
+function boundedInteger(value, fallback, max) {
+ const resolved2 = value ?? fallback;
+ if (!Number.isInteger(resolved2) || resolved2 < 1 || resolved2 > max) {
+ throw new EvaluatorSubprocessError("INPUT_INVALID", "Evaluator controls are invalid.");
+ }
+ return resolved2;
+}
+function terminateProcess(child, detached) {
+ if (!child.pid || child.killed)
+ return;
+ try {
+ if (detached && process.platform !== "win32")
+ process.kill(-child.pid, "SIGKILL");
+ else
+ child.kill("SIGKILL");
+ } catch (error) {
+ if (error.code !== "ESRCH")
+ throw error;
+ }
+}
+async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, launch) {
+ if (controls.signal?.aborted) {
+ throw new EvaluatorSubprocessError("CANCELLED", "Evaluator request was cancelled.");
+ }
+ if (options.textureResolver) {
+ throw new EvaluatorSubprocessError("INPUT_INVALID", "Subprocess evaluation does not accept host resolver capabilities.");
+ }
+ const deadlineMs = boundedInteger(controls.deadlineMs, DEFAULT_DEADLINE_MS, 120000);
+ const maxGlbBytes = boundedInteger(controls.maxGlbBytes, DEFAULT_MAX_GLB_BYTES, 64 * 1024 * 1024);
+ const maxResponseBytes = boundedInteger(controls.maxResponseBytes, DEFAULT_MAX_RESPONSE_BYTES, 96 * 1024 * 1024);
+ const request2 = {
+ version: EVALUATOR_REQUEST_VERSION,
+ requestId: "render-1",
+ operation: "execute-export-glb",
+ code,
+ options,
+ limits: { maxGlbBytes }
+ };
+ const requestJson = JSON.stringify(request2);
+ if (Buffer.byteLength(requestJson, "utf8") > MAX_EVALUATOR_REQUEST_BYTES) {
+ throw new EvaluatorSubprocessError("INPUT_INVALID", "Evaluator request exceeds its size limit.");
+ }
+ const sourceModule = import.meta.url.endsWith(".ts");
+ const workerPath = fileURLToPath2(new URL(process.versions.bun && sourceModule ? "./worker.ts" : sourceModule ? "../../dist/evaluator-worker.mjs" : "./evaluator-worker.mjs", import.meta.url));
+ const maxHeapMb = boundedInteger(controls.maxHeapMb, 512, 4096);
+ if (maxHeapMb < 64 || process.versions.bun && controls.maxHeapMb !== undefined) {
+ throw new EvaluatorSubprocessError("INPUT_INVALID", "Heap limits require a Node worker and 64–4096 MiB.");
+ }
+ const defaultLaunch = {
+ command: process.execPath,
+ args: process.versions.bun ? [workerPath] : [`--max-old-space-size=${maxHeapMb}`, workerPath],
+ env: sanitizedEvaluatorEnv()
+ };
+ const resolvedLaunch = launch ?? defaultLaunch;
+ const detached = resolvedLaunch.detached === true;
+ return await new Promise((resolve, reject) => {
+ const spawnOptions = {
+ env: resolvedLaunch.env,
+ windowsHide: true,
+ stdio: ["pipe", "ignore", "pipe", "pipe"],
+ ...detached ? { detached: true } : {}
+ };
+ const child = spawn2(resolvedLaunch.command, resolvedLaunch.args, spawnOptions);
+ const protocol = child.stdio[3];
+ if (!protocol) {
+ terminateProcess(child, detached);
+ reject(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker did not start."));
+ return;
+ }
+ const chunks = [];
+ let responseBytes = 0;
+ let stderrBytes = 0;
+ let settled = false;
+ const finish = (error, result) => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ controls.signal?.removeEventListener("abort", abort);
+ if (error)
+ reject(error);
+ else
+ resolve(result);
+ };
+ const timer = setTimeout(() => {
+ finish(new EvaluatorSubprocessError("DEADLINE_EXCEEDED", "Evaluator deadline exceeded."));
+ terminateProcess(child, detached);
+ }, deadlineMs);
+ const abort = () => {
+ finish(new EvaluatorSubprocessError("CANCELLED", "Evaluator request was cancelled."));
+ terminateProcess(child, detached);
+ };
+ const pipeFailed = (error) => {
+ if (settled)
+ return;
+ if (["EPIPE", "ECONNRESET", "ERR_STREAM_DESTROYED", "ERR_STREAM_PREMATURE_CLOSE"].includes(error.code ?? ""))
+ return;
+ finish(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker pipe failed."));
+ terminateProcess(child, detached);
+ };
+ child.stdin?.on("error", pipeFailed);
+ protocol.on("error", (error) => {
+ if (process.platform === "win32" && process.versions.bun && error.code === "EBADF")
+ return;
+ pipeFailed(error);
+ });
+ child.stderr?.on("error", pipeFailed);
+ controls.signal?.addEventListener("abort", abort, { once: true });
+ if (controls.signal?.aborted)
+ abort();
+ protocol.on("data", (chunk2) => {
+ responseBytes += chunk2.byteLength;
+ if (responseBytes > maxResponseBytes) {
+ finish(new EvaluatorSubprocessError("OUTPUT_LIMIT_EXCEEDED", "Evaluator output limit exceeded."));
+ terminateProcess(child, detached);
+ return;
+ }
+ chunks.push(Buffer.from(chunk2));
+ });
+ child.stderr?.on("data", (chunk2) => {
+ stderrBytes = Math.min(MAX_STDERR_BYTES, stderrBytes + chunk2.byteLength);
+ });
+ child.on("error", () => {
+ finish(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker failed to start."));
+ });
+ child.on("close", (exitCode) => {
+ if (settled)
+ return;
+ if (exitCode !== 0 || chunks.length === 0) {
+ finish(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker failed."));
+ return;
+ }
+ try {
+ const result = decodeEvaluatorResultV1(Buffer.concat(chunks).toString("utf8"), maxGlbBytes);
+ if (!result.ok) {
+ if (result.error.code === "QA_BLOCKED" && result.error.qa) {
+ finish(new AssetQaBlockedError(result.error.qa.report, result.error.qa.stage, result.error.qa.gltfValidation));
+ return;
+ }
+ finish(new EvaluatorSubprocessError(result.error.code, evaluatorOutcomeMessage(result.error.code), result.error.diagnostic));
+ return;
+ }
+ finish(undefined, result.render);
+ } catch {
+ finish(new EvaluatorSubprocessError("PROTOCOL_ERROR", "Evaluator returned invalid data."));
+ }
+ });
+ if (!settled)
+ child.stdin?.end(requestJson);
+ });
+}
+async function renderGLBViaSubprocess(code, options = {}, controls = {}) {
+ return renderGLBViaProcessLaunch(code, options, controls);
+}
+var DEFAULT_DEADLINE_MS = 60000, DEFAULT_MAX_GLB_BYTES, DEFAULT_MAX_RESPONSE_BYTES, MAX_STDERR_BYTES, EvaluatorSubprocessError;
+var init_subprocess = __esm(() => {
+ init_authoring_diagnostic();
+ init_run();
+ init_protocol();
+ DEFAULT_MAX_GLB_BYTES = 16 * 1024 * 1024;
+ DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
+ MAX_STDERR_BYTES = 16 * 1024;
+ EvaluatorSubprocessError = class EvaluatorSubprocessError extends Error {
+ diagnostic;
+ code;
+ constructor(code, message, diagnostic) {
+ super(diagnostic ? `${message} ${authoringDiagnosticAdvice(diagnostic)}` : message);
+ this.diagnostic = diagnostic;
+ this.name = "EvaluatorSubprocessError";
+ this.code = code;
+ }
+ };
+});
+
+// src/program-store.ts
+function assertProgramRef(ref) {
+ if (typeof ref !== "string" || !programRefPattern.test(ref))
+ throw new Error("Invalid program reference; use a p_ handle or full sha256 reference returned by Kiln.");
+}
+async function retainProgram(store, code) {
+ const canonical2 = await store.put(code);
+ return store.shortRef ? store.shortRef(canonical2) : canonical2;
+}
+function* shortProgramRefCandidates(canonical2) {
+ if (!canonicalProgramRefPattern.test(canonical2) || canonical2.length !== 71)
+ throw new Error("Invalid canonical program reference.");
+ for (let length3 = 12;length3 <= 64; length3 += 4)
+ yield `p_${canonical2.slice(7, 7 + length3)}`;
+}
+async function programReference(code) {
+ const bytes = new TextEncoder().encode(code);
+ if (bytes.length > MAX_PROGRAM_BYTES)
+ throw new Error("Program exceeds the 1 MiB source limit.");
+ if (new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes) !== code)
+ throw new Error("Program must be valid Unicode.");
+ const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
+ return `sha256:${Array.from(hash, (b) => b.toString(16).padStart(2, "0")).join("")}`;
+}
+
+class MemoryProgramStore {
+ maxBytes;
+ programs = new Map;
+ handles = new Map;
+ constructor(maxBytes = 64 * 1024 * 1024) {
+ this.maxBytes = maxBytes;
+ }
+ bytes = 0;
+ async put(code) {
+ const ref = await programReference(code);
+ if (!this.programs.has(ref)) {
+ const size = new TextEncoder().encode(code).length;
+ if (this.bytes + size > this.maxBytes)
+ throw new Error("Program store is full; export your work and start a new store.");
+ this.programs.set(ref, code);
+ this.bytes += size;
+ }
+ return ref;
+ }
+ async stats() {
+ return {
+ entries: this.programs.size,
+ bytes: this.bytes,
+ maxSourceBytes: MAX_PROGRAM_BYTES,
+ maxBytes: this.maxBytes,
+ eviction: "none"
+ };
+ }
+ async get(ref) {
+ assertProgramRef(ref);
+ const canonical2 = ref.startsWith("p_") ? this.handles.get(ref) : ref;
+ const code = canonical2 === undefined ? undefined : this.programs.get(canonical2);
+ if (code === undefined)
+ throw new Error(`Program not found: ${ref}. Import the source into this store again.`);
+ return code;
+ }
+ async shortRef(ref) {
+ await this.get(ref);
+ if (ref.startsWith("p_"))
+ return ref;
+ for (const handle of shortProgramRefCandidates(ref)) {
+ const owner = this.handles.get(handle);
+ if (owner === ref)
+ return handle;
+ if (owner === undefined) {
+ this.handles.set(handle, ref);
+ return handle;
+ }
+ }
+ throw new Error("Unable to register an immutable program handle.");
+ }
+}
+var MAX_PROGRAM_BYTES, canonicalProgramRefPattern, programRefPattern;
+var init_program_store = __esm(() => {
+ MAX_PROGRAM_BYTES = 1024 * 1024;
+ canonicalProgramRefPattern = /^sha256:[a-f0-9]{64}(?![\s\S])/;
+ programRefPattern = /^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\s\S])/;
+});
+
+// src/program-store-node.ts
+import { link, lstat, mkdir, readFile as readFile2, readdir, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
+import { randomUUID } from "node:crypto";
+import { join as join3, resolve } from "node:path";
+
+class FileProgramStore {
+ directory;
+ constructor(directory) {
+ this.directory = directory;
+ }
+ async stats() {
+ let entries = 0;
+ let bytes = 0;
+ try {
+ for (const entry of await readdir(this.directory, { withFileTypes: true })) {
+ if (!entry.isFile() || !/^[a-f0-9]{64}\.js$/.test(entry.name))
+ continue;
+ try {
+ bytes += (await stat(join3(this.directory, entry.name))).size;
+ entries++;
+ } catch (error) {
+ if (error.code !== "ENOENT")
+ throw error;
+ }
+ }
+ } catch (error) {
+ if (error.code !== "ENOENT")
+ throw error;
+ }
+ return { entries, bytes, maxSourceBytes: MAX_PROGRAM_BYTES, eviction: "none" };
+ }
+ async get(ref) {
+ assertProgramRef(ref);
+ const canonical2 = ref.startsWith("p_") ? await this.readHandle(ref) : ref;
+ if (canonical2 === undefined)
+ throw this.notFound(ref);
+ const path = join3(this.directory, `${canonical2.slice(7)}.js`);
+ let code;
+ try {
+ if ((await stat(path)).size > MAX_PROGRAM_BYTES)
+ throw new Error("Stored program exceeds the 1 MiB source limit.");
+ code = await readFile2(path, "utf8");
+ } catch (error) {
+ if (error.code === "ENOENT")
+ throw this.notFound(ref);
+ throw error;
+ }
+ if (await programReference(code) !== canonical2)
+ throw new Error(`Program integrity check failed: ${ref}`);
+ return code;
+ }
+ notFound(ref) {
+ return new Error(`Program not found: ${ref}. Use the same KILN_PROGRAM_STORE or import the source again.`);
+ }
+ async readHandle(handle) {
+ const path = join3(this.directory, "refs", `${handle}.ref`);
+ try {
+ const info = await lstat(path);
+ if (!info.isFile() || info.size !== 71)
+ throw new Error(`Program handle integrity check failed: ${handle}`);
+ const canonical2 = await readFile2(path, "utf8");
+ if (!canonicalProgramRefPattern.test(canonical2) || !canonical2.slice(7).startsWith(handle.slice(2)))
+ throw new Error(`Program handle integrity check failed: ${handle}`);
+ return canonical2;
+ } catch (error) {
+ if (error.code === "ENOENT")
+ return;
+ throw error;
+ }
+ }
+ async shortRef(ref) {
+ await this.get(ref);
+ if (ref.startsWith("p_"))
+ return ref;
+ const directory = join3(this.directory, "refs");
+ await mkdir(directory, { recursive: true });
+ for (const handle of shortProgramRefCandidates(ref)) {
+ const owner = await this.readHandle(handle);
+ if (owner === ref)
+ return handle;
+ if (owner !== undefined)
+ continue;
+ const temporary = join3(directory, `.write-${randomUUID()}`);
+ await writeFile2(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });
+ try {
+ try {
+ await link(temporary, join3(directory, `${handle}.ref`));
+ return handle;
+ } catch (error) {
+ if (error.code !== "EEXIST")
+ throw error;
+ if (await this.readHandle(handle) === ref)
+ return handle;
+ }
+ } finally {
+ await unlink(temporary);
+ }
+ }
+ throw new Error("Unable to register an immutable program handle.");
+ }
+ async put(code) {
+ const ref = await programReference(code);
+ await mkdir(this.directory, { recursive: true });
+ const target = join3(this.directory, `${ref.slice(7)}.js`);
+ const temporary = join3(this.directory, `.write-${randomUUID()}`);
+ await writeFile2(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });
+ try {
+ try {
+ await link(temporary, target);
+ } catch (error) {
+ if (error.code !== "EEXIST")
+ throw error;
+ await this.get(ref);
+ }
+ } finally {
+ await unlink(temporary);
+ }
+ return ref;
+ }
+}
+function localProgramStore() {
+ return new FileProgramStore(resolve(process.env["KILN_PROGRAM_STORE"] ?? ".kiln/programs"));
+}
+var init_program_store_node = __esm(() => {
+ init_program_store();
+});
+
+// src/build-cache.ts
+import { createHash as createHash7 } from "node:crypto";
+import * as acorn2 from "acorn";
+import * as walk2 from "acorn-walk";
+function sourceHasAmbientInputs(code) {
+ let ambient = false;
+ const property = (node) => !node.computed && node.property.type === "Identifier" ? node.property.name : node.computed && node.property.type === "Literal" && typeof node.property.value === "string" ? node.property.value : undefined;
+ try {
+ const ast = acorn2.parse(code, { ecmaVersion: "latest", sourceType: "script" });
+ walk2.ancestor(ast, {
+ Identifier(node, _state, ancestors) {
+ const parent = ancestors.at(-2);
+ if (["Date", "performance", "crypto"].includes(node.name))
+ ambient = true;
+ if (node.name === "Math") {
+ if (parent?.type !== "MemberExpression" || parent.object !== node)
+ ambient = true;
+ else {
+ const name = property(parent);
+ if (!name || name === "random")
+ ambient = true;
+ }
+ }
+ },
+ MemberExpression(node, _state, ancestors) {
+ if (node.object.type !== "Identifier" || node.object.name !== "THREE" || property(node) !== "MathUtils")
+ return;
+ const parent = ancestors.at(-2);
+ if (parent?.type !== "MemberExpression" || parent.object !== node) {
+ ambient = true;
+ return;
+ }
+ const name = property(parent);
+ if (!name || ["randInt", "randFloat", "randFloatSpread", "seededRandom", "generateUUID"].includes(name))
+ ambient = true;
+ }
+ });
+ } catch {
+ return true;
+ }
+ return ambient;
+}
+function copy(result) {
+ return { ...structuredClone(result), glb: Buffer.from(result.glb) };
+}
+
+class MemoryBuildCache {
+ maxBytes;
+ entries = new Map;
+ bytes = 0;
+ constructor(maxBytes = 64 * 1024 * 1024) {
+ this.maxBytes = maxBytes;
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0)
+ throw new Error("Build cache size must be a nonnegative integer.");
+ }
+ async get(key) {
+ const entry = this.entries.get(key);
+ if (!entry)
+ return;
+ this.entries.delete(key);
+ this.entries.set(key, entry);
+ return copy(entry.result);
+ }
+ async put(key, result) {
+ const { glb, ...metadata } = result;
+ const size = glb.byteLength + Buffer.byteLength(JSON.stringify(metadata));
+ if (size > this.maxBytes)
+ return;
+ const old = this.entries.get(key);
+ if (old) {
+ this.bytes -= old.bytes;
+ this.entries.delete(key);
+ }
+ while (this.bytes + size > this.maxBytes) {
+ const first = this.entries.keys().next().value;
+ if (first === undefined)
+ break;
+ this.bytes -= this.entries.get(first).bytes;
+ this.entries.delete(first);
+ }
+ this.entries.set(key, { result: copy(result), bytes: size });
+ this.bytes += size;
+ }
+ stats() {
+ return { entries: this.entries.size, bytes: this.bytes, maxBytes: this.maxBytes };
+ }
+}
+function canonical2(value) {
+ if (value === undefined || value === null || typeof value === "string" || typeof value === "boolean")
+ return value;
+ if (typeof value === "number" && Number.isFinite(value))
+ return value;
+ if (Array.isArray(value))
+ return value.map(canonical2);
+ if (typeof value === "object")
+ return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([key, v]) => [key, canonical2(v)]));
+ throw new Error("Build input contains a non-data dependency.");
+}
+function createCachedEvaluatorPort(evaluator, options) {
+ const pending = new Map;
+ return {
+ async render(code, renderOptions, controls) {
+ const signal = controls?.signal;
+ const checkCancelled = () => {
+ if (signal?.aborted)
+ throw new EvaluatorPortError("CANCELLED");
+ };
+ checkCancelled();
+ const identity = options.identity();
+ if (!identity || renderOptions?.textureResolver || sourceHasAmbientInputs(code))
+ return evaluator.render(code, renderOptions, controls);
+ let serialized;
+ try {
+ renderOptions = structuredClone(renderOptions);
+ const { signal: _signal, ...dataControls } = controls ?? {};
+ const snapshotControls = structuredClone(dataControls);
+ controls = { ...snapshotControls, ...signal ? { signal } : {} };
+ serialized = JSON.stringify(canonical2({ identity, code, options: renderOptions ?? {}, controls: snapshotControls }));
+ } catch {
+ return evaluator.render(code, renderOptions, controls);
+ }
+ const key = `sha256:${createHash7("sha256").update(serialized).digest("hex")}`;
+ const cached = await options.cache.get(key).catch(() => {
+ return;
+ });
+ checkCancelled();
+ if (cached)
+ return { ...cached, buildCache: { key, hit: true } };
+ const existing = signal ? undefined : pending.get(key);
+ if (existing) {
+ const completed = await existing;
+ if (!completed.shareable)
+ return evaluator.render(code, renderOptions, controls);
+ return { ...copy(completed.result), buildCache: { key, hit: true } };
+ }
+ const build = (async () => {
+ const result = await evaluator.render(code, renderOptions, controls);
+ checkCancelled();
+ let snapshot;
+ try {
+ snapshot = copy(result);
+ } catch {
+ return { result, shareable: false };
+ }
+ await options.cache.put(key, snapshot).catch(() => {});
+ return { result: snapshot, shareable: true };
+ })();
+ if (!signal)
+ pending.set(key, build);
+ try {
+ const completed = await build;
+ checkCancelled();
+ return completed.shareable ? { ...copy(completed.result), buildCache: { key, hit: false } } : completed.result;
+ } finally {
+ if (!signal)
+ pending.delete(key);
+ }
+ }
+ };
+}
+var init_build_cache = __esm(() => {
+ init_protocol();
+});
+
+// src/build-cache-node.ts
+import { createHash as createHash8, randomUUID as randomUUID2 } from "node:crypto";
+import {
+ mkdir as mkdir2,
+ readFile as readFile3,
+ readdir as readdir2,
+ rename,
+ stat as stat2,
+ unlink as unlink2,
+ utimes,
+ writeFile as writeFile3
+} from "node:fs/promises";
+import { join as join4, resolve as resolve2 } from "node:path";
+
+class FileBuildCache {
+ maxBytes;
+ directory;
+ constructor(directory, maxBytes = 128 * 1024 * 1024) {
+ this.maxBytes = maxBytes;
+ this.directory = resolve2(directory);
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || maxBytes > 1024 * 1024 * 1024)
+ throw new Error("File build cache size must be 0..1 GiB.");
+ }
+ path(key) {
+ if (!keyPattern.test(key))
+ throw new Error("Invalid build cache key.");
+ return join4(this.directory, `${key.slice(7)}.json`);
+ }
+ async get(key) {
+ const path = this.path(key);
+ try {
+ const entry = await stat2(path);
+ if (entry.size > this.maxBytes || entry.size > 96 * 1024 * 1024)
+ return;
+ const envelope = JSON.parse(await readFile3(path, "utf8"));
+ if (envelope.version !== 1 || envelope.key !== key || typeof envelope.payload !== "string" || envelope.checksum !== digest2(envelope.payload))
+ return;
+ const decoded = decodeEvaluatorResultV1(envelope.payload, 64 * 1024 * 1024);
+ if (!decoded.ok)
+ return;
+ const now = new Date;
+ await utimes(path, now, now).catch(() => {});
+ return decoded.render;
+ } catch {
+ return;
+ }
+ }
+ async put(key, result) {
+ const path = this.path(key);
+ const payload = JSON.stringify(encodeRenderResultV1("cached-build", result));
+ const bytes = JSON.stringify({ version: 1, key, payload, checksum: digest2(payload) });
+ if (Buffer.byteLength(bytes) > Math.min(this.maxBytes, 96 * 1024 * 1024))
+ return;
+ await mkdir2(this.directory, { recursive: true });
+ const temporary = join4(this.directory, `.write-${randomUUID2()}`);
+ await writeFile3(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });
+ try {
+ await rename(temporary, path);
+ } finally {
+ await unlink2(temporary).catch(() => {});
+ }
+ await this.trim();
+ }
+ async trim() {
+ const entries = [];
+ for (const name of await readdir2(this.directory)) {
+ if (!filePattern.test(name))
+ continue;
+ const path = join4(this.directory, name);
+ try {
+ const item = await stat2(path);
+ entries.push({ path, size: item.size, used: item.mtimeMs });
+ } catch {}
+ }
+ let bytes = entries.reduce((sum, item) => sum + item.size, 0);
+ entries.sort((a, b) => a.used - b.used || a.path.localeCompare(b.path));
+ for (const entry of entries) {
+ if (bytes <= this.maxBytes)
+ break;
+ await unlink2(entry.path).catch(() => {});
+ bytes -= entry.size;
+ }
+ }
+}
+var keyPattern, filePattern, digest2 = (text2) => createHash8("sha256").update(text2).digest("hex");
+var init_build_cache_node = __esm(() => {
+ init_protocol();
+ keyPattern = /^sha256:[a-f0-9]{64}$/;
+ filePattern = /^[a-f0-9]{64}\.json$/;
+});
+
+// src/runtime-identity.ts
+import { createHash as createHash9 } from "node:crypto";
+import { readFile as readFile4, readdir as readdir3, realpath, stat as stat3 } from "node:fs/promises";
+import { createRequire as createRequire2 } from "node:module";
+import { dirname, join as join5, relative } from "node:path";
+async function installedRuntimeIdentity(root, limits = {}) {
+ let bytes = 0;
+ let files = 0;
+ const maxBytes = limits.maxBytes ?? 512 * 1024 * 1024;
+ const maxFiles = limits.maxFiles ?? 40000;
+ const manifest = async (directory) => JSON.parse(await readFile4(join5(directory, "package.json"), "utf8"));
+ let readers = 0;
+ const waiting = [];
+ const read = async (path) => {
+ if (readers >= 24)
+ await new Promise((resolve3) => waiting.push(resolve3));
+ else
+ readers++;
+ try {
+ const info = await stat3(path);
+ if (++files > maxFiles || bytes + info.size > maxBytes)
+ throw new Error("Installed runtime fingerprint exceeds its scan budget.");
+ bytes += info.size;
+ return await readFile4(path);
+ } finally {
+ const next = waiting.shift();
+ if (next)
+ next();
+ else
+ readers--;
+ }
+ };
+ try {
+ const pkg = await manifest(root);
+ if (pkg.name !== "@kiln/engine")
+ throw new Error("Not a Kiln installation.");
+ const build = JSON.parse(await readFile4(join5(root, "dist", "build.json"), "utf8"));
+ const worker = build.entries?.worker;
+ if (build.schemaVersion !== 1 || worker?.file !== "evaluator-worker.mjs" || !/^sha256:[a-f0-9]{64}$/.test(worker.identity))
+ throw new Error("No valid packaged worker identity.");
+ const workerHash = `sha256:${digest3(await read(join5(root, "dist", worker.file)))}`;
+ if (worker.bundleHash !== workerHash)
+ throw new Error("Packaged worker differs from its build manifest.");
+ const records = [];
+ const visited = new Map;
+ async function resolvePackage(parent, name) {
+ const require2 = createRequire2(join5(parent, "package.json"));
+ let found;
+ try {
+ found = require2.resolve(`${name}/package.json`);
+ } catch {
+ try {
+ found = require2.resolve(name);
+ } catch {
+ for (const modules of require2.resolve.paths(name) ?? []) {
+ const candidate = join5(modules, name);
+ try {
+ if ((await manifest(candidate)).name === name)
+ return await realpath(candidate);
+ } catch {}
+ }
+ throw new Error(`Cannot resolve installed dependency ${name}.`);
+ }
+ }
+ let directory = dirname(found);
+ for (;; ) {
+ try {
+ if ((await manifest(directory)).name === name)
+ return await realpath(directory);
+ } catch {}
+ const next = dirname(directory);
+ if (next === directory)
+ throw new Error(`Cannot identify installed dependency ${name}.`);
+ directory = next;
+ }
+ }
+ async function tree(directory, base) {
+ const entries = (await readdir3(directory, { withFileTypes: true })).sort((a, b) => compare(a.name, b.name));
+ return (await Promise.all(entries.map(async (entry) => {
+ if (entry.name === "node_modules" || entry.name === ".git")
+ return [];
+ const path = join5(directory, entry.name);
+ if (entry.isSymbolicLink())
+ throw new Error("Dependency contains an untracked internal symlink.");
+ if (entry.isDirectory())
+ return tree(path, base);
+ if (entry.isFile())
+ return [[relative(base, path).replaceAll("\\", "/"), digest3(await read(path))]];
+ throw new Error("Dependency contains a non-file runtime input.");
+ }))).flat();
+ }
+ async function visit(directory, path) {
+ const canonical3 = await realpath(directory);
+ const previous = visited.get(canonical3);
+ if (previous) {
+ records.push([path, `same-package:${previous}`]);
+ return;
+ }
+ visited.set(canonical3, path);
+ const metadata = await manifest(canonical3);
+ records.push([path, digest3(JSON.stringify(await tree(canonical3, canonical3)))]);
+ await dependencies(canonical3, metadata, path);
+ }
+ async function dependencies(directory, metadata, prefix) {
+ const names = [
+ ...new Set([
+ ...Object.keys(metadata.dependencies ?? {}),
+ ...Object.keys(metadata.optionalDependencies ?? {}),
+ ...Object.keys(metadata.peerDependencies ?? {})
+ ])
+ ].sort(compare);
+ for (const name of names) {
+ let child;
+ try {
+ child = await resolvePackage(directory, name);
+ } catch {
+ if (name in (metadata.optionalDependencies ?? {}) || metadata.peerDependenciesMeta?.[name]?.optional) {
+ records.push([`${prefix}/${name}`, "optional-absent"]);
+ continue;
+ }
+ throw new Error(`Cannot fingerprint missing installed dependency ${name}.`);
+ }
+ await visit(child, `${prefix}/${name}`);
+ }
+ }
+ await dependencies(root, { ...pkg, peerDependencies: {} }, "dependencies");
+ const inputs = {
+ version: 1,
+ engine: pkg.version,
+ workerHash,
+ build: worker.identity,
+ runtime: {
+ node: process.versions.node,
+ bun: process.versions.bun,
+ modules: process.versions.modules,
+ platform: process.platform,
+ arch: process.arch
+ },
+ dependencies: records
+ };
+ return { identity: `sha256:${digest3(JSON.stringify(inputs))}`, files, bytes };
+ } catch (error) {
+ return { reason: error instanceof Error ? error.message : String(error), files, bytes };
+ }
+}
+var digest3 = (bytes) => createHash9("sha256").update(bytes).digest("hex"), compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
+var init_runtime_identity = () => {};
+
+// src/local-runtime.ts
+import { dirname as dirname2, join as join6, resolve as resolve3 } from "node:path";
+import { fileURLToPath as fileURLToPath3 } from "node:url";
+function integer2(env, name, fallback, min, max) {
+ const value = env[name] === undefined ? fallback : Number(env[name]);
+ if (!Number.isInteger(value) || value < min || value > max)
+ throw new Error(`${name} requires an integer from ${min} to ${max}.`);
+ return value;
+}
+function createLocalToolContext(base = {}, env = process.env) {
+ const geometryPolicy = base.geometryPolicy ?? env.KILN_GEOMETRY_POLICY ?? "warn";
+ if (!["warn", "strict"].includes(geometryPolicy))
+ throw new Error("KILN_GEOMETRY_POLICY must be warn or strict.");
+ const mode = resolveEvaluatorMode({
+ KILN_EVALUATOR_MODE: env.KILN_EVALUATOR_MODE ?? "subprocess"
+ });
+ const deadlineMs = integer2(env, "KILN_EVALUATOR_TIMEOUT_MS", 60000, 1, 120000);
+ const heapMb = integer2(env, "KILN_EVALUATOR_HEAP_MB", 512, 64, 4096);
+ if (mode === "subprocess" && process.versions.bun && env.KILN_EVALUATOR_HEAP_MB !== undefined) {
+ throw new Error("KILN_EVALUATOR_HEAP_MB requires the packaged Node runtime.");
+ }
+ if (mode !== "in-process" && ["observe", "off"].includes(env.KILN_QA_MODE ?? "")) {
+ throw new Error("KILN_QA_MODE overrides are not transported to the local worker. Remove the override or explicitly select trusted KILN_EVALUATOR_MODE=in-process.");
+ }
+ const optimize = ["auto", "palette", "full"].includes(env.KILN_BAKE_OPTIMIZE ?? "") ? env.KILN_BAKE_OPTIMIZE : "off";
+ const instance2 = ["off", "auto", "on"].includes(env.KILN_BAKE_INSTANCE ?? "") ? env.KILN_BAKE_INSTANCE : "auto";
+ const maxGlbBytes = 16 * 1024 * 1024;
+ const maxResponseBytes = 32 * 1024 * 1024;
+ const evaluatorPort = {
+ async render(code, options = {}, controls = {}) {
+ if (controls.signal?.aborted) {
+ const { EvaluatorPortError: EvaluatorPortError2 } = await Promise.resolve().then(() => (init_protocol(), exports_protocol));
+ throw new EvaluatorPortError2("CANCELLED");
+ }
+ if (options.geometryPolicy !== undefined && !["warn", "strict"].includes(options.geometryPolicy))
+ throw new Error("geometryPolicy must be warn or strict");
+ const resolved2 = {
+ optimize,
+ instance: instance2,
+ ...options,
+ geometryPolicy: geometryPolicy === "strict" ? "strict" : options.geometryPolicy ?? "warn"
+ };
+ if (mode === "in-process") {
+ const result = await renderGLBInProcess(code, resolved2);
+ if (controls.signal?.aborted) {
+ const { EvaluatorPortError: EvaluatorPortError2 } = await Promise.resolve().then(() => (init_protocol(), exports_protocol));
+ throw new EvaluatorPortError2("CANCELLED");
+ }
+ return result;
+ }
+ const limits = { deadlineMs, maxGlbBytes, maxResponseBytes, ...controls };
+ if (mode === "isolated")
+ return renderGLBViaIsolatedEvaluator(code, resolved2, limits);
+ return renderGLBViaSubprocess(code, resolved2, {
+ ...limits,
+ ...!process.versions.bun ? { maxHeapMb: heapMb } : {}
+ });
+ }
+ };
+ const localExecution = {
+ mode,
+ terminable: mode !== "in-process",
+ ...mode !== "in-process" ? { deadlineMs } : {},
+ ...mode === "subprocess" && !process.versions.bun ? { nodeHeapMb: heapMb } : {},
+ ...mode !== "in-process" ? { maxGlbBytes, maxResponseBytes } : {},
+ totalMemoryLimited: false,
+ cacheScope: "process"
+ };
+ return {
+ ...base,
+ geometryPolicy,
+ programStore: base.programStore ?? new FileProgramStore(resolve3(env.KILN_PROGRAM_STORE ?? ".kiln/programs")),
+ evaluatorPort,
+ assetBuildOptions: {
+ optimize,
+ instance: instance2,
+ geometryPolicy,
+ qaMode: env.KILN_QA_MODE ?? "enforce",
+ evaluatorMode: mode
},
- {
- name: "validateAsset",
- signature: "validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture' | 'vegetation' | 'vehicle')",
- returns: "{ valid, errors, warnings }",
- category: "utility",
- description: "Checks geometry and material costs for the selected category. No default triangle limit; choose detail for the intended runtime and inspect measured draw calls.",
- example: "const v = validateAsset(root, 'prop');"
+ buildCache: new MemoryBuildCache,
+ evaluatorCacheIdentity: `kiln-local-${process.pid}-${++scope}:${JSON.stringify({ mode, optimize, instance: instance2, geometryPolicy, qa: env.KILN_QA_MODE, deadlineMs, heapMb })}`,
+ localExecution
+ };
+}
+async function createPackagedLocalToolContext(base = {}, env = process.env, installationRoot = fileURLToPath3(new URL("../", import.meta.url))) {
+ const context = createLocalToolContext(base, env);
+ const managed = () => {
+ const identity2 = context.evaluatorCacheIdentity;
+ const cached = createCachedEvaluatorPort(context.evaluatorPort, {
+ cache: context.buildCache,
+ identity: () => typeof identity2 === "function" ? identity2() : identity2
+ });
+ context.evaluatorPort = {
+ render: (code, options, controls) => cached.render(code, {
+ ...options,
+ geometryPolicy: context.geometryPolicy === "strict" ? "strict" : options?.geometryPolicy ?? context.geometryPolicy
+ }, controls)
+ };
+ context.evaluatorCacheManaged = true;
+ return context;
+ };
+ const policy = env.KILN_BUILD_CACHE ?? "disk";
+ if (!["disk", "memory", "off"].includes(policy))
+ throw new Error("KILN_BUILD_CACHE must be disk, memory, or off.");
+ if (policy === "off" || base.cacheEvaluations === false) {
+ context.cacheEvaluations = false;
+ context.localExecution.cacheScope = "disabled";
+ return context;
+ }
+ if (policy === "memory")
+ return managed();
+ if (process.versions.bun || context.localExecution.mode !== "subprocess") {
+ context.localExecution.cacheReason = "Disk reuse requires the packaged Node subprocess evaluator; this host uses process memory.";
+ return managed();
+ }
+ const identity = await installedRuntimeIdentity(installationRoot);
+ if (!identity.identity) {
+ context.localExecution.cacheReason = identity.reason;
+ return managed();
+ }
+ const cacheBytes = integer2(env, "KILN_BUILD_CACHE_MB", 128, 0, 1024) * 1024 * 1024;
+ const store = context.programStore;
+ const directory = resolve3(env.KILN_BUILD_CACHE_DIR ?? join6(store instanceof FileProgramStore ? dirname2(store.directory) : ".kiln", "cache", "builds"));
+ context.buildCache = new FileBuildCache(directory, cacheBytes);
+ context.evaluatorCacheIdentity = `${identity.identity}:${JSON.stringify({
+ execution: context.localExecution,
+ optimize: env.KILN_BAKE_OPTIMIZE ?? "off",
+ instance: env.KILN_BAKE_INSTANCE ?? "auto",
+ qa: env.KILN_QA_MODE ?? "enforce",
+ geometryPolicy: context.geometryPolicy,
+ timezone: env.TZ
+ })}`;
+ context.localExecution = {
+ ...context.localExecution,
+ cacheScope: "disk",
+ cacheBytes,
+ runtimeIdentity: identity.identity
+ };
+ return managed();
+}
+var scope = 0;
+var init_local_runtime = __esm(() => {
+ init_subprocess();
+ init_isolation();
+ init_render();
+ init_program_store_node();
+ init_build_cache();
+ init_build_cache_node();
+ init_runtime_identity();
+});
+
+// src/assets.ts
+import { z } from "zod";
+import { zipSync, unzipSync } from "three/addons/libs/fflate.module.js";
+function validateRecordShape(record5) {
+ const manifest = assetManifestSchema.parse(record5.manifest);
+ const names = Object.keys(record5.files);
+ if (names.length !== Object.keys(manifest.files).length || !names.includes("asset.glb"))
+ throw new Error("Asset file inventory mismatch");
+ let total = 0;
+ for (const name of names) {
+ if (!allowedFiles.has(name) || !manifest.files[name] || manifest.files[name].bytes !== record5.files[name].length)
+ throw new Error("Invalid asset file inventory");
+ total += record5.files[name].length;
+ }
+ if (total > ASSET_LIMIT || manifest.editable !== names.includes("source.kiln.js"))
+ throw new Error("Invalid asset size or source inventory");
+ if ((record5.files["source.kiln.js"]?.length ?? 0) > 1024 * 1024)
+ throw new Error("Source exceeds 1 MiB");
+ validateAssetGlb(record5.files["asset.glb"]);
+}
+function validateAssetGlb(bytes) {
+ if (bytes.length < 20 || bytes.length > ASSET_LIMIT)
+ throw new Error("Invalid GLB size");
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ if (view.getUint32(0, true) !== 1179937895 || view.getUint32(4, true) !== 2 || view.getUint32(8, true) !== bytes.length || view.getUint32(16, true) !== 1313821514)
+ throw new Error("Invalid GLB header");
+ const end = 20 + view.getUint32(12, true);
+ if (end > bytes.length)
+ throw new Error("Invalid GLB JSON length");
+ const json = JSON.parse(new TextDecoder().decode(bytes.subarray(20, end)));
+ for (const resource of [...json.buffers ?? [], ...json.images ?? []]) {
+ if (resource.uri && !String(resource.uri).startsWith("data:"))
+ throw new Error("GLB must embed its resources");
+ }
+}
+function encodeAssetBundle(records) {
+ if (!records.length || records.length > 100)
+ throw new Error("Bundle requires 1..100 revisions");
+ const files = {};
+ let total = 0;
+ for (const record5 of records) {
+ validateRecordShape(record5);
+ const prefix = `${record5.manifest.assetId}/${record5.manifest.revisionId}/`;
+ if (files[`${prefix}manifest.json`])
+ throw new Error("Duplicate bundle revision");
+ files[`${prefix}manifest.json`] = new TextEncoder().encode(JSON.stringify(record5.manifest, null, 2));
+ for (const [name, bytes] of Object.entries(record5.files))
+ files[prefix + name] = bytes;
+ }
+ for (const bytes of Object.values(files))
+ total += bytes.length;
+ if (total > ASSET_LIMIT)
+ throw new Error("Bundle exceeds 64 MiB");
+ return zipSync(files, { level: 0 });
+}
+function decodeAssetBundle(bytes) {
+ if (bytes.length > ASSET_LIMIT + 1024 * 1024)
+ throw new Error("Bundle exceeds 64 MiB");
+ let total = 0;
+ let count = 0;
+ const files = unzipSync(bytes, {
+ filter: (entry) => {
+ total += entry.originalSize;
+ count++;
+ if (total > ASSET_LIMIT || count > 400 || !/^[a-z][a-z0-9_-]{0,79}\/[a-z][a-z0-9_-]{0,79}\/(manifest\.json|asset\.glb|source\.kiln\.js|preview\.png)$/.test(entry.name))
+ throw new Error("Unsafe or oversized asset bundle");
+ return true;
}
- ];
+ });
+ const records = [];
+ const used = new Set;
+ for (const [path, data] of Object.entries(files)) {
+ if (!path.endsWith("/manifest.json"))
+ continue;
+ if (data.length > 1024 * 1024)
+ throw new Error("Manifest exceeds 1 MiB");
+ const manifest = assetManifestSchema.parse(JSON.parse(new TextDecoder().decode(data)));
+ const prefix = `${manifest.assetId}/${manifest.revisionId}/`;
+ if (path !== `${prefix}manifest.json`)
+ throw new Error("Bundle identity mismatch");
+ const record5 = { manifest, files: {} };
+ used.add(path);
+ for (const name of Object.keys(manifest.files)) {
+ if (!files[prefix + name])
+ throw new Error("Bundle file missing");
+ record5.files[name] = files[prefix + name];
+ used.add(prefix + name);
+ }
+ validateRecordShape(record5);
+ records.push(record5);
+ }
+ if (!records.length || used.size !== Object.keys(files).length)
+ throw new Error("Incomplete asset bundle");
+ return records;
+}
+var ASSET_LIMIT, assetIdSchema, hash, assetManifestSchema, allowedFiles;
+var init_assets = __esm(() => {
+ ASSET_LIMIT = 64 * 1024 * 1024;
+ assetIdSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+ hash = z.string().regex(/^sha256:[a-f0-9]{64}$/);
+ assetManifestSchema = z.object({
+ version: z.literal("kiln.asset.v1"),
+ assetId: assetIdSchema,
+ revisionId: assetIdSchema,
+ parentRevision: assetIdSchema.optional(),
+ name: z.string().min(1).max(200),
+ tags: z.array(z.string().max(80)).max(30),
+ createdAt: z.string().datetime(),
+ description: z.string().max(4000).optional(),
+ brief: z.string().max(8000).optional(),
+ attribution: z.object({
+ model: z.string().max(200).optional(),
+ harness: z.string().max(200).optional(),
+ author: z.string().max(200).optional()
+ }).optional(),
+ editable: z.boolean(),
+ files: z.record(z.string(), z.object({ sha256: hash, bytes: z.number().int().nonnegative().max(ASSET_LIMIT) })),
+ build: z.object({
+ engine: z.string(),
+ options: z.record(z.string(), z.unknown()),
+ warnings: z.array(z.string()),
+ integration: z.unknown().optional(),
+ qa: z.unknown().optional(),
+ dependencies: z.array(z.unknown()).optional(),
+ rebuild: z.enum(["engine-required", "external-dependencies-required"])
+ }).optional(),
+ preview: z.object({ fidelity: z.unknown().optional(), error: z.string().optional() }).optional()
+ });
+ allowedFiles = new Set(["asset.glb", "source.kiln.js", "preview.png"]);
+});
+
+// src/tools/programs.ts
+import { z as z2 } from "zod";
+function withProgramReferences(def, store) {
+ if (!(def.inputSchema instanceof z2.ZodObject))
+ throw new Error(`${def.name} must have an object input schema.`);
+ const inputSchema = def.inputSchema.extend({
+ code: z2.string().optional().describe("New source. Supply code OR programRef."),
+ programRef: refInput.optional(),
+ ...def.name === "kiln_edit" ? {
+ includeCode: z2.boolean().optional().describe("Return the full updated source. Defaults to false with programRef, true with code.")
+ } : {}
+ }).refine((input) => input.code !== undefined !== (input.programRef !== undefined), {
+ message: "Supply exactly one of code or programRef."
+ });
+ const summaries = {
+ kiln_validate: "Check program syntax and sandbox rules before building. Returns validation findings; use kiln_render to evaluate geometry and see the asset.",
+ kiln_render: "Build a program and return geometry metrics, exact part paths and images. Omit capture for six views; choose preset/cells for orbit grids or version kiln.capture.v1 plus shots for part-local framing, perspective and separate images. Check viewFidelity before judging materials. Failed builds return errors without an image.",
+ kiln_screenshot_animation: "Render sampled animation frames to check motion and attachments. Use shot for the shared camera controls, frameTimes for selected phases, and framing locked (default) or follow. The program must define animate(). Check viewFidelity before judging materials.",
+ kiln_view_interior: "Render roof-off floor-plan, dollhouse, and eye-level cutaway views. Optional versioned capture selects custom roof-off shots. Select a roof by nodeName or let Kiln resolve its role/name. Review roofsHidden and warnings for unresolved occlusion.",
+ kiln_inspect: "Inspect a part with context or isolation. Use legacy part/orbit controls or shot for exact paths, part-local axes and perspective. Use names from the source or render result; check viewFidelity before judging materials."
+ };
+ const description = def.name === "kiln_edit" ? "Apply exact-string replacements to a program revision and render the result (render:false skips images). Edits are ordered and atomic: missing or ambiguous matches fail without changing the base. Returns a new programRef, parentRef and diff; untouched text stays identical. Read anchors with kiln_source. Optional capture chooses the same cameras as kiln_render. Use includeCode only when full source is needed." : `${summaries[def.name] ?? def.description} Supply code once or reuse programRef from an earlier result. Returns programRef even for an invalid draft. kiln_source reads that revision.`;
+ return {
+ ...def,
+ inputSchema,
+ description,
+ run: async (input) => {
+ const args = inputSchema.parse(input);
+ const code = typeof args.code === "string" ? args.code : await store.get(args.programRef);
+ const parentRef = await retainProgram(store, code);
+ const output = await def.run({ ...args, code });
+ if (def.name !== "kiln_edit" || output.ok !== true || typeof output.code !== "string")
+ return { ...output, programRef: parentRef };
+ const programRef = await retainProgram(store, output.code);
+ const { code: updatedCode, ...rest } = output;
+ const includeCode = args.includeCode ?? args.code !== undefined;
+ const diff = typeof rest.diff === "string" ? rest.diff : "";
+ return {
+ ...rest,
+ programRef,
+ parentRef,
+ ...includeCode ? { code: updatedCode } : {
+ diff: diff.slice(0, 8000),
+ diffTruncated: diff.length > 8000
+ }
+ };
+ }
+ };
+}
+function createKilnSourceDef(store) {
+ const inputSchema = z2.object({
+ programRef: refInput,
+ offset: z2.number().int().min(0).default(0).describe("UTF-16 character offset; use nextOffset to continue."),
+ limit: z2.number().int().min(1).max(16000).default(8000).describe("Maximum characters returned."),
+ query: z2.string().min(1).max(1000).optional().describe("Find literal text at or after offset; return bounded surrounding source.")
+ });
+ return {
+ name: "kiln_source",
+ description: "Read a saved program revision without changing it. Returns exact source text in bounded pages, or searches for literal text with surrounding context. Copy edit anchors from code. Follow nextOffset for more; use matchOffset + 1 to find the next match. Offsets count UTF-16 characters, not bytes.",
+ inputSchema,
+ run: async (input) => {
+ const { programRef, offset, limit, query } = inputSchema.parse(input);
+ const source = await store.get(programRef);
+ const matchOffset = query ? source.indexOf(query, offset) : undefined;
+ const start = matchOffset !== undefined && matchOffset >= 0 ? Math.max(offset, matchOffset - Math.floor(limit / 4)) : Math.min(offset, source.length);
+ const code = matchOffset === -1 ? "" : source.slice(start, start + limit);
+ const end = start + code.length;
+ return {
+ programRef,
+ code,
+ offset: start,
+ nextOffset: matchOffset === -1 || end >= source.length ? null : end,
+ totalCharacters: source.length,
+ totalBytes: new TextEncoder().encode(source).length,
+ ...matchOffset !== undefined ? { matchOffset, found: matchOffset >= 0 } : {}
+ };
+ }
+ };
+}
+var refInput;
+var init_programs = __esm(() => {
+ init_program_store();
+ refInput = z2.string().regex(programRefPattern).describe("Returned p_ handle or full sha256 ref.");
});
// src/tools/discovery.ts
@@ -28653,6 +28756,17 @@ function collectSceneMetrics(root) {
}
return { meshes, materials: materialSet.size, bbox, lowestPart };
}
+function withSyntaxDetail(message, code) {
+ if (!message.startsWith(evaluatorOutcomeMessage("EXECUTION_REJECTED")))
+ return message;
+ let syntax;
+ try {
+ syntax = validate(code).errors.find((error) => error.startsWith("Syntax error:"));
+ } catch {
+ return message;
+ }
+ return syntax ? `${message} ${syntax}` : message;
+}
async function runRender(input, context) {
try {
const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);
@@ -28671,6 +28785,7 @@ async function runRender(input, context) {
tris: rendered.tris,
meshes: metrics.meshes,
materials: metrics.materials,
+ ...rendered.meta.instanceability ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials } : {},
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
...instanceability ? {
@@ -28685,7 +28800,7 @@ async function runRender(input, context) {
} catch (err) {
return {
ok: false,
- error: err instanceof Error ? err.message : String(err),
+ error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
warnings: []
};
}
@@ -28709,7 +28824,7 @@ async function runScreenshot(input, context) {
} catch (err) {
return {
ok: false,
- error: err instanceof Error ? err.message : String(err),
+ error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
warnings: []
};
}
@@ -28742,6 +28857,7 @@ async function runRenderViews(input, context) {
tris: rendered.tris,
meshes: metrics.meshes,
materials: metrics.materials,
+ ...rendered.meta.instanceability ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials } : {},
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
views: grid2.views,
@@ -28838,6 +28954,7 @@ async function runRenderViews(input, context) {
tris: rendered.tris,
meshes: metrics.meshes,
materials: metrics.materials,
+ ...rendered.meta.instanceability ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials } : {},
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
...rendered.meta.instanceability ? {
@@ -28861,7 +28978,7 @@ async function runRenderViews(input, context) {
} catch (err) {
return {
ok: false,
- error: err instanceof Error ? err.message : String(err),
+ error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
warnings: []
};
}
@@ -29520,6 +29637,7 @@ var init_registry2 = __esm(() => {
init_discovery();
init_build_cache();
init_validation();
+ init_protocol();
init_render();
init_list_primitives();
init_evaluator();
diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjs
index bd38569a..530e5d11 100644
--- a/dist/evaluator-worker.mjs
+++ b/dist/evaluator-worker.mjs
@@ -16,7 +16,7 @@ function rethrowAuthoringError(error) {
}
throw error;
}
-var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", AuthoringDiagnosticError;
+var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_list_primitives to confirm the exact name and signature; the sandbox exposes only those globals.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", AuthoringDiagnosticError;
var init_authoring_diagnostic = __esm(() => {
AuthoringDiagnosticError = class AuthoringDiagnosticError extends Error {
diagnostic;
@@ -17769,6 +17769,928 @@ var init_texture_resolver = __esm(() => {
DEFAULT_TEXTURE_RESOLVER = createTextureResolver();
});
+// src/geometry-catalog.ts
+var geometryPrimitives;
+var init_geometry_catalog = __esm(() => {
+ geometryPrimitives = [
+ {
+ name: "copyGeometry",
+ signature: "copyGeometry(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "instancing",
+ description: "Returns an independent geometry with copied vertex buffers. Use before direct mutation of a cached primitive.",
+ example: "const editable = copyGeometry(boxGeo(1, 1, 1)); editable.translate(0, 0.5, 0);"
+ },
+ {
+ name: "copyMaterial",
+ signature: "copyMaterial(material: Material)",
+ returns: "THREE.Material (same subtype)",
+ category: "instancing",
+ description: "Copies material properties so edits do not change other parts. Referenced textures remain shared.",
+ example: "const red = copyMaterial(steel); red.color.set(0xaa2222);"
+ },
+ {
+ name: "meshGeo",
+ signature: "meshGeo({ positions: number[], indices?: number[], normals?: number[], uvs?: number[], tangents?: number[] })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Builds an owned triangle mesh from flat numeric arrays. Validates finite values, attribute lengths and indices; computes normals if absent. Counterclockwise winding.",
+ example: "const triangle = meshGeo({ positions: [0,0,0, 1,0,0, 0,1,0], indices: [0,1,2] });"
+ },
+ {
+ name: "parametricSurface",
+ signature: "parametricSurface(sample: (u,v) => [x,y,z], opts?: { u?: [0,1], v?: [0,1], uSegments?: 24, vSegments?: 24, periodicU?: false, periodicV?: false, orientation?: 'uv'|'vu' })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Samples an equation into an owned surface with UVs. Periodic endpoints must coincide; UV seams retain matching normals. A surface is not automatically a watertight solid.",
+ example: "const canopy = parametricSurface((u,v) => [u, 0.3*Math.sin(u*3)*Math.cos(v*2), v], { u: [-2,2], v: [-1,1] });"
+ },
+ {
+ name: "geometryDiagnostics",
+ signature: "geometryDiagnostics(geometry: BufferGeometry, tolerance?: 1e-6)",
+ returns: "{ vertices, triangles, boundaryEdges, nonManifoldEdges, orientationConflicts, degenerateTriangles, invalidIndices, nonFiniteVertices }",
+ category: "utility",
+ description: "Counts mesh topology problems after position-based seam matching. Open boundaries are valid for sheets; closed edges alone do not prove a self-intersection-free solid.",
+ example: "const topology = geometryDiagnostics(shell);"
+ },
+ {
+ name: "creaseNormals",
+ signature: "creaseNormals(geometry: BufferGeometry, opts?: { angle?: 60, tolerance?: number })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Returns owned geometry with angle-limited smooth normals, preserving UV corners. Angle is degrees. Invalidates tangents; use after shaping for sharp rims and smooth walls.",
+ example: "const shell = creaseNormals(cylinderGeo(1,1,2,32), { angle: 45 });"
+ },
+ {
+ name: "bend",
+ signature: "bend(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Bends local +Y toward +X through angle degrees. Returns owned geometry and updated normals/bounds; preserves UVs, invalidates tangents. Frame rotation is Euler XYZ degrees.",
+ promptNotes: "Deformation interval uses local Y distances; outside vertices stay unchanged. Add enough segments before bending. Falloff returns 0..1; use it to avoid a discontinuity at a selected interval boundary.",
+ example: "const arch = bend(planeGeo(1,4,4,32), { angle: 90 });"
+ },
+ {
+ name: "twist",
+ signature: "twist(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Rotates the cross-section progressively around local +Y, reaching angle degrees at the end. Returns owned geometry; frame rotation uses Euler XYZ degrees.",
+ example: "const spiral = twist(column, { angle: 120 });"
+ },
+ {
+ name: "taper",
+ signature: "taper(geometry, { startScale?: [1,1], endScale: [x,z], frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Scales local X/Z across the local Y interval using positive start/end scale pairs. Returns owned geometry; preserves UVs and invalidates tangents.",
+ example: "const narrowed = taper(column, { endScale: [0.4,0.7] });"
+ },
+ {
+ name: "displace",
+ signature: "displace(geometry, offset: ([x,y,z], t) => [dx,dy,dz], opts?: { frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Adds an authored displacement vector in the chosen local frame. Returns owned geometry; callback coordinates are local and t is normalized along the interval.",
+ example: "const rippled = displace(surface, ([x,y,z]) => [0, 0.1*Math.sin(x*8), 0]);"
+ },
+ {
+ name: "sweepProfile",
+ signature: "sweepProfile(profile: [x,z][], path: [x,y,z][], opts?: { cap?: true, closed?: false, up?: [x,y,z], twist?: 0, scale?: number | [x,z][] })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Sweeps a simple noncircular profile along polyline stations using transported frames. Supports total twist in degrees and per-station scales. Generates UVs and optional caps.",
+ promptNotes: "First version supports one simple profile without holes. Closed paths omit the repeated endpoint and require twist to be a multiple of 360. up sets the initial profile +Z direction and cannot parallel the path. Tight-turn warnings do not replace visual inspection for self-intersections.",
+ example: "const rail = sweepProfile([[-.1,-.2],[.1,-.2],[.1,.2],[-.1,.2]], [[0,0,0],[0,1,0],[1,2,0]]);"
+ },
+ {
+ name: "loftProfiles",
+ signature: "loftProfiles(sections: { profile: [x,z][], frame?: { origin, rotation } }[], opts?: { cap?: true })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Joins corresponding simple profiles in explicit local XZ planes. Each frame uses Euler XYZ degrees and local +Y along the loft. Profiles need equal point counts and corresponding vertices.",
+ promptNotes: "No holes or automatic profile correspondence. Opposite winding is normalized while preserving the first point. Caps close boundaries but do not prove the loft has no self-intersections.",
+ example: "const hull = loftProfiles([{ profile: wide }, { profile: narrow, frame: { origin: [0,2,0] } }]);"
+ },
+ {
+ name: "implicitSurface",
+ signature: "await implicitSurface(sample: ([x,y,z]) => signedValue, { bounds: { min, max }, edgeLength, maxCells?: 1000000, maxEvaluations?: 8000000, level?: 0, tolerance?: -1, smooth?: true })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "geometry",
+ description: "Experimental positive-inside implicit field sampled into a solid mesh. Requires explicit bounds and resolution; checks grid size and actual evaluation count. Output has no UVs.",
+ promptNotes: "Use async build and await. Smaller edgeLength increases cost sharply. This helper cannot stop a callback that never returns; the host evaluator process provides that boundary. Thin features and geometric accuracy require inspection.",
+ example: "const blob = await implicitSurface(([x,y,z]) => 1-Math.hypot(x,y,z), { bounds: { min: [-1.2,-1.2,-1.2], max: [1.2,1.2,1.2] }, edgeLength: 0.15 });"
+ }
+ ];
+});
+
+// src/list-primitives.ts
+function listPrimitives() {
+ return PRIMITIVES.map((p) => ({ ...p }));
+}
+var PRIMITIVES;
+var init_list_primitives = __esm(() => {
+ init_geometry_catalog();
+ PRIMITIVES = [
+ ...geometryPrimitives,
+ {
+ name: "createRoot",
+ signature: "createRoot(name: string)",
+ returns: "THREE.Object3D",
+ category: "structure",
+ description: "Creates the root Object3D for an asset. Call first in build().",
+ example: "const root = createRoot('FuelDrum');"
+ },
+ {
+ name: "createPivot",
+ signature: "createPivot(name: string, position?: [x, y, z], parent?: Object3D)",
+ returns: "THREE.Object3D (prefixed `Joint_`)",
+ category: "structure",
+ description: "Creates an empty pivot node for skeletal animation. Name is auto-prefixed with `Joint_`.",
+ example: "const hip = createPivot('Hip', [0, 1, 0], root);"
+ },
+ {
+ name: "createJointChain",
+ signature: "createJointChain(name, segments: { role, offset, aliases?, side?, localForwardAxis?, localBendAxis?, endEffector?, contact? }[], opts?: { parent?, parentRole? })",
+ returns: "{ root, end, nodes, byRole, descriptors }",
+ category: "structure",
+ description: "Creates one body-plan-neutral deterministic Joint_* chain with explicit parent edges, rest frames, local axes, end effectors, contacts, and semantic metadata.",
+ example: "const leg = createJointChain('LegL', [{ role: 'hip.left', offset: [0, 1, -0.2], side: 'left' }, { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' }, { role: 'ankle.left', offset: [0, -0.5, 0], side: 'left', endEffector: true, contact: true }], { parent: root });",
+ promptNotes: "Use only the resolved body-plan graph. Offsets are local to the previous joint; contact end effectors must land at world Y=0."
+ },
+ {
+ name: "createVehicleFrame",
+ signature: "createVehicleFrame(name, opts?: { chassis?, axles?, seats?, contacts?, steering?, propulsion?, parent? })",
+ returns: "{ root, chassis, axles, seats, contacts, steering, propulsion }",
+ category: "structure",
+ description: "Creates a canonical +X-forward/+Y-up/+Z-right vehicle frame with typed semantic sockets for chassis, support, steering, and propulsion.",
+ example: "const frame = createVehicleFrame('CarFrame', { axles: [{ id: 'front', position: [1.2, 0.45, 0] }, { id: 'rear', position: [-1.2, 0.45, 0] }], parent: root });",
+ promptNotes: "Generated vehicles keep +X as front. Boats and other non-wheeled subtypes use declared support/propulsion sockets, not wheel rules."
+ },
+ {
+ name: "createWheelGeometrySet",
+ signature: "createWheelGeometrySet(radius: number, width: number)",
+ returns: "{ tire, rim, hub } shared THREE.BufferGeometry set",
+ category: "instancing",
+ description: "Creates one reusable +Z-axle tire/rim/hub geometry set for instanced wheel assemblies.",
+ example: "const wheelGeo = createWheelGeometrySet(0.45, 0.22);"
+ },
+ {
+ name: "createWheelAssembly",
+ signature: "createWheelAssembly(name, { tire, rim, hub? }, { radius, width, side, index, position?, rimRadius?, hubRadius?, steering?, loadBearing?, geometries?, parent? })",
+ returns: "{ root, steeringPivot?, spinPivot, tire, rim, hub, contact, radius, width, side, index, spinAxis }",
+ category: "structure",
+ description: "Creates one axle-centered wheel pivot containing concentric tire/rim/hub roles, a contact marker, +Z spin frame, and optional steering pivot.",
+ example: "createWheelAssembly('FrontLeft', { tire: rubber, rim: metal }, { radius: 0.45, width: 0.22, side: 'left', index: 'front', position: [1.2, 0.45, -0.9], steering: true, geometries: wheelGeo, parent: frame.root });",
+ promptNotes: "Keep tire, rim, and hub descendants concentric at the axle pivot. Reuse one geometry set across matching wheels."
+ },
+ {
+ name: "createPart",
+ signature: "createPart(name, geometry, material, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, pivot, parent })",
+ returns: "THREE.Object3D (mesh or wrapping pivot)",
+ category: "structure",
+ description: "Creates a mesh, optionally wrapped in a pivot, and attaches it to `opts.parent`. `rotation` is in DEGREES (like rotationTrack), NOT radians: [0, 0, 90] is a quarter turn; [0, 0, 1.57] is a no-op.",
+ example: "createPart('Barrel', cylinderGeo(0.1, 0.1, 1), gameMaterial(0x556b2f), { position: [0, 0.5, 0], rotation: [0, 0, 90], parent: root });",
+ promptNotes: "AUTO-ADDS to opts.parent. NEVER call parent.add(createPart(...)) — pass { parent } instead. rotation is DEGREES — writing radians (e.g. 0.785 or Math.PI/4) silently produces ~zero rotation."
+ },
+ {
+ name: "beamBetween",
+ signature: "beamBetween(name, start: [x,y,z], end: [x,y,z], radius, material, opts?: { segments, parent })",
+ returns: "THREE.Object3D (prefixed `Mesh_`)",
+ category: "structure",
+ description: "Creates a cylindrical rail/strut exactly between two endpoints. Use for braces, gun barrels, skid struts, cables, and scaffolding.",
+ example: "beamBetween('SkidBraceA', [0.8, 0.3, 0.7], [0.8, 1.0, 0.45], 0.025, black, { parent: root });"
+ },
+ {
+ name: "snapTo",
+ signature: "snapTo(part: Object3D, host: Object3D, opts?: { axis?: 'x'|'y'|'z', overlap?: 0.02 })",
+ returns: "THREE.Object3D (the part, for chaining)",
+ category: "structure",
+ description: 'Translates `part` by the minimal vector that brings its bounding box into contact with `host` (plus a small overlap). The direct cure for a "Floating parts" warning — attach the part instead of eyeballing a corrective offset. No-op if they already touch.',
+ example: `const scope = createPart('Scope', cylinderXGeo(0.04, 0.04, 0.3), steel, { parent: root, position: [0.1, 0.32, 0] });
+snapTo(scope, receiver);`
+ },
+ {
+ name: "createLadder",
+ signature: "createLadder(name, { bottom, top, material, width?, rungCount?, railRadius?, rungRadius?, widthAxis?, parent? })",
+ returns: "{ leftRail: Object3D, rightRail: Object3D, rungs: Object3D[] }",
+ category: "structure",
+ description: "Builds two continuous rails plus evenly-spaced rungs. Use this instead of loose boxes for ladders.",
+ example: "createLadder('TowerLadder', { bottom: [0,0,0], top: [0,2.2,0], width: 0.45, rungCount: 7, material: steel, parent: root });"
+ },
+ {
+ name: "createWingPair",
+ signature: "createWingPair(name, material, { rootZ, span, rootChord, tipChord, sweep?, thickness?, dihedral?, rootX?, rootY?, parent? })",
+ returns: "{ right: Object3D, left: Object3D }",
+ category: "structure",
+ description: "Creates mirrored trapezoid aircraft wings with roots attached at +/-rootZ. Use for aircraft wings and helicopter stub wings.",
+ example: "createWingPair('MainWing', olive, { rootX: 0, rootY: 1.0, rootZ: 0.42, span: 2.4, rootChord: 0.9, tipChord: 0.35, sweep: 0.25, dihedral: 0.08, parent: root });"
+ },
+ {
+ name: "room",
+ signature: "room(name, material, { width?, depth?, height?, wallThickness?, floor?, floorThickness?, openings?: [{ wall: 'front'|'back'|'left'|'right', kind?: 'door'|'window', offset?, width?, height?, sill? }], parent? })",
+ returns: "{ root: Object3D, walls: { front, back, left, right }, floor: Object3D | null }",
+ category: "structure",
+ description: "Builds a HOLLOW, enterable room: four thin walls + a floor, human-scaled (defaults: 2.8m ceiling, a centered 1.1x2.1m front door so it is enterable by default). `front` faces +X; the floor sits on the ground. The keystone of an architecture asset — add a roof with createRoofPlanes and fixtures as separate parts.",
+ example: "const { root: hut } = room('Hut', wood, { width: 5, depth: 4, height: 2.8, openings: [{ wall: 'front', kind: 'door' }, { wall: 'right', kind: 'window' }], parent: root });",
+ promptNotes: "Use for any building the player enters. Do NOT model a building as a solid block — room() guarantees real interior space and a doorway gap. Pass openings to add windows / side doors."
+ },
+ {
+ name: "wallWithOpening",
+ signature: "wallWithOpening(name, material, { length, height, thickness, axis?: 'x'|'z', opening?: { kind?: 'door'|'window', offset?, width?, height?, sill? }, parent? })",
+ returns: "THREE.Object3D (wall container)",
+ category: "structure",
+ description: "A single wall panel with an optional real door/window cut, composed from solid box segments (side panels + lintel + window sill) — no CSG. Base at local Y=0, centered on the run axis. Use to compose custom building layouts or interior dividing walls beyond the default room().",
+ example: "wallWithOpening('Partition', plaster, { length: 4, height: 2.8, thickness: 0.12, axis: 'x', opening: { kind: 'door', offset: 0.5 }, parent: root });"
+ },
+ {
+ name: "createRoofPlanes",
+ signature: "createRoofPlanes(name, material, { width, depth, height, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",
+ returns: "{ root: Object3D, slopes: [Object3D, Object3D] }",
+ category: "structure",
+ description: "A pitched roof: two thin slopes meeting at one ridge and falling DOWN-AND-OUTWARD (opposite tilts — never mirrored the same way), footprint-matched with an eave overhang. Eave at local Y=0, ridge at Y=height, so position the group at Y=wallHeight. Returns a named group (e.g. `Roof`) the engine can lift to reveal the interior.",
+ example: `const { root: roof } = createRoofPlanes('Roof', shingle, { width: 5, depth: 4, height: 1.6, overhang: 0.4, ridgeAxis: 'x', parent: root });
+roof.position.y = 2.8;`,
+ promptNotes: "The two slopes must fall AWAY from each other from the ridge — createRoofPlanes does this for you. Drop it onto the walls (position.y = wall height)."
+ },
+ {
+ name: "createGableRoof",
+ signature: "createGableRoof(name, material, { spanX, spanZ, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",
+ returns: "{ root, slopes: [Object3D, Object3D], faces: [RoofFaceFrame, RoofFaceFrame], rise, pitchDegrees }",
+ category: "structure",
+ description: "Explicit-axis gable roof using unambiguous footprint spans. Each face owns a rigid frame with ridge tangent, outward normal, downhill direction, ridge/eave endpoints, dimensions, and a live local-to-world transform.",
+ example: "const roof = createGableRoof('Roof', shingles, { spanX: 8, spanZ: 5, pitchDegrees: 35, overhang: 0.35, ridgeAxis: 'x', parent: root });",
+ promptNotes: "Prefer this over width/depth roof math. ridgeAxis is the direction of the ridge; roof panels run along each returned face downhill direction."
+ },
+ {
+ name: "createGableEndPanel",
+ signature: "createGableEndPanel(name, material, { span, rise, thickness?, ridgeAxis?: 'x'|'z', side?: 'positive'|'negative', openings?: [{ id?, offset?, bottom?, width, height }], parent? })",
+ returns: "{ root, geometry, openings }",
+ category: "structure",
+ description: "Exact thick triangular end closure for a gable roof, with optional rectangular openings cut from the geometry and semantic boundary metadata.",
+ example: "createGableEndPanel('FrontGable', siding, { span: 5, rise: 1.8, ridgeAxis: 'x', side: 'positive', parent: root });"
+ },
+ {
+ name: "createGableShell",
+ signature: "createGableShell(name, { wall, roof, floor?, gable? }, { spanX, spanZ, wallHeight?, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, wallThickness?, floorThickness?, closedEnds?, enterable?, openings?, gableOpenings?, parent? })",
+ returns: "{ root, walls, floor, roof, gables, openings }",
+ category: "structure",
+ description: "Closed-by-default, correct-by-construction gable building: hollow room, floor, two opposing roof slopes, two complete gable ends, and a real front doorway when enterable.",
+ example: "const house = createGableShell('House', { wall: plaster, roof: shingles }, { spanX: 8, spanZ: 5, wallHeight: 2.8, pitchDegrees: 35, ridgeAxis: 'x', parent: root });",
+ promptNotes: "Use for complete gable buildings. It stamps wall, floor, slope, gable, opening, adjacency, coverage, and separability semantics for deterministic QA and roof-off views."
+ },
+ {
+ name: "createRoofSurfaceLayout",
+ signature: "createRoofSurfaceLayout(name, material, { face, kind: 'panels'|'shingles'|'seams'|'corrugations', parent?, panelWidth?, rowHeight?, spacing?, thickness? })",
+ returns: "{ root, items: Object3D[] }",
+ category: "structure",
+ description: "Places roof-local panels, shingles, seams, or corrugations from a returned RoofFaceFrame, so repeated elements run ridge-to-eave for either ridge axis without manual Euler rotations.",
+ example: "for (const face of roof.faces) createRoofSurfaceLayout('Panels_' + face.side, metal, { face, kind: 'panels', parent: roof.root });",
+ promptNotes: "Always pass the face object returned by createGableRoof/createGableShell. Never infer the panel rotation from world axes."
+ },
+ {
+ name: "createStairs",
+ signature: "createStairs(name, material, { steps?, totalRise, totalRun, width, axis?: 'x'|'z', treadThickness?, riser?, parent? })",
+ returns: "{ root: Object3D, steps: Object3D[] }",
+ category: "structure",
+ description: "A straight flight of stairs: box treads (with optional risers) climbing totalRise over totalRun from local origin toward +axis. Use for porch/entry steps or to connect storeys in a multi-storey building.",
+ example: "createStairs('Porch', stone, { steps: 4, totalRise: 0.6, totalRun: 1.0, width: 1.4, axis: 'x', parent: root });"
+ },
+ {
+ name: "boxGeo",
+ signature: "boxGeo(width: number, height: number, depth: number)",
+ returns: "THREE.BoxGeometry",
+ category: "geometry",
+ description: "6-face box. 12 tris regardless of size. Cheapest geometry.",
+ example: "const geo = boxGeo(1, 0.5, 2);"
+ },
+ {
+ name: "sphereGeo",
+ signature: "sphereGeo(radius: number, widthSegments?: 8, heightSegments?: 6)",
+ returns: "THREE.SphereGeometry",
+ category: "geometry",
+ description: "UV sphere. Default 8x6 segments = 84 tris. Bump segments for smoother curves.",
+ example: "const geo = sphereGeo(0.5, 12, 8);"
+ },
+ {
+ name: "cylinderGeo",
+ signature: "cylinderGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Y-axis cylinder. Use radiusTop != radiusBottom for cones / tapered pieces.",
+ example: "const geo = cylinderGeo(0.25, 0.25, 1, 12);"
+ },
+ {
+ name: "cylinderYGeo",
+ signature: "cylinderYGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Alias for cylinderGeo — a Y-axis cylinder. Provided because the sandbox exposes cylinderXGeo / cylinderZGeo and the symmetric Y form is commonly reached for.",
+ example: "const geo = cylinderYGeo(0.25, 0.25, 1, 12);"
+ },
+ {
+ name: "cylinderXGeo",
+ signature: "cylinderXGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Cylinder pre-rotated to run along +X/-X. Use for fuselages, cannons, barrels, axles, and forward-facing tubes.",
+ example: "const geo = cylinderXGeo(0.1, 0.1, 1.2, 12);"
+ },
+ {
+ name: "cylinderZGeo",
+ signature: "cylinderZGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Cylinder pre-rotated to run along +Z/-Z. Use for side-mounted weapons, rails, crossbars, and pipes.",
+ example: "const geo = cylinderZGeo(0.08, 0.08, 0.9, 10);"
+ },
+ {
+ name: "cylinderOnAxis",
+ signature: "cylinderOnAxis(center: [x,y,z], normal: [x,y,z], radiusBottom: number, height: number, opts?: { radiusTop?, segments? })",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Frame-first cylinder: position + axis specified directly, no post-hoc rotation. Use when the cylinder needs to point along a non-cardinal direction (struts inside CSG operands, antennas off a tilted surface). For cardinal axes prefer the terser cylinderXGeo / cylinderYGeo / cylinderZGeo helpers.",
+ example: "const strut = cylinderOnAxis([0.5, 0.7, 0], [1, 1, 0.3], 0.05, 0.9);"
+ },
+ {
+ name: "capsuleGeo",
+ signature: "capsuleGeo(radius: number, height: number, segments?: 6)",
+ returns: "THREE.CapsuleGeometry",
+ category: "geometry",
+ description: "Stadium shape (cylinder with hemispherical caps). Good for limbs.",
+ example: "const geo = capsuleGeo(0.1, 0.5, 6);"
+ },
+ {
+ name: "capsuleYGeo",
+ signature: "capsuleYGeo(radius: number, height: number, segments?: 6)",
+ returns: "THREE.CapsuleGeometry",
+ category: "geometry",
+ description: "Alias for capsuleGeo — a Y-axis capsule. Provided for symmetry with capsuleXGeo / capsuleZGeo.",
+ example: "const geo = capsuleYGeo(0.1, 0.5, 6);"
+ },
+ {
+ name: "capsuleXGeo",
+ signature: "capsuleXGeo(radius: number, length: number, segments?: 6)",
+ returns: "THREE.CapsuleGeometry",
+ category: "geometry",
+ description: "Capsule pre-rotated to run along +X/-X. Use for aircraft bodies, rounded vehicle hulls, and missiles.",
+ example: "const geo = capsuleXGeo(0.35, 2.4, 10);"
+ },
+ {
+ name: "capsuleZGeo",
+ signature: "capsuleZGeo(radius: number, length: number, segments?: 6)",
+ returns: "THREE.CapsuleGeometry",
+ category: "geometry",
+ description: "Capsule pre-rotated to run along +Z/-Z. Use for lateral pods, floats, and side tanks.",
+ example: "const geo = capsuleZGeo(0.18, 1.1, 8);"
+ },
+ {
+ name: "coneGeo",
+ signature: "coneGeo(radius: number, height: number, segments?: 8)",
+ returns: "THREE.ConeGeometry",
+ category: "geometry",
+ description: "Y-axis cone (pointed up). Use for spikes, roofs, projectiles.",
+ example: "const geo = coneGeo(0.3, 0.8, 8);"
+ },
+ {
+ name: "coneYGeo",
+ signature: "coneYGeo(radius: number, height: number, segments?: 8)",
+ returns: "THREE.ConeGeometry",
+ category: "geometry",
+ description: "Alias for coneGeo — a Y-axis cone (point +Y). Provided for symmetry with coneXGeo / coneZGeo.",
+ example: "const geo = coneYGeo(0.3, 0.8, 8);"
+ },
+ {
+ name: "coneXGeo",
+ signature: "coneXGeo(radius: number, length: number, segments?: 8)",
+ returns: "THREE.ConeGeometry",
+ category: "geometry",
+ description: "Cone pre-rotated so its point faces +X. Use for noses, rockets, shells, and forward-facing tips.",
+ example: "const geo = coneXGeo(0.18, 0.45, 12);"
+ },
+ {
+ name: "coneZGeo",
+ signature: "coneZGeo(radius: number, length: number, segments?: 8)",
+ returns: "THREE.ConeGeometry",
+ category: "geometry",
+ description: "Cone pre-rotated so its point faces +Z. Use for side-facing projectiles and tips.",
+ example: "const geo = coneZGeo(0.12, 0.35, 10);"
+ },
+ {
+ name: "taperConeGeo",
+ signature: "taperConeGeo(radiusBottom: number, radiusTop: number, height: number, axis?: 'x'|'y'|'z', segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Truncated cone (frustum) — exposes both bottom and top radius. radiusTop=0 matches coneGeo, radiusTop=radiusBottom matches cylinderGeo. Use for pylon caps, soda cans, lampshades, anything tapered that does not come to a point. axis selects orientation (default Y).",
+ example: "const cap = taperConeGeo(0.3, 0.18, 0.4); // frustum"
+ },
+ {
+ name: "torusGeo",
+ signature: "torusGeo(radius: number, tube: number, radialSegments?: 8, tubularSegments?: 12)",
+ returns: "THREE.TorusGeometry",
+ category: "geometry",
+ description: "Donut shape. For rings, tyres, barrel ribs.",
+ example: "const geo = torusGeo(0.4, 0.04, 8, 16);"
+ },
+ {
+ name: "planeGeo",
+ signature: "planeGeo(width: number, height: number, widthSegments?: 1, heightSegments?: 1)",
+ returns: "THREE.PlaneGeometry",
+ category: "geometry",
+ description: "Flat quad for TEXTURED surfaces (ground, signs, walls with albedo maps). For solid-color decals like red stars, hull numbers, stamps, or window cutouts on no-texture assets use decalBox — a bare planeGeo without a texture will render as a disconnected 2-tri square and get flagged as a stray plane.",
+ example: "const geo = planeGeo(4, 4);"
+ },
+ {
+ name: "decalBox",
+ signature: "decalBox(width: number, height: number, depth?: 0.01)",
+ returns: "THREE.BoxGeometry",
+ category: "geometry",
+ description: "Thin box for solid-color surface decals: red stars, hull numbers, stamps, no-texture windows. Unlike planeGeo, has real depth so it visibly attaches to its host surface. Must be placed on a surface with position + rotation.",
+ example: `const star = decalBox(0.18, 0.18, 0.01);
+createPart('Mesh_StarPort', star, gameMaterial(0xc61f2a), { position: [0.4, 0.6, 0.41], parent: fuselage });`,
+ promptNotes: "Offset at least 0.01 outside the host surface to avoid z-fighting (a 0.8-wide hull has faces at z=±0.4, so place the decal at z=±0.41)."
+ },
+ {
+ name: "foliageCardGeo",
+ signature: "foliageCardGeo(opts?: { width?, height?, yPivot?: 0..1 })",
+ returns: "THREE.PlaneGeometry",
+ category: "geometry",
+ description: "Single-quad foliage card with a configurable Y pivot. yPivot=0 plants the quad on the ground. Pair with an alpha-tested material and a leaf/plant sprite.",
+ example: `const leaves = await materialRecipe('kiln.material.leaf.v1');
+const quad = foliageCardGeo({ width: 4, height: 6, yPivot: 0 });
+createPart('Mesh_Fern', quad, leaves, { parent: root });`
+ },
+ {
+ name: "crossedQuadsGeo",
+ signature: "crossedQuadsGeo(opts?: { width?, height?, planes?: 2 | 3, yPivot? })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Cross-billboard bush primitive: 2 or 3 planes intersecting along the Y axis. Reads as a dense plant from any angle, cheaper than real geometry.",
+ example: `const leaves = await materialRecipe('kiln.material.leaf.v1');
+const bush = crossedQuadsGeo({ width: 2, height: 2, planes: 3 });
+createPart('Mesh_Bush', bush, leaves, { parent: root });`
+ },
+ {
+ name: "octaGridPlane",
+ signature: "octaGridPlane({ tilesX, tilesY, width?, height?, yPivot? })",
+ returns: "THREE.PlaneGeometry",
+ category: "geometry",
+ description: "Atlas-ready billboard quad. UVs are pre-scaled to cover one tile of a tilesX×tilesY atlas; the consumer shader adds per-instance tile offsets at draw time.",
+ example: "const card = octaGridPlane({ tilesX: 4, tilesY: 4, width: 6, height: 6 });"
+ },
+ {
+ name: "wingGeo",
+ signature: "wingGeo(opts?: { span, rootChord, tipChord, sweep, thickness, dihedral })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Trapezoid wing panel. Local root edge is at Z=0, span extends toward +Z, positive sweep moves the tip aft along -X.",
+ example: "const geo = wingGeo({ span: 2.2, rootChord: 0.8, tipChord: 0.3, sweep: 0.25, dihedral: 0.08 });"
+ },
+ {
+ name: "gearGeo",
+ signature: "gearGeo(opts?: { teeth?: 12, rootRadius?: 0.8, tipRadius?: 1.0, boreRadius?: 0.2, height?: 0.3, toothWidthFrac?: 0.5 })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Stylized gear with flat edges and an optional center bore; no CSG. Use boreRadius < rootRadius < tipRadius. Radii are absolute: an omitted rootRadius stays 0.8 when tipRadius changes. Set all three radii for small gears.",
+ example: `const g = gearGeo({ teeth: 28, rootRadius: 0.063, tipRadius: 0.075, boreRadius: 0.012, height: 0.024 });
+createPart('Gear', g, gameMaterial(0x909090, { metalness: 0.8 }), { parent: root });`
+ },
+ {
+ name: "bladeGeo",
+ signature: "bladeGeo(opts?: { length?: 1.5, baseWidth?: 0.1, thickness?: 0.015, tipLength?: 0.25, edgeBevel?: 0 })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Parametric sword blade: rectangular base tapering to a point over tipLength. edgeBevel > 0 pinches the cross-section toward a diamond ridge.",
+ example: `const b = bladeGeo({ length: 1.6, baseWidth: 0.09, tipLength: 0.3, edgeBevel: 0.5 });
+createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`
+ },
+ {
+ name: "gameMaterial",
+ signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Flat-shaded PBR material. Default for game-ready low-poly. Use for 95% of parts.",
+ example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9 });"
+ },
+ {
+ name: "materialRecipe",
+ signature: "await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })",
+ returns: "Promise<THREE.MeshStandardMaterial>",
+ category: "material",
+ description: "Resolves a versioned portable bark/leaf/wood/stone/rubber/painted-metal/cloth/skin/glass/emissive recipe to standard glTF PBR.",
+ example: "const bark = await materialRecipe('kiln.material.bark.v1', { baseColor: '#6b4328' });",
+ promptNotes: "Use only listed kiln.material.*.v1 IDs and approved kiln.texture.* resource IDs. Leaf is MASK, glass is BLEND, and host file paths are forbidden."
+ },
+ {
+ name: "compilePortableMaterialSpecV2",
+ signature: "await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', name?, baseColor?, roughness?, metalness?, emissive?, emissiveIntensity?, alphaMode?, alphaCutoff?, doubleSided?, textures?: { baseColor?, normal?, metallicRoughness?, emissive?, occlusion? } })",
+ returns: "Promise<THREE.MeshStandardMaterial>",
+ category: "material",
+ description: "Compiles the strict portable material contract. Texture refs are either typed procedural V2 specs or closed approved kiln.texture.* IDs; paths, URLs, raw textures, callbacks, and shader source are rejected.",
+ example: "const steel = await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', roughness: 0.45, metalness: 0.85, textures: { metallicRoughness: { kind: 'procedural', spec: { schemaVersion: 2, usage: 'metallicRoughness', size: 64, layers: [{ op: 'solid', color: 0x0080cc }] } } } });",
+ promptNotes: "Use metallicRoughness as one packed G=roughness/B=metalness map. Every procedural ref usage must match its slot; resource refs must be approved for that exact slot."
+ },
+ {
+ name: "basicMaterial",
+ signature: "basicMaterial(color, opts?: { transparent, opacity })",
+ returns: "THREE.MeshBasicMaterial",
+ category: "material",
+ description: "Unlit flat material. For UI / effects where lighting is baked in.",
+ example: "const mat = basicMaterial(0xffffff, { transparent: true, opacity: 0.5 });"
+ },
+ {
+ name: "glassMaterial",
+ signature: "glassMaterial(color, opts?: { opacity, roughness, metalness })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.",
+ example: "const mat = glassMaterial(0x66ccff, { opacity: 0.3 });"
+ },
+ {
+ name: "lambertMaterial",
+ signature: "lambertMaterial(color, opts?: { flatShading, emissive })",
+ returns: "THREE.MeshLambertMaterial",
+ category: "material",
+ description: "Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.",
+ example: "const mat = lambertMaterial(0x2a4d14, { flatShading: true });"
+ },
+ {
+ name: "rotationTrack",
+ signature: "rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP')",
+ returns: "THREE.QuaternionKeyframeTrack",
+ category: "animation",
+ description: "Rotation track in degrees, auto-converted to quaternions. Joint name must include `Joint_` prefix.",
+ example: "rotationTrack('Joint_Lid', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [90, 0, 0] }]);"
+ },
+ {
+ name: "positionTrack",
+ signature: "positionTrack(jointName: string, keyframes: Array<{ time, position: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')",
+ returns: "THREE.VectorKeyframeTrack",
+ category: "animation",
+ description: "Position track in world units. Always use `position:` not `value:` in keyframes.",
+ example: "positionTrack('Joint_Body', [{ time: 0, position: [0, 0, 0] }, { time: 1, position: [0, 0.1, 0] }]);"
+ },
+ {
+ name: "scaleTrack",
+ signature: "scaleTrack(jointName: string, keyframes: Array<{ time, scale: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')",
+ returns: "THREE.VectorKeyframeTrack",
+ category: "animation",
+ description: "Uniform or per-axis scale track.",
+ example: "scaleTrack('Joint_Chest', [{ time: 0, scale: [1, 1, 1] }, { time: 1, scale: [1.1, 1.1, 1.1] }]);"
+ },
+ {
+ name: "createClip",
+ signature: "createClip(name: string, duration: number, tracks: KeyframeTrack[])",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "Collects tracks into a named clip. Returned from animate().",
+ example: "return [createClip('Open', 1, [rotationTrack('Joint_Lid', [...])])];"
+ },
+ {
+ name: "idleBreathing",
+ signature: "idleBreathing(bodyJoint: string, duration?: 2, amount?: 0.02)",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "Gentle Y-axis bob. For NPC idle states.",
+ example: "return [idleBreathing('Joint_Body')];"
+ },
+ {
+ name: "bobbingAnimation",
+ signature: "bobbingAnimation(rootName: string, duration?: 2, height?: 0.1)",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "Floating / bobbing loop for pickups and effects.",
+ example: "return [bobbingAnimation('Joint_Root', 1.5, 0.08)];"
+ },
+ {
+ name: "spinAnimation",
+ signature: "spinAnimation(jointName: string, duration?: 2, axis?: 'x' | 'y' | 'z')",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "360° rotation over `duration` around `axis`.",
+ example: "return [spinAnimation('Joint_Rotor', 0.5, 'y')];"
+ },
+ {
+ name: "cloneGeometry",
+ signature: "cloneGeometry(geo: BufferGeometry)",
+ returns: "THREE.BufferGeometry (same ref)",
+ category: "instancing",
+ description: "Deprecated name: returns the SAME geometry, without copying. Use copyGeometry for independent vertex edits, or pass the original geometry directly for intentional sharing.",
+ example: "const wheelGeo = cylinderGeo(0.4, 0.4, 0.2, 12);"
+ },
+ {
+ name: "cloneMaterial",
+ signature: "cloneMaterial(mat: Material)",
+ returns: "THREE.Material (same ref)",
+ category: "instancing",
+ description: "Deprecated name: returns the SAME material. Use copyMaterial for independent property edits, or pass the original for intentional sharing.",
+ example: "const rubberMat = gameMaterial(0x1a1a1a, { roughness: 0.95 });"
+ },
+ {
+ name: "createInstance",
+ signature: "createInstance(name, source, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, parent })",
+ returns: "THREE.Object3D",
+ category: "instancing",
+ description: "Creates a new mesh reusing an existing part's geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows. `rotation` is in DEGREES, like createPart.",
+ example: `const wheelFL = createPart('WheelFL', wheelGeo, rubberMat, { position: [-0.8, 0.3, 1.2], parent: root });
+createInstance('WheelFR', wheelFL, { position: [0.8, 0.3, 1.2], parent: root });
+createInstance('WheelRL', wheelFL, { position: [-0.8, 0.3, -1.2], parent: root });
+createInstance('WheelRR', wheelFL, { position: [0.8, 0.3, -1.2], parent: root });`
+ },
+ {
+ name: "boolUnion",
+ signature: "await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Merges two or more parts into one watertight manifold mesh. Default flat shading (hard edges) — pass { smooth: true } as last arg for averaged normals on organic merges.",
+ example: `const body = new THREE.Mesh(boxGeo(2, 1, 1), steel);
+const turret = new THREE.Mesh(cylinderGeo(0.3, 0.3, 0.4, 16), steel);
+turret.position.y = 0.5;
+const hull = await boolUnion('Hull', body, turret);`
+ },
+ {
+ name: "boolDiff",
+ signature: "await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Subtracts cutters from a body (holes, button recesses, window slots). Default flat shading for sharp mechanical edges.",
+ example: `const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel);
+const teeth = [...]; // 8 radially-arrayed box meshes
+const gear = await boolDiff('Gear', body, ...teeth); // hard-edged`
+ },
+ {
+ name: "roundedBoxGeo",
+ signature: "await roundedBoxGeo(width: number, height: number, depth: number, radius: number, opts?: { style?: 'round' | 'chamfer', segments?: 12, smooth?: boolean })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "csg",
+ description: "A box with all twelve edges rounded (or chamfered) at the EXACT outer size requested — roundedBoxGeo(1, 1, 1, 0.1) measures 1x1x1, it does not grow. Use it anywhere boxGeo reads too sharp: consoles, crates, appliances, handheld props, machined blocks.",
+ promptNotes: "Real objects almost never have perfectly sharp box edges, and a small radius is the single cheapest upgrade to how manufactured an asset looks. Prefer this over boxGeo for anything moulded, cast, or machined. Keep radius small relative to the box (5-10% of the smallest dimension); radius must be less than half the smallest dimension or the call throws. style: 'chamfer' reads as machined metal, 'round' as moulded plastic. This is async — build() must be async and the call must use await.",
+ example: `const geo = await roundedBoxGeo(1.2, 0.6, 0.8, 0.05);
+createPart('Console', geo, plastic, { position: [0, 0.3, 0], parent: root });`
+ },
+ {
+ name: "extrudeProfile",
+ signature: "await extrudeProfile(profile: [number, number][], opts?: { depth?: 1, holes?: [number, number][][], bevel?: 0, bevelStyle?: 'round' | 'chamfer', segments?: 12, twist?: 0, taper?: number | [number, number], divisions?: number, axis?: 'x' | 'y' | 'z', center?: true, smooth?: false })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "csg",
+ description: "Sweeps a closed 2D outline into a watertight solid, with optional holes, corner rounding/chamfering, twist, and taper. The way to build any cross-section that is not a box or a cylinder: L-brackets, I-beams, gaskets, washers, star and gear plates, signage, extruded trim.",
+ promptNotes: "The bevel rounds the edges PARALLEL to the sweep axis (the profile corners) — the two flat caps stay sharp. For a box rounded on all twelve edges use roundedBoxGeo instead. Holes are subtracted, so their winding order does not matter. A bevel larger than half the outline's narrowest feature throws rather than silently returning an empty solid. Output is manifold, so it feeds straight into boolUnion / boolDiff / boolIntersect. Async — await it inside an async build().",
+ example: `// L-bracket, inner AND outer corners filleted
+const outline = [[0, 0], [2, 0], [2, 0.4], [0.4, 0.4], [0.4, 2], [0, 2]];
+const geo = await extrudeProfile(outline, { depth: 0.5, bevel: 0.06 });
+createPart('Bracket', geo, steel, { parent: root });`
+ },
+ {
+ name: "revolveProfile",
+ signature: "await revolveProfile(profile: [number, number][], opts?: { segments?: 24, angle?: 360, bevel?: 0, bevelStyle?: 'round' | 'chamfer', bevelSegments?: 12, axis?: 'x' | 'y' | 'z', smooth?: true })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "csg",
+ description: "Revolves a closed 2D outline around an axis into a watertight SOLID, optionally rounding the profile corners first. Bottles, tanks, pressure vessels, wheels, turned wood, domes, buttons, pills.",
+ promptNotes: "Use this instead of lathe/revolveGeo whenever the result must survive a boolean or needs a rounded rim — lathe and revolveGeo build an open surface, this builds a closed solid. Profile convention matches lathe: x is distance from the axis, y is position along it, and only the x >= 0 side is used. Async — await it inside an async build().",
+ example: `// capsule tank with a rounded rim, then carve a port into it
+const profile = [[0, -0.5], [0.4, -0.5], [0.4, 0.5], [0, 0.5]];
+const body = await revolveProfile(profile, { bevel: 0.08, segments: 32 });
+const tank = await boolDiff('Tank', createPart('B', body, steel), portCutter);`
+ },
+ {
+ name: "circleProfile",
+ signature: "circleProfile(radius: number, segments?: 24, center?: [number, number])",
+ returns: "[number, number][]",
+ category: "csg",
+ description: "Builds a closed circular outline for extrudeProfile / revolveProfile, so you never hand-write the trigonometry. Synchronous.",
+ example: `const washer = await extrudeProfile(circleProfile(1), {
+ depth: 0.1,
+ holes: [circleProfile(0.4), circleProfile(0.1, 16, [0.7, 0])],
+});`
+ },
+ {
+ name: "boolIntersect",
+ signature: "await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Keeps only the volume where both operands overlap. Default flat shading.",
+ example: "const lens = await boolIntersect('Lens', boxMesh, sphereMesh);"
+ },
+ {
+ name: "hull",
+ signature: "await hull(name: string, ...parts: Object3D[], opts?: { smooth?: true })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Tightest convex mesh enclosing all input points. Default smooth shading (rocks, collision volumes). Pass { smooth: false } for a faceted look.",
+ example: `const rockChunks = [...]; // scattered box meshes
+const rock = await hull('Rock', ...rockChunks);`
+ },
+ {
+ name: "arrayLinear",
+ signature: "arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)",
+ returns: "THREE.Object3D[]",
+ category: "arrays",
+ description: "Places N copies of `source` along a constant offset vector. Copies share geometry + material via createInstance.",
+ example: `const post = createPart('Post0', cylinderGeo(0.05,0.05,1.5,6), wood, { position: [0,0.75,0], parent: root });
+arrayLinear('Post', post, 10, [0.5, 0, 0], root);`
+ },
+ {
+ name: "arrayRadial",
+ signature: "arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?)",
+ returns: "THREE.Object3D[]",
+ category: "arrays",
+ description: "Places N copies of `source` around the given axis. Source's local rotation is oriented outward. Perfect for gear teeth, radial bolts, circle of columns.",
+ example: `const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });
+arrayRadial('Bolt', bolt, 8, 'y', root);`
+ },
+ {
+ name: "mirror",
+ signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",
+ returns: "THREE.Object3D",
+ category: "arrays",
+ description: "Reflects source across the plane whose normal is `axis`. Uses negative scale (winding flip handled by viewers).",
+ example: "mirror('WingR', wingL, 'x', root);"
+ },
+ {
+ name: "subdivide",
+ signature: "subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { preserveUV?: boolean, split?: boolean, uvSmooth?: boolean, preserveEdges?: boolean, flatOnly?: boolean, weld?: boolean })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Loop subdivision returns new geometry; each iteration roughly quadruples triangles and smooths the surface. Use preserveUV:true for textured meshes. Legacy position-only welding discards UVs and reports that loss. This smooths shapes, not selected-edge beveling.",
+ example: "const smoothRock = subdivide(boxGeo(1, 1, 1), 2);"
+ },
+ {
+ name: "mergeVertices",
+ signature: "mergeVertices(geometry: BufferGeometry, opts?: { tolerance?: 1e-4, positionOnly?: boolean } | number)",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Returns indexed geometry. Default welding preserves attribute seams, so a textured cube retains separate face corners. positionOnly:true welds coincident positions and discards other attributes; use it explicitly when changing topology and regenerate shading/UVs afterward.",
+ example: `const welded = mergeVertices(boxGeo(1, 1, 1), { positionOnly: true });
+const rock = displace(subdivide(welded, 2), ([x,y,z]) => [0.08*Math.sin(y*7+z*3), 0.04*Math.sin(x*9), 0]);`
+ },
+ {
+ name: "curveToMesh",
+ signature: "curveToMesh(points: [x,y,z][], radius, tubularSegs?: 32, radialSegs?: 8, closed?: false)",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Sweeps a circular profile along a path. Equivalent to Blender's Curve to Mesh node with a circle profile. Use for pipes, cables, tubular frames.",
+ example: "const pipe = curveToMesh([[0,0,0],[0,1,0],[1,1,0],[1,2,0]], 0.1);"
+ },
+ {
+ name: "pipeAlongPath",
+ signature: "pipeAlongPath(points: [x,y,z][], radius: number, opts?: { bendRadius?: 0, closed?: false, tubularSegments?: 32, radialSegments?: 8 })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Path-driven swept circle with optional bend smoothing. Generalises beamBetween (point-to-point) and curveToMesh (raw spline) into one helper. bendRadius>0 inserts interpolated waypoints near interior corners so the spline reads as a rounded turn instead of pinching to the control point.",
+ example: "const cable = pipeAlongPath([[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]], 0.02, { bendRadius: 0.1 });"
+ },
+ {
+ name: "lathe",
+ signature: "lathe(profile: [x,y][], segments?: 12)",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Surface of revolution. Spins a 2D profile around the Y axis. For bottles, vases, wheels, turned wood parts.",
+ example: "const vase = lathe([[0.1,0],[0.3,0.5],[0.2,1],[0.1,1.2]], 16);"
+ },
+ {
+ name: "revolveGeo",
+ signature: "revolveGeo(profile: [x,y][], opts?: { angle?: 2π, axis?: [x,y,z]=[0,1,0], segments?: 12 })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Surface of revolution with explicit axis + sweep angle. Generalises lathe — use it when you need a partial sweep (half-dome, 90° wedge) or revolution around a non-Y axis. Profile convention is identical to lathe: x = radial distance, y = position along the axis.",
+ example: `// Half-dome (180° sweep around +Y):
+const quarter = [...Array(8)].map((_, i) => { const t = (i/7)*Math.PI/2; return [Math.cos(t), Math.sin(t)] as [number, number]; });
+const dome = revolveGeo(quarter, { angle: Math.PI });`
+ },
+ {
+ name: "bezierCurve",
+ signature: "bezierCurve(controlPoints: [x,y,z][], samples?: 32)",
+ returns: "[x,y,z][]",
+ category: "curves",
+ description: "Samples a quadratic (3 ctrl pts) or cubic (4 ctrl pts) Bézier into a point list you can feed into curveToMesh.",
+ example: `const path = bezierCurve([[0,0,0],[1,2,0],[3,2,0],[4,0,0]], 24);
+const geo = curveToMesh(path, 0.1);`
+ },
+ {
+ name: "autoUnwrap",
+ signature: "await autoUnwrap(geometry: BufferGeometry, opts?: { resolution?: 1024, padding?: 2, useNormals?: false })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "uv",
+ description: "xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware unwraps below.",
+ example: `const unwrapped = await autoUnwrap(someCsgResult, { resolution: 1024 });
+const mesh = new THREE.Mesh(unwrapped, bakedPbr);`
+ },
+ {
+ name: "boxUnwrap",
+ signature: "boxUnwrap(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Preserves BoxGeometry's built-in per-face UVs — every face maps [0,1] with consistent orientation. Use for crates/blocks with a tileable texture. Sync; no WASM cost.",
+ example: `const crate = boxUnwrap(boxGeo(1, 1, 1));
+const mesh = new THREE.Mesh(crate, pbrMaterial({ albedo: planksTex }));`
+ },
+ {
+ name: "cylinderUnwrap",
+ signature: "cylinderUnwrap(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Preserves CylinderGeometry's built-in UVs: u wraps around the axis (horizontal texture features ring the cylinder), v runs up the height. Caps use circle-in-square. Sync; no WASM cost.",
+ example: `const barrel = cylinderUnwrap(cylinderGeo(0.5, 0.5, 1.2, 24));
+const mesh = new THREE.Mesh(barrel, pbrMaterial({ albedo: bandsTex }));`
+ },
+ {
+ name: "planeUnwrap",
+ signature: "planeUnwrap(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Projects xy-extent of the bbox to [0,1]. Use for signs/decals/posters where you want ONE readable texture and no edge-face bleeding. Sync.",
+ example: `const sign = planeUnwrap(planeGeo(1, 0.6));
+const mesh = new THREE.Mesh(sign, pbrMaterial({ albedo: kilnTextTex }));`
+ },
+ {
+ name: "panelRemapV",
+ signature: "panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Scales an existing UV attribute so a small mesh samples a sub-region of a SHARED texture. Replaces the broken texture.clone() pattern (Three.js Texture.clone() runs JSON.stringify on userData, mangling encoded PNG bytes — panelRemapV avoids that by remapping UVs on the geometry instead). Typical use: multi-zone albedo where v=0..0.30 is plain panel and v=0.30..1 has windows/markings — small parts call panelRemapV(unwrap(geo), 0.30) to sample only the clean strip.",
+ example: `const cowlGeo = panelRemapV(cylinderUnwrap(capsuleXGeo(0.45, 1.0)), 0.30);
+const cowl = new THREE.Mesh(cowlGeo, bodyMat); // SAME bodyMat as fuselage, no clone needed`
+ },
+ {
+ name: "loadApprovedTexture",
+ signature: "await loadApprovedTexture(resourceId)",
+ returns: "Promise<THREE.DataTexture>",
+ category: "textures",
+ description: "Loads one approved kiln.texture.* resource ID through the host-injected closed resolver. The registry fixes bytes, MIME, usage, dimensions, hash, and deadline; paths, URLs, byte arrays, resolver objects, hashes, and options are rejected.",
+ example: "const bark = await loadApprovedTexture('kiln.texture.bark-brown-01-albedo.v1');",
+ promptNotes: "Use only a concrete resource ID listed in material capabilities; never invent one. Prefer materialRecipe when a recipe already binds the family, or proceduralTexture V2 for authored surfaces. NEVER texture.clone() a loaded texture (clone() corrupts encoded bytes and breaks GLB export)."
+ },
+ {
+ name: "proceduralTexture",
+ signature: "proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })",
+ returns: "THREE.DataTexture (tiling, sRGB or linear per usage)",
+ category: "textures",
+ description: "Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.",
+ example: "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",
+ promptNotes: "Sync — no await. Strict V2 JSON boundary: unknown/prototype keys, callbacks, paths, URLs, and shader source are rejected. Prefer this over approved resources for describable surfaces. Max 8 layers, power-of-two size up to 1024. Only the six listed ops exist."
+ },
+ {
+ name: "normalMapFromHeight",
+ signature: "normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })",
+ returns: "THREE.DataTexture (linear normal map)",
+ category: "textures",
+ description: "Derives a tangent-space normal map from the source texture's brightness, treating it as height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at the edges, so a tiling source gives a tiling normal map.",
+ example: `const bark = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] });
+const mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });`,
+ promptNotes: "strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always linear data — never assign it to an albedo/emissive slot."
+ },
+ {
+ name: "pbrMaterial",
+ signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, aoMap?, alphaMode?, alphaCutoff?, doubleSided? })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. Supports OPAQUE/MASK/BLEND and double-sided output.",
+ example: `const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });
+const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });`
+ },
+ {
+ name: "foliageMaterial",
+ signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",
+ example: "const mat = await materialRecipe('kiln.material.leaf.v1');"
+ },
+ {
+ name: "countTriangles",
+ signature: "countTriangles(root: Object3D)",
+ returns: "number",
+ category: "utility",
+ description: "Sums triangle count across every mesh in the subtree.",
+ example: "meta.tris = countTriangles(root);"
+ },
+ {
+ name: "countMaterials",
+ signature: "countMaterials(root: Object3D)",
+ returns: "number",
+ category: "utility",
+ description: "Unique material count (by reference) across the subtree.",
+ example: "const mats = countMaterials(root);"
+ },
+ {
+ name: "getJointNames",
+ signature: "getJointNames(root: Object3D)",
+ returns: "string[]",
+ category: "utility",
+ description: "All node names beginning with `Joint_`. Use to sanity-check animation targets.",
+ example: "const joints = getJointNames(root);"
+ },
+ {
+ name: "validateAsset",
+ signature: "validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture' | 'vegetation' | 'vehicle')",
+ returns: "{ valid, errors, warnings }",
+ category: "utility",
+ description: "Checks geometry and material costs for the selected category. No default triangle limit; choose detail for the intended runtime and inspect measured draw calls.",
+ example: "const v = validateAsset(root, 'prop');"
+ }
+ ];
+});
+
// src/validation.ts
import * as acorn from "acorn";
import * as walk from "acorn-walk";
@@ -18018,8 +18940,45 @@ function collectStaticStringBindings(ast) {
}
return values;
}
-var GeneratedSourcePolicyError, FORBIDDEN_AMBIENT_IDENTIFIERS, FORBIDDEN_THREE_CONSTRUCTORS, ROTATION_OPTION_FNS;
+var SANDBOX_CALLABLES, GeneratedSourcePolicyError, FORBIDDEN_AMBIENT_IDENTIFIERS, FORBIDDEN_THREE_CONSTRUCTORS, ROTATION_OPTION_FNS;
var init_validation = __esm(() => {
+ init_list_primitives();
+ SANDBOX_CALLABLES = new Set([
+ ...listPrimitives().map((primitive) => primitive.name),
+ "Array",
+ "BigInt",
+ "Boolean",
+ "Error",
+ "Float32Array",
+ "Float64Array",
+ "Int16Array",
+ "Int32Array",
+ "Int8Array",
+ "Map",
+ "Number",
+ "Object",
+ "Promise",
+ "Proxy",
+ "RangeError",
+ "Reflect",
+ "RegExp",
+ "Set",
+ "String",
+ "Symbol",
+ "TypeError",
+ "Uint16Array",
+ "Uint32Array",
+ "Uint8Array",
+ "WeakMap",
+ "WeakSet",
+ "decodeURIComponent",
+ "encodeURIComponent",
+ "isFinite",
+ "isNaN",
+ "parseFloat",
+ "parseInt",
+ "structuredClone"
+ ]);
GeneratedSourcePolicyError = class GeneratedSourcePolicyError extends Error {
code;
line;
diff --git a/dist/mcp-server.mjs b/dist/mcp-server.mjs
index cd5de272..ef29850b 100644
--- a/dist/mcp-server.mjs
+++ b/dist/mcp-server.mjs
@@ -1676,6 +1676,928 @@ var init_capture_cache = __esm(() => {
init_capture_limits();
});
+// src/geometry-catalog.ts
+var geometryPrimitives;
+var init_geometry_catalog = __esm(() => {
+ geometryPrimitives = [
+ {
+ name: "copyGeometry",
+ signature: "copyGeometry(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "instancing",
+ description: "Returns an independent geometry with copied vertex buffers. Use before direct mutation of a cached primitive.",
+ example: "const editable = copyGeometry(boxGeo(1, 1, 1)); editable.translate(0, 0.5, 0);"
+ },
+ {
+ name: "copyMaterial",
+ signature: "copyMaterial(material: Material)",
+ returns: "THREE.Material (same subtype)",
+ category: "instancing",
+ description: "Copies material properties so edits do not change other parts. Referenced textures remain shared.",
+ example: "const red = copyMaterial(steel); red.color.set(0xaa2222);"
+ },
+ {
+ name: "meshGeo",
+ signature: "meshGeo({ positions: number[], indices?: number[], normals?: number[], uvs?: number[], tangents?: number[] })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Builds an owned triangle mesh from flat numeric arrays. Validates finite values, attribute lengths and indices; computes normals if absent. Counterclockwise winding.",
+ example: "const triangle = meshGeo({ positions: [0,0,0, 1,0,0, 0,1,0], indices: [0,1,2] });"
+ },
+ {
+ name: "parametricSurface",
+ signature: "parametricSurface(sample: (u,v) => [x,y,z], opts?: { u?: [0,1], v?: [0,1], uSegments?: 24, vSegments?: 24, periodicU?: false, periodicV?: false, orientation?: 'uv'|'vu' })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Samples an equation into an owned surface with UVs. Periodic endpoints must coincide; UV seams retain matching normals. A surface is not automatically a watertight solid.",
+ example: "const canopy = parametricSurface((u,v) => [u, 0.3*Math.sin(u*3)*Math.cos(v*2), v], { u: [-2,2], v: [-1,1] });"
+ },
+ {
+ name: "geometryDiagnostics",
+ signature: "geometryDiagnostics(geometry: BufferGeometry, tolerance?: 1e-6)",
+ returns: "{ vertices, triangles, boundaryEdges, nonManifoldEdges, orientationConflicts, degenerateTriangles, invalidIndices, nonFiniteVertices }",
+ category: "utility",
+ description: "Counts mesh topology problems after position-based seam matching. Open boundaries are valid for sheets; closed edges alone do not prove a self-intersection-free solid.",
+ example: "const topology = geometryDiagnostics(shell);"
+ },
+ {
+ name: "creaseNormals",
+ signature: "creaseNormals(geometry: BufferGeometry, opts?: { angle?: 60, tolerance?: number })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Returns owned geometry with angle-limited smooth normals, preserving UV corners. Angle is degrees. Invalidates tangents; use after shaping for sharp rims and smooth walls.",
+ example: "const shell = creaseNormals(cylinderGeo(1,1,2,32), { angle: 45 });"
+ },
+ {
+ name: "bend",
+ signature: "bend(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Bends local +Y toward +X through angle degrees. Returns owned geometry and updated normals/bounds; preserves UVs, invalidates tangents. Frame rotation is Euler XYZ degrees.",
+ promptNotes: "Deformation interval uses local Y distances; outside vertices stay unchanged. Add enough segments before bending. Falloff returns 0..1; use it to avoid a discontinuity at a selected interval boundary.",
+ example: "const arch = bend(planeGeo(1,4,4,32), { angle: 90 });"
+ },
+ {
+ name: "twist",
+ signature: "twist(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Rotates the cross-section progressively around local +Y, reaching angle degrees at the end. Returns owned geometry; frame rotation uses Euler XYZ degrees.",
+ example: "const spiral = twist(column, { angle: 120 });"
+ },
+ {
+ name: "taper",
+ signature: "taper(geometry, { startScale?: [1,1], endScale: [x,z], frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Scales local X/Z across the local Y interval using positive start/end scale pairs. Returns owned geometry; preserves UVs and invalidates tangents.",
+ example: "const narrowed = taper(column, { endScale: [0.4,0.7] });"
+ },
+ {
+ name: "displace",
+ signature: "displace(geometry, offset: ([x,y,z], t) => [dx,dy,dz], opts?: { frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Adds an authored displacement vector in the chosen local frame. Returns owned geometry; callback coordinates are local and t is normalized along the interval.",
+ example: "const rippled = displace(surface, ([x,y,z]) => [0, 0.1*Math.sin(x*8), 0]);"
+ },
+ {
+ name: "sweepProfile",
+ signature: "sweepProfile(profile: [x,z][], path: [x,y,z][], opts?: { cap?: true, closed?: false, up?: [x,y,z], twist?: 0, scale?: number | [x,z][] })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Sweeps a simple noncircular profile along polyline stations using transported frames. Supports total twist in degrees and per-station scales. Generates UVs and optional caps.",
+ promptNotes: "First version supports one simple profile without holes. Closed paths omit the repeated endpoint and require twist to be a multiple of 360. up sets the initial profile +Z direction and cannot parallel the path. Tight-turn warnings do not replace visual inspection for self-intersections.",
+ example: "const rail = sweepProfile([[-.1,-.2],[.1,-.2],[.1,.2],[-.1,.2]], [[0,0,0],[0,1,0],[1,2,0]]);"
+ },
+ {
+ name: "loftProfiles",
+ signature: "loftProfiles(sections: { profile: [x,z][], frame?: { origin, rotation } }[], opts?: { cap?: true })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Joins corresponding simple profiles in explicit local XZ planes. Each frame uses Euler XYZ degrees and local +Y along the loft. Profiles need equal point counts and corresponding vertices.",
+ promptNotes: "No holes or automatic profile correspondence. Opposite winding is normalized while preserving the first point. Caps close boundaries but do not prove the loft has no self-intersections.",
+ example: "const hull = loftProfiles([{ profile: wide }, { profile: narrow, frame: { origin: [0,2,0] } }]);"
+ },
+ {
+ name: "implicitSurface",
+ signature: "await implicitSurface(sample: ([x,y,z]) => signedValue, { bounds: { min, max }, edgeLength, maxCells?: 1000000, maxEvaluations?: 8000000, level?: 0, tolerance?: -1, smooth?: true })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "geometry",
+ description: "Experimental positive-inside implicit field sampled into a solid mesh. Requires explicit bounds and resolution; checks grid size and actual evaluation count. Output has no UVs.",
+ promptNotes: "Use async build and await. Smaller edgeLength increases cost sharply. This helper cannot stop a callback that never returns; the host evaluator process provides that boundary. Thin features and geometric accuracy require inspection.",
+ example: "const blob = await implicitSurface(([x,y,z]) => 1-Math.hypot(x,y,z), { bounds: { min: [-1.2,-1.2,-1.2], max: [1.2,1.2,1.2] }, edgeLength: 0.15 });"
+ }
+ ];
+});
+
+// src/list-primitives.ts
+function listPrimitives() {
+ return PRIMITIVES.map((p) => ({ ...p }));
+}
+var PRIMITIVES;
+var init_list_primitives = __esm(() => {
+ init_geometry_catalog();
+ PRIMITIVES = [
+ ...geometryPrimitives,
+ {
+ name: "createRoot",
+ signature: "createRoot(name: string)",
+ returns: "THREE.Object3D",
+ category: "structure",
+ description: "Creates the root Object3D for an asset. Call first in build().",
+ example: "const root = createRoot('FuelDrum');"
+ },
+ {
+ name: "createPivot",
+ signature: "createPivot(name: string, position?: [x, y, z], parent?: Object3D)",
+ returns: "THREE.Object3D (prefixed `Joint_`)",
+ category: "structure",
+ description: "Creates an empty pivot node for skeletal animation. Name is auto-prefixed with `Joint_`.",
+ example: "const hip = createPivot('Hip', [0, 1, 0], root);"
+ },
+ {
+ name: "createJointChain",
+ signature: "createJointChain(name, segments: { role, offset, aliases?, side?, localForwardAxis?, localBendAxis?, endEffector?, contact? }[], opts?: { parent?, parentRole? })",
+ returns: "{ root, end, nodes, byRole, descriptors }",
+ category: "structure",
+ description: "Creates one body-plan-neutral deterministic Joint_* chain with explicit parent edges, rest frames, local axes, end effectors, contacts, and semantic metadata.",
+ example: "const leg = createJointChain('LegL', [{ role: 'hip.left', offset: [0, 1, -0.2], side: 'left' }, { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' }, { role: 'ankle.left', offset: [0, -0.5, 0], side: 'left', endEffector: true, contact: true }], { parent: root });",
+ promptNotes: "Use only the resolved body-plan graph. Offsets are local to the previous joint; contact end effectors must land at world Y=0."
+ },
+ {
+ name: "createVehicleFrame",
+ signature: "createVehicleFrame(name, opts?: { chassis?, axles?, seats?, contacts?, steering?, propulsion?, parent? })",
+ returns: "{ root, chassis, axles, seats, contacts, steering, propulsion }",
+ category: "structure",
+ description: "Creates a canonical +X-forward/+Y-up/+Z-right vehicle frame with typed semantic sockets for chassis, support, steering, and propulsion.",
+ example: "const frame = createVehicleFrame('CarFrame', { axles: [{ id: 'front', position: [1.2, 0.45, 0] }, { id: 'rear', position: [-1.2, 0.45, 0] }], parent: root });",
+ promptNotes: "Generated vehicles keep +X as front. Boats and other non-wheeled subtypes use declared support/propulsion sockets, not wheel rules."
+ },
+ {
+ name: "createWheelGeometrySet",
+ signature: "createWheelGeometrySet(radius: number, width: number)",
+ returns: "{ tire, rim, hub } shared THREE.BufferGeometry set",
+ category: "instancing",
+ description: "Creates one reusable +Z-axle tire/rim/hub geometry set for instanced wheel assemblies.",
+ example: "const wheelGeo = createWheelGeometrySet(0.45, 0.22);"
+ },
+ {
+ name: "createWheelAssembly",
+ signature: "createWheelAssembly(name, { tire, rim, hub? }, { radius, width, side, index, position?, rimRadius?, hubRadius?, steering?, loadBearing?, geometries?, parent? })",
+ returns: "{ root, steeringPivot?, spinPivot, tire, rim, hub, contact, radius, width, side, index, spinAxis }",
+ category: "structure",
+ description: "Creates one axle-centered wheel pivot containing concentric tire/rim/hub roles, a contact marker, +Z spin frame, and optional steering pivot.",
+ example: "createWheelAssembly('FrontLeft', { tire: rubber, rim: metal }, { radius: 0.45, width: 0.22, side: 'left', index: 'front', position: [1.2, 0.45, -0.9], steering: true, geometries: wheelGeo, parent: frame.root });",
+ promptNotes: "Keep tire, rim, and hub descendants concentric at the axle pivot. Reuse one geometry set across matching wheels."
+ },
+ {
+ name: "createPart",
+ signature: "createPart(name, geometry, material, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, pivot, parent })",
+ returns: "THREE.Object3D (mesh or wrapping pivot)",
+ category: "structure",
+ description: "Creates a mesh, optionally wrapped in a pivot, and attaches it to `opts.parent`. `rotation` is in DEGREES (like rotationTrack), NOT radians: [0, 0, 90] is a quarter turn; [0, 0, 1.57] is a no-op.",
+ example: "createPart('Barrel', cylinderGeo(0.1, 0.1, 1), gameMaterial(0x556b2f), { position: [0, 0.5, 0], rotation: [0, 0, 90], parent: root });",
+ promptNotes: "AUTO-ADDS to opts.parent. NEVER call parent.add(createPart(...)) — pass { parent } instead. rotation is DEGREES — writing radians (e.g. 0.785 or Math.PI/4) silently produces ~zero rotation."
+ },
+ {
+ name: "beamBetween",
+ signature: "beamBetween(name, start: [x,y,z], end: [x,y,z], radius, material, opts?: { segments, parent })",
+ returns: "THREE.Object3D (prefixed `Mesh_`)",
+ category: "structure",
+ description: "Creates a cylindrical rail/strut exactly between two endpoints. Use for braces, gun barrels, skid struts, cables, and scaffolding.",
+ example: "beamBetween('SkidBraceA', [0.8, 0.3, 0.7], [0.8, 1.0, 0.45], 0.025, black, { parent: root });"
+ },
+ {
+ name: "snapTo",
+ signature: "snapTo(part: Object3D, host: Object3D, opts?: { axis?: 'x'|'y'|'z', overlap?: 0.02 })",
+ returns: "THREE.Object3D (the part, for chaining)",
+ category: "structure",
+ description: 'Translates `part` by the minimal vector that brings its bounding box into contact with `host` (plus a small overlap). The direct cure for a "Floating parts" warning — attach the part instead of eyeballing a corrective offset. No-op if they already touch.',
+ example: `const scope = createPart('Scope', cylinderXGeo(0.04, 0.04, 0.3), steel, { parent: root, position: [0.1, 0.32, 0] });
+snapTo(scope, receiver);`
+ },
+ {
+ name: "createLadder",
+ signature: "createLadder(name, { bottom, top, material, width?, rungCount?, railRadius?, rungRadius?, widthAxis?, parent? })",
+ returns: "{ leftRail: Object3D, rightRail: Object3D, rungs: Object3D[] }",
+ category: "structure",
+ description: "Builds two continuous rails plus evenly-spaced rungs. Use this instead of loose boxes for ladders.",
+ example: "createLadder('TowerLadder', { bottom: [0,0,0], top: [0,2.2,0], width: 0.45, rungCount: 7, material: steel, parent: root });"
+ },
+ {
+ name: "createWingPair",
+ signature: "createWingPair(name, material, { rootZ, span, rootChord, tipChord, sweep?, thickness?, dihedral?, rootX?, rootY?, parent? })",
+ returns: "{ right: Object3D, left: Object3D }",
+ category: "structure",
+ description: "Creates mirrored trapezoid aircraft wings with roots attached at +/-rootZ. Use for aircraft wings and helicopter stub wings.",
+ example: "createWingPair('MainWing', olive, { rootX: 0, rootY: 1.0, rootZ: 0.42, span: 2.4, rootChord: 0.9, tipChord: 0.35, sweep: 0.25, dihedral: 0.08, parent: root });"
+ },
+ {
+ name: "room",
+ signature: "room(name, material, { width?, depth?, height?, wallThickness?, floor?, floorThickness?, openings?: [{ wall: 'front'|'back'|'left'|'right', kind?: 'door'|'window', offset?, width?, height?, sill? }], parent? })",
+ returns: "{ root: Object3D, walls: { front, back, left, right }, floor: Object3D | null }",
+ category: "structure",
+ description: "Builds a HOLLOW, enterable room: four thin walls + a floor, human-scaled (defaults: 2.8m ceiling, a centered 1.1x2.1m front door so it is enterable by default). `front` faces +X; the floor sits on the ground. The keystone of an architecture asset — add a roof with createRoofPlanes and fixtures as separate parts.",
+ example: "const { root: hut } = room('Hut', wood, { width: 5, depth: 4, height: 2.8, openings: [{ wall: 'front', kind: 'door' }, { wall: 'right', kind: 'window' }], parent: root });",
+ promptNotes: "Use for any building the player enters. Do NOT model a building as a solid block — room() guarantees real interior space and a doorway gap. Pass openings to add windows / side doors."
+ },
+ {
+ name: "wallWithOpening",
+ signature: "wallWithOpening(name, material, { length, height, thickness, axis?: 'x'|'z', opening?: { kind?: 'door'|'window', offset?, width?, height?, sill? }, parent? })",
+ returns: "THREE.Object3D (wall container)",
+ category: "structure",
+ description: "A single wall panel with an optional real door/window cut, composed from solid box segments (side panels + lintel + window sill) — no CSG. Base at local Y=0, centered on the run axis. Use to compose custom building layouts or interior dividing walls beyond the default room().",
+ example: "wallWithOpening('Partition', plaster, { length: 4, height: 2.8, thickness: 0.12, axis: 'x', opening: { kind: 'door', offset: 0.5 }, parent: root });"
+ },
+ {
+ name: "createRoofPlanes",
+ signature: "createRoofPlanes(name, material, { width, depth, height, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",
+ returns: "{ root: Object3D, slopes: [Object3D, Object3D] }",
+ category: "structure",
+ description: "A pitched roof: two thin slopes meeting at one ridge and falling DOWN-AND-OUTWARD (opposite tilts — never mirrored the same way), footprint-matched with an eave overhang. Eave at local Y=0, ridge at Y=height, so position the group at Y=wallHeight. Returns a named group (e.g. `Roof`) the engine can lift to reveal the interior.",
+ example: `const { root: roof } = createRoofPlanes('Roof', shingle, { width: 5, depth: 4, height: 1.6, overhang: 0.4, ridgeAxis: 'x', parent: root });
+roof.position.y = 2.8;`,
+ promptNotes: "The two slopes must fall AWAY from each other from the ridge — createRoofPlanes does this for you. Drop it onto the walls (position.y = wall height)."
+ },
+ {
+ name: "createGableRoof",
+ signature: "createGableRoof(name, material, { spanX, spanZ, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",
+ returns: "{ root, slopes: [Object3D, Object3D], faces: [RoofFaceFrame, RoofFaceFrame], rise, pitchDegrees }",
+ category: "structure",
+ description: "Explicit-axis gable roof using unambiguous footprint spans. Each face owns a rigid frame with ridge tangent, outward normal, downhill direction, ridge/eave endpoints, dimensions, and a live local-to-world transform.",
+ example: "const roof = createGableRoof('Roof', shingles, { spanX: 8, spanZ: 5, pitchDegrees: 35, overhang: 0.35, ridgeAxis: 'x', parent: root });",
+ promptNotes: "Prefer this over width/depth roof math. ridgeAxis is the direction of the ridge; roof panels run along each returned face downhill direction."
+ },
+ {
+ name: "createGableEndPanel",
+ signature: "createGableEndPanel(name, material, { span, rise, thickness?, ridgeAxis?: 'x'|'z', side?: 'positive'|'negative', openings?: [{ id?, offset?, bottom?, width, height }], parent? })",
+ returns: "{ root, geometry, openings }",
+ category: "structure",
+ description: "Exact thick triangular end closure for a gable roof, with optional rectangular openings cut from the geometry and semantic boundary metadata.",
+ example: "createGableEndPanel('FrontGable', siding, { span: 5, rise: 1.8, ridgeAxis: 'x', side: 'positive', parent: root });"
+ },
+ {
+ name: "createGableShell",
+ signature: "createGableShell(name, { wall, roof, floor?, gable? }, { spanX, spanZ, wallHeight?, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, wallThickness?, floorThickness?, closedEnds?, enterable?, openings?, gableOpenings?, parent? })",
+ returns: "{ root, walls, floor, roof, gables, openings }",
+ category: "structure",
+ description: "Closed-by-default, correct-by-construction gable building: hollow room, floor, two opposing roof slopes, two complete gable ends, and a real front doorway when enterable.",
+ example: "const house = createGableShell('House', { wall: plaster, roof: shingles }, { spanX: 8, spanZ: 5, wallHeight: 2.8, pitchDegrees: 35, ridgeAxis: 'x', parent: root });",
+ promptNotes: "Use for complete gable buildings. It stamps wall, floor, slope, gable, opening, adjacency, coverage, and separability semantics for deterministic QA and roof-off views."
+ },
+ {
+ name: "createRoofSurfaceLayout",
+ signature: "createRoofSurfaceLayout(name, material, { face, kind: 'panels'|'shingles'|'seams'|'corrugations', parent?, panelWidth?, rowHeight?, spacing?, thickness? })",
+ returns: "{ root, items: Object3D[] }",
+ category: "structure",
+ description: "Places roof-local panels, shingles, seams, or corrugations from a returned RoofFaceFrame, so repeated elements run ridge-to-eave for either ridge axis without manual Euler rotations.",
+ example: "for (const face of roof.faces) createRoofSurfaceLayout('Panels_' + face.side, metal, { face, kind: 'panels', parent: roof.root });",
+ promptNotes: "Always pass the face object returned by createGableRoof/createGableShell. Never infer the panel rotation from world axes."
+ },
+ {
+ name: "createStairs",
+ signature: "createStairs(name, material, { steps?, totalRise, totalRun, width, axis?: 'x'|'z', treadThickness?, riser?, parent? })",
+ returns: "{ root: Object3D, steps: Object3D[] }",
+ category: "structure",
+ description: "A straight flight of stairs: box treads (with optional risers) climbing totalRise over totalRun from local origin toward +axis. Use for porch/entry steps or to connect storeys in a multi-storey building.",
+ example: "createStairs('Porch', stone, { steps: 4, totalRise: 0.6, totalRun: 1.0, width: 1.4, axis: 'x', parent: root });"
+ },
+ {
+ name: "boxGeo",
+ signature: "boxGeo(width: number, height: number, depth: number)",
+ returns: "THREE.BoxGeometry",
+ category: "geometry",
+ description: "6-face box. 12 tris regardless of size. Cheapest geometry.",
+ example: "const geo = boxGeo(1, 0.5, 2);"
+ },
+ {
+ name: "sphereGeo",
+ signature: "sphereGeo(radius: number, widthSegments?: 8, heightSegments?: 6)",
+ returns: "THREE.SphereGeometry",
+ category: "geometry",
+ description: "UV sphere. Default 8x6 segments = 84 tris. Bump segments for smoother curves.",
+ example: "const geo = sphereGeo(0.5, 12, 8);"
+ },
+ {
+ name: "cylinderGeo",
+ signature: "cylinderGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Y-axis cylinder. Use radiusTop != radiusBottom for cones / tapered pieces.",
+ example: "const geo = cylinderGeo(0.25, 0.25, 1, 12);"
+ },
+ {
+ name: "cylinderYGeo",
+ signature: "cylinderYGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Alias for cylinderGeo — a Y-axis cylinder. Provided because the sandbox exposes cylinderXGeo / cylinderZGeo and the symmetric Y form is commonly reached for.",
+ example: "const geo = cylinderYGeo(0.25, 0.25, 1, 12);"
+ },
+ {
+ name: "cylinderXGeo",
+ signature: "cylinderXGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Cylinder pre-rotated to run along +X/-X. Use for fuselages, cannons, barrels, axles, and forward-facing tubes.",
+ example: "const geo = cylinderXGeo(0.1, 0.1, 1.2, 12);"
+ },
+ {
+ name: "cylinderZGeo",
+ signature: "cylinderZGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Cylinder pre-rotated to run along +Z/-Z. Use for side-mounted weapons, rails, crossbars, and pipes.",
+ example: "const geo = cylinderZGeo(0.08, 0.08, 0.9, 10);"
+ },
+ {
+ name: "cylinderOnAxis",
+ signature: "cylinderOnAxis(center: [x,y,z], normal: [x,y,z], radiusBottom: number, height: number, opts?: { radiusTop?, segments? })",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Frame-first cylinder: position + axis specified directly, no post-hoc rotation. Use when the cylinder needs to point along a non-cardinal direction (struts inside CSG operands, antennas off a tilted surface). For cardinal axes prefer the terser cylinderXGeo / cylinderYGeo / cylinderZGeo helpers.",
+ example: "const strut = cylinderOnAxis([0.5, 0.7, 0], [1, 1, 0.3], 0.05, 0.9);"
+ },
+ {
+ name: "capsuleGeo",
+ signature: "capsuleGeo(radius: number, height: number, segments?: 6)",
+ returns: "THREE.CapsuleGeometry",
+ category: "geometry",
+ description: "Stadium shape (cylinder with hemispherical caps). Good for limbs.",
+ example: "const geo = capsuleGeo(0.1, 0.5, 6);"
+ },
+ {
+ name: "capsuleYGeo",
+ signature: "capsuleYGeo(radius: number, height: number, segments?: 6)",
+ returns: "THREE.CapsuleGeometry",
+ category: "geometry",
+ description: "Alias for capsuleGeo — a Y-axis capsule. Provided for symmetry with capsuleXGeo / capsuleZGeo.",
+ example: "const geo = capsuleYGeo(0.1, 0.5, 6);"
+ },
+ {
+ name: "capsuleXGeo",
+ signature: "capsuleXGeo(radius: number, length: number, segments?: 6)",
+ returns: "THREE.CapsuleGeometry",
+ category: "geometry",
+ description: "Capsule pre-rotated to run along +X/-X. Use for aircraft bodies, rounded vehicle hulls, and missiles.",
+ example: "const geo = capsuleXGeo(0.35, 2.4, 10);"
+ },
+ {
+ name: "capsuleZGeo",
+ signature: "capsuleZGeo(radius: number, length: number, segments?: 6)",
+ returns: "THREE.CapsuleGeometry",
+ category: "geometry",
+ description: "Capsule pre-rotated to run along +Z/-Z. Use for lateral pods, floats, and side tanks.",
+ example: "const geo = capsuleZGeo(0.18, 1.1, 8);"
+ },
+ {
+ name: "coneGeo",
+ signature: "coneGeo(radius: number, height: number, segments?: 8)",
+ returns: "THREE.ConeGeometry",
+ category: "geometry",
+ description: "Y-axis cone (pointed up). Use for spikes, roofs, projectiles.",
+ example: "const geo = coneGeo(0.3, 0.8, 8);"
+ },
+ {
+ name: "coneYGeo",
+ signature: "coneYGeo(radius: number, height: number, segments?: 8)",
+ returns: "THREE.ConeGeometry",
+ category: "geometry",
+ description: "Alias for coneGeo — a Y-axis cone (point +Y). Provided for symmetry with coneXGeo / coneZGeo.",
+ example: "const geo = coneYGeo(0.3, 0.8, 8);"
+ },
+ {
+ name: "coneXGeo",
+ signature: "coneXGeo(radius: number, length: number, segments?: 8)",
+ returns: "THREE.ConeGeometry",
+ category: "geometry",
+ description: "Cone pre-rotated so its point faces +X. Use for noses, rockets, shells, and forward-facing tips.",
+ example: "const geo = coneXGeo(0.18, 0.45, 12);"
+ },
+ {
+ name: "coneZGeo",
+ signature: "coneZGeo(radius: number, length: number, segments?: 8)",
+ returns: "THREE.ConeGeometry",
+ category: "geometry",
+ description: "Cone pre-rotated so its point faces +Z. Use for side-facing projectiles and tips.",
+ example: "const geo = coneZGeo(0.12, 0.35, 10);"
+ },
+ {
+ name: "taperConeGeo",
+ signature: "taperConeGeo(radiusBottom: number, radiusTop: number, height: number, axis?: 'x'|'y'|'z', segments?: 8)",
+ returns: "THREE.CylinderGeometry",
+ category: "geometry",
+ description: "Truncated cone (frustum) — exposes both bottom and top radius. radiusTop=0 matches coneGeo, radiusTop=radiusBottom matches cylinderGeo. Use for pylon caps, soda cans, lampshades, anything tapered that does not come to a point. axis selects orientation (default Y).",
+ example: "const cap = taperConeGeo(0.3, 0.18, 0.4); // frustum"
+ },
+ {
+ name: "torusGeo",
+ signature: "torusGeo(radius: number, tube: number, radialSegments?: 8, tubularSegments?: 12)",
+ returns: "THREE.TorusGeometry",
+ category: "geometry",
+ description: "Donut shape. For rings, tyres, barrel ribs.",
+ example: "const geo = torusGeo(0.4, 0.04, 8, 16);"
+ },
+ {
+ name: "planeGeo",
+ signature: "planeGeo(width: number, height: number, widthSegments?: 1, heightSegments?: 1)",
+ returns: "THREE.PlaneGeometry",
+ category: "geometry",
+ description: "Flat quad for TEXTURED surfaces (ground, signs, walls with albedo maps). For solid-color decals like red stars, hull numbers, stamps, or window cutouts on no-texture assets use decalBox — a bare planeGeo without a texture will render as a disconnected 2-tri square and get flagged as a stray plane.",
+ example: "const geo = planeGeo(4, 4);"
+ },
+ {
+ name: "decalBox",
+ signature: "decalBox(width: number, height: number, depth?: 0.01)",
+ returns: "THREE.BoxGeometry",
+ category: "geometry",
+ description: "Thin box for solid-color surface decals: red stars, hull numbers, stamps, no-texture windows. Unlike planeGeo, has real depth so it visibly attaches to its host surface. Must be placed on a surface with position + rotation.",
+ example: `const star = decalBox(0.18, 0.18, 0.01);
+createPart('Mesh_StarPort', star, gameMaterial(0xc61f2a), { position: [0.4, 0.6, 0.41], parent: fuselage });`,
+ promptNotes: "Offset at least 0.01 outside the host surface to avoid z-fighting (a 0.8-wide hull has faces at z=±0.4, so place the decal at z=±0.41)."
+ },
+ {
+ name: "foliageCardGeo",
+ signature: "foliageCardGeo(opts?: { width?, height?, yPivot?: 0..1 })",
+ returns: "THREE.PlaneGeometry",
+ category: "geometry",
+ description: "Single-quad foliage card with a configurable Y pivot. yPivot=0 plants the quad on the ground. Pair with an alpha-tested material and a leaf/plant sprite.",
+ example: `const leaves = await materialRecipe('kiln.material.leaf.v1');
+const quad = foliageCardGeo({ width: 4, height: 6, yPivot: 0 });
+createPart('Mesh_Fern', quad, leaves, { parent: root });`
+ },
+ {
+ name: "crossedQuadsGeo",
+ signature: "crossedQuadsGeo(opts?: { width?, height?, planes?: 2 | 3, yPivot? })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Cross-billboard bush primitive: 2 or 3 planes intersecting along the Y axis. Reads as a dense plant from any angle, cheaper than real geometry.",
+ example: `const leaves = await materialRecipe('kiln.material.leaf.v1');
+const bush = crossedQuadsGeo({ width: 2, height: 2, planes: 3 });
+createPart('Mesh_Bush', bush, leaves, { parent: root });`
+ },
+ {
+ name: "octaGridPlane",
+ signature: "octaGridPlane({ tilesX, tilesY, width?, height?, yPivot? })",
+ returns: "THREE.PlaneGeometry",
+ category: "geometry",
+ description: "Atlas-ready billboard quad. UVs are pre-scaled to cover one tile of a tilesX×tilesY atlas; the consumer shader adds per-instance tile offsets at draw time.",
+ example: "const card = octaGridPlane({ tilesX: 4, tilesY: 4, width: 6, height: 6 });"
+ },
+ {
+ name: "wingGeo",
+ signature: "wingGeo(opts?: { span, rootChord, tipChord, sweep, thickness, dihedral })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Trapezoid wing panel. Local root edge is at Z=0, span extends toward +Z, positive sweep moves the tip aft along -X.",
+ example: "const geo = wingGeo({ span: 2.2, rootChord: 0.8, tipChord: 0.3, sweep: 0.25, dihedral: 0.08 });"
+ },
+ {
+ name: "gearGeo",
+ signature: "gearGeo(opts?: { teeth?: 12, rootRadius?: 0.8, tipRadius?: 1.0, boreRadius?: 0.2, height?: 0.3, toothWidthFrac?: 0.5 })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Stylized gear with flat edges and an optional center bore; no CSG. Use boreRadius < rootRadius < tipRadius. Radii are absolute: an omitted rootRadius stays 0.8 when tipRadius changes. Set all three radii for small gears.",
+ example: `const g = gearGeo({ teeth: 28, rootRadius: 0.063, tipRadius: 0.075, boreRadius: 0.012, height: 0.024 });
+createPart('Gear', g, gameMaterial(0x909090, { metalness: 0.8 }), { parent: root });`
+ },
+ {
+ name: "bladeGeo",
+ signature: "bladeGeo(opts?: { length?: 1.5, baseWidth?: 0.1, thickness?: 0.015, tipLength?: 0.25, edgeBevel?: 0 })",
+ returns: "THREE.BufferGeometry",
+ category: "geometry",
+ description: "Parametric sword blade: rectangular base tapering to a point over tipLength. edgeBevel > 0 pinches the cross-section toward a diamond ridge.",
+ example: `const b = bladeGeo({ length: 1.6, baseWidth: 0.09, tipLength: 0.3, edgeBevel: 0.5 });
+createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`
+ },
+ {
+ name: "gameMaterial",
+ signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Flat-shaded PBR material. Default for game-ready low-poly. Use for 95% of parts.",
+ example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9 });"
+ },
+ {
+ name: "materialRecipe",
+ signature: "await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })",
+ returns: "Promise<THREE.MeshStandardMaterial>",
+ category: "material",
+ description: "Resolves a versioned portable bark/leaf/wood/stone/rubber/painted-metal/cloth/skin/glass/emissive recipe to standard glTF PBR.",
+ example: "const bark = await materialRecipe('kiln.material.bark.v1', { baseColor: '#6b4328' });",
+ promptNotes: "Use only listed kiln.material.*.v1 IDs and approved kiln.texture.* resource IDs. Leaf is MASK, glass is BLEND, and host file paths are forbidden."
+ },
+ {
+ name: "compilePortableMaterialSpecV2",
+ signature: "await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', name?, baseColor?, roughness?, metalness?, emissive?, emissiveIntensity?, alphaMode?, alphaCutoff?, doubleSided?, textures?: { baseColor?, normal?, metallicRoughness?, emissive?, occlusion? } })",
+ returns: "Promise<THREE.MeshStandardMaterial>",
+ category: "material",
+ description: "Compiles the strict portable material contract. Texture refs are either typed procedural V2 specs or closed approved kiln.texture.* IDs; paths, URLs, raw textures, callbacks, and shader source are rejected.",
+ example: "const steel = await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', roughness: 0.45, metalness: 0.85, textures: { metallicRoughness: { kind: 'procedural', spec: { schemaVersion: 2, usage: 'metallicRoughness', size: 64, layers: [{ op: 'solid', color: 0x0080cc }] } } } });",
+ promptNotes: "Use metallicRoughness as one packed G=roughness/B=metalness map. Every procedural ref usage must match its slot; resource refs must be approved for that exact slot."
+ },
+ {
+ name: "basicMaterial",
+ signature: "basicMaterial(color, opts?: { transparent, opacity })",
+ returns: "THREE.MeshBasicMaterial",
+ category: "material",
+ description: "Unlit flat material. For UI / effects where lighting is baked in.",
+ example: "const mat = basicMaterial(0xffffff, { transparent: true, opacity: 0.5 });"
+ },
+ {
+ name: "glassMaterial",
+ signature: "glassMaterial(color, opts?: { opacity, roughness, metalness })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.",
+ example: "const mat = glassMaterial(0x66ccff, { opacity: 0.3 });"
+ },
+ {
+ name: "lambertMaterial",
+ signature: "lambertMaterial(color, opts?: { flatShading, emissive })",
+ returns: "THREE.MeshLambertMaterial",
+ category: "material",
+ description: "Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.",
+ example: "const mat = lambertMaterial(0x2a4d14, { flatShading: true });"
+ },
+ {
+ name: "rotationTrack",
+ signature: "rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP')",
+ returns: "THREE.QuaternionKeyframeTrack",
+ category: "animation",
+ description: "Rotation track in degrees, auto-converted to quaternions. Joint name must include `Joint_` prefix.",
+ example: "rotationTrack('Joint_Lid', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [90, 0, 0] }]);"
+ },
+ {
+ name: "positionTrack",
+ signature: "positionTrack(jointName: string, keyframes: Array<{ time, position: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')",
+ returns: "THREE.VectorKeyframeTrack",
+ category: "animation",
+ description: "Position track in world units. Always use `position:` not `value:` in keyframes.",
+ example: "positionTrack('Joint_Body', [{ time: 0, position: [0, 0, 0] }, { time: 1, position: [0, 0.1, 0] }]);"
+ },
+ {
+ name: "scaleTrack",
+ signature: "scaleTrack(jointName: string, keyframes: Array<{ time, scale: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')",
+ returns: "THREE.VectorKeyframeTrack",
+ category: "animation",
+ description: "Uniform or per-axis scale track.",
+ example: "scaleTrack('Joint_Chest', [{ time: 0, scale: [1, 1, 1] }, { time: 1, scale: [1.1, 1.1, 1.1] }]);"
+ },
+ {
+ name: "createClip",
+ signature: "createClip(name: string, duration: number, tracks: KeyframeTrack[])",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "Collects tracks into a named clip. Returned from animate().",
+ example: "return [createClip('Open', 1, [rotationTrack('Joint_Lid', [...])])];"
+ },
+ {
+ name: "idleBreathing",
+ signature: "idleBreathing(bodyJoint: string, duration?: 2, amount?: 0.02)",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "Gentle Y-axis bob. For NPC idle states.",
+ example: "return [idleBreathing('Joint_Body')];"
+ },
+ {
+ name: "bobbingAnimation",
+ signature: "bobbingAnimation(rootName: string, duration?: 2, height?: 0.1)",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "Floating / bobbing loop for pickups and effects.",
+ example: "return [bobbingAnimation('Joint_Root', 1.5, 0.08)];"
+ },
+ {
+ name: "spinAnimation",
+ signature: "spinAnimation(jointName: string, duration?: 2, axis?: 'x' | 'y' | 'z')",
+ returns: "THREE.AnimationClip",
+ category: "animation",
+ description: "360° rotation over `duration` around `axis`.",
+ example: "return [spinAnimation('Joint_Rotor', 0.5, 'y')];"
+ },
+ {
+ name: "cloneGeometry",
+ signature: "cloneGeometry(geo: BufferGeometry)",
+ returns: "THREE.BufferGeometry (same ref)",
+ category: "instancing",
+ description: "Deprecated name: returns the SAME geometry, without copying. Use copyGeometry for independent vertex edits, or pass the original geometry directly for intentional sharing.",
+ example: "const wheelGeo = cylinderGeo(0.4, 0.4, 0.2, 12);"
+ },
+ {
+ name: "cloneMaterial",
+ signature: "cloneMaterial(mat: Material)",
+ returns: "THREE.Material (same ref)",
+ category: "instancing",
+ description: "Deprecated name: returns the SAME material. Use copyMaterial for independent property edits, or pass the original for intentional sharing.",
+ example: "const rubberMat = gameMaterial(0x1a1a1a, { roughness: 0.95 });"
+ },
+ {
+ name: "createInstance",
+ signature: "createInstance(name, source, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, parent })",
+ returns: "THREE.Object3D",
+ category: "instancing",
+ description: "Creates a new mesh reusing an existing part's geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows. `rotation` is in DEGREES, like createPart.",
+ example: `const wheelFL = createPart('WheelFL', wheelGeo, rubberMat, { position: [-0.8, 0.3, 1.2], parent: root });
+createInstance('WheelFR', wheelFL, { position: [0.8, 0.3, 1.2], parent: root });
+createInstance('WheelRL', wheelFL, { position: [-0.8, 0.3, -1.2], parent: root });
+createInstance('WheelRR', wheelFL, { position: [0.8, 0.3, -1.2], parent: root });`
+ },
+ {
+ name: "boolUnion",
+ signature: "await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Merges two or more parts into one watertight manifold mesh. Default flat shading (hard edges) — pass { smooth: true } as last arg for averaged normals on organic merges.",
+ example: `const body = new THREE.Mesh(boxGeo(2, 1, 1), steel);
+const turret = new THREE.Mesh(cylinderGeo(0.3, 0.3, 0.4, 16), steel);
+turret.position.y = 0.5;
+const hull = await boolUnion('Hull', body, turret);`
+ },
+ {
+ name: "boolDiff",
+ signature: "await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Subtracts cutters from a body (holes, button recesses, window slots). Default flat shading for sharp mechanical edges.",
+ example: `const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel);
+const teeth = [...]; // 8 radially-arrayed box meshes
+const gear = await boolDiff('Gear', body, ...teeth); // hard-edged`
+ },
+ {
+ name: "roundedBoxGeo",
+ signature: "await roundedBoxGeo(width: number, height: number, depth: number, radius: number, opts?: { style?: 'round' | 'chamfer', segments?: 12, smooth?: boolean })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "csg",
+ description: "A box with all twelve edges rounded (or chamfered) at the EXACT outer size requested — roundedBoxGeo(1, 1, 1, 0.1) measures 1x1x1, it does not grow. Use it anywhere boxGeo reads too sharp: consoles, crates, appliances, handheld props, machined blocks.",
+ promptNotes: "Real objects almost never have perfectly sharp box edges, and a small radius is the single cheapest upgrade to how manufactured an asset looks. Prefer this over boxGeo for anything moulded, cast, or machined. Keep radius small relative to the box (5-10% of the smallest dimension); radius must be less than half the smallest dimension or the call throws. style: 'chamfer' reads as machined metal, 'round' as moulded plastic. This is async — build() must be async and the call must use await.",
+ example: `const geo = await roundedBoxGeo(1.2, 0.6, 0.8, 0.05);
+createPart('Console', geo, plastic, { position: [0, 0.3, 0], parent: root });`
+ },
+ {
+ name: "extrudeProfile",
+ signature: "await extrudeProfile(profile: [number, number][], opts?: { depth?: 1, holes?: [number, number][][], bevel?: 0, bevelStyle?: 'round' | 'chamfer', segments?: 12, twist?: 0, taper?: number | [number, number], divisions?: number, axis?: 'x' | 'y' | 'z', center?: true, smooth?: false })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "csg",
+ description: "Sweeps a closed 2D outline into a watertight solid, with optional holes, corner rounding/chamfering, twist, and taper. The way to build any cross-section that is not a box or a cylinder: L-brackets, I-beams, gaskets, washers, star and gear plates, signage, extruded trim.",
+ promptNotes: "The bevel rounds the edges PARALLEL to the sweep axis (the profile corners) — the two flat caps stay sharp. For a box rounded on all twelve edges use roundedBoxGeo instead. Holes are subtracted, so their winding order does not matter. A bevel larger than half the outline's narrowest feature throws rather than silently returning an empty solid. Output is manifold, so it feeds straight into boolUnion / boolDiff / boolIntersect. Async — await it inside an async build().",
+ example: `// L-bracket, inner AND outer corners filleted
+const outline = [[0, 0], [2, 0], [2, 0.4], [0.4, 0.4], [0.4, 2], [0, 2]];
+const geo = await extrudeProfile(outline, { depth: 0.5, bevel: 0.06 });
+createPart('Bracket', geo, steel, { parent: root });`
+ },
+ {
+ name: "revolveProfile",
+ signature: "await revolveProfile(profile: [number, number][], opts?: { segments?: 24, angle?: 360, bevel?: 0, bevelStyle?: 'round' | 'chamfer', bevelSegments?: 12, axis?: 'x' | 'y' | 'z', smooth?: true })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "csg",
+ description: "Revolves a closed 2D outline around an axis into a watertight SOLID, optionally rounding the profile corners first. Bottles, tanks, pressure vessels, wheels, turned wood, domes, buttons, pills.",
+ promptNotes: "Use this instead of lathe/revolveGeo whenever the result must survive a boolean or needs a rounded rim — lathe and revolveGeo build an open surface, this builds a closed solid. Profile convention matches lathe: x is distance from the axis, y is position along it, and only the x >= 0 side is used. Async — await it inside an async build().",
+ example: `// capsule tank with a rounded rim, then carve a port into it
+const profile = [[0, -0.5], [0.4, -0.5], [0.4, 0.5], [0, 0.5]];
+const body = await revolveProfile(profile, { bevel: 0.08, segments: 32 });
+const tank = await boolDiff('Tank', createPart('B', body, steel), portCutter);`
+ },
+ {
+ name: "circleProfile",
+ signature: "circleProfile(radius: number, segments?: 24, center?: [number, number])",
+ returns: "[number, number][]",
+ category: "csg",
+ description: "Builds a closed circular outline for extrudeProfile / revolveProfile, so you never hand-write the trigonometry. Synchronous.",
+ example: `const washer = await extrudeProfile(circleProfile(1), {
+ depth: 0.1,
+ holes: [circleProfile(0.4), circleProfile(0.1, 16, [0.7, 0])],
+});`
+ },
+ {
+ name: "boolIntersect",
+ signature: "await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Keeps only the volume where both operands overlap. Default flat shading.",
+ example: "const lens = await boolIntersect('Lens', boxMesh, sphereMesh);"
+ },
+ {
+ name: "hull",
+ signature: "await hull(name: string, ...parts: Object3D[], opts?: { smooth?: true })",
+ returns: "Promise<THREE.Mesh>",
+ category: "csg",
+ description: "Tightest convex mesh enclosing all input points. Default smooth shading (rocks, collision volumes). Pass { smooth: false } for a faceted look.",
+ example: `const rockChunks = [...]; // scattered box meshes
+const rock = await hull('Rock', ...rockChunks);`
+ },
+ {
+ name: "arrayLinear",
+ signature: "arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)",
+ returns: "THREE.Object3D[]",
+ category: "arrays",
+ description: "Places N copies of `source` along a constant offset vector. Copies share geometry + material via createInstance.",
+ example: `const post = createPart('Post0', cylinderGeo(0.05,0.05,1.5,6), wood, { position: [0,0.75,0], parent: root });
+arrayLinear('Post', post, 10, [0.5, 0, 0], root);`
+ },
+ {
+ name: "arrayRadial",
+ signature: "arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?)",
+ returns: "THREE.Object3D[]",
+ category: "arrays",
+ description: "Places N copies of `source` around the given axis. Source's local rotation is oriented outward. Perfect for gear teeth, radial bolts, circle of columns.",
+ example: `const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });
+arrayRadial('Bolt', bolt, 8, 'y', root);`
+ },
+ {
+ name: "mirror",
+ signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",
+ returns: "THREE.Object3D",
+ category: "arrays",
+ description: "Reflects source across the plane whose normal is `axis`. Uses negative scale (winding flip handled by viewers).",
+ example: "mirror('WingR', wingL, 'x', root);"
+ },
+ {
+ name: "subdivide",
+ signature: "subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { preserveUV?: boolean, split?: boolean, uvSmooth?: boolean, preserveEdges?: boolean, flatOnly?: boolean, weld?: boolean })",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Loop subdivision returns new geometry; each iteration roughly quadruples triangles and smooths the surface. Use preserveUV:true for textured meshes. Legacy position-only welding discards UVs and reports that loss. This smooths shapes, not selected-edge beveling.",
+ example: "const smoothRock = subdivide(boxGeo(1, 1, 1), 2);"
+ },
+ {
+ name: "mergeVertices",
+ signature: "mergeVertices(geometry: BufferGeometry, opts?: { tolerance?: 1e-4, positionOnly?: boolean } | number)",
+ returns: "THREE.BufferGeometry",
+ category: "mesh-ops",
+ description: "Returns indexed geometry. Default welding preserves attribute seams, so a textured cube retains separate face corners. positionOnly:true welds coincident positions and discards other attributes; use it explicitly when changing topology and regenerate shading/UVs afterward.",
+ example: `const welded = mergeVertices(boxGeo(1, 1, 1), { positionOnly: true });
+const rock = displace(subdivide(welded, 2), ([x,y,z]) => [0.08*Math.sin(y*7+z*3), 0.04*Math.sin(x*9), 0]);`
+ },
+ {
+ name: "curveToMesh",
+ signature: "curveToMesh(points: [x,y,z][], radius, tubularSegs?: 32, radialSegs?: 8, closed?: false)",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Sweeps a circular profile along a path. Equivalent to Blender's Curve to Mesh node with a circle profile. Use for pipes, cables, tubular frames.",
+ example: "const pipe = curveToMesh([[0,0,0],[0,1,0],[1,1,0],[1,2,0]], 0.1);"
+ },
+ {
+ name: "pipeAlongPath",
+ signature: "pipeAlongPath(points: [x,y,z][], radius: number, opts?: { bendRadius?: 0, closed?: false, tubularSegments?: 32, radialSegments?: 8 })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Path-driven swept circle with optional bend smoothing. Generalises beamBetween (point-to-point) and curveToMesh (raw spline) into one helper. bendRadius>0 inserts interpolated waypoints near interior corners so the spline reads as a rounded turn instead of pinching to the control point.",
+ example: "const cable = pipeAlongPath([[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]], 0.02, { bendRadius: 0.1 });"
+ },
+ {
+ name: "lathe",
+ signature: "lathe(profile: [x,y][], segments?: 12)",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Surface of revolution. Spins a 2D profile around the Y axis. For bottles, vases, wheels, turned wood parts.",
+ example: "const vase = lathe([[0.1,0],[0.3,0.5],[0.2,1],[0.1,1.2]], 16);"
+ },
+ {
+ name: "revolveGeo",
+ signature: "revolveGeo(profile: [x,y][], opts?: { angle?: 2π, axis?: [x,y,z]=[0,1,0], segments?: 12 })",
+ returns: "THREE.BufferGeometry",
+ category: "curves",
+ description: "Surface of revolution with explicit axis + sweep angle. Generalises lathe — use it when you need a partial sweep (half-dome, 90° wedge) or revolution around a non-Y axis. Profile convention is identical to lathe: x = radial distance, y = position along the axis.",
+ example: `// Half-dome (180° sweep around +Y):
+const quarter = [...Array(8)].map((_, i) => { const t = (i/7)*Math.PI/2; return [Math.cos(t), Math.sin(t)] as [number, number]; });
+const dome = revolveGeo(quarter, { angle: Math.PI });`
+ },
+ {
+ name: "bezierCurve",
+ signature: "bezierCurve(controlPoints: [x,y,z][], samples?: 32)",
+ returns: "[x,y,z][]",
+ category: "curves",
+ description: "Samples a quadratic (3 ctrl pts) or cubic (4 ctrl pts) Bézier into a point list you can feed into curveToMesh.",
+ example: `const path = bezierCurve([[0,0,0],[1,2,0],[3,2,0],[4,0,0]], 24);
+const geo = curveToMesh(path, 0.1);`
+ },
+ {
+ name: "autoUnwrap",
+ signature: "await autoUnwrap(geometry: BufferGeometry, opts?: { resolution?: 1024, padding?: 2, useNormals?: false })",
+ returns: "Promise<THREE.BufferGeometry>",
+ category: "uv",
+ description: "xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware unwraps below.",
+ example: `const unwrapped = await autoUnwrap(someCsgResult, { resolution: 1024 });
+const mesh = new THREE.Mesh(unwrapped, bakedPbr);`
+ },
+ {
+ name: "boxUnwrap",
+ signature: "boxUnwrap(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Preserves BoxGeometry's built-in per-face UVs — every face maps [0,1] with consistent orientation. Use for crates/blocks with a tileable texture. Sync; no WASM cost.",
+ example: `const crate = boxUnwrap(boxGeo(1, 1, 1));
+const mesh = new THREE.Mesh(crate, pbrMaterial({ albedo: planksTex }));`
+ },
+ {
+ name: "cylinderUnwrap",
+ signature: "cylinderUnwrap(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Preserves CylinderGeometry's built-in UVs: u wraps around the axis (horizontal texture features ring the cylinder), v runs up the height. Caps use circle-in-square. Sync; no WASM cost.",
+ example: `const barrel = cylinderUnwrap(cylinderGeo(0.5, 0.5, 1.2, 24));
+const mesh = new THREE.Mesh(barrel, pbrMaterial({ albedo: bandsTex }));`
+ },
+ {
+ name: "planeUnwrap",
+ signature: "planeUnwrap(geometry: BufferGeometry)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Projects xy-extent of the bbox to [0,1]. Use for signs/decals/posters where you want ONE readable texture and no edge-face bleeding. Sync.",
+ example: `const sign = planeUnwrap(planeGeo(1, 0.6));
+const mesh = new THREE.Mesh(sign, pbrMaterial({ albedo: kilnTextTex }));`
+ },
+ {
+ name: "panelRemapV",
+ signature: "panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)",
+ returns: "THREE.BufferGeometry",
+ category: "uv",
+ description: "Scales an existing UV attribute so a small mesh samples a sub-region of a SHARED texture. Replaces the broken texture.clone() pattern (Three.js Texture.clone() runs JSON.stringify on userData, mangling encoded PNG bytes — panelRemapV avoids that by remapping UVs on the geometry instead). Typical use: multi-zone albedo where v=0..0.30 is plain panel and v=0.30..1 has windows/markings — small parts call panelRemapV(unwrap(geo), 0.30) to sample only the clean strip.",
+ example: `const cowlGeo = panelRemapV(cylinderUnwrap(capsuleXGeo(0.45, 1.0)), 0.30);
+const cowl = new THREE.Mesh(cowlGeo, bodyMat); // SAME bodyMat as fuselage, no clone needed`
+ },
+ {
+ name: "loadApprovedTexture",
+ signature: "await loadApprovedTexture(resourceId)",
+ returns: "Promise<THREE.DataTexture>",
+ category: "textures",
+ description: "Loads one approved kiln.texture.* resource ID through the host-injected closed resolver. The registry fixes bytes, MIME, usage, dimensions, hash, and deadline; paths, URLs, byte arrays, resolver objects, hashes, and options are rejected.",
+ example: "const bark = await loadApprovedTexture('kiln.texture.bark-brown-01-albedo.v1');",
+ promptNotes: "Use only a concrete resource ID listed in material capabilities; never invent one. Prefer materialRecipe when a recipe already binds the family, or proceduralTexture V2 for authored surfaces. NEVER texture.clone() a loaded texture (clone() corrupts encoded bytes and breaks GLB export)."
+ },
+ {
+ name: "proceduralTexture",
+ signature: "proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })",
+ returns: "THREE.DataTexture (tiling, sRGB or linear per usage)",
+ category: "textures",
+ description: "Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.",
+ example: "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",
+ promptNotes: "Sync — no await. Strict V2 JSON boundary: unknown/prototype keys, callbacks, paths, URLs, and shader source are rejected. Prefer this over approved resources for describable surfaces. Max 8 layers, power-of-two size up to 1024. Only the six listed ops exist."
+ },
+ {
+ name: "normalMapFromHeight",
+ signature: "normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })",
+ returns: "THREE.DataTexture (linear normal map)",
+ category: "textures",
+ description: "Derives a tangent-space normal map from the source texture's brightness, treating it as height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at the edges, so a tiling source gives a tiling normal map.",
+ example: `const bark = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] });
+const mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });`,
+ promptNotes: "strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always linear data — never assign it to an albedo/emissive slot."
+ },
+ {
+ name: "pbrMaterial",
+ signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, aoMap?, alphaMode?, alphaCutoff?, doubleSided? })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. Supports OPAQUE/MASK/BLEND and double-sided output.",
+ example: `const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });
+const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });`
+ },
+ {
+ name: "foliageMaterial",
+ signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",
+ returns: "THREE.MeshStandardMaterial",
+ category: "material",
+ description: "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",
+ example: "const mat = await materialRecipe('kiln.material.leaf.v1');"
+ },
+ {
+ name: "countTriangles",
+ signature: "countTriangles(root: Object3D)",
+ returns: "number",
+ category: "utility",
+ description: "Sums triangle count across every mesh in the subtree.",
+ example: "meta.tris = countTriangles(root);"
+ },
+ {
+ name: "countMaterials",
+ signature: "countMaterials(root: Object3D)",
+ returns: "number",
+ category: "utility",
+ description: "Unique material count (by reference) across the subtree.",
+ example: "const mats = countMaterials(root);"
+ },
+ {
+ name: "getJointNames",
+ signature: "getJointNames(root: Object3D)",
+ returns: "string[]",
+ category: "utility",
+ description: "All node names beginning with `Joint_`. Use to sanity-check animation targets.",
+ example: "const joints = getJointNames(root);"
+ },
+ {
+ name: "validateAsset",
+ signature: "validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture' | 'vegetation' | 'vehicle')",
+ returns: "{ valid, errors, warnings }",
+ category: "utility",
+ description: "Checks geometry and material costs for the selected category. No default triangle limit; choose detail for the intended runtime and inspect measured draw calls.",
+ example: "const v = validateAsset(root, 'prop');"
+ }
+ ];
+});
+
// src/evaluator/authoring-diagnostic.ts
function authoringDiagnosticAdvice(diagnostic) {
if (diagnostic === "UNBOUND_VARIABLE")
@@ -1690,7 +2612,7 @@ function rethrowAuthoringError(error) {
}
throw error;
}
-var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", AuthoringDiagnosticError;
+var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_list_primitives to confirm the exact name and signature; the sandbox exposes only those globals.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", AuthoringDiagnosticError;
var init_authoring_diagnostic = __esm(() => {
AuthoringDiagnosticError = class AuthoringDiagnosticError extends Error {
diagnostic;
@@ -19811,8 +20733,74 @@ function validate(code, _opts = {}) {
line: smell.line
});
}
+ warnings.push(...unknownHelperWarnings(ast));
return toResult(issues, warnings, analysis.estimatedTris);
}
+function unknownHelperWarnings(ast) {
+ const declared = new Set;
+ const bind = (node) => {
+ const target = node;
+ if (!target?.type)
+ return;
+ if (target.type === "Identifier")
+ declared.add(target["name"]);
+ else if (target.type === "ObjectPattern")
+ for (const prop of target["properties"])
+ bind(prop.value ?? prop.argument);
+ else if (target.type === "ArrayPattern")
+ for (const el of target["elements"])
+ bind(el);
+ else if (target.type === "AssignmentPattern")
+ bind(target["left"]);
+ else if (target.type === "RestElement")
+ bind(target["argument"]);
+ };
+ const params = (node) => {
+ const fn = node;
+ if (fn.id?.name)
+ declared.add(fn.id.name);
+ for (const param of fn.params ?? [])
+ bind(param);
+ };
+ walk.simple(ast, {
+ VariableDeclarator(node) {
+ bind(node.id);
+ },
+ FunctionDeclaration(node) {
+ params(node);
+ },
+ FunctionExpression(node) {
+ params(node);
+ },
+ ArrowFunctionExpression(node) {
+ params(node);
+ },
+ ClassDeclaration(node) {
+ params(node);
+ },
+ CatchClause(node) {
+ bind(node.param);
+ }
+ });
+ const seen = new Map;
+ walk.simple(ast, {
+ CallExpression(node) {
+ const callee = node.callee;
+ if (callee?.type !== "Identifier" || !callee.name)
+ return;
+ const name = callee.name;
+ if (declared.has(name) || SANDBOX_CALLABLES.has(name) || seen.has(name))
+ return;
+ seen.set(name, node.loc?.start?.line);
+ }
+ });
+ return [...seen].map(([name, line]) => ({
+ code: "UNKNOWN_HELPER",
+ message: `${name}() is not declared in this program and is not a Kiln sandbox global; the build will fail when it runs.`,
+ fixHint: "Call kiln_list_primitives to confirm the helper name and signature, or declare the function in this program.",
+ ...line === undefined ? {} : { line }
+ }));
+}
function assertGeneratedSourceSafe(code) {
let ast;
try {
@@ -20327,8 +21315,45 @@ function hasBreak(body) {
});
return found;
}
-var GeneratedSourcePolicyError, FORBIDDEN_AMBIENT_IDENTIFIERS, FORBIDDEN_THREE_CONSTRUCTORS, ROTATION_OPTION_FNS;
+var SANDBOX_CALLABLES, GeneratedSourcePolicyError, FORBIDDEN_AMBIENT_IDENTIFIERS, FORBIDDEN_THREE_CONSTRUCTORS, ROTATION_OPTION_FNS;
var init_validation = __esm(() => {
+ init_list_primitives();
+ SANDBOX_CALLABLES = new Set([
+ ...listPrimitives().map((primitive) => primitive.name),
+ "Array",
+ "BigInt",
+ "Boolean",
+ "Error",
+ "Float32Array",
+ "Float64Array",
+ "Int16Array",
+ "Int32Array",
+ "Int8Array",
+ "Map",
+ "Number",
+ "Object",
+ "Promise",
+ "Proxy",
+ "RangeError",
+ "Reflect",
+ "RegExp",
+ "Set",
+ "String",
+ "Symbol",
+ "TypeError",
+ "Uint16Array",
+ "Uint32Array",
+ "Uint8Array",
+ "WeakMap",
+ "WeakSet",
+ "decodeURIComponent",
+ "encodeURIComponent",
+ "isFinite",
+ "isNaN",
+ "parseFloat",
+ "parseInt",
+ "structuredClone"
+ ]);
GeneratedSourcePolicyError = class GeneratedSourcePolicyError extends Error {
code;
line;
@@ -26425,6 +27450,7 @@ async function readAssetResource(library, uri) {
// src/mcp-server.ts
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { AsyncLocalStorage } from "async_hooks";
+import { fileURLToPath as fileURLToPath4 } from "url";
// src/tools/registry.ts
init_capture_cache();
@@ -26594,924 +27620,8 @@ function createKilnSourceDef(store) {
}
// src/tools/discovery.ts
+init_list_primitives();
import { z as z3 } from "zod";
-
-// src/geometry-catalog.ts
-var geometryPrimitives = [
- {
- name: "copyGeometry",
- signature: "copyGeometry(geometry: BufferGeometry)",
- returns: "THREE.BufferGeometry",
- category: "instancing",
- description: "Returns an independent geometry with copied vertex buffers. Use before direct mutation of a cached primitive.",
- example: "const editable = copyGeometry(boxGeo(1, 1, 1)); editable.translate(0, 0.5, 0);"
- },
- {
- name: "copyMaterial",
- signature: "copyMaterial(material: Material)",
- returns: "THREE.Material (same subtype)",
- category: "instancing",
- description: "Copies material properties so edits do not change other parts. Referenced textures remain shared.",
- example: "const red = copyMaterial(steel); red.color.set(0xaa2222);"
- },
- {
- name: "meshGeo",
- signature: "meshGeo({ positions: number[], indices?: number[], normals?: number[], uvs?: number[], tangents?: number[] })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Builds an owned triangle mesh from flat numeric arrays. Validates finite values, attribute lengths and indices; computes normals if absent. Counterclockwise winding.",
- example: "const triangle = meshGeo({ positions: [0,0,0, 1,0,0, 0,1,0], indices: [0,1,2] });"
- },
- {
- name: "parametricSurface",
- signature: "parametricSurface(sample: (u,v) => [x,y,z], opts?: { u?: [0,1], v?: [0,1], uSegments?: 24, vSegments?: 24, periodicU?: false, periodicV?: false, orientation?: 'uv'|'vu' })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Samples an equation into an owned surface with UVs. Periodic endpoints must coincide; UV seams retain matching normals. A surface is not automatically a watertight solid.",
- example: "const canopy = parametricSurface((u,v) => [u, 0.3*Math.sin(u*3)*Math.cos(v*2), v], { u: [-2,2], v: [-1,1] });"
- },
- {
- name: "geometryDiagnostics",
- signature: "geometryDiagnostics(geometry: BufferGeometry, tolerance?: 1e-6)",
- returns: "{ vertices, triangles, boundaryEdges, nonManifoldEdges, orientationConflicts, degenerateTriangles, invalidIndices, nonFiniteVertices }",
- category: "utility",
- description: "Counts mesh topology problems after position-based seam matching. Open boundaries are valid for sheets; closed edges alone do not prove a self-intersection-free solid.",
- example: "const topology = geometryDiagnostics(shell);"
- },
- {
- name: "creaseNormals",
- signature: "creaseNormals(geometry: BufferGeometry, opts?: { angle?: 60, tolerance?: number })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Returns owned geometry with angle-limited smooth normals, preserving UV corners. Angle is degrees. Invalidates tangents; use after shaping for sharp rims and smooth walls.",
- example: "const shell = creaseNormals(cylinderGeo(1,1,2,32), { angle: 45 });"
- },
- {
- name: "bend",
- signature: "bend(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Bends local +Y toward +X through angle degrees. Returns owned geometry and updated normals/bounds; preserves UVs, invalidates tangents. Frame rotation is Euler XYZ degrees.",
- promptNotes: "Deformation interval uses local Y distances; outside vertices stay unchanged. Add enough segments before bending. Falloff returns 0..1; use it to avoid a discontinuity at a selected interval boundary.",
- example: "const arch = bend(planeGeo(1,4,4,32), { angle: 90 });"
- },
- {
- name: "twist",
- signature: "twist(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Rotates the cross-section progressively around local +Y, reaching angle degrees at the end. Returns owned geometry; frame rotation uses Euler XYZ degrees.",
- example: "const spiral = twist(column, { angle: 120 });"
- },
- {
- name: "taper",
- signature: "taper(geometry, { startScale?: [1,1], endScale: [x,z], frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Scales local X/Z across the local Y interval using positive start/end scale pairs. Returns owned geometry; preserves UVs and invalidates tangents.",
- example: "const narrowed = taper(column, { endScale: [0.4,0.7] });"
- },
- {
- name: "displace",
- signature: "displace(geometry, offset: ([x,y,z], t) => [dx,dy,dz], opts?: { frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Adds an authored displacement vector in the chosen local frame. Returns owned geometry; callback coordinates are local and t is normalized along the interval.",
- example: "const rippled = displace(surface, ([x,y,z]) => [0, 0.1*Math.sin(x*8), 0]);"
- },
- {
- name: "sweepProfile",
- signature: "sweepProfile(profile: [x,z][], path: [x,y,z][], opts?: { cap?: true, closed?: false, up?: [x,y,z], twist?: 0, scale?: number | [x,z][] })",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Sweeps a simple noncircular profile along polyline stations using transported frames. Supports total twist in degrees and per-station scales. Generates UVs and optional caps.",
- promptNotes: "First version supports one simple profile without holes. Closed paths omit the repeated endpoint and require twist to be a multiple of 360. up sets the initial profile +Z direction and cannot parallel the path. Tight-turn warnings do not replace visual inspection for self-intersections.",
- example: "const rail = sweepProfile([[-.1,-.2],[.1,-.2],[.1,.2],[-.1,.2]], [[0,0,0],[0,1,0],[1,2,0]]);"
- },
- {
- name: "loftProfiles",
- signature: "loftProfiles(sections: { profile: [x,z][], frame?: { origin, rotation } }[], opts?: { cap?: true })",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Joins corresponding simple profiles in explicit local XZ planes. Each frame uses Euler XYZ degrees and local +Y along the loft. Profiles need equal point counts and corresponding vertices.",
- promptNotes: "No holes or automatic profile correspondence. Opposite winding is normalized while preserving the first point. Caps close boundaries but do not prove the loft has no self-intersections.",
- example: "const hull = loftProfiles([{ profile: wide }, { profile: narrow, frame: { origin: [0,2,0] } }]);"
- },
- {
- name: "implicitSurface",
- signature: "await implicitSurface(sample: ([x,y,z]) => signedValue, { bounds: { min, max }, edgeLength, maxCells?: 1000000, maxEvaluations?: 8000000, level?: 0, tolerance?: -1, smooth?: true })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "geometry",
- description: "Experimental positive-inside implicit field sampled into a solid mesh. Requires explicit bounds and resolution; checks grid size and actual evaluation count. Output has no UVs.",
- promptNotes: "Use async build and await. Smaller edgeLength increases cost sharply. This helper cannot stop a callback that never returns; the host evaluator process provides that boundary. Thin features and geometric accuracy require inspection.",
- example: "const blob = await implicitSurface(([x,y,z]) => 1-Math.hypot(x,y,z), { bounds: { min: [-1.2,-1.2,-1.2], max: [1.2,1.2,1.2] }, edgeLength: 0.15 });"
- }
-];
-
-// src/list-primitives.ts
-var PRIMITIVES = [
- ...geometryPrimitives,
- {
- name: "createRoot",
- signature: "createRoot(name: string)",
- returns: "THREE.Object3D",
- category: "structure",
- description: "Creates the root Object3D for an asset. Call first in build().",
- example: "const root = createRoot('FuelDrum');"
- },
- {
- name: "createPivot",
- signature: "createPivot(name: string, position?: [x, y, z], parent?: Object3D)",
- returns: "THREE.Object3D (prefixed `Joint_`)",
- category: "structure",
- description: "Creates an empty pivot node for skeletal animation. Name is auto-prefixed with `Joint_`.",
- example: "const hip = createPivot('Hip', [0, 1, 0], root);"
- },
- {
- name: "createJointChain",
- signature: "createJointChain(name, segments: { role, offset, aliases?, side?, localForwardAxis?, localBendAxis?, endEffector?, contact? }[], opts?: { parent?, parentRole? })",
- returns: "{ root, end, nodes, byRole, descriptors }",
- category: "structure",
- description: "Creates one body-plan-neutral deterministic Joint_* chain with explicit parent edges, rest frames, local axes, end effectors, contacts, and semantic metadata.",
- example: "const leg = createJointChain('LegL', [{ role: 'hip.left', offset: [0, 1, -0.2], side: 'left' }, { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' }, { role: 'ankle.left', offset: [0, -0.5, 0], side: 'left', endEffector: true, contact: true }], { parent: root });",
- promptNotes: "Use only the resolved body-plan graph. Offsets are local to the previous joint; contact end effectors must land at world Y=0."
- },
- {
- name: "createVehicleFrame",
- signature: "createVehicleFrame(name, opts?: { chassis?, axles?, seats?, contacts?, steering?, propulsion?, parent? })",
- returns: "{ root, chassis, axles, seats, contacts, steering, propulsion }",
- category: "structure",
- description: "Creates a canonical +X-forward/+Y-up/+Z-right vehicle frame with typed semantic sockets for chassis, support, steering, and propulsion.",
- example: "const frame = createVehicleFrame('CarFrame', { axles: [{ id: 'front', position: [1.2, 0.45, 0] }, { id: 'rear', position: [-1.2, 0.45, 0] }], parent: root });",
- promptNotes: "Generated vehicles keep +X as front. Boats and other non-wheeled subtypes use declared support/propulsion sockets, not wheel rules."
- },
- {
- name: "createWheelGeometrySet",
- signature: "createWheelGeometrySet(radius: number, width: number)",
- returns: "{ tire, rim, hub } shared THREE.BufferGeometry set",
- category: "instancing",
- description: "Creates one reusable +Z-axle tire/rim/hub geometry set for instanced wheel assemblies.",
- example: "const wheelGeo = createWheelGeometrySet(0.45, 0.22);"
- },
- {
- name: "createWheelAssembly",
- signature: "createWheelAssembly(name, { tire, rim, hub? }, { radius, width, side, index, position?, rimRadius?, hubRadius?, steering?, loadBearing?, geometries?, parent? })",
- returns: "{ root, steeringPivot?, spinPivot, tire, rim, hub, contact, radius, width, side, index, spinAxis }",
- category: "structure",
- description: "Creates one axle-centered wheel pivot containing concentric tire/rim/hub roles, a contact marker, +Z spin frame, and optional steering pivot.",
- example: "createWheelAssembly('FrontLeft', { tire: rubber, rim: metal }, { radius: 0.45, width: 0.22, side: 'left', index: 'front', position: [1.2, 0.45, -0.9], steering: true, geometries: wheelGeo, parent: frame.root });",
- promptNotes: "Keep tire, rim, and hub descendants concentric at the axle pivot. Reuse one geometry set across matching wheels."
- },
- {
- name: "createPart",
- signature: "createPart(name, geometry, material, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, pivot, parent })",
- returns: "THREE.Object3D (mesh or wrapping pivot)",
- category: "structure",
- description: "Creates a mesh, optionally wrapped in a pivot, and attaches it to `opts.parent`. `rotation` is in DEGREES (like rotationTrack), NOT radians: [0, 0, 90] is a quarter turn; [0, 0, 1.57] is a no-op.",
- example: "createPart('Barrel', cylinderGeo(0.1, 0.1, 1), gameMaterial(0x556b2f), { position: [0, 0.5, 0], rotation: [0, 0, 90], parent: root });",
- promptNotes: "AUTO-ADDS to opts.parent. NEVER call parent.add(createPart(...)) — pass { parent } instead. rotation is DEGREES — writing radians (e.g. 0.785 or Math.PI/4) silently produces ~zero rotation."
- },
- {
- name: "beamBetween",
- signature: "beamBetween(name, start: [x,y,z], end: [x,y,z], radius, material, opts?: { segments, parent })",
- returns: "THREE.Object3D (prefixed `Mesh_`)",
- category: "structure",
- description: "Creates a cylindrical rail/strut exactly between two endpoints. Use for braces, gun barrels, skid struts, cables, and scaffolding.",
- example: "beamBetween('SkidBraceA', [0.8, 0.3, 0.7], [0.8, 1.0, 0.45], 0.025, black, { parent: root });"
- },
- {
- name: "snapTo",
- signature: "snapTo(part: Object3D, host: Object3D, opts?: { axis?: 'x'|'y'|'z', overlap?: 0.02 })",
- returns: "THREE.Object3D (the part, for chaining)",
- category: "structure",
- description: 'Translates `part` by the minimal vector that brings its bounding box into contact with `host` (plus a small overlap). The direct cure for a "Floating parts" warning — attach the part instead of eyeballing a corrective offset. No-op if they already touch.',
- example: `const scope = createPart('Scope', cylinderXGeo(0.04, 0.04, 0.3), steel, { parent: root, position: [0.1, 0.32, 0] });
-snapTo(scope, receiver);`
- },
- {
- name: "createLadder",
- signature: "createLadder(name, { bottom, top, material, width?, rungCount?, railRadius?, rungRadius?, widthAxis?, parent? })",
- returns: "{ leftRail: Object3D, rightRail: Object3D, rungs: Object3D[] }",
- category: "structure",
- description: "Builds two continuous rails plus evenly-spaced rungs. Use this instead of loose boxes for ladders.",
- example: "createLadder('TowerLadder', { bottom: [0,0,0], top: [0,2.2,0], width: 0.45, rungCount: 7, material: steel, parent: root });"
- },
- {
- name: "createWingPair",
- signature: "createWingPair(name, material, { rootZ, span, rootChord, tipChord, sweep?, thickness?, dihedral?, rootX?, rootY?, parent? })",
- returns: "{ right: Object3D, left: Object3D }",
- category: "structure",
- description: "Creates mirrored trapezoid aircraft wings with roots attached at +/-rootZ. Use for aircraft wings and helicopter stub wings.",
- example: "createWingPair('MainWing', olive, { rootX: 0, rootY: 1.0, rootZ: 0.42, span: 2.4, rootChord: 0.9, tipChord: 0.35, sweep: 0.25, dihedral: 0.08, parent: root });"
- },
- {
- name: "room",
- signature: "room(name, material, { width?, depth?, height?, wallThickness?, floor?, floorThickness?, openings?: [{ wall: 'front'|'back'|'left'|'right', kind?: 'door'|'window', offset?, width?, height?, sill? }], parent? })",
- returns: "{ root: Object3D, walls: { front, back, left, right }, floor: Object3D | null }",
- category: "structure",
- description: "Builds a HOLLOW, enterable room: four thin walls + a floor, human-scaled (defaults: 2.8m ceiling, a centered 1.1x2.1m front door so it is enterable by default). `front` faces +X; the floor sits on the ground. The keystone of an architecture asset — add a roof with createRoofPlanes and fixtures as separate parts.",
- example: "const { root: hut } = room('Hut', wood, { width: 5, depth: 4, height: 2.8, openings: [{ wall: 'front', kind: 'door' }, { wall: 'right', kind: 'window' }], parent: root });",
- promptNotes: "Use for any building the player enters. Do NOT model a building as a solid block — room() guarantees real interior space and a doorway gap. Pass openings to add windows / side doors."
- },
- {
- name: "wallWithOpening",
- signature: "wallWithOpening(name, material, { length, height, thickness, axis?: 'x'|'z', opening?: { kind?: 'door'|'window', offset?, width?, height?, sill? }, parent? })",
- returns: "THREE.Object3D (wall container)",
- category: "structure",
- description: "A single wall panel with an optional real door/window cut, composed from solid box segments (side panels + lintel + window sill) — no CSG. Base at local Y=0, centered on the run axis. Use to compose custom building layouts or interior dividing walls beyond the default room().",
- example: "wallWithOpening('Partition', plaster, { length: 4, height: 2.8, thickness: 0.12, axis: 'x', opening: { kind: 'door', offset: 0.5 }, parent: root });"
- },
- {
- name: "createRoofPlanes",
- signature: "createRoofPlanes(name, material, { width, depth, height, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",
- returns: "{ root: Object3D, slopes: [Object3D, Object3D] }",
- category: "structure",
- description: "A pitched roof: two thin slopes meeting at one ridge and falling DOWN-AND-OUTWARD (opposite tilts — never mirrored the same way), footprint-matched with an eave overhang. Eave at local Y=0, ridge at Y=height, so position the group at Y=wallHeight. Returns a named group (e.g. `Roof`) the engine can lift to reveal the interior.",
- example: `const { root: roof } = createRoofPlanes('Roof', shingle, { width: 5, depth: 4, height: 1.6, overhang: 0.4, ridgeAxis: 'x', parent: root });
-roof.position.y = 2.8;`,
- promptNotes: "The two slopes must fall AWAY from each other from the ridge — createRoofPlanes does this for you. Drop it onto the walls (position.y = wall height)."
- },
- {
- name: "createGableRoof",
- signature: "createGableRoof(name, material, { spanX, spanZ, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",
- returns: "{ root, slopes: [Object3D, Object3D], faces: [RoofFaceFrame, RoofFaceFrame], rise, pitchDegrees }",
- category: "structure",
- description: "Explicit-axis gable roof using unambiguous footprint spans. Each face owns a rigid frame with ridge tangent, outward normal, downhill direction, ridge/eave endpoints, dimensions, and a live local-to-world transform.",
- example: "const roof = createGableRoof('Roof', shingles, { spanX: 8, spanZ: 5, pitchDegrees: 35, overhang: 0.35, ridgeAxis: 'x', parent: root });",
- promptNotes: "Prefer this over width/depth roof math. ridgeAxis is the direction of the ridge; roof panels run along each returned face downhill direction."
- },
- {
- name: "createGableEndPanel",
- signature: "createGableEndPanel(name, material, { span, rise, thickness?, ridgeAxis?: 'x'|'z', side?: 'positive'|'negative', openings?: [{ id?, offset?, bottom?, width, height }], parent? })",
- returns: "{ root, geometry, openings }",
- category: "structure",
- description: "Exact thick triangular end closure for a gable roof, with optional rectangular openings cut from the geometry and semantic boundary metadata.",
- example: "createGableEndPanel('FrontGable', siding, { span: 5, rise: 1.8, ridgeAxis: 'x', side: 'positive', parent: root });"
- },
- {
- name: "createGableShell",
- signature: "createGableShell(name, { wall, roof, floor?, gable? }, { spanX, spanZ, wallHeight?, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, wallThickness?, floorThickness?, closedEnds?, enterable?, openings?, gableOpenings?, parent? })",
- returns: "{ root, walls, floor, roof, gables, openings }",
- category: "structure",
- description: "Closed-by-default, correct-by-construction gable building: hollow room, floor, two opposing roof slopes, two complete gable ends, and a real front doorway when enterable.",
- example: "const house = createGableShell('House', { wall: plaster, roof: shingles }, { spanX: 8, spanZ: 5, wallHeight: 2.8, pitchDegrees: 35, ridgeAxis: 'x', parent: root });",
- promptNotes: "Use for complete gable buildings. It stamps wall, floor, slope, gable, opening, adjacency, coverage, and separability semantics for deterministic QA and roof-off views."
- },
- {
- name: "createRoofSurfaceLayout",
- signature: "createRoofSurfaceLayout(name, material, { face, kind: 'panels'|'shingles'|'seams'|'corrugations', parent?, panelWidth?, rowHeight?, spacing?, thickness? })",
- returns: "{ root, items: Object3D[] }",
- category: "structure",
- description: "Places roof-local panels, shingles, seams, or corrugations from a returned RoofFaceFrame, so repeated elements run ridge-to-eave for either ridge axis without manual Euler rotations.",
- example: "for (const face of roof.faces) createRoofSurfaceLayout('Panels_' + face.side, metal, { face, kind: 'panels', parent: roof.root });",
- promptNotes: "Always pass the face object returned by createGableRoof/createGableShell. Never infer the panel rotation from world axes."
- },
- {
- name: "createStairs",
- signature: "createStairs(name, material, { steps?, totalRise, totalRun, width, axis?: 'x'|'z', treadThickness?, riser?, parent? })",
- returns: "{ root: Object3D, steps: Object3D[] }",
- category: "structure",
- description: "A straight flight of stairs: box treads (with optional risers) climbing totalRise over totalRun from local origin toward +axis. Use for porch/entry steps or to connect storeys in a multi-storey building.",
- example: "createStairs('Porch', stone, { steps: 4, totalRise: 0.6, totalRun: 1.0, width: 1.4, axis: 'x', parent: root });"
- },
- {
- name: "boxGeo",
- signature: "boxGeo(width: number, height: number, depth: number)",
- returns: "THREE.BoxGeometry",
- category: "geometry",
- description: "6-face box. 12 tris regardless of size. Cheapest geometry.",
- example: "const geo = boxGeo(1, 0.5, 2);"
- },
- {
- name: "sphereGeo",
- signature: "sphereGeo(radius: number, widthSegments?: 8, heightSegments?: 6)",
- returns: "THREE.SphereGeometry",
- category: "geometry",
- description: "UV sphere. Default 8x6 segments = 84 tris. Bump segments for smoother curves.",
- example: "const geo = sphereGeo(0.5, 12, 8);"
- },
- {
- name: "cylinderGeo",
- signature: "cylinderGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",
- returns: "THREE.CylinderGeometry",
- category: "geometry",
- description: "Y-axis cylinder. Use radiusTop != radiusBottom for cones / tapered pieces.",
- example: "const geo = cylinderGeo(0.25, 0.25, 1, 12);"
- },
- {
- name: "cylinderYGeo",
- signature: "cylinderYGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",
- returns: "THREE.CylinderGeometry",
- category: "geometry",
- description: "Alias for cylinderGeo — a Y-axis cylinder. Provided because the sandbox exposes cylinderXGeo / cylinderZGeo and the symmetric Y form is commonly reached for.",
- example: "const geo = cylinderYGeo(0.25, 0.25, 1, 12);"
- },
- {
- name: "cylinderXGeo",
- signature: "cylinderXGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",
- returns: "THREE.CylinderGeometry",
- category: "geometry",
- description: "Cylinder pre-rotated to run along +X/-X. Use for fuselages, cannons, barrels, axles, and forward-facing tubes.",
- example: "const geo = cylinderXGeo(0.1, 0.1, 1.2, 12);"
- },
- {
- name: "cylinderZGeo",
- signature: "cylinderZGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",
- returns: "THREE.CylinderGeometry",
- category: "geometry",
- description: "Cylinder pre-rotated to run along +Z/-Z. Use for side-mounted weapons, rails, crossbars, and pipes.",
- example: "const geo = cylinderZGeo(0.08, 0.08, 0.9, 10);"
- },
- {
- name: "cylinderOnAxis",
- signature: "cylinderOnAxis(center: [x,y,z], normal: [x,y,z], radiusBottom: number, height: number, opts?: { radiusTop?, segments? })",
- returns: "THREE.CylinderGeometry",
- category: "geometry",
- description: "Frame-first cylinder: position + axis specified directly, no post-hoc rotation. Use when the cylinder needs to point along a non-cardinal direction (struts inside CSG operands, antennas off a tilted surface). For cardinal axes prefer the terser cylinderXGeo / cylinderYGeo / cylinderZGeo helpers.",
- example: "const strut = cylinderOnAxis([0.5, 0.7, 0], [1, 1, 0.3], 0.05, 0.9);"
- },
- {
- name: "capsuleGeo",
- signature: "capsuleGeo(radius: number, height: number, segments?: 6)",
- returns: "THREE.CapsuleGeometry",
- category: "geometry",
- description: "Stadium shape (cylinder with hemispherical caps). Good for limbs.",
- example: "const geo = capsuleGeo(0.1, 0.5, 6);"
- },
- {
- name: "capsuleYGeo",
- signature: "capsuleYGeo(radius: number, height: number, segments?: 6)",
- returns: "THREE.CapsuleGeometry",
- category: "geometry",
- description: "Alias for capsuleGeo — a Y-axis capsule. Provided for symmetry with capsuleXGeo / capsuleZGeo.",
- example: "const geo = capsuleYGeo(0.1, 0.5, 6);"
- },
- {
- name: "capsuleXGeo",
- signature: "capsuleXGeo(radius: number, length: number, segments?: 6)",
- returns: "THREE.CapsuleGeometry",
- category: "geometry",
- description: "Capsule pre-rotated to run along +X/-X. Use for aircraft bodies, rounded vehicle hulls, and missiles.",
- example: "const geo = capsuleXGeo(0.35, 2.4, 10);"
- },
- {
- name: "capsuleZGeo",
- signature: "capsuleZGeo(radius: number, length: number, segments?: 6)",
- returns: "THREE.CapsuleGeometry",
- category: "geometry",
- description: "Capsule pre-rotated to run along +Z/-Z. Use for lateral pods, floats, and side tanks.",
- example: "const geo = capsuleZGeo(0.18, 1.1, 8);"
- },
- {
- name: "coneGeo",
- signature: "coneGeo(radius: number, height: number, segments?: 8)",
- returns: "THREE.ConeGeometry",
- category: "geometry",
- description: "Y-axis cone (pointed up). Use for spikes, roofs, projectiles.",
- example: "const geo = coneGeo(0.3, 0.8, 8);"
- },
- {
- name: "coneYGeo",
- signature: "coneYGeo(radius: number, height: number, segments?: 8)",
- returns: "THREE.ConeGeometry",
- category: "geometry",
- description: "Alias for coneGeo — a Y-axis cone (point +Y). Provided for symmetry with coneXGeo / coneZGeo.",
- example: "const geo = coneYGeo(0.3, 0.8, 8);"
- },
- {
- name: "coneXGeo",
- signature: "coneXGeo(radius: number, length: number, segments?: 8)",
- returns: "THREE.ConeGeometry",
- category: "geometry",
- description: "Cone pre-rotated so its point faces +X. Use for noses, rockets, shells, and forward-facing tips.",
- example: "const geo = coneXGeo(0.18, 0.45, 12);"
- },
- {
- name: "coneZGeo",
- signature: "coneZGeo(radius: number, length: number, segments?: 8)",
- returns: "THREE.ConeGeometry",
- category: "geometry",
- description: "Cone pre-rotated so its point faces +Z. Use for side-facing projectiles and tips.",
- example: "const geo = coneZGeo(0.12, 0.35, 10);"
- },
- {
- name: "taperConeGeo",
- signature: "taperConeGeo(radiusBottom: number, radiusTop: number, height: number, axis?: 'x'|'y'|'z', segments?: 8)",
- returns: "THREE.CylinderGeometry",
- category: "geometry",
- description: "Truncated cone (frustum) — exposes both bottom and top radius. radiusTop=0 matches coneGeo, radiusTop=radiusBottom matches cylinderGeo. Use for pylon caps, soda cans, lampshades, anything tapered that does not come to a point. axis selects orientation (default Y).",
- example: "const cap = taperConeGeo(0.3, 0.18, 0.4); // frustum"
- },
- {
- name: "torusGeo",
- signature: "torusGeo(radius: number, tube: number, radialSegments?: 8, tubularSegments?: 12)",
- returns: "THREE.TorusGeometry",
- category: "geometry",
- description: "Donut shape. For rings, tyres, barrel ribs.",
- example: "const geo = torusGeo(0.4, 0.04, 8, 16);"
- },
- {
- name: "planeGeo",
- signature: "planeGeo(width: number, height: number, widthSegments?: 1, heightSegments?: 1)",
- returns: "THREE.PlaneGeometry",
- category: "geometry",
- description: "Flat quad for TEXTURED surfaces (ground, signs, walls with albedo maps). For solid-color decals like red stars, hull numbers, stamps, or window cutouts on no-texture assets use decalBox — a bare planeGeo without a texture will render as a disconnected 2-tri square and get flagged as a stray plane.",
- example: "const geo = planeGeo(4, 4);"
- },
- {
- name: "decalBox",
- signature: "decalBox(width: number, height: number, depth?: 0.01)",
- returns: "THREE.BoxGeometry",
- category: "geometry",
- description: "Thin box for solid-color surface decals: red stars, hull numbers, stamps, no-texture windows. Unlike planeGeo, has real depth so it visibly attaches to its host surface. Must be placed on a surface with position + rotation.",
- example: `const star = decalBox(0.18, 0.18, 0.01);
-createPart('Mesh_StarPort', star, gameMaterial(0xc61f2a), { position: [0.4, 0.6, 0.41], parent: fuselage });`,
- promptNotes: "Offset at least 0.01 outside the host surface to avoid z-fighting (a 0.8-wide hull has faces at z=±0.4, so place the decal at z=±0.41)."
- },
- {
- name: "foliageCardGeo",
- signature: "foliageCardGeo(opts?: { width?, height?, yPivot?: 0..1 })",
- returns: "THREE.PlaneGeometry",
- category: "geometry",
- description: "Single-quad foliage card with a configurable Y pivot. yPivot=0 plants the quad on the ground. Pair with an alpha-tested material and a leaf/plant sprite.",
- example: `const leaves = await materialRecipe('kiln.material.leaf.v1');
-const quad = foliageCardGeo({ width: 4, height: 6, yPivot: 0 });
-createPart('Mesh_Fern', quad, leaves, { parent: root });`
- },
- {
- name: "crossedQuadsGeo",
- signature: "crossedQuadsGeo(opts?: { width?, height?, planes?: 2 | 3, yPivot? })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Cross-billboard bush primitive: 2 or 3 planes intersecting along the Y axis. Reads as a dense plant from any angle, cheaper than real geometry.",
- example: `const leaves = await materialRecipe('kiln.material.leaf.v1');
-const bush = crossedQuadsGeo({ width: 2, height: 2, planes: 3 });
-createPart('Mesh_Bush', bush, leaves, { parent: root });`
- },
- {
- name: "octaGridPlane",
- signature: "octaGridPlane({ tilesX, tilesY, width?, height?, yPivot? })",
- returns: "THREE.PlaneGeometry",
- category: "geometry",
- description: "Atlas-ready billboard quad. UVs are pre-scaled to cover one tile of a tilesX×tilesY atlas; the consumer shader adds per-instance tile offsets at draw time.",
- example: "const card = octaGridPlane({ tilesX: 4, tilesY: 4, width: 6, height: 6 });"
- },
- {
- name: "wingGeo",
- signature: "wingGeo(opts?: { span, rootChord, tipChord, sweep, thickness, dihedral })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Trapezoid wing panel. Local root edge is at Z=0, span extends toward +Z, positive sweep moves the tip aft along -X.",
- example: "const geo = wingGeo({ span: 2.2, rootChord: 0.8, tipChord: 0.3, sweep: 0.25, dihedral: 0.08 });"
- },
- {
- name: "gearGeo",
- signature: "gearGeo(opts?: { teeth?: 12, rootRadius?: 0.8, tipRadius?: 1.0, boreRadius?: 0.2, height?: 0.3, toothWidthFrac?: 0.5 })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Stylized gear with flat edges and an optional center bore; no CSG. Use boreRadius < rootRadius < tipRadius. Radii are absolute: an omitted rootRadius stays 0.8 when tipRadius changes. Set all three radii for small gears.",
- example: `const g = gearGeo({ teeth: 28, rootRadius: 0.063, tipRadius: 0.075, boreRadius: 0.012, height: 0.024 });
-createPart('Gear', g, gameMaterial(0x909090, { metalness: 0.8 }), { parent: root });`
- },
- {
- name: "bladeGeo",
- signature: "bladeGeo(opts?: { length?: 1.5, baseWidth?: 0.1, thickness?: 0.015, tipLength?: 0.25, edgeBevel?: 0 })",
- returns: "THREE.BufferGeometry",
- category: "geometry",
- description: "Parametric sword blade: rectangular base tapering to a point over tipLength. edgeBevel > 0 pinches the cross-section toward a diamond ridge.",
- example: `const b = bladeGeo({ length: 1.6, baseWidth: 0.09, tipLength: 0.3, edgeBevel: 0.5 });
-createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`
- },
- {
- name: "gameMaterial",
- signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })",
- returns: "THREE.MeshStandardMaterial",
- category: "material",
- description: "Flat-shaded PBR material. Default for game-ready low-poly. Use for 95% of parts.",
- example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9 });"
- },
- {
- name: "materialRecipe",
- signature: "await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })",
- returns: "Promise<THREE.MeshStandardMaterial>",
- category: "material",
- description: "Resolves a versioned portable bark/leaf/wood/stone/rubber/painted-metal/cloth/skin/glass/emissive recipe to standard glTF PBR.",
- example: "const bark = await materialRecipe('kiln.material.bark.v1', { baseColor: '#6b4328' });",
- promptNotes: "Use only listed kiln.material.*.v1 IDs and approved kiln.texture.* resource IDs. Leaf is MASK, glass is BLEND, and host file paths are forbidden."
- },
- {
- name: "compilePortableMaterialSpecV2",
- signature: "await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', name?, baseColor?, roughness?, metalness?, emissive?, emissiveIntensity?, alphaMode?, alphaCutoff?, doubleSided?, textures?: { baseColor?, normal?, metallicRoughness?, emissive?, occlusion? } })",
- returns: "Promise<THREE.MeshStandardMaterial>",
- category: "material",
- description: "Compiles the strict portable material contract. Texture refs are either typed procedural V2 specs or closed approved kiln.texture.* IDs; paths, URLs, raw textures, callbacks, and shader source are rejected.",
- example: "const steel = await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', roughness: 0.45, metalness: 0.85, textures: { metallicRoughness: { kind: 'procedural', spec: { schemaVersion: 2, usage: 'metallicRoughness', size: 64, layers: [{ op: 'solid', color: 0x0080cc }] } } } });",
- promptNotes: "Use metallicRoughness as one packed G=roughness/B=metalness map. Every procedural ref usage must match its slot; resource refs must be approved for that exact slot."
- },
- {
- name: "basicMaterial",
- signature: "basicMaterial(color, opts?: { transparent, opacity })",
- returns: "THREE.MeshBasicMaterial",
- category: "material",
- description: "Unlit flat material. For UI / effects where lighting is baked in.",
- example: "const mat = basicMaterial(0xffffff, { transparent: true, opacity: 0.5 });"
- },
- {
- name: "glassMaterial",
- signature: "glassMaterial(color, opts?: { opacity, roughness, metalness })",
- returns: "THREE.MeshStandardMaterial",
- category: "material",
- description: "Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.",
- example: "const mat = glassMaterial(0x66ccff, { opacity: 0.3 });"
- },
- {
- name: "lambertMaterial",
- signature: "lambertMaterial(color, opts?: { flatShading, emissive })",
- returns: "THREE.MeshLambertMaterial",
- category: "material",
- description: "Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.",
- example: "const mat = lambertMaterial(0x2a4d14, { flatShading: true });"
- },
- {
- name: "rotationTrack",
- signature: "rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP')",
- returns: "THREE.QuaternionKeyframeTrack",
- category: "animation",
- description: "Rotation track in degrees, auto-converted to quaternions. Joint name must include `Joint_` prefix.",
- example: "rotationTrack('Joint_Lid', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [90, 0, 0] }]);"
- },
- {
- name: "positionTrack",
- signature: "positionTrack(jointName: string, keyframes: Array<{ time, position: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')",
- returns: "THREE.VectorKeyframeTrack",
- category: "animation",
- description: "Position track in world units. Always use `position:` not `value:` in keyframes.",
- example: "positionTrack('Joint_Body', [{ time: 0, position: [0, 0, 0] }, { time: 1, position: [0, 0.1, 0] }]);"
- },
- {
- name: "scaleTrack",
- signature: "scaleTrack(jointName: string, keyframes: Array<{ time, scale: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')",
- returns: "THREE.VectorKeyframeTrack",
- category: "animation",
- description: "Uniform or per-axis scale track.",
- example: "scaleTrack('Joint_Chest', [{ time: 0, scale: [1, 1, 1] }, { time: 1, scale: [1.1, 1.1, 1.1] }]);"
- },
- {
- name: "createClip",
- signature: "createClip(name: string, duration: number, tracks: KeyframeTrack[])",
- returns: "THREE.AnimationClip",
- category: "animation",
- description: "Collects tracks into a named clip. Returned from animate().",
- example: "return [createClip('Open', 1, [rotationTrack('Joint_Lid', [...])])];"
- },
- {
- name: "idleBreathing",
- signature: "idleBreathing(bodyJoint: string, duration?: 2, amount?: 0.02)",
- returns: "THREE.AnimationClip",
- category: "animation",
- description: "Gentle Y-axis bob. For NPC idle states.",
- example: "return [idleBreathing('Joint_Body')];"
- },
- {
- name: "bobbingAnimation",
- signature: "bobbingAnimation(rootName: string, duration?: 2, height?: 0.1)",
- returns: "THREE.AnimationClip",
- category: "animation",
- description: "Floating / bobbing loop for pickups and effects.",
- example: "return [bobbingAnimation('Joint_Root', 1.5, 0.08)];"
- },
- {
- name: "spinAnimation",
- signature: "spinAnimation(jointName: string, duration?: 2, axis?: 'x' | 'y' | 'z')",
- returns: "THREE.AnimationClip",
- category: "animation",
- description: "360° rotation over `duration` around `axis`.",
- example: "return [spinAnimation('Joint_Rotor', 0.5, 'y')];"
- },
- {
- name: "cloneGeometry",
- signature: "cloneGeometry(geo: BufferGeometry)",
- returns: "THREE.BufferGeometry (same ref)",
- category: "instancing",
- description: "Deprecated name: returns the SAME geometry, without copying. Use copyGeometry for independent vertex edits, or pass the original geometry directly for intentional sharing.",
- example: "const wheelGeo = cylinderGeo(0.4, 0.4, 0.2, 12);"
- },
- {
- name: "cloneMaterial",
- signature: "cloneMaterial(mat: Material)",
- returns: "THREE.Material (same ref)",
- category: "instancing",
- description: "Deprecated name: returns the SAME material. Use copyMaterial for independent property edits, or pass the original for intentional sharing.",
- example: "const rubberMat = gameMaterial(0x1a1a1a, { roughness: 0.95 });"
- },
- {
- name: "createInstance",
- signature: "createInstance(name, source, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, parent })",
- returns: "THREE.Object3D",
- category: "instancing",
- description: "Creates a new mesh reusing an existing part's geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows. `rotation` is in DEGREES, like createPart.",
- example: `const wheelFL = createPart('WheelFL', wheelGeo, rubberMat, { position: [-0.8, 0.3, 1.2], parent: root });
-createInstance('WheelFR', wheelFL, { position: [0.8, 0.3, 1.2], parent: root });
-createInstance('WheelRL', wheelFL, { position: [-0.8, 0.3, -1.2], parent: root });
-createInstance('WheelRR', wheelFL, { position: [0.8, 0.3, -1.2], parent: root });`
- },
- {
- name: "boolUnion",
- signature: "await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
- returns: "Promise<THREE.Mesh>",
- category: "csg",
- description: "Merges two or more parts into one watertight manifold mesh. Default flat shading (hard edges) — pass { smooth: true } as last arg for averaged normals on organic merges.",
- example: `const body = new THREE.Mesh(boxGeo(2, 1, 1), steel);
-const turret = new THREE.Mesh(cylinderGeo(0.3, 0.3, 0.4, 16), steel);
-turret.position.y = 0.5;
-const hull = await boolUnion('Hull', body, turret);`
- },
- {
- name: "boolDiff",
- signature: "await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",
- returns: "Promise<THREE.Mesh>",
- category: "csg",
- description: "Subtracts cutters from a body (holes, button recesses, window slots). Default flat shading for sharp mechanical edges.",
- example: `const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel);
-const teeth = [...]; // 8 radially-arrayed box meshes
-const gear = await boolDiff('Gear', body, ...teeth); // hard-edged`
- },
- {
- name: "roundedBoxGeo",
- signature: "await roundedBoxGeo(width: number, height: number, depth: number, radius: number, opts?: { style?: 'round' | 'chamfer', segments?: 12, smooth?: boolean })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "csg",
- description: "A box with all twelve edges rounded (or chamfered) at the EXACT outer size requested — roundedBoxGeo(1, 1, 1, 0.1) measures 1x1x1, it does not grow. Use it anywhere boxGeo reads too sharp: consoles, crates, appliances, handheld props, machined blocks.",
- promptNotes: "Real objects almost never have perfectly sharp box edges, and a small radius is the single cheapest upgrade to how manufactured an asset looks. Prefer this over boxGeo for anything moulded, cast, or machined. Keep radius small relative to the box (5-10% of the smallest dimension); radius must be less than half the smallest dimension or the call throws. style: 'chamfer' reads as machined metal, 'round' as moulded plastic. This is async — build() must be async and the call must use await.",
- example: `const geo = await roundedBoxGeo(1.2, 0.6, 0.8, 0.05);
-createPart('Console', geo, plastic, { position: [0, 0.3, 0], parent: root });`
- },
- {
- name: "extrudeProfile",
- signature: "await extrudeProfile(profile: [number, number][], opts?: { depth?: 1, holes?: [number, number][][], bevel?: 0, bevelStyle?: 'round' | 'chamfer', segments?: 12, twist?: 0, taper?: number | [number, number], divisions?: number, axis?: 'x' | 'y' | 'z', center?: true, smooth?: false })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "csg",
- description: "Sweeps a closed 2D outline into a watertight solid, with optional holes, corner rounding/chamfering, twist, and taper. The way to build any cross-section that is not a box or a cylinder: L-brackets, I-beams, gaskets, washers, star and gear plates, signage, extruded trim.",
- promptNotes: "The bevel rounds the edges PARALLEL to the sweep axis (the profile corners) — the two flat caps stay sharp. For a box rounded on all twelve edges use roundedBoxGeo instead. Holes are subtracted, so their winding order does not matter. A bevel larger than half the outline's narrowest feature throws rather than silently returning an empty solid. Output is manifold, so it feeds straight into boolUnion / boolDiff / boolIntersect. Async — await it inside an async build().",
- example: `// L-bracket, inner AND outer corners filleted
-const outline = [[0, 0], [2, 0], [2, 0.4], [0.4, 0.4], [0.4, 2], [0, 2]];
-const geo = await extrudeProfile(outline, { depth: 0.5, bevel: 0.06 });
-createPart('Bracket', geo, steel, { parent: root });`
- },
- {
- name: "revolveProfile",
- signature: "await revolveProfile(profile: [number, number][], opts?: { segments?: 24, angle?: 360, bevel?: 0, bevelStyle?: 'round' | 'chamfer', bevelSegments?: 12, axis?: 'x' | 'y' | 'z', smooth?: true })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "csg",
- description: "Revolves a closed 2D outline around an axis into a watertight SOLID, optionally rounding the profile corners first. Bottles, tanks, pressure vessels, wheels, turned wood, domes, buttons, pills.",
- promptNotes: "Use this instead of lathe/revolveGeo whenever the result must survive a boolean or needs a rounded rim — lathe and revolveGeo build an open surface, this builds a closed solid. Profile convention matches lathe: x is distance from the axis, y is position along it, and only the x >= 0 side is used. Async — await it inside an async build().",
- example: `// capsule tank with a rounded rim, then carve a port into it
-const profile = [[0, -0.5], [0.4, -0.5], [0.4, 0.5], [0, 0.5]];
-const body = await revolveProfile(profile, { bevel: 0.08, segments: 32 });
-const tank = await boolDiff('Tank', createPart('B', body, steel), portCutter);`
- },
- {
- name: "circleProfile",
- signature: "circleProfile(radius: number, segments?: 24, center?: [number, number])",
- returns: "[number, number][]",
- category: "csg",
- description: "Builds a closed circular outline for extrudeProfile / revolveProfile, so you never hand-write the trigonometry. Synchronous.",
- example: `const washer = await extrudeProfile(circleProfile(1), {
- depth: 0.1,
- holes: [circleProfile(0.4), circleProfile(0.1, 16, [0.7, 0])],
-});`
- },
- {
- name: "boolIntersect",
- signature: "await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })",
- returns: "Promise<THREE.Mesh>",
- category: "csg",
- description: "Keeps only the volume where both operands overlap. Default flat shading.",
- example: "const lens = await boolIntersect('Lens', boxMesh, sphereMesh);"
- },
- {
- name: "hull",
- signature: "await hull(name: string, ...parts: Object3D[], opts?: { smooth?: true })",
- returns: "Promise<THREE.Mesh>",
- category: "csg",
- description: "Tightest convex mesh enclosing all input points. Default smooth shading (rocks, collision volumes). Pass { smooth: false } for a faceted look.",
- example: `const rockChunks = [...]; // scattered box meshes
-const rock = await hull('Rock', ...rockChunks);`
- },
- {
- name: "arrayLinear",
- signature: "arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)",
- returns: "THREE.Object3D[]",
- category: "arrays",
- description: "Places N copies of `source` along a constant offset vector. Copies share geometry + material via createInstance.",
- example: `const post = createPart('Post0', cylinderGeo(0.05,0.05,1.5,6), wood, { position: [0,0.75,0], parent: root });
-arrayLinear('Post', post, 10, [0.5, 0, 0], root);`
- },
- {
- name: "arrayRadial",
- signature: "arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?)",
- returns: "THREE.Object3D[]",
- category: "arrays",
- description: "Places N copies of `source` around the given axis. Source's local rotation is oriented outward. Perfect for gear teeth, radial bolts, circle of columns.",
- example: `const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });
-arrayRadial('Bolt', bolt, 8, 'y', root);`
- },
- {
- name: "mirror",
- signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",
- returns: "THREE.Object3D",
- category: "arrays",
- description: "Reflects source across the plane whose normal is `axis`. Uses negative scale (winding flip handled by viewers).",
- example: "mirror('WingR', wingL, 'x', root);"
- },
- {
- name: "subdivide",
- signature: "subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { preserveUV?: boolean, split?: boolean, uvSmooth?: boolean, preserveEdges?: boolean, flatOnly?: boolean, weld?: boolean })",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Loop subdivision returns new geometry; each iteration roughly quadruples triangles and smooths the surface. Use preserveUV:true for textured meshes. Legacy position-only welding discards UVs and reports that loss. This smooths shapes, not selected-edge beveling.",
- example: "const smoothRock = subdivide(boxGeo(1, 1, 1), 2);"
- },
- {
- name: "mergeVertices",
- signature: "mergeVertices(geometry: BufferGeometry, opts?: { tolerance?: 1e-4, positionOnly?: boolean } | number)",
- returns: "THREE.BufferGeometry",
- category: "mesh-ops",
- description: "Returns indexed geometry. Default welding preserves attribute seams, so a textured cube retains separate face corners. positionOnly:true welds coincident positions and discards other attributes; use it explicitly when changing topology and regenerate shading/UVs afterward.",
- example: `const welded = mergeVertices(boxGeo(1, 1, 1), { positionOnly: true });
-const rock = displace(subdivide(welded, 2), ([x,y,z]) => [0.08*Math.sin(y*7+z*3), 0.04*Math.sin(x*9), 0]);`
- },
- {
- name: "curveToMesh",
- signature: "curveToMesh(points: [x,y,z][], radius, tubularSegs?: 32, radialSegs?: 8, closed?: false)",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Sweeps a circular profile along a path. Equivalent to Blender's Curve to Mesh node with a circle profile. Use for pipes, cables, tubular frames.",
- example: "const pipe = curveToMesh([[0,0,0],[0,1,0],[1,1,0],[1,2,0]], 0.1);"
- },
- {
- name: "pipeAlongPath",
- signature: "pipeAlongPath(points: [x,y,z][], radius: number, opts?: { bendRadius?: 0, closed?: false, tubularSegments?: 32, radialSegments?: 8 })",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Path-driven swept circle with optional bend smoothing. Generalises beamBetween (point-to-point) and curveToMesh (raw spline) into one helper. bendRadius>0 inserts interpolated waypoints near interior corners so the spline reads as a rounded turn instead of pinching to the control point.",
- example: "const cable = pipeAlongPath([[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]], 0.02, { bendRadius: 0.1 });"
- },
- {
- name: "lathe",
- signature: "lathe(profile: [x,y][], segments?: 12)",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Surface of revolution. Spins a 2D profile around the Y axis. For bottles, vases, wheels, turned wood parts.",
- example: "const vase = lathe([[0.1,0],[0.3,0.5],[0.2,1],[0.1,1.2]], 16);"
- },
- {
- name: "revolveGeo",
- signature: "revolveGeo(profile: [x,y][], opts?: { angle?: 2π, axis?: [x,y,z]=[0,1,0], segments?: 12 })",
- returns: "THREE.BufferGeometry",
- category: "curves",
- description: "Surface of revolution with explicit axis + sweep angle. Generalises lathe — use it when you need a partial sweep (half-dome, 90° wedge) or revolution around a non-Y axis. Profile convention is identical to lathe: x = radial distance, y = position along the axis.",
- example: `// Half-dome (180° sweep around +Y):
-const quarter = [...Array(8)].map((_, i) => { const t = (i/7)*Math.PI/2; return [Math.cos(t), Math.sin(t)] as [number, number]; });
-const dome = revolveGeo(quarter, { angle: Math.PI });`
- },
- {
- name: "bezierCurve",
- signature: "bezierCurve(controlPoints: [x,y,z][], samples?: 32)",
- returns: "[x,y,z][]",
- category: "curves",
- description: "Samples a quadratic (3 ctrl pts) or cubic (4 ctrl pts) Bézier into a point list you can feed into curveToMesh.",
- example: `const path = bezierCurve([[0,0,0],[1,2,0],[3,2,0],[4,0,0]], 24);
-const geo = curveToMesh(path, 0.1);`
- },
- {
- name: "autoUnwrap",
- signature: "await autoUnwrap(geometry: BufferGeometry, opts?: { resolution?: 1024, padding?: 2, useNormals?: false })",
- returns: "Promise<THREE.BufferGeometry>",
- category: "uv",
- description: "xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware unwraps below.",
- example: `const unwrapped = await autoUnwrap(someCsgResult, { resolution: 1024 });
-const mesh = new THREE.Mesh(unwrapped, bakedPbr);`
- },
- {
- name: "boxUnwrap",
- signature: "boxUnwrap(geometry: BufferGeometry)",
- returns: "THREE.BufferGeometry",
- category: "uv",
- description: "Preserves BoxGeometry's built-in per-face UVs — every face maps [0,1] with consistent orientation. Use for crates/blocks with a tileable texture. Sync; no WASM cost.",
- example: `const crate = boxUnwrap(boxGeo(1, 1, 1));
-const mesh = new THREE.Mesh(crate, pbrMaterial({ albedo: planksTex }));`
- },
- {
- name: "cylinderUnwrap",
- signature: "cylinderUnwrap(geometry: BufferGeometry)",
- returns: "THREE.BufferGeometry",
- category: "uv",
- description: "Preserves CylinderGeometry's built-in UVs: u wraps around the axis (horizontal texture features ring the cylinder), v runs up the height. Caps use circle-in-square. Sync; no WASM cost.",
- example: `const barrel = cylinderUnwrap(cylinderGeo(0.5, 0.5, 1.2, 24));
-const mesh = new THREE.Mesh(barrel, pbrMaterial({ albedo: bandsTex }));`
- },
- {
- name: "planeUnwrap",
- signature: "planeUnwrap(geometry: BufferGeometry)",
- returns: "THREE.BufferGeometry",
- category: "uv",
- description: "Projects xy-extent of the bbox to [0,1]. Use for signs/decals/posters where you want ONE readable texture and no edge-face bleeding. Sync.",
- example: `const sign = planeUnwrap(planeGeo(1, 0.6));
-const mesh = new THREE.Mesh(sign, pbrMaterial({ albedo: kilnTextTex }));`
- },
- {
- name: "panelRemapV",
- signature: "panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)",
- returns: "THREE.BufferGeometry",
- category: "uv",
- description: "Scales an existing UV attribute so a small mesh samples a sub-region of a SHARED texture. Replaces the broken texture.clone() pattern (Three.js Texture.clone() runs JSON.stringify on userData, mangling encoded PNG bytes — panelRemapV avoids that by remapping UVs on the geometry instead). Typical use: multi-zone albedo where v=0..0.30 is plain panel and v=0.30..1 has windows/markings — small parts call panelRemapV(unwrap(geo), 0.30) to sample only the clean strip.",
- example: `const cowlGeo = panelRemapV(cylinderUnwrap(capsuleXGeo(0.45, 1.0)), 0.30);
-const cowl = new THREE.Mesh(cowlGeo, bodyMat); // SAME bodyMat as fuselage, no clone needed`
- },
- {
- name: "loadApprovedTexture",
- signature: "await loadApprovedTexture(resourceId)",
- returns: "Promise<THREE.DataTexture>",
- category: "textures",
- description: "Loads one approved kiln.texture.* resource ID through the host-injected closed resolver. The registry fixes bytes, MIME, usage, dimensions, hash, and deadline; paths, URLs, byte arrays, resolver objects, hashes, and options are rejected.",
- example: "const bark = await loadApprovedTexture('kiln.texture.bark-brown-01-albedo.v1');",
- promptNotes: "Use only a concrete resource ID listed in material capabilities; never invent one. Prefer materialRecipe when a recipe already binds the family, or proceduralTexture V2 for authored surfaces. NEVER texture.clone() a loaded texture (clone() corrupts encoded bytes and breaks GLB export)."
- },
- {
- name: "proceduralTexture",
- signature: "proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })",
- returns: "THREE.DataTexture (tiling, sRGB or linear per usage)",
- category: "textures",
- description: "Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.",
- example: "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",
- promptNotes: "Sync — no await. Strict V2 JSON boundary: unknown/prototype keys, callbacks, paths, URLs, and shader source are rejected. Prefer this over approved resources for describable surfaces. Max 8 layers, power-of-two size up to 1024. Only the six listed ops exist."
- },
- {
- name: "normalMapFromHeight",
- signature: "normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })",
- returns: "THREE.DataTexture (linear normal map)",
- category: "textures",
- description: "Derives a tangent-space normal map from the source texture's brightness, treating it as height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at the edges, so a tiling source gives a tiling normal map.",
- example: `const bark = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] });
-const mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });`,
- promptNotes: "strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always linear data — never assign it to an albedo/emissive slot."
- },
- {
- name: "pbrMaterial",
- signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, aoMap?, alphaMode?, alphaCutoff?, doubleSided? })",
- returns: "THREE.MeshStandardMaterial",
- category: "material",
- description: "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. Supports OPAQUE/MASK/BLEND and double-sided output.",
- example: `const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });
-const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });`
- },
- {
- name: "foliageMaterial",
- signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",
- returns: "THREE.MeshStandardMaterial",
- category: "material",
- description: "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",
- example: "const mat = await materialRecipe('kiln.material.leaf.v1');"
- },
- {
- name: "countTriangles",
- signature: "countTriangles(root: Object3D)",
- returns: "number",
- category: "utility",
- description: "Sums triangle count across every mesh in the subtree.",
- example: "meta.tris = countTriangles(root);"
- },
- {
- name: "countMaterials",
- signature: "countMaterials(root: Object3D)",
- returns: "number",
- category: "utility",
- description: "Unique material count (by reference) across the subtree.",
- example: "const mats = countMaterials(root);"
- },
- {
- name: "getJointNames",
- signature: "getJointNames(root: Object3D)",
- returns: "string[]",
- category: "utility",
- description: "All node names beginning with `Joint_`. Use to sanity-check animation targets.",
- example: "const joints = getJointNames(root);"
- },
- {
- name: "validateAsset",
- signature: "validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture' | 'vegetation' | 'vehicle')",
- returns: "{ valid, errors, warnings }",
- category: "utility",
- description: "Checks geometry and material costs for the selected category. No default triangle limit; choose detail for the intended runtime and inspect measured draw calls.",
- example: "const v = validateAsset(root, 'prop');"
- }
-];
-function listPrimitives() {
- return PRIMITIVES.map((p) => ({ ...p }));
-}
-
-// src/tools/discovery.ts
init_protocol();
init_capture_limits();
var inputSchema = z3.object({
@@ -27835,10 +27945,12 @@ function createCachedEvaluatorPort(evaluator, options) {
// src/tools/registry.ts
init_validation();
+init_protocol();
init_render();
-import * as THREE35 from "three";
+init_list_primitives();
init_evaluator();
init_material_resources();
+import * as THREE35 from "three";
// src/edit-buffer.ts
class KilnDraftBuffer {
@@ -28430,6 +28542,17 @@ function collectSceneMetrics(root) {
}
return { meshes, materials: materialSet.size, bbox, lowestPart };
}
+function withSyntaxDetail(message, code) {
+ if (!message.startsWith(evaluatorOutcomeMessage("EXECUTION_REJECTED")))
+ return message;
+ let syntax;
+ try {
+ syntax = validate(code).errors.find((error) => error.startsWith("Syntax error:"));
+ } catch {
+ return message;
+ }
+ return syntax ? `${message} ${syntax}` : message;
+}
async function runRender(input, context) {
try {
const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);
@@ -28448,6 +28571,7 @@ async function runRender(input, context) {
tris: rendered.tris,
meshes: metrics.meshes,
materials: metrics.materials,
+ ...rendered.meta.instanceability ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials } : {},
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
...instanceability ? {
@@ -28462,7 +28586,7 @@ async function runRender(input, context) {
} catch (err) {
return {
ok: false,
- error: err instanceof Error ? err.message : String(err),
+ error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
warnings: []
};
}
@@ -28486,7 +28610,7 @@ async function runScreenshot(input, context) {
} catch (err) {
return {
ok: false,
- error: err instanceof Error ? err.message : String(err),
+ error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
warnings: []
};
}
@@ -28519,6 +28643,7 @@ async function runRenderViews(input, context) {
tris: rendered.tris,
meshes: metrics.meshes,
materials: metrics.materials,
+ ...rendered.meta.instanceability ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials } : {},
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
views: grid2.views,
@@ -28615,6 +28740,7 @@ async function runRenderViews(input, context) {
tris: rendered.tris,
meshes: metrics.meshes,
materials: metrics.materials,
+ ...rendered.meta.instanceability ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials } : {},
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
...rendered.meta.instanceability ? {
@@ -28638,7 +28764,7 @@ async function runRenderViews(input, context) {
} catch (err) {
return {
ok: false,
- error: err instanceof Error ? err.message : String(err),
+ error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
warnings: []
};
}
@@ -30096,6 +30222,24 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst
// src/mcp-server.ts
var MCP_SERVER_NAME = "kiln";
var MCP_SERVER_VERSION = "0.6.0";
+var packagedSkillsDir = fileURLToPath4(new URL("../skills", import.meta.url));
+var MCP_SERVER_INSTRUCTIONS = `Kiln turns JavaScript you write into GLB 3D assets and returns rendered views for review.
+
+Work by reference. Send a program once to kiln_validate or kiln_render; the result carries a programRef. Keep it exactly as returned, including a short p_ handle, and use it for every later view and edit. kiln_source with that ref and a literal query returns exact edit anchors, and kiln_edit with that ref plus edits returns a new ref and renders by default. Do not resend a whole program to change part of it.
+
+Call kiln_list_primitives before writing code to get exact helper signatures, with capabilities: true for the runtime, source, export and camera contract. Read viewFidelity in any render result before judging materials: a geometry-flat CPU image is evidence about shape, not about material.
+
+Detailed workflows ship beside this server as Agent Skills, one directory each under ${packagedSkillsDir}:
+- kiln-setup-workspace: create a managed workspace for authoring, and verify its tools came up
+- kiln-author-asset: write a new asset and export a GLB
+- kiln-refine-asset: change a saved asset through revisions
+- kiln-qa-asset: verify geometry, export fidelity, and behaviour in the destination project
+- kiln-compose-scene: arrange several existing GLB assets into a scene
+- kiln-batch-dispatch: run comparable trials across harnesses or models
+
+Read the one matching the task before authoring; each names its own reference files.
+
+Most harnesses register skills only from their own directories, so these may not appear as registered skills where you are. If the user wants them registered, offer to copy the relevant directories into .claude/skills/ or .agents/skills/ in their project. Ask before writing, and say that registration takes effect in a new session.`;
function kilnMcpToolDefs(context = {}) {
return createKilnProgramToolRegistry(context);
}
@@ -30144,7 +30288,7 @@ function createKilnMcpServer(context = {}) {
const server = new McpServer({
name: MCP_SERVER_NAME,
version: MCP_SERVER_VERSION
- });
+ }, { instructions: MCP_SERVER_INSTRUCTIONS });
server.registerResource("kiln-asset-viewer", KILN_ASSET_WIDGET_URI, {
description: "Interactive Kiln asset viewer and downloads",
mimeType: "text/html;profile=mcp-app"
@@ -30251,5 +30395,6 @@ export {
kilnMcpToolDefs,
createKilnMcpServer,
MCP_SERVER_VERSION,
- MCP_SERVER_NAME
+ MCP_SERVER_NAME,
+ MCP_SERVER_INSTRUCTIONS
};
diff --git a/docs/chatgpt.md b/docs/chatgpt.md
index 7193d0d4..0bf4f709 100644
--- a/docs/chatgpt.md
+++ b/docs/chatgpt.md
@@ -17,7 +17,7 @@ Local subprocess evaluation has deadlines and a sanitized environment; it is not
Keep `skills/*/SKILL.md` and their adjacent `references/` directories as the maintained source. Skill descriptions provide discovery; instructions load on selection, and reference files provide modeling detail when needed. Avoid pasting the complete modeling catalog into every tool description or prompt.
-The repository now contains `.codex-plugin/plugin.json` and `.mcp.json` for local plugin hosts. Generated project workspaces continue to receive their own explicit skill copies. No global skills are installed.
+The repository contains `.codex-plugin/plugin.json` for local plugin hosts, carrying its MCP server inline with a plugin-root-relative `cwd`. Root `.mcp.json` is separate and serves a different case: a plain `git clone` opened directly in a harness, where no plugin variable is defined. Generated project workspaces continue to receive their own explicit skill copies. No global skills are installed.
For ChatGPT, first register the connector and copy its technical `plugin_asdk_app...` ID from the connector page. Then build a separate package:
diff --git a/docs/plans/repo-size-and-r2-migration-2026-09-10.md b/docs/plans/repo-size-and-r2-migration-2026-09-10.md
index 3ab11739..326b46f8 100644
--- a/docs/plans/repo-size-and-r2-migration-2026-09-10.md
+++ b/docs/plans/repo-size-and-r2-migration-2026-09-10.md
@@ -149,7 +149,7 @@ disruption instead of several.
| ID | Task | State |
| --- | --- | --- |
| 3.1 | Install `git-filter-repo`. `pipx` and `pip3` are both absent on this machine, so it came from the distribution package instead: `pacman -S git-filter-repo`, version 2.47.0-3 | Done |
-| 3.2 | Commit all Phase 1 and Phase 2 changes first, so the rewrite carries them | Pending |
+| 3.2 | Commit all Phase 1 and Phase 2 changes first, so the rewrite carries them | Done; state was stale. The shipped rewrite demonstrably carries them -- corrected 2026-09-10 |
| 3.3 | Re-verify fork and PR counts immediately before proceeding | Done; 0 forks, 0 open pull requests, 0 open issues, 21 stars, unchanged from the Phase 0 reading |
| 3.4 | Add `.gitignore` guards for the removed paths | Done; `examples/renders/*.png`, `examples/renders/*.gif` and `assets/video/` are ignored, inert while the files are still tracked and effective the moment 3.5 removes them |
| 3.4a | Move the render-existence assertions off `readdir`. Added during execution; resolved by splitting the check across the two layers that can each honestly make it. See the Phase 3 record | Done |
@@ -174,16 +174,16 @@ content-addressed ref and reused the build.
| ID | Task | State |
| --- | --- | --- |
-| 4.0 | Independently reproduce findings 4.5 to 4.9 before editing. They came from a delegated run and are not yet personally confirmed | Pending |
-| 4.1 | `--harness claude` writes skills to `./skills/`, so the harness registers none of them; they work only because `CLAUDE.md` instructs the agent to read them. Either install to `.claude/skills/` or correct `START.md`, which currently states they are installed | Pending |
-| 4.2 | `kiln_render` reports only "Generated asset execution was rejected." on a syntax error, while `kiln_validate` on the same source reports `Syntax error: Unexpected token (2:39)`. Surface the underlying message | Pending |
-| 4.3 | The same rejection for an unknown helper never names the identifier. Name it and point at `kiln_list_primitives` | Pending |
-| 4.4 | The MCP server sends an empty `instructions` field, so a client reading only `.mcp.json` gets 13 tools with no indication that `programRef` should be reused rather than re-sending source | Pending |
-| 4.5 | `.mcp.json` records an absolute `node` path, which breaks for `nvm` users after `nvm use`. `--repair` fixes it; `START.md` frames repair as relocation-only | Pending |
-| 4.6 | `scripts/create-workspace.mjs` exits 0 on a usage error and names `kiln-init`, which the caller did not invoke | Pending |
-| 4.7 | `START.md` offers no copy-pasteable first command | Pending |
-| 4.8 | Reconcile metric naming: top-level `materials: 8` against `qaReport` `materialCount: 2` and `drawCalls: 8` for one render | Pending |
-| 4.9 | Reconsider `kiln_validate` returning `valid: true` for a program using an undefined helper | Pending |
+| 4.0 | Independently reproduce findings 4.5 to 4.9 before editing. They came from a delegated run and are not yet personally confirmed | Done; all nine reproduced 2026-09-10 against `dist/mcp-server.mjs`. See "Phase 4 verification" |
+| 4.1 | `--harness claude` writes skills to `./skills/`, so the harness registers none of them; they work only because `CLAUDE.md` instructs the agent to read them | Confirmed, then superseded. The either/or in the original wording is wrong: `.claude/skills/` serves only Claude, while `.agents/skills/` serves codex, opencode, hermes and agy. Rescoped into Phase 7 |
+| 4.2 | `kiln_render` reports only "Generated asset execution was rejected." on a syntax error, while `kiln_validate` on the same source reports `Syntax error: Unexpected token (1:48)`. Surface the underlying message | Done; `runRenderViews` and `runScreenshot` now append the host-side acorn diagnostic. Verified: render reports `Syntax error: Unexpected token (1:48)`, matching validate. Safe because that parse precedes execution, so nothing crosses the evaluator boundary |
+| 4.3 | The same rejection for an unknown helper never names the identifier. Name it and point at `kiln_list_primitives` | Done, within the boundary. The advice now points at `kiln_list_primitives`; the identifier is still not named, because only the sandboxed exception carries it and this module's contract forbids that. 4.9 names it from the host-side parse instead |
+| 4.4 | The MCP server sends an empty `instructions` field, so a client reading only `.mcp.json` gets 13 tools with no indication that `programRef` should be reused rather than re-sending source | Done; `instructions` is 1,776 characters, about 354 tokens, verified delivered in the initialize result and guarded by `src/__tests__/mcp-instructions.test.ts` |
+| 4.5 | `.mcp.json` records an absolute `node` path, which breaks for `nvm` users after `nvm use`. `--repair` fixes it; `START.md` frames repair as relocation-only | Done; `START.md` now says repair is needed after a replaced Node as well as a move, and explains that the manifest pins the interpreter the preflight validated |
+| 4.6 | `scripts/create-workspace.mjs` exits 0 on a usage error and names `kiln-init`, which the caller did not invoke | Refuted and closed. Measured without a pipe: no args exits 1, `--bogus` exits 1, `--help` exits 0; `kiln-init` is a real `bin` entry. The original finding read `$?` from a piped command |
+| 4.7 | `START.md` offers no copy-pasteable first command | Done; a fenced `cd` plus launch command, and a second block for repair, both carrying the workspace's own absolute path |
+| 4.8 | Corrected: `qaReport` carries neither `materialCount` nor `drawCalls`. The real defect is that top-level `materials` always equals `meshes` -- it counts per-mesh material slots, not distinct materials | Done additively. Root cause proven and different from the hypothesis: the metric measures a scene re-imported from GLB. `distinctMaterials` now comes from the post-dedup GLB metrics at all three result sites. 20 parts sharing one material report `materials: 20, distinctMaterials: 1` |
+| 4.9 | Reconsider `kiln_validate` returning `valid: true` for a program using an undefined helper | Done as a warning. `validate` names the undeclared called identifier with its line, from the host-side parse. Zero false positives across all 86 example programs; local functions and arrow consts are not flagged. Promoting it to an error would change `valid` for source that parses, and is left as a contract decision |
## Phase 5 — Test-artifact cleanup
@@ -582,3 +582,445 @@ file that `scripts/create-workspace.mjs` writes, not to the shipped manifest.
Phases 0, 1, 2, 3 and 5 are complete. Phase 4 remains open and is now partly
verified: 4.4 confirmed, 4.5 needs rewording, 4.6 partly refuted earlier. Phase 6
is open and untouched.
+
+## Phase 4 verification
+
+Run on 2026-09-10 against `dist/mcp-server.mjs` over stdio, after first reading
+`skills/kiln-author-asset/SKILL.md` and `references/program-contract.md` so the
+probe programs were contract-valid (`const meta` plus `function build()`, no
+imports, exports or TypeScript). Omitting that step is what invalidated the
+earlier delegated run.
+
+Two findings changed on measurement. 4.6 is refuted outright. 4.8 was described
+wrongly in the original table and is a different, worse defect than recorded.
+
+Engine health measured in passing, so it is on the record rather than assumed:
+server start 1.3 s; one-part render 913 ms; five parts 862 ms; twenty parts
+798 ms; an identical re-render 57 ms from cache. Render cost is flat in part
+count. An earlier impression that renders were slow was a probe script leaking
+uncleared `setTimeout` handles, not engine behaviour.
+
+Protocol negotiation is correct and current: the server echoes `2025-06-18` and
+`2025-11-25` when asked, and falls back to `2025-11-25` for anything newer,
+which is `LATEST_PROTOCOL_VERSION` in the pinned SDK 1.30.0. The `2026-01-26`
+literal in `src/viewer/chat-app.ts` is the MCP-UI `ui/initialize` protocol, a
+different protocol, and is not an inconsistency.
+
+## Phase 7 -- Cross-harness skills and clean-room loadout
+
+Opened 2026-09-10. Phase 4 task 4.1 was scoped as a Claude-only choice between
+`.claude/skills/` and a `START.md` correction. Reading each harness's own
+documentation shows that framing was wrong, and that the gap is a whole class of
+defect rather than one setting.
+
+### The documented harness matrix
+
+| Harness | Project-local skill paths | Instruction file |
+| --- | --- | --- |
+| claude (Claude Code) | `.claude/skills/` only | `CLAUDE.md` only; does not read `AGENTS.md` |
+| codex (OpenAI Codex) | `.agents/skills/`, scanned from cwd up to repo root | `AGENTS.md` |
+| opencode | `.opencode/skills/`, `.claude/skills/`, `.agents/skills/` | `AGENTS.md` |
+| hermes (NousResearch) | `.hermes/skills/`, `.agents/skills/` | -- |
+| agy (Google Antigravity) | `.agents/skills/` | `agents.md` |
+
+`.agents/skills/` serves four of the five; Claude Code is the sole holdout.
+
+An important nuance, checked against the specification rather than inferred:
+`.agents/skills/` is a **de-facto convention, not part of the standard.** Agent
+Skills became a formal open standard on 2025-12-18 with the specification at
+`agentskills.io/specification`, adopted across 20-plus platforms, but that
+specification deliberately defines only the skill *format* -- directory layout
+and `SKILL.md` frontmatter -- and says nothing about where agents should look for
+skills. Discovery is left entirely to implementations, which is exactly why the
+matrix above has five different answers and why no single directory can serve
+all of them.
+
+Two corrections to earlier belief. Codex does support skills, from December
+2025; the claim that it had no native concept was wrong. And `skills/` at the
+repository root is not a mistake -- it is the plugin convention, auto-discovered
+from a Claude Code plugin root and declared explicitly by
+`.codex-plugin/plugin.json`. The layout is correct for the path it was built for.
+
+### Three install paths, one of them served
+
+| Path | Tools | Skills |
+| --- | --- | --- |
+| Installed as a plugin | yes | yes -- Claude by auto-discovery, Codex by explicit field |
+| `git clone` plus an agent | **no, see 7.1** | no -- root `skills/` is not a discovery path outside plugin context |
+| `kiln-init` workspace | yes, all five harnesses | opencode only |
+| Ad-hoc: configure the server by hand, open an empty folder | yes | files exist in the install root but sit in no scanned directory |
+
+### Clean rooms invert the registration rule
+
+A generated workspace is a plain directory; `create-workspace.mjs` writes a
+`.gitignore` but never runs `git init`. Both opencode and hermes gate
+project-local skill discovery on being inside a git checkout, so convention
+directories alone cannot be relied on there. Explicit configuration therefore
+beats convention in a clean room, which reverses the first proposal drafted for
+this phase: opencode's `skills.paths` must be KEPT, not replaced. It is a real
+key, verified against the published `opencode.ai/config.json` schema
+("Additional paths to skill folders").
+
+### Repo-side and workspace-side skills are different audiences
+
+All five existing skills are workspace-side: they assume a live `kiln_workspace`
+server and a workspace to author in. Nothing is repo-side, and `AGENTS.md` never
+mentions workspaces, `kiln-init` or clean rooms -- it addresses engine
+contributors only. An agent in a bare clone has no way to learn that
+`scripts/create-workspace.mjs` exists.
+
+This also rules out an approach that was nearly adopted: committing all five
+authoring skills to a root `.claude/skills/`. That would register, for an agent
+sitting in the engine checkout, skills whose own guidance is to keep the engine
+checkout out of the agent's task context. Root registers the repo-side skill
+only.
+
+| ID | Task | State |
+| --- | --- | --- |
+| 7.11 | Add specification validation of the skill files to CI. The standard ships a reference validator (`skills-ref validate`); a local equivalent avoids a new dependency. Guards the format against drift now that it is a published standard with 20-plus implementations | Done; folded into `check:skills` rather than adding a dependency on the reference validator |
+| 7.1 | Root `.mcp.json` borrowed Antigravity's `${PLUGIN_ROOT}` while serving Claude Code project config and the Codex plugin, neither of which defines it, so a fresh clone opened onto a `kiln` server that could not start | Done. Root `.mcp.json` now uses `${CLAUDE_PROJECT_DIR:-.}`, the documented project-scoped idiom; the Codex manifest carries its server inline with a plugin-root-relative `cwd`, the documented alternative to a path. Both expansion branches verified to start the server; `mcp_config.json` untouched; a guard test asserts no plugin variable returns to this file |
+| 7.2 | Author a repo-side `kiln-setup-workspace` skill: choosing a harness, generating the clean room, verifying `kiln_workspace` came up, and what `--repair` does and does not touch | Done; `skills/kiln-setup-workspace/`, specification-validated |
+| 7.3 | Register 7.2 at the repository root in both `.claude/skills/` and `.agents/skills/`. Copies, not symlinks: symlinks need developer mode or admin on Windows and a `core.symlinks` checkout | Done; committed to `.claude/skills/` and `.agents/skills/`. `.gitignore` needed the `.claude/*` plus negation form, because git will not descend into a wholly excluded directory |
+| 7.4 | Add a root `CLAUDE.md` containing the documented `@AGENTS.md` import, and an "authoring assets versus contributing to the engine" section to `AGENTS.md` naming 7.2. A skill cannot make itself discoverable, so this is the bootstrap | Done; root `CLAUDE.md` carries the documented `@AGENTS.md` import, and `AGENTS.md` gained an authoring-versus-contributing section |
+| 7.5 | Workspace generator: copy the authoring skills into `.claude/skills/` and `.agents/skills/` instead of plain `skills/`, upgrading four harnesses from prose to native registration | Done; all five harnesses now receive `.claude/skills/` and `.agents/skills/` alongside the maintained `skills/` |
+| 7.6 | Keep opencode `skills.paths`; add the hermes equivalent to the generated `.hermes/config.yaml`. The key is reported as `skills.external_dirs` but that came from prose, not a schema -- verify before writing it | Done; opencode `skills.paths` kept, hermes `skills.external_dirs` added after confirming the key and that its project-local scan needs a git checkout |
+| 7.7 | Populate the MCP `instructions` field from the five skill descriptions, as the harness-independent floor. Same work as 4.4 | Done; 1,776 characters, about 354 tokens, verified delivered in the initialize result |
+| 7.8 | Add a `check:skills` gate asserting the registered copies are byte-identical to canonical `skills/`, mirroring `check:toolchain`, and wire it into CI. This is what makes copying safe rather than a drift hazard | Done; `scripts/check-skills.mjs`, wired into CI before install, negative-tested against three distinct failure modes |
+| 7.9 | Trim `skills/kiln-batch-dispatch/references/clean-room-evaluation.md` to evaluation scope once 7.2 owns setup, so two documents do not describe workspace creation | Done; trimmed 42 lines to 30, setup now owned by 7.2 |
+| 7.10 | DECIDED: no `git init`. Clean rooms stay plain directories and skill registration goes through explicit configuration (7.6), which is independent of git state. Closed | Done |
+
+### Clone readiness, measured
+
+Verified 2026-09-10 against the live remote at `9b0c610`, in a fresh clone
+rather than the working tree: clone 3.3 s for 52 MB; `bun install
+--frozen-lockfile` 0.59 s, exit 0; `check:toolchain`, `typecheck` and `lint` all
+exit 0 with the unchanged 14-warning baseline; `bun run test` 1805 pass, 0 fail,
+2 skip. `dist/` is committed, so no build step precedes first use. Both
+previously flaky tests passed here, so they are intermittent rather than broken.
+
+Phase 6 does not gate a cloning developer: there is no `build:assets` script in
+`package.json`, and the only consumer of the poster receipts is the Pages
+workflow, already pinned to `windows-2022`. It stays maintainer-only work.
+
+## Decisions taken 2026-09-10
+
+| Ref | Decision | Rationale |
+| --- | --- | --- |
+| 7.1 | Split the two uses of `.mcp.json` | A fresh clone must not open onto a failing MCP server. The Codex plugin gets its own file; root `.mcp.json` becomes correct for a bare clone |
+| 4.8 | Add a correct `distinctMaterials` alongside `materials` rather than changing `materials` | Additive. Nothing reading the existing key breaks, including the instanceability grade. Root cause is still to be proven before any edit |
+| 7.10 | No `git init` for generated workspaces | Explicit configuration already covers opencode and hermes, and it works regardless of git state. Preserves the documented meaning of a clean room |
+| Scope | This pass covers Phase 7, the Phase 4 error-legibility and docs tasks, and 4.8. Phase 6 and the two intermittent tests stay out | Phase 6 needs a Windows or GPU host to re-record receipts and gates no cloning developer |
+
+### The ad-hoc path, and why `instructions` is not optional
+
+Raised by the owner 2026-09-10: a user may never create a clean room at all.
+They may start the MCP server, configure it in their coding agent, and open a
+new empty folder. That path works today for tools and for storage --
+`KILN_PROGRAM_STORE ?? '.kiln/programs'` resolves against the working directory,
+so the store is created in the folder the agent opened, which is the correct
+behaviour and not incidental.
+
+A correction to an earlier statement in this section: that user is not missing
+the skill files. All thirteen ship in the npm tarball and `skills/` sits as a
+sibling of `dist/`, so the server can compute its own install root and name a
+real absolute directory at runtime. What is missing is *registration* -- the
+files are in a location no harness scans. The MCP `instructions` field is the
+only channel that can tell that user the files exist and where. Task 7.7 therefore carries the whole
+loadout for this path and must be substantive on its own -- an orientation to
+the tool surface and the `programRef` contract -- rather than a pointer to skill
+files that are not present.
+
+### 7.1 is lower risk than first assessed
+
+`scripts/package-plugin.mjs` deletes `manifest.mcpServers` when it builds the
+Codex connector, so the published artifact is skills-only and never reads root
+`.mcp.json`. The `"mcpServers": "./.mcp.json"` field in
+`.codex-plugin/plugin.json` is effectively vestigial for the distributed plugin.
+Root `.mcp.json` can be made correct for a bare clone without disturbing the
+Codex packaging path. The Codex `plugin.json` schema could not be confirmed from
+OpenAI's published documentation; the packaging script is the authority used here.
+
+### The skills format is a published standard, and ours conforms
+
+Validated 2026-09-10 against `agentskills.io/specification`, not against this
+repository's own conventions.
+
+Required frontmatter is `name` (max 64 characters, lowercase alphanumerics and
+single hyphens, no leading, trailing or consecutive hyphens, and it **must match
+the parent directory name**) and `description` (max 1024 characters, stating both
+what the skill does and when to use it). Optional: `license`, `compatibility`
+(max 500), `metadata` (string-to-string map), and the experimental
+`allowed-tools`. The specification also sets progressive-disclosure guidance:
+name and description are loaded for every skill at startup, so roughly 100
+tokens each; the body loads on activation and should stay under 5000 tokens and
+500 lines; `references/`, `scripts/` and `assets/` load on demand and file
+references should stay one level deep.
+
+All five skills pass every one of those checks:
+
+| Skill | Lines | Description chars | Body tokens (approx) |
+| --- | --- | --- | --- |
+| kiln-author-asset | 47 | 117 | 911 |
+| kiln-batch-dispatch | 21 | 225 | 338 |
+| kiln-compose-scene | 20 | 133 | 239 |
+| kiln-qa-asset | 28 | 182 | 421 |
+| kiln-refine-asset | 45 | 160 | 795 |
+
+Names match their directories, no non-specification frontmatter keys are
+present, and the existing `references/` layout is the specification's own
+recommended convention. The content layer needs no change; only registration
+does.
+
+### `${PLUGIN_ROOT}` is not a variable in either plugin system
+
+Checked against both vendors rather than assumed from this repository. Claude
+Code expands `${CLAUDE_PLUGIN_ROOT}`, which is the token the Claude plugin
+manifest already uses correctly. Codex exposes no equivalent at all: its
+plugin-provided MCP servers take a relative `cwd` that Codex resolves against
+the installed plugin root, and the gap is tracked upstream in openai/codex
+issues 22842 and 22105. Codex `plugin.json` accepts `mcpServers` as either a
+relative path or an inline object, and `skills` as a relative path that
+supplements rather than replaces default discovery.
+
+**Correction, from this repository's own tests rather than vendor docs.**
+`${PLUGIN_ROOT}` *is* a real variable: it is Antigravity's, and root
+`mcp_config.json` uses it deliberately. `src/__tests__/mcp-bundle.test.ts`
+records the measurement -- on `agy` 1.1.25 the file validates at the plugin root
+(`mcpServers: 1 processed`) but is not merged into the session, so the test
+asserts only that it names the node bundle and pointedly does not assert that
+the variable expands. That file is correct and must be left alone.
+
+The defect is narrower than first written: root `.mcp.json` borrowed
+Antigravity's variable while serving two consumers that never define it -- Claude
+Code reading project-scoped configuration in a plain clone, and the Codex plugin
+manifest. Task 7.1 fixes that file only.
+
+### 7.7 shape: an index and a pointer, not the skill bodies
+
+Decided 2026-09-10 on the owner's suggestion that `instructions` should tell the
+agent to add skills to its workspace rather than carry them inline. Agreed, for
+two measured reasons.
+
+Inlining the five bodies would cost roughly 2704 tokens (911, 338, 239, 421 and
+795), paid at every session start by every client for content that is needed in
+perhaps one conversation. That is exactly what the specification's progressive
+disclosure model exists to prevent: name and description at startup, body only
+on activation. And the pointer can be concrete rather than aspirational, because
+`skills/` ships as a sibling of `dist/`.
+
+`instructions` therefore carries three things, in roughly 350 to 450 tokens:
+the tool-surface orientation and the `programRef` contract, which the ad-hoc user
+has no other way to learn; the five names with a one-line trigger each and the
+absolute source path; and one line offering to copy them into the workspace's
+`.claude/skills/` or `.agents/skills/`.
+
+Two constraints on the wording. The copy must be framed as something the agent
+proposes, not performs unasked -- an MCP server prompting unrequested writes into
+a user's project is a side effect, and someone who wanted one render should not
+find new directories afterwards. And the text must say the copy takes effect
+from the next session, because most harnesses will not register newly written
+skills mid-session; without that, the agent copies files, observes no new
+skills, and may retry.
+
+Deferred, not adopted: exposing the skills as MCP resources. That idea has a
+name and a specification -- see "Skills over MCP" below -- and this plan should
+use it rather than describe the mechanism informally.
+
+## Skills over MCP, and remote skill discovery
+
+Raised by the owner 2026-09-10 as a half-remembered "new skill paradigm exposed
+through MCP". It is real, and it matters for how much of Phase 7 is worth
+building by hand.
+
+### SEP-2640, the Skills Extension
+
+Extension identifier `io.modelcontextprotocol/skills`. It serves Agent Skills
+over MCP on the existing Resources primitive under a `skill://` URI scheme, with
+`skills/list` returning lightweight discovery metadata and `skills/activate`
+returning the full bundle plus scoped tools, prompts, resources and nested
+skills. Scoped primitives stay out of the top-level lists until activation, so
+progressive disclosure moves into the protocol itself.
+
+Ratified, this would collapse most of Phase 7: no per-harness directories, no
+filesystem copies, no registration step, and the ad-hoc path served by the same
+mechanism as every other path.
+
+It is not ratified. The SEP is an open pull request, accepted by core
+maintainers and still under review in the Skills Over MCP working group at 45
+commits, and it still requires reference-implementation completion, conformance
+tests and specification documentation. It is absent from the 2026-07-28 release
+candidate, which shipped MCP Apps and Tasks as the official extensions. It is an
+optional extension rather than a core primitive. Host support is prototype-level
+across gemini-cli, fast-agent, goose, codex and Claude Code. The SDK pinned here
+is 1.30.0 at protocol 2025-11-25, well before any of it.
+
+Decision: do not build on it in this pass. Building against an in-review API with
+no conformance tests would mean rewriting when it lands. Task 7.7 is already the
+manual form of `skills/list` -- an index plus a pointer -- so when the extension
+ratifies the same five skills become `skill://` resources and nothing authored
+now is wasted.
+
+### `.well-known/skills/`, which is usable today
+
+Cloudflare's Agent Skills Discovery RFC applies RFC 8615 well-known URIs to
+skill distribution, and it is already adopted by Mintlify, Docus and Vercel's
+skills CLI. It is what opencode's `skills.urls` config key consumes. Because
+this project already publishes a site, serving the five skills at
+`/.well-known/skills/` would let any opencode user fetch them by URL with no
+clone and no install. It does not depend on SEP-2640.
+
+| ID | Task | State |
+| --- | --- | --- |
+| 7.12 | Watch SEP-2640 to ratification, then expose the skills as `skill://` resources and retire the hand-built per-harness registration where clients support the extension | Deferred by decision; not this pass |
+| 7.13 | Publish the skills at `/.well-known/skills/` on the existing site per the Cloudflare discovery RFC, giving opencode `skills.urls` users a zero-install path | Pending; optional, independent of the rest of Phase 7 |
+
+### 7.1 execution record
+
+Root `.mcp.json` now reads `${CLAUDE_PROJECT_DIR:-.}/dist/mcp-server.mjs`.
+Claude Code expands `${VAR}` and `${VAR:-default}` in `command`, `args` and
+`env`, sets `CLAUDE_PROJECT_DIR` to the project root, and supports no `cwd`
+field for stdio servers -- so the default form is what makes the file resolve
+when nothing defines the variable. Verified by expanding both branches and
+launching each: unset falls back to `./dist/mcp-server.mjs` and starts; set
+resolves absolute and starts. The previous value failed with MODULE_NOT_FOUND.
+
+`.codex-plugin/plugin.json` no longer points at that shared file. It carries the
+server inline -- the documented alternative to a path -- with `"cwd": "."`, which
+Codex resolves against the installed plugin root. `scripts/package-plugin.mjs`
+still deletes `mcpServers` for the published connector: re-run after the change,
+16 files, `connectorBound: true`, `mcpServers` absent, `skills` preserved.
+
+Guarded by a new case in `src/__tests__/mcp-bundle.test.ts` asserting the exact
+argument and that neither `${PLUGIN_ROOT}` nor `${CLAUDE_PLUGIN_ROOT}` appears in
+root `.mcp.json`. Related suites re-run green: mcp-bundle, workspace-node-path,
+workspace-bootstrap, workspace-setup and integration-manifest, 18 tests then 6.
+`docs/chatgpt.md` corrected; the harness table in `docs/install.md` needed no
+change because it describes the generated workspace, not repository root.
+
+## Execution record, 2026-09-10
+
+All nineteen sequenced tasks are complete. Full gate on the working tree:
+`check:toolchain`, `check:skills`, `typecheck` and `lint` all exit 0 with the
+unchanged 14-warning / 11-info baseline, `bun run test` reports **1810 pass, 0
+fail, 2 skip** across 207 files, up from 1805 by the five tests added here, and
+`build:runtime` is byte-identical across consecutive runs.
+
+### What the docs changed about the plan
+
+Four claims written earlier in this document were wrong and are corrected in
+place above. `${PLUGIN_ROOT}` is real -- it is Antigravity's, used deliberately
+by root `mcp_config.json`, which this work left untouched. Codex has supported
+skills since December 2025. Root `skills/` is the plugin convention and was
+never misplaced. And the "SDK pinned here" was `@modelcontextprotocol/sdk`
+1.30.0, a transitive optional peer of `@google/genai` and `@strands-agents/sdk`
+that nothing in this repository imports; the direct dependencies are
+`@modelcontextprotocol/server` and `client` at 2.0.0, both the latest published,
+whose own `LATEST_PROTOCOL_VERSION` is `2025-11-25`. There was nothing to update.
+
+The skill format is a published standard, and all six skills validate against
+it: names match their directories, descriptions sit inside 1024 characters,
+bodies stay under the 500-line and 5000-token guidance, and no non-specification
+frontmatter key is present. `.agents/skills/` is a de-facto convention rather
+than part of that standard, which is why the matrix has five answers.
+
+### 4.8 root cause, which was not the hypothesis
+
+The leading hypothesis in this document -- that `mergeDocuments` gave each part a
+distinctly named material copy that `dedup()` would not merge -- was wrong.
+`loadEvaluatedReviewScene` renders to GLB and then **re-imports** the scene
+(`loadGlbReviewScene(rendered.glb)`), and `collectSceneMetrics` measures that
+re-imported scene, where authored sharing no longer survives as object identity.
+That is why `materials` could never disagree with `meshes`.
+
+The correct figure already existed, post-dedup, in
+`rendered.meta.instanceability.metrics.uniqueMaterials`. `distinctMaterials` is
+surfaced from it at all three render result sites. Verified: 20 parts sharing one
+material now report `materials: 20, distinctMaterials: 1`; 20 distinct report 20
+and 20. `materials` is unchanged and documented for what it actually measures.
+
+### 4.2 and 4.3 are bounded by a security boundary, not by effort
+
+`src/evaluator/authoring-diagnostic.ts` exists to stop exception text crossing
+out of the isolated evaluator: "No captured identifier, path, message, or stack
+crosses the boundary." Naming the identifier in a render rejection, as 4.3 asked,
+would breach that deliberately. What was added instead is engine-owned text
+pointing at `kiln_list_primitives`, and a test above it already asserts that
+arbitrary exceptions keep the generic rejection.
+
+4.2 is safe for a different reason: acorn parses host-side, before any generated
+code runs, which is exactly why `kiln_validate` can already report a position.
+Repeating that parse in the rejection path leaks nothing new. `kiln_render`
+routes through `runRenderViews`, not `runRender`, so the diagnostic is applied at
+both raw-source catches and deliberately not at the `programRef` paths, whose
+source was validated when it was saved.
+
+4.9 is where the identifier can be named, because that check is host-side and
+pre-execution. It reports a warning rather than an error, and its declaration
+set over-approximates -- every binding anywhere in the program counts as in
+scope -- so a shadowed or conditionally declared name is never falsely flagged.
+Measured against all 86 example programs: **zero** false positives; the
+undefined helper is named with its line. Promoting it to an error would change
+`valid` for programs that parse, and is left as a deliberate contract decision.
+
+### Left open, with reasons
+
+Task 7.13 (`/.well-known/skills/`) is grouped with Phase 6 as maintainer-side:
+publishing it runs through `pages.yml`, which is pinned to `windows-2022`, so it
+cannot be verified from a Linux checkout. Task 7.12 (SEP-2640) stays deferred
+until the SEP ratifies.
+
+A third order-dependent test was found and is **pre-existing**, not a
+regression: `authoring-diagnostic.test.ts` "shipping registry exposes repair
+advice from its isolated evaluator" fails when that file runs alone, with
+"Evaluator worker failed.", and passes in a full run. The pristine clone at
+`9b0c610` fails identically. It does not affect users: driving the shipped
+server directly over stdio returns the full advice, `kiln_list_primitives`
+pointer included. Test hygiene, tracked with the other two flaky tests.
+
+Codex's published plugin sample does not enumerate `command`, `args`, `cwd` or
+`env` for an inline `mcpServers` entry, so the `"cwd": "."` written into
+`.codex-plugin/plugin.json` rests on two secondary sources rather than the
+specification. It degrades gracefully -- the argument is relative, so it still
+resolves if `cwd` is ignored but the server already starts at the plugin root --
+and `scripts/package-plugin.mjs` deletes `mcpServers` from the published
+connector regardless.
+
+## Phase 8 -- `kiln save` writes nothing under Bun
+
+Found 2026-09-10 while confirming CI readiness, by chasing the test recorded
+above as merely flaky. It is not flaky in the way it looked, and it is not a
+test problem.
+
+| Runtime and entry | `kiln save` stdout | Exit |
+| --- | --- | --- |
+| `node dist/cli.mjs` | 2,061 bytes of JSON | 0 |
+| `bun dist/cli.mjs` | **0 bytes** | 0 |
+| `bun src/cli.ts` | **0 bytes** | 0 |
+
+The trigger is Bun, not the TypeScript source, and the failure is silent: exit 0,
+empty stdout, empty stderr, no unhandled rejection reported. The program store
+*is* written -- the source is imported and a `p_` ref file appears -- so the
+command runs partway and then stops without a diagnostic. `--help` prints
+correctly under Bun, so the entry guard is fine; `isDirectCliEntry()` was checked
+directly and both sides of its comparison match.
+
+This explains `src/asset-cli.test.ts` completely. That test invokes
+`spawnSync(process.execPath, [resolve('src/cli.ts'), 'save', ...])`, and under
+`bun test` `process.execPath` is Bun, so `saved.stdout` is empty and
+`JSON.parse('')` throws at line 34 -- while line 33's `expect(saved.status).toBe(0)`
+passes, because the exit code really is 0. Measured 1 pass in 4 isolated runs on
+this tree and 1 in 3 on a pristine `9b0c610`, so it is pre-existing and roughly a
+coin flip; it passed in both full-suite runs here and failed once under
+`test:coverage`.
+
+End users are not affected: every shipped launcher and manifest invokes `node`
+-- the workspace manifest pins the interpreter the preflight validated, and the
+plugin manifests use bare `node`. Contributors are, because `AGENTS.md`
+documents Bun as the toolchain.
+
+| ID | Task | State |
+| --- | --- | --- |
+| 8.1 | Find where the `save` path exits early under Bun without a diagnostic. The store write succeeds, so the divergence is after program import; suspect the in-process evaluator or an output flush racing process exit | Pending |
+| 8.2 | Decide whether the CLI should refuse to exit 0 having produced no output at all, independent of the Bun cause. A silent success is the part that made this look like flakiness for so long | Pending |
+| 8.3 | Point `src/asset-cli.test.ts` at an interpreter that reflects how the CLI actually ships, or assert non-empty stdout before parsing so the failure names the real cause | Pending |
+| 8.4 | Re-check the other two intermittent tests against this finding; a shared `spawnSync` under Bun may explain more than one of them | Pending |
diff --git a/package.json b/package.json
index efa0701e..fd910693 100644
--- a/package.json
+++ b/package.json
@@ -83,6 +83,7 @@
"scripts": {
"kiln": "bun src/cli.ts",
"check:toolchain": "bun scripts/check-toolchain.mjs",
+ "check:skills": "node scripts/check-skills.mjs",
"typecheck": "tsc --noEmit",
"build": "tsc --noEmit",
"build:mcp": "node scripts/build-runtime.mjs mcp",
diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs
new file mode 100644
index 00000000..95693fc5
--- /dev/null
+++ b/scripts/check-skills.mjs
@@ -0,0 +1,150 @@
+#!/usr/bin/env node
+/**
+ * Two checks that nothing else performs.
+ *
+ * First, the skill files are a published format now, not a local convention:
+ * Agent Skills became an open standard whose `name` and `description` rules are
+ * load-bearing for every harness that reads them. A violation is silent -- the
+ * harness simply skips the skill -- so the constraints are asserted here.
+ *
+ * Second, `skills/` is the maintained copy, but a bare clone registers nothing
+ * from it: Claude Code scans only `.claude/skills/`, while codex, opencode,
+ * hermes and agy scan `.agents/skills/`. Those copies exist so a fresh clone has
+ * a working loadout, and copies drift. Symlinks would avoid the duplication but
+ * need developer mode or an administrator on Windows, so the files are real and
+ * this check is what keeps them honest.
+ */
+import { readdir, readFile, stat } from 'node:fs/promises';
+import { join, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const repo = fileURLToPath(new URL('..', import.meta.url));
+const CANONICAL = 'skills';
+/** Skills that must also be registered at the repository root, and where. */
+const REGISTERED = ['kiln-setup-workspace'];
+const REGISTRIES = ['.claude/skills', '.agents/skills'];
+const SPEC_KEYS = new Set([
+ 'name',
+ 'description',
+ 'license',
+ 'compatibility',
+ 'metadata',
+ 'allowed-tools',
+]);
+
+const errors = [];
+
+/** Files under `dir`, relative to it, sorted, recursing into subdirectories. */
+async function tree(dir) {
+ const out = [];
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) out.push(...(await tree(full)).map((p) => join(entry.name, p)));
+ else out.push(entry.name);
+ }
+ return out.sort();
+}
+
+function frontmatter(text) {
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/u.exec(text);
+ if (!match) return null;
+ const fields = new Map();
+ for (const line of match[1].split(/\r?\n/u)) {
+ const kv = /^([A-Za-z-]+):\s*(.*)$/u.exec(line);
+ if (kv) fields.set(kv[1], kv[2]);
+ }
+ return fields;
+}
+
+/** The specification's own constraints, applied to one skill directory. */
+async function validate(label, dir, name) {
+ const file = join(dir, 'SKILL.md');
+ let text;
+ try {
+ text = await readFile(file, 'utf8');
+ } catch {
+ errors.push(`${label}: missing SKILL.md`);
+ return;
+ }
+ const fields = frontmatter(text);
+ if (!fields) {
+ errors.push(`${label}: SKILL.md has no YAML frontmatter`);
+ return;
+ }
+ const declared = fields.get('name');
+ const description = fields.get('description');
+ if (declared !== name) {
+ errors.push(`${label}: name is ${declared ?? '(absent)'} but must match the directory, ${name}`);
+ }
+ if (!/^[a-z0-9]+(-[a-z0-9]+)*$/u.test(name) || name.length > 64) {
+ errors.push(`${label}: name must be 1-64 lowercase alphanumerics with single hyphens`);
+ }
+ if (!description) errors.push(`${label}: description is required`);
+ else if (description.length > 1024) {
+ errors.push(`${label}: description is ${description.length} characters, over the 1024 maximum`);
+ }
+ for (const key of fields.keys()) {
+ if (!SPEC_KEYS.has(key)) errors.push(`${label}: ${key} is not an Agent Skills frontmatter field`);
+ }
+ const lines = text.split(/\r?\n/u).length;
+ if (lines > 500) errors.push(`${label}: SKILL.md is ${lines} lines, over the recommended 500`);
+}
+
+const canonicalDir = join(repo, CANONICAL);
+const names = (await readdir(canonicalDir, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => entry.name)
+ .sort();
+
+if (names.length === 0) errors.push(`${CANONICAL}/ contains no skills`);
+for (const name of names) await validate(`${CANONICAL}/${name}`, join(canonicalDir, name), name);
+
+for (const registry of REGISTRIES) {
+ const dir = join(repo, registry);
+ try {
+ await stat(dir);
+ } catch {
+ errors.push(`${registry}/ is missing; a bare clone would register no skills there`);
+ continue;
+ }
+ const present = (await readdir(dir, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => entry.name)
+ .sort();
+ const expected = [...REGISTERED].sort();
+ if (present.join(',') !== expected.join(',')) {
+ errors.push(`${registry}/ holds [${present.join(', ')}] but must hold exactly [${expected.join(', ')}]`);
+ }
+ for (const name of expected) {
+ if (!present.includes(name)) continue;
+ await validate(`${registry}/${name}`, join(dir, name), name);
+ const from = join(canonicalDir, name);
+ const to = join(dir, name);
+ const [a, b] = await Promise.all([tree(from), tree(to)]);
+ if (a.join('\n') !== b.join('\n')) {
+ errors.push(`${registry}/${name} has a different file list than ${CANONICAL}/${name}`);
+ continue;
+ }
+ for (const file of a) {
+ const [left, right] = await Promise.all([
+ readFile(join(from, file)),
+ readFile(join(to, file)),
+ ]);
+ if (!left.equals(right)) {
+ errors.push(
+ `${relative(repo, join(to, file))} differs from ${relative(repo, join(from, file))}; copy the maintained file over it`,
+ );
+ }
+ }
+ }
+}
+
+if (errors.length > 0) {
+ for (const error of errors) console.error(`- ${error}`);
+ process.exit(1);
+}
+
+const mirrored = REGISTERED.length * REGISTRIES.length;
+console.log(
+ `Skills: ${names.length} conform to the Agent Skills specification; ${mirrored} registered copies are byte-identical.`,
+);
diff --git a/scripts/create-workspace.mjs b/scripts/create-workspace.mjs
index da9a2f80..5001ce9c 100644
--- a/scripts/create-workspace.mjs
+++ b/scripts/create-workspace.mjs
@@ -10,6 +10,8 @@ const installation = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const quote = JSON.stringify;
const hash = (value) => createHash('sha256').update(value).digest('hex');
const harnesses = ['claude', 'codex', 'opencode', 'hermes', 'agy'];
+/** Where each harness family actually looks for skills, relative to the workspace. */
+const skillRegistries = ['.claude/skills', '.agents/skills'];
const core = ['kiln-author-asset', 'kiln-refine-asset', 'kiln-qa-asset'];
const optional = { compose: 'kiln-compose-scene', batch: 'kiln-batch-dispatch' };
const inside = (parent, child) => { const rel = relative(parent, child); return !rel || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`)); };
@@ -48,7 +50,11 @@ function managedFiles(root, runtime, harness, nodeExecutable) {
}
if (harness === 'opencode') files['opencode.json'] = quote({ $schema: 'https://opencode.ai/config.json', skills: { paths: [join(root, 'skills')] }, mcp: { kiln_workspace: { type: 'local', command: [mcp.command, server], environment: mcp.env, enabled: true } } });
if (harness === 'hermes') {
- files['.hermes/config.yaml'] = quote({ mcp_servers: { kiln_workspace: mcp } });
+ // Hermes scans project-local skills only inside a git checkout (nearest
+ // ancestor with .git), and a workspace is deliberately not one. `external_dirs`
+ // is unconditional, so it is what actually registers them here. YAML is a
+ // superset of JSON, so the JSON form below is valid config.
+ files['.hermes/config.yaml'] = quote({ mcp_servers: { kiln_workspace: mcp }, skills: { external_dirs: [join(root, '.agents', 'skills')] } });
files['hermes.mjs'] = `import { spawn } from 'node:child_process';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst root = dirname(fileURLToPath(import.meta.url));\nconst child = spawn('hermes', process.argv.slice(2), { cwd: root, stdio: 'inherit', windowsHide: true, env: { ...process.env, HERMES_HOME: join(root, '.hermes'), TERMINAL_CWD: root } });\nchild.on('error', (error) => { console.error(error.message); process.exitCode = 1; });\nchild.on('exit', (code) => { process.exitCode = code ?? 1; });\n`;
}
return { files, store, server };
@@ -58,7 +64,7 @@ const guide = `# Kiln asset workspace
Use the kiln_workspace MCP server configured in this project to author and refine assets in this directory. Another server named kiln may use a different installation; do not substitute it silently. The engine is installed separately. Do not read its implementation or example collection to solve an asset task.
-- Read the relevant skill from this project's skills/ directory, not a global plugin copy. Use kiln_list_primitives on kiln_workspace for API signatures. If that server is unavailable, report the setup problem instead of using another installation.
+- This project's own skills are installed and registered for your harness; read the relevant one from here, never a global plugin copy. The maintained copies are in skills/, mirrored to .claude/skills/ and .agents/skills/ because harnesses scan different directories. Use kiln_list_primitives on kiln_workspace for API signatures. If that server is unavailable, report the setup problem instead of using another installation.
- Import an existing file with node kiln.mjs source asset.kiln.js. It returns a programRef, normally a short immutable p_ handle. Copy it exactly; do not expand or shorten it.
- For a new draft, pass code once to kiln_validate or kiln_render. Keep its programRef even if validation fails.
- Use kiln_source with programRef and a literal query to read exact edit anchors. Follow nextOffset for more context.
@@ -151,10 +157,20 @@ export async function createWorkspace(directory, harness = 'claude', options = {
await writeFile(join(stage, '.gitignore'), '.kiln/programs/\n.hermes/\n*.glb\n*.png\n');
for (const name of ['AGENTS.md', 'CLAUDE.md']) await writeFile(join(stage, name), guide);
for (const name of skills) await cp(join(runtime, 'skills', name), join(stage, 'skills', name), { recursive: true });
+ // Registration copies. No harness scans a bare `skills/`: Claude Code reads
+ // only `.claude/skills/`, while codex, opencode, hermes and agy read
+ // `.agents/skills/`. Without these the workspace has skill files that the
+ // agent can read only when told to, which is how it worked before. Copies
+ // rather than symlinks because those need developer mode or an
+ // administrator on Windows.
+ for (const registry of skillRegistries)
+ for (const name of skills)
+ await cp(join(runtime, 'skills', name), join(stage, registry, name), { recursive: true });
manifest.skillHashes = await fileHashes(join(stage, 'skills'));
await writeFile(join(stage, '.kiln/workspace.json'), quote(manifest));
- const launch = harness === 'hermes' ? 'Run node hermes.mjs --ignore-rules. It uses a separate profile; authenticate in that profile or supply provider credentials through the environment.' : harness === 'agy' ? 'Run node agy.mjs from this directory. The launcher supplies the absolute project directory. For headless runs, use node agy.mjs --model MODEL --print \"Read AGENTS.md and the project skills. Use only kiln_workspace MCP tools. YOUR TASK.\". Print mode disables automatic slash-command/skill expansion to avoid automatic expansion of a global skill. Use absolute task-file paths in headless prompts and verify that tool calls use kiln_workspace; global configuration and authentication remain unchanged.' : `Open ${harness} in this directory.`;
- await writeFile(join(stage, 'START.md'), `# Start making assets\n\n${launch} Accept the project/MCP trust prompts. Ask the agent to read AGENTS.md and create an asset. Kiln needs no separate model key.\n\nCore author/refine/QA skills are installed. Optional compose/batch skills are selected at setup with --skills compose,batch.\n\nKeep assets here and engine source outside. This separates task context, not operating-system permissions. User instructions and authentication can still apply.\n\nAfter relocating this workspace or the runtime, run node /current/kiln/scripts/create-workspace.mjs /absolute/workspace --repair. Repair updates generated runtime paths only and refuses edited configuration; it preserves skills, assets, and saved revisions.\n`);
+ const command = harness === 'hermes' ? 'node hermes.mjs --ignore-rules' : harness === 'agy' ? 'node agy.mjs' : harness;
+ const launch = harness === 'hermes' ? 'Hermes uses a separate profile; authenticate in that profile or supply provider credentials through the environment.' : harness === 'agy' ? 'The launcher supplies the absolute project directory. For headless runs, use node agy.mjs --model MODEL --print \"Read AGENTS.md and the project skills. Use only kiln_workspace MCP tools. YOUR TASK.\". Print mode disables automatic slash-command/skill expansion to avoid automatic expansion of a global skill. Use absolute task-file paths in headless prompts and verify that tool calls use kiln_workspace; global configuration and authentication remain unchanged.' : `This directory is configured for ${harness}.`;
+ await writeFile(join(stage, 'START.md'), `# Start making assets\n\n\`\`\`bash\ncd ${root}\n${command}\n\`\`\`\n\n${launch} Accept the project/MCP trust prompts. Ask the agent to read AGENTS.md and create an asset. Kiln needs no separate model key.\n\nCore author/refine/QA skills are installed and registered for this harness. Optional compose/batch skills are selected at setup with --skills compose,batch.\n\nKeep assets here and engine source outside. This separates task context, not operating-system permissions. User instructions and authentication can still apply.\n\nRun repair after anything that invalidates the generated absolute paths: moving this workspace, moving or reinstalling the runtime, or replacing the Node that setup recorded -- an nvm switch or uninstall does that, because the manifest pins the exact interpreter the preflight check validated.\n\n\`\`\`bash\nnode /current/kiln/scripts/create-workspace.mjs ${root} --repair\n\`\`\`\n\nRepair updates generated runtime paths only and refuses edited configuration; it preserves skills, assets, and saved revisions.\n`);
if (exists) {
// Windows cannot remove the caller's current directory, even when empty.
// Move only staged entries and track them so a failed install rolls back.
diff --git a/skills/kiln-batch-dispatch/references/clean-room-evaluation.md b/skills/kiln-batch-dispatch/references/clean-room-evaluation.md
index 88bc87ec..f1abfb5b 100644
--- a/skills/kiln-batch-dispatch/references/clean-room-evaluation.md
+++ b/skills/kiln-batch-dispatch/references/clean-room-evaluation.md
@@ -1,20 +1,8 @@
# Clean-room evaluation
-With the Kiln package installed, create a fresh directory outside the engine checkout:
+Workspace creation, harness choice and verifying that the tools came up are covered by the `kiln-setup-workspace` skill; this file covers only what an evaluation adds on top. Create the workspace with `--skills batch` so this workflow is present in the candidate, and use a separate fresh workspace per candidate.
-```bash
-kiln-init /absolute/empty-workspace --harness opencode --skills batch
-```
-
-Supported harness names are `claude`, `codex`, `opencode`, `hermes`, and `agy`. Author, refine, and QA skills are installed by default; `--skills compose,batch` adds optional workflows. Read the generated project start instructions and run its local `node kiln.mjs` launcher.
-
-From an engine source checkout, the equivalent setup command is:
-
-```bash
-node scripts/create-workspace.mjs /absolute/empty-workspace --harness opencode --skills batch
-```
-
-The project contains its copied skills and their resources. Keep evaluation notes and output there; do not give the model the engine implementation or prior examples unless that is the comparison being tested.
+Keep evaluation notes and output in the workspace. Do not give the model the engine implementation or prior examples unless that is the comparison being tested.
## What isolation means
diff --git a/skills/kiln-setup-workspace/SKILL.md b/skills/kiln-setup-workspace/SKILL.md
new file mode 100644
index 00000000..53d90ff8
--- /dev/null
+++ b/skills/kiln-setup-workspace/SKILL.md
@@ -0,0 +1,53 @@
+---
+name: kiln-setup-workspace
+description: Create and verify a Kiln asset workspace for a chosen coding-agent harness. Use before authoring when the current directory is the engine repository, an empty folder, or any project without a working kiln_workspace server.
+license: MIT
+---
+
+# Set up a workspace for asset authoring
+
+This repository is the engine. Asset authoring happens in a separate workspace, and the two are different tasks with different tools. Establish which one is being asked before running anything.
+
+Authoring an asset needs a workspace. Changing the engine's own behaviour does not; read `AGENTS.md` at the repository root instead and stay in the checkout.
+
+Do not author assets inside the engine checkout. The authoring skills assume a workspace, and giving a model the engine implementation and the example collection alongside its task changes what it produces.
+
+## Create the workspace
+
+Choose an absolute path to an empty directory outside the checkout.
+
+```bash
+node scripts/create-workspace.mjs /absolute/empty-workspace --harness claude
+```
+
+From an installed package, the equivalent is `kiln-init /absolute/empty-workspace --harness claude`. Author, refine and QA skills are installed by default; `--skills compose,batch` adds the optional scene-composition and trial-dispatch workflows. Ask the user which harness they use rather than assuming; the choice writes different configuration and cannot be changed afterwards without a fresh workspace.
+
+| `--harness` | Launch from the workspace |
+| --- | --- |
+| `claude` | `claude` |
+| `codex` | `codex` |
+| `opencode` | `opencode` |
+| `agy` | `node agy.mjs` |
+| `hermes` | `node hermes.mjs --ignore-rules` |
+
+Antigravity and Hermes get a generated launcher because each needs arguments or a separate profile that the bare command does not supply. Hermes authenticates in its own profile; setup copies no credentials.
+
+## Verify the loadout before authoring
+
+Accept the project and MCP trust prompts, then confirm the server is actually live rather than assuming it from configuration. Call `kiln_list_primitives` on `kiln_workspace` with `capabilities: true`; it returns the runtime, source, export and camera contract and proves the tools resolved. A server named `kiln` from a global installation is a different thing. Do not substitute it silently; report the setup problem instead.
+
+Confirm the installed skills are readable at `skills/` in the workspace, and read the relevant one from there rather than a global copy. Whether the harness also registers them natively depends on the harness.
+
+## Relocation and repair
+
+Moving the workspace or the engine installation breaks the generated absolute paths, and so does replacing the Node that setup validated.
+
+```bash
+node /current/kiln/scripts/create-workspace.mjs /absolute/empty-workspace --repair
+```
+
+Repair rewrites generated runtime paths only. It preserves copied skills, saved revisions and assets, refuses configuration that was edited by hand, and does not upgrade the skills. To evaluate a different engine version, create a fresh workspace from that version so instructions and tools match.
+
+## What isolation means
+
+A separate workspace limits task context. It is not an operating-system sandbox, and it is not a git repository. User-level instructions, memory, authentication and filesystem permissions still apply. For comparing harnesses or models, read `skills/kiln-batch-dispatch/references/clean-room-evaluation.md` in the engine checkout, which covers recording inherited context and reporting trials.
diff --git a/src/__tests__/mcp-bundle.test.ts b/src/__tests__/mcp-bundle.test.ts
index 29dfdde8..5eac9efc 100644
--- a/src/__tests__/mcp-bundle.test.ts
+++ b/src/__tests__/mcp-bundle.test.ts
@@ -128,6 +128,13 @@ describe('harness manifests', () => {
*
* A bare `mcp.json` is read by neither harness, which is why it no longer
* exists.
+ *
+ * Root `.mcp.json` is a third case with a different job, asserted separately
+ * below. It is not a plugin manifest: Claude Code reads it as project-scoped
+ * configuration in a plain `git clone`, where no plugin variable is defined at
+ * all. It once carried `${PLUGIN_ROOT}`, which only Antigravity intends to
+ * expand, so a fresh clone opened onto a `kiln` server that could not start --
+ * no tools, on first contact, before the reader had done anything wrong.
*/
const cases = [
{ file: '.claude-plugin/plugin.json', variable: 'CLAUDE_PLUGIN_ROOT' },
@@ -147,4 +154,25 @@ describe('harness manifests', () => {
expect(kiln!.args).toEqual([`\${${variable}}/dist/mcp-server.mjs`]);
});
}
+
+ it('root .mcp.json resolves in a bare clone, with no plugin variable', async () => {
+ const raw = JSON.parse(await readFile(join(REPO, '.mcp.json'), 'utf8')) as {
+ mcpServers: Record<string, { command: string; args: string[] }>;
+ };
+ const kiln = raw.mcpServers['kiln'];
+ expect(kiln).toBeDefined();
+ expect(kiln!.command).toBe('node');
+ // Claude Code expands `${VAR:-default}` in project-scoped config, so the
+ // default is what makes this resolve when nothing sets the variable.
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: the harness expands this, so the assertion must hold the literal text
+ expect(kiln!.args).toEqual(['${CLAUDE_PROJECT_DIR:-.}/dist/mcp-server.mjs']);
+ // The regression itself: no plugin-root variable belongs in this file,
+ // because no plugin context defines one when a clone is opened directly.
+ for (const arg of kiln!.args) {
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: literal tokens, not interpolation
+ expect(arg).not.toContain('${PLUGIN_ROOT}');
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: literal tokens, not interpolation
+ expect(arg).not.toContain('${CLAUDE_PLUGIN_ROOT}');
+ }
+ });
});
diff --git a/src/__tests__/mcp-instructions.test.ts b/src/__tests__/mcp-instructions.test.ts
new file mode 100644
index 00000000..8c2fc116
--- /dev/null
+++ b/src/__tests__/mcp-instructions.test.ts
@@ -0,0 +1,54 @@
+/**
+ * The `instructions` field is the only orientation channel that reaches every
+ * install shape. A user who configures the server by hand and opens an empty
+ * folder has no AGENTS.md, no CLAUDE.md and no registered skills; the skills
+ * still ship beside the server, so this text is what tells them so.
+ *
+ * It names its skills as literal strings, which is what makes it worth testing:
+ * a renamed or removed skill directory would leave the server advertising a
+ * path that does not exist, and nothing else would notice.
+ */
+import { describe, expect, it } from 'bun:test';
+import { stat } from 'node:fs/promises';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { MCP_SERVER_INSTRUCTIONS } from '../mcp-server';
+
+const repo = fileURLToPath(new URL('../..', import.meta.url));
+
+describe('MCP server instructions', () => {
+ it('names only skills that exist on disk', async () => {
+ const named = [...new Set(MCP_SERVER_INSTRUCTIONS.match(/kiln-[a-z-]+/g) ?? [])];
+ expect(named.length).toBeGreaterThan(0);
+ for (const name of named) {
+ const skill = join(repo, 'skills', name, 'SKILL.md');
+ expect((await stat(skill)).isFile()).toBe(true);
+ }
+ });
+
+ it('carries the contract an ad-hoc client cannot learn anywhere else', () => {
+ // Re-sending whole programs instead of reusing a ref is the failure this
+ // text exists to prevent, and viewFidelity is what stops a CPU image being
+ // read as material evidence.
+ expect(MCP_SERVER_INSTRUCTIONS).toContain('programRef');
+ expect(MCP_SERVER_INSTRUCTIONS).toContain('viewFidelity');
+ expect(MCP_SERVER_INSTRUCTIONS).toContain('kiln_list_primitives');
+ });
+
+ it('offers registration without instructing an unrequested write', () => {
+ expect(MCP_SERVER_INSTRUCTIONS).toContain('.claude/skills/');
+ expect(MCP_SERVER_INSTRUCTIONS).toContain('.agents/skills/');
+ // Two constraints on the wording: the copy is proposed, never performed
+ // unasked, and it does not take effect until the next session.
+ expect(MCP_SERVER_INSTRUCTIONS).toContain('Ask before writing');
+ expect(MCP_SERVER_INSTRUCTIONS).toContain('new session');
+ });
+
+ it('stays an index rather than the skill bodies', () => {
+ // The five authoring bodies are about 2,700 tokens. Inlining them would be
+ // paid at every session start by every client, which is what the Agent
+ // Skills progressive-disclosure model exists to avoid.
+ const approxTokens = MCP_SERVER_INSTRUCTIONS.split(/\s+/u).length * 1.3;
+ expect(approxTokens).toBeLessThan(700);
+ });
+});
diff --git a/src/__tests__/mcp-payload.test.ts b/src/__tests__/mcp-payload.test.ts
index bf001f94..7dc11afe 100644
--- a/src/__tests__/mcp-payload.test.ts
+++ b/src/__tests__/mcp-payload.test.ts
@@ -154,7 +154,11 @@ describe('always-on context cost', () => {
it('skill discovery stays within the context budget', async () => {
const { total, count } = await frontMatterChars();
- expect(count).toBe(5);
+ // Six since kiln-setup-workspace was added: the authoring five plus the
+ // repo-side setup skill, which is the one an agent in a bare clone needs
+ // before any of the others apply. A hard count keeps adding a skill a
+ // deliberate act, because every one of these is paid at session start.
+ expect(count).toBe(6);
// Front matter is a name and one sentence. Anything much past this is a
// skill trying to teach from the index instead of from its body.
expect(total).toBeLessThan(2048);
diff --git a/src/evaluator/authoring-diagnostic.ts b/src/evaluator/authoring-diagnostic.ts
index 62a5f639..bbe9db25 100644
--- a/src/evaluator/authoring-diagnostic.ts
+++ b/src/evaluator/authoring-diagnostic.ts
@@ -1,7 +1,13 @@
/** Closed, engine-owned repair hints. Never serialize exception messages or stacks. */
export type AuthoringDiagnostic = 'UNBOUND_VARIABLE' | 'GEAR_RADII_ORDER' | 'ROUNDED_BOX_RADIUS';
+// Names no identifier on purpose. The identifier is only available from the
+// sandboxed exception message, and this module's contract is that no captured
+// identifier, path, message or stack crosses that boundary. Pointing at the
+// discovery tool is engine-owned text, so it costs nothing to include and is
+// the actionable half: an undeclared name here is usually a helper that does
+// not exist rather than a typo in a local.
export const UNBOUND_VARIABLE_ADVICE =
- 'Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying.';
+ 'Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_list_primitives to confirm the exact name and signature; the sandbox exposes only those globals.';
export const GEAR_RADII_ORDER_ADVICE =
'gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.';
export const ROUNDED_BOX_RADIUS_ADVICE =
diff --git a/src/mcp-server.ts b/src/mcp-server.ts
index ee89ce89..f6c6083e 100644
--- a/src/mcp-server.ts
+++ b/src/mcp-server.ts
@@ -9,6 +9,7 @@ import { localAssetLibrary } from './assets-node';
import { readAssetResource, type AssetLink } from './assets-resources';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import { AsyncLocalStorage } from 'node:async_hooks';
+import { fileURLToPath } from 'node:url';
import {
createKilnProgramToolRegistry,
@@ -24,6 +25,45 @@ import { createPackagedLocalToolContext } from './local-runtime';
export const MCP_SERVER_NAME = 'kiln';
export const MCP_SERVER_VERSION = '0.6.0';
+/**
+ * Absolute path to the skills that ship beside this server. Both entry shapes
+ * resolve correctly: `dist/mcp-server.mjs` and `src/mcp-server.ts` each sit one
+ * level below the installation root, where `skills/` lives. URL arithmetic only,
+ * so nothing touches the filesystem at module load.
+ */
+const packagedSkillsDir = fileURLToPath(new URL('../skills', import.meta.url));
+
+/**
+ * The spec's optional `instructions` field, returned in the initialize result.
+ *
+ * This is the only orientation channel that survives every install shape. A
+ * user who configures the server by hand and opens an empty folder has no
+ * AGENTS.md, no CLAUDE.md and no registered skills -- but the skills do ship
+ * beside the server, so the useful thing to say is that they exist and where.
+ *
+ * Deliberately an index and a pointer rather than the skill bodies themselves.
+ * The bodies are about 2,700 tokens and would be paid at every session start by
+ * every client, which is exactly what the Agent Skills progressive-disclosure
+ * model exists to avoid: names and descriptions up front, bodies on activation.
+ */
+export const MCP_SERVER_INSTRUCTIONS = `Kiln turns JavaScript you write into GLB 3D assets and returns rendered views for review.
+
+Work by reference. Send a program once to kiln_validate or kiln_render; the result carries a programRef. Keep it exactly as returned, including a short p_ handle, and use it for every later view and edit. kiln_source with that ref and a literal query returns exact edit anchors, and kiln_edit with that ref plus edits returns a new ref and renders by default. Do not resend a whole program to change part of it.
+
+Call kiln_list_primitives before writing code to get exact helper signatures, with capabilities: true for the runtime, source, export and camera contract. Read viewFidelity in any render result before judging materials: a geometry-flat CPU image is evidence about shape, not about material.
+
+Detailed workflows ship beside this server as Agent Skills, one directory each under ${packagedSkillsDir}:
+- kiln-setup-workspace: create a managed workspace for authoring, and verify its tools came up
+- kiln-author-asset: write a new asset and export a GLB
+- kiln-refine-asset: change a saved asset through revisions
+- kiln-qa-asset: verify geometry, export fidelity, and behaviour in the destination project
+- kiln-compose-scene: arrange several existing GLB assets into a scene
+- kiln-batch-dispatch: run comparable trials across harnesses or models
+
+Read the one matching the task before authoring; each names its own reference files.
+
+Most harnesses register skills only from their own directories, so these may not appear as registered skills where you are. If the user wants them registered, offer to copy the relevant directories into .claude/skills/ or .agents/skills/ in their project. Ask before writing, and say that registration takes effect in a new session.`;
+
/** One MCP content block. Mirrors the SDK's `CallToolResult['content']` element. */
type ContentBlock =
| AssetLink
@@ -115,10 +155,13 @@ export async function runTool(def: KilnToolDef, args: unknown): Promise<KilnTool
/** Build the server, registering every def from the registry. */
export function createKilnMcpServer(context: KilnToolContext = {}): McpServer {
- const server = new McpServer({
- name: MCP_SERVER_NAME,
- version: MCP_SERVER_VERSION,
- });
+ const server = new McpServer(
+ {
+ name: MCP_SERVER_NAME,
+ version: MCP_SERVER_VERSION,
+ },
+ { instructions: MCP_SERVER_INSTRUCTIONS },
+ );
server.registerResource(
'kiln-asset-viewer',
KILN_ASSET_WIDGET_URI,
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index 34c803bf..291ca272 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -18,6 +18,7 @@ import { createCachedEvaluatorPort, MemoryBuildCache, type BuildCache } from '..
import * as THREE from 'three';
import { validate } from '../validation';
+import { evaluatorOutcomeMessage } from '../evaluator/protocol';
import { inspectSceneStructure, renderSceneToGLB, type RenderResult } from '../render';
import { listPrimitives, type PrimitiveSpec } from '../list-primitives';
import type { AssetCategory, AssetIntentV1 } from '../contracts';
@@ -845,7 +846,20 @@ export interface KilnRenderMetrics {
ok: boolean;
tris?: number;
meshes?: number;
+ /**
+ * Material slots on the re-imported review scene, which is one per mesh. The
+ * scene measured here has been round-tripped through GLB, so authored sharing
+ * no longer survives as object identity and this can never disagree with
+ * `meshes`. Kept for output-shape stability; judge material sprawl from
+ * `distinctMaterials`.
+ */
materials?: number;
+ /**
+ * Distinct materials in the exported GLB, measured post-dedup. This is the
+ * number that actually falls when parts share a material, and the one the
+ * instanceability grade is driven by.
+ */
+ distinctMaterials?: number;
bbox?: { min: number[]; max: number[]; size: number[] };
/** Mesh touching the lowest world point — ground-contact attribution. When
* bbox.min[1] dips below 0, this names the buried part so the agent can
@@ -918,6 +932,27 @@ function collectSceneMetrics(root: THREE.Object3D): SceneMetrics {
* Execute Kiln code, render it to an in-memory GLB, and report metrics.
* Never writes files; never throws — failures come back as { ok:false, error }.
*/
+/**
+ * The evaluator's rejection message is deliberately opaque, because nothing
+ * from a sandboxed exception may cross that boundary -- not a message, not a
+ * stack, not an identifier. A syntax error is the one exception worth making,
+ * and it costs nothing: acorn parses host-side before any generated code runs,
+ * which is exactly why `kiln_validate` can already report its line and column.
+ * Repeating that parse here leaks nothing new and turns an unactionable
+ * rejection into a position, without a second round-trip through validate.
+ */
+function withSyntaxDetail(message: string, code: string): string {
+ if (!message.startsWith(evaluatorOutcomeMessage('EXECUTION_REJECTED'))) return message;
+ let syntax: string | undefined;
+ try {
+ syntax = validate(code).errors.find((error) => error.startsWith('Syntax error:'));
+ } catch {
+ // A diagnostic must never turn a handled failure into an unhandled one.
+ return message;
+ }
+ return syntax ? `${message} ${syntax}` : message;
+}
+
async function runRender(
input: z.infer<typeof renderInput>,
context: KilnToolContext,
@@ -945,6 +980,9 @@ async function runRender(
tris: rendered.tris,
meshes: metrics.meshes,
materials: metrics.materials,
+ ...(rendered.meta.instanceability
+ ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials }
+ : {}),
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
...(instanceability
@@ -961,7 +999,7 @@ async function runRender(
} catch (err) {
return {
ok: false,
- error: err instanceof Error ? err.message : String(err),
+ error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
warnings: [],
};
}
@@ -1015,7 +1053,7 @@ async function runScreenshot(
} catch (err) {
return {
ok: false,
- error: err instanceof Error ? err.message : String(err),
+ error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
warnings: [],
};
}
@@ -1044,7 +1082,20 @@ export interface KilnRenderViewsResult {
ok: boolean;
tris?: number;
meshes?: number;
+ /**
+ * Material slots on the re-imported review scene, which is one per mesh. The
+ * scene measured here has been round-tripped through GLB, so authored sharing
+ * no longer survives as object identity and this can never disagree with
+ * `meshes`. Kept for output-shape stability; judge material sprawl from
+ * `distinctMaterials`.
+ */
materials?: number;
+ /**
+ * Distinct materials in the exported GLB, measured post-dedup. This is the
+ * number that actually falls when parts share a material, and the one the
+ * instanceability grade is driven by.
+ */
+ distinctMaterials?: number;
bbox?: { min: number[]; max: number[]; size: number[] };
lowestPart?: { name: string; y: number };
/** Post-dedup instanceability grade (informational): how cheap to render at scale. */
@@ -1111,6 +1162,9 @@ async function runRenderViews(
tris: rendered.tris,
meshes: metrics.meshes,
materials: metrics.materials,
+ ...(rendered.meta.instanceability
+ ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials }
+ : {}),
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
views: grid.views,
@@ -1261,6 +1315,9 @@ async function runRenderViews(
tris: rendered.tris,
meshes: metrics.meshes,
materials: metrics.materials,
+ ...(rendered.meta.instanceability
+ ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials }
+ : {}),
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
...(rendered.meta.instanceability
@@ -1286,7 +1343,7 @@ async function runRenderViews(
} catch (err) {
return {
ok: false,
- error: err instanceof Error ? err.message : String(err),
+ error: withSyntaxDetail(err instanceof Error ? err.message : String(err), input.code),
warnings: [],
};
}
diff --git a/src/validation.ts b/src/validation.ts
index ca16f57c..a35ca0c7 100644
--- a/src/validation.ts
+++ b/src/validation.ts
@@ -24,6 +24,7 @@
import * as acorn from 'acorn';
import * as walk from 'acorn-walk';
+import { listPrimitives } from './list-primitives';
// =============================================================================
// Types
@@ -339,9 +340,131 @@ export function validate(code: string, _opts: { category?: string } = {}): Valid
});
}
+ warnings.push(...unknownHelperWarnings(ast));
+
return toResult(issues, warnings, analysis.estimatedTris);
}
+/**
+ * Identifiers that are called but neither declared in the program nor exposed
+ * by the sandbox. Calling one throws the moment the program runs, so reporting
+ * it before execution is strictly better than discovering it from a render.
+ *
+ * This is also the only place the name can be reported at all. The isolated
+ * evaluator deliberately lets no identifier, message or stack cross its
+ * boundary, so `kiln_render` can say that some variable was undeclared but
+ * never which one. This parse happens host-side, before anything executes.
+ *
+ * Reported as a warning rather than an error, and the declaration set below
+ * deliberately over-approximates: every binding anywhere in the program counts
+ * as in scope, so a shadowed or conditionally declared name is never falsely
+ * flagged. The cost is that some genuinely unbound names go unreported, which
+ * is the safe direction for a check that would otherwise reject valid source.
+ */
+function unknownHelperWarnings(ast: acorn.Program): ValidationIssue[] {
+ const declared = new Set<string>();
+ const bind = (node: unknown): void => {
+ const target = node as { type?: string; [key: string]: unknown } | null;
+ if (!target?.type) return;
+ if (target.type === 'Identifier') declared.add(target['name'] as string);
+ else if (target.type === 'ObjectPattern')
+ for (const prop of target['properties'] as { value?: unknown; argument?: unknown }[])
+ bind(prop.value ?? prop.argument);
+ else if (target.type === 'ArrayPattern')
+ for (const el of target['elements'] as unknown[]) bind(el);
+ else if (target.type === 'AssignmentPattern') bind(target['left']);
+ else if (target.type === 'RestElement') bind(target['argument']);
+ };
+ const params = (node: unknown): void => {
+ const fn = node as { id?: { name?: string }; params?: unknown[] };
+ if (fn.id?.name) declared.add(fn.id.name);
+ for (const param of fn.params ?? []) bind(param);
+ };
+ walk.simple(ast, {
+ VariableDeclarator(node) {
+ bind((node as unknown as { id: unknown }).id);
+ },
+ FunctionDeclaration(node) {
+ params(node);
+ },
+ FunctionExpression(node) {
+ params(node);
+ },
+ ArrowFunctionExpression(node) {
+ params(node);
+ },
+ ClassDeclaration(node) {
+ params(node);
+ },
+ CatchClause(node) {
+ bind((node as unknown as { param: unknown }).param);
+ },
+ });
+
+ const seen = new Map<string, number | undefined>();
+ walk.simple(ast, {
+ CallExpression(node) {
+ const callee = (node as unknown as { callee?: { type?: string; name?: string } }).callee;
+ if (callee?.type !== 'Identifier' || !callee.name) return;
+ const name = callee.name;
+ if (declared.has(name) || SANDBOX_CALLABLES.has(name) || seen.has(name)) return;
+ seen.set(name, (node as unknown as { loc?: { start?: { line?: number } } }).loc?.start?.line);
+ },
+ });
+
+ return [...seen].map(([name, line]) => ({
+ code: 'UNKNOWN_HELPER',
+ message: `${name}() is not declared in this program and is not a Kiln sandbox global; the build will fail when it runs.`,
+ fixHint:
+ 'Call kiln_list_primitives to confirm the helper name and signature, or declare the function in this program.',
+ ...(line === undefined ? {} : { line }),
+ }));
+}
+
+/**
+ * Everything a program may legitimately call by bare name: the sandbox catalog,
+ * which a bidirectional test keeps in step with `buildSandboxGlobals()`, plus
+ * the JavaScript built-ins the sandbox does not remove. The catalog is imported
+ * rather than the sandbox itself so this module's dependency graph stays free of
+ * three.js.
+ */
+const SANDBOX_CALLABLES: ReadonlySet<string> = new Set([
+ ...listPrimitives().map((primitive) => primitive.name),
+ 'Array',
+ 'BigInt',
+ 'Boolean',
+ 'Error',
+ 'Float32Array',
+ 'Float64Array',
+ 'Int16Array',
+ 'Int32Array',
+ 'Int8Array',
+ 'Map',
+ 'Number',
+ 'Object',
+ 'Promise',
+ 'Proxy',
+ 'RangeError',
+ 'Reflect',
+ 'RegExp',
+ 'Set',
+ 'String',
+ 'Symbol',
+ 'TypeError',
+ 'Uint16Array',
+ 'Uint32Array',
+ 'Uint8Array',
+ 'WeakMap',
+ 'WeakSet',
+ 'decodeURIComponent',
+ 'encodeURIComponent',
+ 'isFinite',
+ 'isNaN',
+ 'parseFloat',
+ 'parseInt',
+ 'structuredClone',
+]);
+
// Backward-compat alias.
export const validateKilnCode = validate;