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.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
Add delivery roles: colliders, anchors, kit modules and the LOD impostor marker
Matt Kissinger61714767fa87
diff --git a/docs/plans/2026-10-15-game-delivery-contract.md b/docs/plans/2026-10-15-game-delivery-contract.mdnew file mode 100644index 00000000..677420ea--- /dev/null+++ b/docs/plans/2026-10-15-game-delivery-contract.md@@ -0,0 +1,202 @@+# Game delivery contract (2026-10-15)++Status: scoped by the owner's game session on 15 October 2026, before any asset work+in the consuming game. This is a dated plan: it never overrides code, `AGENTS.md`+or the changelog, and it is not release acceptance. It lands on a branch as a pull+request candidate; whether it merges, bumps a version or publishes is a separate+owner decision taken after the consuming game has built assets against it.++## Why++The consuming game (a three.js r185 WebGPU/TSL title, `OBJEKT-62`) authors nearly+every object as code from welded primitives, owns its own shader graphs, effects and+hand-rolled collision, and loads GLBs through a one-off import step per asset. For+Kiln to author its monuments, a walkable ship kit, cacti and a Keeper body kit, the+GLB has to carry everything the game's import step needs so that ONE generic step+replaces per-asset wiring. Today it carries shape, UVs, materials and LOD chains. It+does not carry colliders, anchors, kit metadata, the two wear attributes the game's+shaders read, a triangle budget, a solid guarantee, or a qualified three.js runtime+derivative, and the atlas is a hand-laid sheet.++Everything below extends the GLB contract through plain glTF (roles in node extras,+underscore custom attributes, vendor extensions already in use). Nothing teaches Kiln+about three.js materials, effects or physics; those stay in the consumer.++## Non-goals++- No version bump, no changelog release entry, no publish, no merge to main, no push+ without explicit owner approval.+- No three.js node materials, VFX, physics or collision response inside Kiln.+- No crash-damage or destruction helper (a later design, see "Deferred").+- No snap solver for kits; this cycle delivers the contract and diagnostics only.+- No change to MCP tool input schemas. New behaviour is reached through authored+ source helpers and existing CLI flags, so the prompt-cached schemas stay stable.+- No general self-intersection detection beyond the existing sweep analysis.++## Scope, in delivery order++Each item is one or more commits on the branch, with its own tests, so items can be+cherry-picked independently if the owner ships only part of this.++### 1. Semantic roles for delivery (`src/contracts/semantic.ts`, integration manifest)++`KILN_SEMANTIC_ROLES` is documented as part of the GLB contract, so this is a+versioned additive change. Add:++| Role | On | Meaning |+|---|---|---|+| `collider.box.<id>` | a hidden proxy node whose geometry is a unit box under the node transform | yaw-capable oriented box collider |+| `collider.capsule.<id>` | hidden proxy node, unit capsule (radius 0.5, height 1 along +Y) | capsule collider |+| `collider.hull.<id>` | hidden proxy node with its own mesh | convex hull from the proxy vertices |+| `anchor.<kind>.<id>` | an empty node | a named point with transform: doors, vault plates, beacons, hardpoints, lights, spawn points |+| `kit.module` | the root of a modular piece | carries extras `kiln.kit`: `{ footprint: [w, d], height, snapAxis: 'x'|'y'|'z', origin: 'corner'|'center' }` |+| `kit.port.<id>` | an empty node under a `kit.module` | a snap point with transform |+| `lod.impostor` | the last level of a `defineLod` chain | that level is a card or billboard tier |++Authoring helpers, in a new `delivery` subpath exported from the package root map+and advertised in Discovery: `colliderBox(size, { id })`, `colliderCapsule(radius,+height, { id })`, `colliderHull(mesh, { id })`, `anchor(kind, id)`, `defineModule(root,+spec)`, `port(id)`, and `{ impostor: true }` on the last `defineLod` level. Colliders and+anchors are hidden through the existing hidden-node mechanism so every importer that+ignores roles still draws the right thing.++Integration manifest: additive fields on `IntegrationManifestV1` (or a `v2` if the+existing reader rejects unknown fields; choose whichever keeps old sidecars valid):+`colliders[]`, `anchors[]`, `kit?`, `ports[]`, and `impostor: true` on the LOD level+record. Each entry carries role, node path, and the world-space transform relative to+the asset root.++Diagnostics (advisory, never QA acceptance): a collider proxy must be hidden and+inside the asset bounds; a box or capsule collider should overlap at least one drawn+triangle; ports must lie within the module footprint; an anchor must be a leaf.++### 2. Baked surface attributes (`_EDGE`, `_CAVITY`)++`bakeSurfaceAttributes(target, { edge?, cavity? })` on a mesh or subtree writes two+float vertex attributes, both in [0, 1]:++- `_EDGE`: convex-rim weight from the dihedral angle of the faces around the vertex,+ with a configurable threshold angle (default 35 degrees) and a one-ring smoothing+ step. Flat faces read 0, chamfers and rims read toward 1.+- `_CAVITY`: exposure, 1 minus a vertex-level occlusion from a fixed hemispherical+ ray set (default 32 directions, radius default 0.5 x bounds diagonal) cast against+ the asset's own triangles. Recess and overhang vertices read toward 0.++Deterministic: fixed direction set, no `Math.random`, no `Date.now`. Bounded by new+entries in `GEOMETRY_ALLOCATION_LIMITS` (vertices, triangles, rays). Both converters+must write the attributes; the export diagnostic lists custom attributes preserved,+and the integration manifest records `vertexAttributes: [{ name, meshes, params }]`.++Tests: a chamfered box bakes edge near 1 on chamfer vertices and near 0 on face+centres; a box inside an open-topped box bakes cavity lower than a free box; both+attributes survive export through `legacy` and `three` converters and are readable+through gltf-transform.++### 3. Triangle and draw budgets in the receipt++`defineBudget({ triangles: number | { LOD0, LOD1, ... }, draws?: number })` in source.+The render receipt (CLI `--json`, `kiln_render` metrics) gains `budget: { declared,+measured, status: 'pass' | 'fail' | 'none' }` per tier. CLI gains `--strict-budget`+(non-zero exit on fail). Advisory by default; it never changes QA acceptance.++### 4. Solid diagnostics++`geometryDiagnostics` gains a `solid` section per mesh: `closed` (zero boundary+edges), `manifold` (zero non-manifold edges), `orientation: 'outward' | 'inward' |+'mixed'` from consistent winding plus the sign of the signed volume, and+`signedVolume`. An opt-in `requireSolid(mesh)` authoring assertion fails the build+with a closed repair message when any of the three is false. Use the existing edge+analysis for the first two; signed volume is a direct sum. `manifold-3d` is not+required for this item.++### 5. Atlas packer++`textureAtlas` accepts regions without a `content` rectangle plus a `pack` option:+`{ edge: 1024 | 2048, gutter, algorithm: 'maxrects' }`. Packed placement is+deterministic (sort by area descending, then name). Explicit rectangles remain and+may be mixed with packed regions. Limits move with a versioned compiler id+(`kiln.texture-atlas.v1.2`): edge 2048, output texels 4,194,304, sources 32, regions+128. Provenance records the resolved placement of every packed region so a saved+record is reproducible without re-packing.++### 6. three.js runtime delivery profile++`export --profile runtime --target three` (and the library equivalent) produces a+derived GLB that is: meshopt-compressed and quantized (`EXT_meshopt_compression`,+`KHR_mesh_quantization`), with `EXT_mesh_gpu_instancing` for repeated identical+mesh-plus-material children marked by a `repeatInstances(parent)` helper, KTX2 when+the encoder is present and reported `skipped` otherwise, and with `_EDGE`/`_CAVITY`,+roles, hidden collider nodes, anchors, kit extras and `MSFT_lod` chains preserved.++The sidecar states the quantization and node-scale facts explicitly (which nodes+carry a metre scale after quantization, so a consumer that re-parents bare geometry+knows it will drop it), the list of custom attributes, and the extension set used.++Qualification: a test loads the derived GLB through three's `GLTFLoader` (three is a+dependency) with the meshopt decoder in a Node test, and asserts LOD nodes, roles+in extras, custom attributes, instancing and hidden nodes are all present. If+`GLTFLoader` cannot run under the test runner, record the exact reason in the plan's+execution log, assert the same facts through gltf-transform, and leave a documented+manual viewer check for the owner.++### 7. Small items++- Vegetation recipe `cactus` beside `succulent` in `src/vegetation-prompt.ts`:+ ribbed star-profile loft trunk, swept arms with elbows, spine cards on ribs,+ explicit LOD tiers with an impostor last.+- `definePalette([...hex])` in source: an advisory diagnostic lists every material+ base colour farther than a threshold from the nearest palette entry.+- Authoring guidance: update `skills/kiln-author-asset/references/geometry-recipes.md`+ for colliders, anchors, kits, bakes, budgets and the cactus recipe, then run+ `bun run check:skills`.+- Docs: `docs/geometry.md` (solid, bakes, budgets), `docs/export-profiles.md`+ (three target), `docs/procedural-surfaces-v3.md` (packer), a new+ `docs/delivery-contract.md` that is the single reference for roles, attributes+ and the manifest fields, and regenerated `docs/tools.md` if Discovery entries+ changed (tool schemas must not).++### 8. End-to-end fixture++One committed fixture source under `src/__tests__/fixtures/` or `examples/`: a+bunker door frame as a `kit.module` with two ports, a box collider, three anchors,+a two-tier `defineLod` plus an impostor, baked attributes, a packed atlas with two+procedural regions, a budget and `requireSolid`. The fixture exports through both+converters and the three target and is the subject of the item 6 qualification test.++## Deferred (named so nobody re-scopes them by accident)++- A crash-damage or tearing helper for wreck module sets.+- A kit snap solver and composition validation across modules.+- General self-intersection detection.+- An engine-side palette lock that fails builds (this cycle is advisory only).++## Acceptance for the branch++In the Kiln checkout, all of `AGENTS.md`'s offline gate must pass:+`bun run check:toolchain`, `bun run check:skills`, `bun run build:sdk`,+`bun run typecheck`, `bun run lint`, `bun run test`, `bun run test:render-service`,+`bun run test:coverage` with the ratchet in `bunfig.toml` not lowered, and+`node scripts/build-runtime.mjs all` after runtime changes. Strict TDD per the+guide: focused failing test first, smallest fix, rerun focused then full gates.++The branch must not touch the pre-existing uncommitted changes in the checkout+(`ROADMAP.md`, `docs/backlog.md`, `docs/install.md`, and the untracked+`docs/plans/2026-10-12-scenes-trailer-plan.md`); stage only the paths this plan+creates or edits. Commits are per item with messages that name the item number.+No push.++## Execution log++The implementer appends one dated line per completed item here, plus any deviation+from this scope and why. The owner's game session reads this log to monitor.++- 2026-10-15 baseline (branch `feat/game-delivery-contract` from `743965ac`, before any change):+ `bun install --frozen-lockfile` clean; `bun run check:toolchain` and `bun run build:sdk`+ (59 entrypoints) pass; `bun run typecheck` and `bun run lint` (988 files) pass;+ `bun run test` 3674 pass, 2 skip, 20 fail. The 20 failures are environmental or+ pre-existing and are not counted against this branch: 19 in `scripts/` (17+ `prepare-npm-release.test.mjs` and 2 `example-archive.test.mjs`) fail because this+ Git Bash PATH resolves GNU tar 1.35, which reads `C:\...` as a remote host ("Cannot+ connect to C: resolve failed"); 1 `src/__tests__/workspace-setup.test.ts` "ships a CLI+ bundle matching the current source" fails because the committed `dist/cli.mjs` differs+ from a fresh build at HEAD on this machine (Node 24.20.0 on PATH, toolchain pins 22.23.3).diff --git a/docs/sdk.md b/docs/sdk.mdindex 439c45c3..9d8415a0 100644--- a/docs/sdk.md+++ b/docs/sdk.md@@ -23,7 +23,7 @@ const result = await renderGLB(code);The complete authoring and host APIs remain available through documented subpaths.The original 55 export paths are retained; version 1.1 added four-host entrypoints below. The root exposes rendering, validation,+host entrypoints below, and the game delivery contract adds `delivery`. The root exposes rendering, validation,Discovery and engine identity; it does not re-export every name from every module.CommonJS is not part of this release's contract.@@ -36,7 +36,7 @@ Use the existing material payload and asset-bundle encoders for portable deliver| Area | Subpaths || --- | --- || Root library | `@instruktlabs/kiln` |-| Authoring | `primitives`, `geometry`, `deform`, `sweep`, `architecture`, `assembly`, `character`, `vehicle`, `palette` |+| Authoring | `primitives`, `geometry`, `deform`, `sweep`, `architecture`, `assembly`, `character`, `vehicle`, `palette`, `delivery` || Materials | `material-library`, `material-library/node`, `material-presets`, `material-recipes`, `material-resources`, `material-recipe-runtime`, `material-recipe-prompt`, `material-metrics`, `texture-resolver` || Rendering and inspection | `render`, `views`, `views/port`, `validation`, `metrics`, `inspect`, `qa`, `asset-export`, `kit` || Host contracts | `tools`, `tools/input`, `mcp`, `evaluator`, `discovery`, `discovery/portable`, `requirements`, `requirements/migration`, `contracts`, `prompt-api`, `profile` |@@ -53,7 +53,7 @@ entrypoint list. Files inside `lib/`, including declaration dependencies under## Stability in 1.x-The table classifies all 59 public entrypoints. The root and every listed subpath+The table classifies all 60 public entrypoints. The root and every listed subpathexcept `implicit` are stable entrypoints for v1: their declared public signatures,record shapes and documented behavior receive normal semantic-versioningcompatibility. Optional dependencies do not make the two agent APIs experimental.diff --git a/package.json b/package.jsonindex 1e2fd8b5..f7c98c5e 100644--- a/package.json+++ b/package.json@@ -115,6 +115,10 @@"types": "./lib/kit.d.ts","import": "./lib/kit.js"},+ "./delivery": {+ "types": "./lib/delivery.d.ts",+ "import": "./lib/delivery.js"+ },"./palette": {"types": "./lib/palette.d.ts","import": "./lib/palette.js"diff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snapindex b0f973b3..5a0981f3 100644--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap@@ -61,13 +61,13 @@ createPart(name, geometry, material, opts?: { position, rotation: [xDeg, yDeg, z// ~zero rotation.// e.g. createPart('Barrel', cylinderGeo(0.1, 0.1, 1), gameMaterial(0x556b2f), { position: [0,// 0.5, 0], rotation: [0, 0, 90], parent: root });-defineLod(levels: Object3D[], opts: { screenCoverage: number[] })+defineLod(levels: Object3D[], opts: { screenCoverage: number[], impostor?: boolean })// Declares one set of level-of-detail tiers, LOD0 (full detail) first, and the minimum screen// coverage (0..1) at which each level draws.// NOTE: Only when the brief asks for LOD tiers; otherwise build one tier. Tiers are sibling// nodes named with one stem and consecutive LOD<n> tokens. screenCoverage has one value per// level, strictly decreasing; below the last the asset is culled, and a last value of 0 never- // culls.+ // culls. impostor: true marks the last level a card or billboard tier.// e.g. const tiers = ['Body_LOD0', 'Body_LOD1', 'Body_LOD2'].map((name) => { const g = new// THREE.Group(); g.name = name; root.add(g); return g; }); defineLod(tiers, { screenCoverage:// [0.25, 0.06, 0.01] });@@ -79,6 +79,39 @@ markOpenShell(part: Object3D, reason: string)// group covers its meshes. Overlap with a marked part stays unmeasured, not clear.// e.g. const rail = createPart('Rail', new THREE.CylinderGeometry(0.2, 0.2, 2, 16, 1, true),// steel, { parent: root }); markOpenShell(rail, 'Tube closed by the end plates');+colliderBox(size: [w, h, d] | number, opts: { id, parent?, position?, rotation?: [xDeg, yDeg, zDeg] })+ // Adds a hidden oriented-box collider proxy with role collider.box.<id>: a unit box whose+ // node scale is the size, so a consumer reads centre, orientation and size from the transform+ // alone.+ // NOTE: Only when the brief asks for colliders. The proxy never draws; it must wrap or cross+ // the surface it stands for and stay inside the drawn bounds. id is one segment without dots.+ // e.g. colliderBox([2, 3, 0.4], { id: 'frame', parent: root, position: [0, 1.5, 0] });+colliderCapsule(radius: number, height: number, opts: { id, parent?, position?, rotation? })+ // Adds a hidden capsule collider proxy along local +Y with role collider.capsule.<id>. height+ // is the TOTAL end-to-end height including both caps (at least 2 * radius); the node scale is+ // [2r, height, 2r].+ // NOTE: height here is total height, unlike capsuleGeo whose height is the straight middle+ // length.+ // e.g. colliderCapsule(0.15, 1.8, { id: 'post', parent: root, position: [0.8, 0.9, 0] });+colliderHull(mesh: Mesh, opts: { id, parent? })+ // Adds a hidden convex-hull collider proxy of a mesh's vertices beside it, with the mesh's+ // local transform and role collider.hull.<id>. The input mesh is unchanged.+ // e.g. const frame = createPart('Frame', boxGeo(2, 3, 0.4), steel, { parent: root });+ // colliderHull(frame, { id: 'frame' });+anchor(kind: string, id: string, opts?: { parent?, position?, rotation? })+ // Adds a named point with a transform and role anchor.<kind>.<id>: a door, vault plate,+ // beacon, hardpoint, light or spawn point the consumer attaches behaviour to.+ // NOTE: An anchor is a leaf: never add parts under it. kind and id are single segments.+ // e.g. anchor('door', 'main', { parent: root, position: [0, 1, 0.25] });+defineModule(root: Object3D, spec: { footprint: [w, d], height, snapAxis: 'x'|'y'|'z', origin: 'corner'|'center' })+ // Marks root as one modular kit piece (role kit.module) and records its footprint (width X,+ // depth Z), height and snap axis as kilnKit node extras.+ // NOTE: Only for modular kit pieces. Place each port inside the footprint.+ // e.g. defineModule(root, { footprint: [4, 4], height: 3, snapAxis: 'x', origin: 'center' });+port(id: string, opts?: { parent?, position?, rotation? })+ // Adds a kit snap point with role kit.port.<id> under a defineModule root; its transform is+ // the snap frame.+ // e.g. port('west', { parent: root, position: [-2, 0, 0], rotation: [0, 180, 0] });beamBetween(name, start: [x,y,z], end: [x,y,z], radius, material, opts?: { segments, parent })// Creates a cylindrical rail/strut exactly between two endpoints in its parent frame. Derive// attachment endpoints from the neighboring geometry; the helper does not find joints or joindiff --git a/src/__tests__/delivery-roles.test.ts b/src/__tests__/delivery-roles.test.tsnew file mode 100644index 00000000..a94fcadd--- /dev/null+++ b/src/__tests__/delivery-roles.test.ts@@ -0,0 +1,258 @@+/**+ * Game-delivery roles (delivery contract item 1).+ *+ * Collider proxies, anchors, kit modules and ports travel as plain glTF: semantic roles in+ * node extras, hidden proxy nodes through KHR_node_visibility, and the kit spec as engine+ * extras. The integration manifest lists each with its transform relative to the asset root,+ * and advisory diagnostics name a proxy that draws, leaves the bounds or touches nothing.+ */+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';+import {+ KILN_SEMANTIC_ROLES,+ KILN_SEMANTIC_ROLES_REVISION,+ readSemanticMetadataV1,+} from '../contracts';+import {+ anchor,+ colliderBox,+ colliderCapsule,+ colliderHull,+ defineModule,+ KILN_KIT_KEY,+ port,+} from '../delivery';+import { AuthoringDiagnosticError } from '../evaluator/authoring-diagnostic';+import { defineLod } from '../lod';+import { buildSandboxGlobals } from '../primitives';+import { renderGLBInProcess } from '../render';++const program = (extra = '') => `const meta={name:'Bunker Frame'};+function build(){+ const root=createRoot('Root');+ const m=gameMaterial('#777777');+ const frame=createPart('Frame',boxGeo(2,3,0.4),m,{parent:root,position:[0,1.5,0]});+ defineModule(root,{footprint:[2,0.4],height:3,snapAxis:'x',origin:'center'});+ port('west',{parent:root,position:[-1,0,0],rotation:[0,180,0]});+ port('east',{parent:root,position:[1,0,0]});+ colliderBox([2,3,0.4],{id:'frame',parent:root,position:[0,1.5,0]});+ colliderBox([0.25,0.25,0.25],{id:'latch',parent:root,position:[0,3,0],rotation:[0,30,0]});+ colliderCapsule(0.15,0.8,{id:'post',parent:root,position:[0.6,2.7,0]});+ colliderHull(frame,{id:'hull'});+ anchor('door','main',{parent:root,position:[0,1,0.25]});+ anchor('light','top',{parent:root,position:[0,2.9,0]});+ const tiers=['Tile_LOD0','Tile_LOD1'].map((name)=>{const g=new THREE.Group();g.name=name;root.add(g);return g;});+ createPart('Tile',boxGeo(0.2,0.2,0.2),m,{parent:tiers[0],position:[0,3.1,0]});+ createPart('Card',planeGeo(0.2,0.2),m,{parent:tiers[1],position:[0,3.1,0]});+ defineLod(tiers,{screenCoverage:[0.2,0],impostor:true});+ ${extra}+ return root;+}`;++const close = (actual: readonly number[], expected: readonly number[], digits = 5) => {+ expect(actual.length).toBe(expected.length);+ actual.forEach((value, index) => {+ expect(value).toBeCloseTo(expected[index]!, digits);+ });+};++describe('delivery role vocabulary', () => {+ test('adds the delivery roles as revision 2 of the vocabulary', () => {+ expect(KILN_SEMANTIC_ROLES_REVISION).toBe(2);+ expect(KILN_SEMANTIC_ROLES.colliderBox).toBe('collider.box');+ expect(KILN_SEMANTIC_ROLES.colliderCapsule).toBe('collider.capsule');+ expect(KILN_SEMANTIC_ROLES.colliderHull).toBe('collider.hull');+ expect(KILN_SEMANTIC_ROLES.anchor).toBe('anchor');+ expect(KILN_SEMANTIC_ROLES.kitModule).toBe('kit.module');+ expect(KILN_SEMANTIC_ROLES.kitPort).toBe('kit.port');+ expect(KILN_SEMANTIC_ROLES.lodImpostor).toBe('lod.impostor');+ });+});++describe('delivery helpers', () => {+ test('colliderBox is a hidden unit box whose node scale is the size', () => {+ const root = new THREE.Group();+ const box = colliderBox([2, 3, 0.5], { id: 'door', parent: root, position: [1, 2, 3] });+ expect(box.parent).toBe(root);+ expect(box.visible).toBe(false);+ expect(box.name).toBe('Collider_box_door');+ close(box.scale.toArray(), [2, 3, 0.5]);+ close(box.position.toArray(), [1, 2, 3]);+ const geometry = (box as THREE.Mesh).geometry;+ geometry.computeBoundingBox();+ close(geometry.boundingBox!.min.toArray(), [-0.5, -0.5, -0.5]);+ close(geometry.boundingBox!.max.toArray(), [0.5, 0.5, 0.5]);+ expect(readSemanticMetadataV1(box)?.roles).toEqual(['collider.box.door']);+ expect(colliderBox(1, { id: 'cube' }).scale.toArray()).toEqual([1, 1, 1]);+ });++ test('colliderCapsule is a hidden unit capsule scaled to [2r, height, 2r]', () => {+ const capsule = colliderCapsule(0.25, 2, { id: 'pole' }) as THREE.Mesh;+ expect(capsule.visible).toBe(false);+ close(capsule.scale.toArray(), [0.5, 2, 0.5]);+ capsule.geometry.computeBoundingBox();+ close(capsule.geometry.boundingBox!.min.toArray(), [-0.5, -0.5, -0.5]);+ close(capsule.geometry.boundingBox!.max.toArray(), [0.5, 0.5, 0.5]);+ expect(readSemanticMetadataV1(capsule)?.roles).toEqual(['collider.capsule.pole']);+ expect(() => colliderCapsule(1, 1, { id: 'flat' })).toThrow(AuthoringDiagnosticError);+ });++ test('colliderHull wraps a mesh in its convex hull beside it', () => {+ const root = new THREE.Group();+ const part = new THREE.Mesh(new THREE.TorusGeometry(1, 0.2, 8, 16));+ part.position.set(0, 2, 0);+ root.add(part);+ const hull = colliderHull(part, { id: 'ring' }) as THREE.Mesh;+ expect(hull.parent).toBe(root);+ expect(hull.visible).toBe(false);+ close(hull.position.toArray(), [0, 2, 0]);+ hull.geometry.computeBoundingBox();+ close(hull.geometry.boundingBox!.max.toArray(), [1.2, 1.2, 0.2], 3);+ expect(readSemanticMetadataV1(hull)?.roles).toEqual(['collider.hull.ring']);+ });++ test('anchors and ports are empty named nodes; anchors are hidden', () => {+ const root = new THREE.Group();+ const door = anchor('door', 'main', { parent: root, position: [0, 1, 0] });+ expect(door.name).toBe('Anchor_door_main');+ expect(door.visible).toBe(false);+ expect(door.children).toEqual([]);+ expect(readSemanticMetadataV1(door)?.roles).toEqual(['anchor.door.main']);+ const west = port('west', { parent: root, rotation: [0, 90, 0] });+ expect(west.name).toBe('Port_west');+ expect(west.visible).toBe(true);+ expect(readSemanticMetadataV1(west)?.roles).toEqual(['kit.port.west']);+ expect(() => anchor('door.frame', 'main')).toThrow(AuthoringDiagnosticError);+ expect(() => port('')).toThrow(AuthoringDiagnosticError);+ });++ test('defineModule stamps the role and validated kit extras without losing roles', () => {+ const root = new THREE.Group();+ colliderBox(1, { id: 'a', parent: root });+ expect(+ defineModule(root, { footprint: [4, 2], height: 3, snapAxis: 'x', origin: 'corner' }),+ ).toBe(root);+ expect(KILN_KIT_KEY).toBe('kilnKit');+ expect(root.userData.kilnKit).toEqual({+ schemaVersion: 1,+ footprint: [4, 2],+ height: 3,+ snapAxis: 'x',+ origin: 'corner',+ });+ expect(readSemanticMetadataV1(root)?.roles).toEqual(['kit.module']);+ expect(() =>+ defineModule(root, {+ footprint: [4, 0],+ height: 3,+ snapAxis: 'x',+ origin: 'corner',+ }),+ ).toThrow(AuthoringDiagnosticError);+ });++ test('defineLod({ impostor: true }) gives the last tier the impostor role', () => {+ const tiers = ['A_LOD0', 'A_LOD1', 'A_LOD2'].map((name) => {+ const group = new THREE.Group();+ group.name = name;+ return group;+ });+ defineLod(tiers, { screenCoverage: [0.3, 0.1, 0], impostor: true });+ expect(readSemanticMetadataV1(tiers[2]!)?.roles).toEqual(['lod.impostor']);+ expect(readSemanticMetadataV1(tiers[1]!)).toBeUndefined();+ });++ test('every helper is a sandbox global', () => {+ const globals = buildSandboxGlobals();+ for (const name of [+ 'colliderBox',+ 'colliderCapsule',+ 'colliderHull',+ 'anchor',+ 'defineModule',+ 'port',+ ])+ expect(typeof globals[name]).toBe('function');+ });+});++describe('delivery in the integration manifest', () => {+ for (const gltfExporter of ['legacy', 'three'] as const)+ test(`lists colliders, anchors, the kit and its ports (${gltfExporter})`, async () => {+ const result = await renderGLBInProcess(program(), { gltfExporter });+ const manifest = result.integrationManifest;+ expect(manifest.deliveryDiagnostics).toBeUndefined();+ // Proxies are hidden: the headline counts the frame and the LOD0 tile only.+ expect(manifest.bounds.size[0]).toBeCloseTo(2, 5);+ expect(manifest.colliders?.map((collider) => collider.role)).toEqual([+ 'collider.box.frame',+ 'collider.box.latch',+ 'collider.capsule.post',+ 'collider.hull.hull',+ ]);+ const [box, latch, capsule, hull] = manifest.colliders!;+ expect(box!.shape.kind).toBe('box');+ close((box!.shape as { size: number[] }).size, [2, 3, 0.4]);+ close(box!.transform.translation, [0, 1.5, 0]);+ const yaw = new THREE.Euler().setFromQuaternion(+ new THREE.Quaternion(...latch!.transform.rotation),+ );+ expect(THREE.MathUtils.radToDeg(yaw.y)).toBeCloseTo(30, 4);+ expect(capsule!.shape.kind).toBe('capsule');+ const { radius, height } = capsule!.shape as { radius: number; height: number };+ expect(radius).toBeCloseTo(0.15, 6);+ expect(height).toBeCloseTo(0.8, 6);+ expect(hull!.shape.kind).toBe('hull');+ expect(box!.path).toBe('/Bunker%20Frame[0]/Root[0]/Collider_box_frame[0]');+ expect(manifest.anchors?.map((item) => [item.kind, item.id])).toEqual([+ ['door', 'main'],+ ['light', 'top'],+ ]);+ close(manifest.anchors![0]!.transform.translation, [0, 1, 0.25]);+ expect(manifest.kit).toMatchObject({+ role: 'kit.module',+ path: '/Bunker%20Frame[0]/Root[0]',+ footprint: [2, 0.4],+ height: 3,+ snapAxis: 'x',+ origin: 'center',+ });+ expect(manifest.ports?.map((item) => item.id)).toEqual(['west', 'east']);+ expect(manifest.ports![0]!.module).toBe('/Bunker%20Frame[0]/Root[0]');+ close(manifest.ports![1]!.transform.translation, [1, 0, 0]);+ const chain = manifest.levelsOfDetail![0]!;+ expect(chain.levels.map((level) => level.impostor)).toEqual([undefined, true]);+ // Hidden collider and anchor nodes stay listed with the hidden nodes.+ expect(manifest.hiddenNodes?.map((node) => node.name)).toContain('Collider_box_frame');+ expect(manifest.hiddenNodes?.map((node) => node.name)).toContain('Anchor_door_main');+ });++ test('advisory diagnostics name a drawn proxy, an escaped one, a stray port and a parent anchor', async () => {+ const result = await renderGLBInProcess(+ program(`+ const shown=colliderBox(0.5,{id:'shown',parent:root,position:[0,1.5,0]});+ shown.visible=true;+ colliderBox(0.5,{id:'far',parent:root,position:[9,9,9]});+ colliderBox(0.1,{id:'empty',parent:root,position:[0.8,3.1,0]});+ port('stray',{parent:root,position:[5,0,0]});+ const parentAnchor=anchor('spawn','one',{parent:root});+ parentAnchor.add(new THREE.Object3D());`),+ );+ const codes = (result.integrationManifest.deliveryDiagnostics ?? []).map(+ (finding) => `${finding.code} ${finding.path.split('/').pop()}`,+ );+ expect(codes).toEqual([+ 'DELIVERY_COLLIDER_NOT_HIDDEN Collider_box_shown[0]',+ 'DELIVERY_COLLIDER_OUTSIDE_BOUNDS Collider_box_far[0]',+ 'DELIVERY_COLLIDER_NO_OVERLAP Collider_box_far[0]',+ 'DELIVERY_COLLIDER_NO_OVERLAP Collider_box_empty[0]',+ 'DELIVERY_PORT_OUTSIDE_FOOTPRINT Port_stray[0]',+ 'DELIVERY_ANCHOR_NOT_LEAF Anchor_spawn_one[0]',+ ]);+ // Advisory: the build succeeds, and each finding is also a build warning.+ for (const code of codes) {+ const [name] = code.split(' ');+ expect(result.warnings.some((warning) => warning.startsWith(name!))).toBe(true);+ }+ });+});diff --git a/src/community-exporter.ts b/src/community-exporter.tsindex 45aa34b5..1435e040 100644--- a/src/community-exporter.ts+++ b/src/community-exporter.ts@@ -3,6 +3,7 @@ import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';import { GLB_BUFFER, type Document } from '@gltf-transform/core';import { createGltfIO } from './gltf-io';import { openShellExtras } from './open-shell';+import { kitExtras } from './delivery';import { rigExtrasForExport } from './rig-export';import type { AuthorExtras } from './user-data-extras';import { assertPortableMaterialSides } from './material-export';@@ -163,6 +164,7 @@ export async function communitySceneDocument(authorExtras?.node(source),rigExtrasForExport(source),openShellExtras(source),+ kitExtras(source),);const semantic = source.userData[KILN_SEMANTIC_EXTRAS_KEY];if (semantic !== undefined) {diff --git a/src/contracts/integration.ts b/src/contracts/integration.tsindex 5af791d4..d1a2d979 100644--- a/src/contracts/integration.ts+++ b/src/contracts/integration.ts@@ -28,6 +28,9 @@ export interface LevelOfDetailLevelV1 {path: string;/** Placed triangles in the level's subtree. */triangles: number;+ /** Present on the last level when `defineLod` declared it a card or billboard tier+ * (`lod.impostor` role on that node). */+ impostor?: true;}/** One node `MSFT_lod` chain: LOD0 in the scene and the lower levels it lists. */@@ -56,6 +59,76 @@ export interface ReviewedLevelOfDetailChainV1 extends LevelOfDetailChainV1 {drawn: number[];}+/** A node transform relative to the asset root (the default scene), decomposed as glTF TRS. */+export interface DeliveryTransformV1 {+ translation: [number, number, number];+ /** Unit quaternion [x, y, z, w]. A consumer that collides with yaw only reads yaw from it. */+ rotation: [number, number, number, number];+ scale: [number, number, number];+}++/** The resolved shape of a collider proxy, in metres, measured from its transform. */+export type DeliveryColliderShapeV1 =+ | { kind: 'box'; size: [number, number, number] }+ /** `height` is the total end-to-end height along the node's local +Y, caps included. */+ | { kind: 'capsule'; radius: number; height: number }+ | { kind: 'hull'; vertices: number };++/** A hidden collider proxy node (`collider.<shape>.<id>` role). */+export interface DeliveryColliderV1 {+ role: string;+ id: string;+ /** Inspection path, as `kiln_inspect` `listParts` lists it. */+ path: string;+ name: string;+ transform: DeliveryTransformV1;+ shape: DeliveryColliderShapeV1;+}++/** A named point (`anchor.<kind>.<id>` role). */+export interface DeliveryAnchorV1 {+ role: string;+ kind: string;+ id: string;+ path: string;+ name: string;+ transform: DeliveryTransformV1;+}++/** `kilnKit` node extras on a `kit.module` root. Footprint is width along X, depth along Z. */+export interface KitModuleSpecV1 {+ footprint: [number, number];+ height: number;+ snapAxis: 'x' | 'y' | 'z';+ origin: 'corner' | 'center';+}++/** The kit module this GLB delivers (`kit.module` role). */+export interface DeliveryKitModuleV1 extends KitModuleSpecV1 {+ role: string;+ path: string;+ name: string;+ transform: DeliveryTransformV1;+}++/** A snap point (`kit.port.<id>` role). */+export interface DeliveryPortV1 {+ role: string;+ id: string;+ path: string;+ name: string;+ /** Inspection path of the kit module the port belongs to, when it is under one. */+ module?: string;+ transform: DeliveryTransformV1;+}++/** An advisory delivery finding. Never QA acceptance. */+export interface DeliveryDiagnosticV1 {+ code: string;+ path: string;+ message: string;+}+export interface IntegrationManifestV1 {schemaVersion: 'kiln.integration-manifest.v1';analyzerVersion: 1;@@ -89,6 +162,16 @@ export interface IntegrationManifestV1 {/** Outermost hidden nodes in scene order, when the GLB has any. The bounds and render* metrics above count what draws; these triangles are not in them. */hiddenNodes?: HiddenNodeV1[];+ /** Collider proxies in scene order, when the GLB has any (additive in analyzer v1). */+ colliders?: DeliveryColliderV1[];+ /** Anchors in scene order, when the GLB has any. */+ anchors?: DeliveryAnchorV1[];+ /** The first kit module, when the GLB has one. */+ kit?: DeliveryKitModuleV1;+ /** Kit ports in scene order, when the GLB has any. */+ ports?: DeliveryPortV1[];+ /** Advisory delivery findings (colliders, anchors, ports), when there are any. */+ deliveryDiagnostics?: DeliveryDiagnosticV1[];structuralQa: {hasDefaultScene: boolean;finiteBounds: boolean;diff --git a/src/contracts/semantic.ts b/src/contracts/semantic.tsindex 3aa50b01..7bc74e5b 100644--- a/src/contracts/semantic.ts+++ b/src/contracts/semantic.ts@@ -62,8 +62,35 @@ export const KILN_SEMANTIC_ROLES = Object.freeze({roof: 'roof',/** Long-form spelling of {@link KILN_SEMANTIC_ROLES.roof}, accepted on read. */architectureRoof: 'architecture.roof',++ // -- game delivery (role vocabulary revision 2, additive) ---------------------+ /** Any collider proxy; full role is `collider.<shape>.<id>`. Proxies are hidden nodes. */+ collider: 'collider',+ /** Oriented box: a unit box (-0.5..0.5) whose node scale is the box size. */+ colliderBox: 'collider.box',+ /** Capsule along local +Y: a unit capsule (radius 0.5, height 1) whose node scale is+ * [2 * radius, total height, 2 * radius]. */+ colliderCapsule: 'collider.capsule',+ /** Convex hull of the proxy node's own mesh vertices. */+ colliderHull: 'collider.hull',+ /** A named point with a transform; full role is `anchor.<kind>.<id>`. An empty leaf node. */+ anchor: 'anchor',+ /** The root of one modular kit piece; carries the `kilnKit` extras. */+ kitModule: 'kit.module',+ /** A snap point under a kit module; full role is `kit.port.<id>`. */+ kitPort: 'kit.port',+ /** The last level of a `defineLod` chain when it is a card or billboard tier. */+ lodImpostor: 'lod.impostor',} as const);+/**+ * Revision of the {@link KILN_SEMANTIC_ROLES} vocabulary. The payload schema stays+ * {@link KILN_SEMANTIC_SCHEMA_VERSION} 1; revisions only add roles, so every older+ * asset stays valid. Revision 2 added the game-delivery roles (colliders, anchors,+ * kit modules and ports, and the impostor LOD tier).+ */+export const KILN_SEMANTIC_ROLES_REVISION = 2 as const;+export type KilnSemanticRoleKey = keyof typeof KILN_SEMANTIC_ROLES;/**diff --git a/src/delivery-inspect.ts b/src/delivery-inspect.tsnew file mode 100644index 00000000..899d99d9--- /dev/null+++ b/src/delivery-inspect.ts@@ -0,0 +1,525 @@+/**+ * Delivery facts read from a written GLB alone (delivery contract item 1).+ *+ * Walks the default scene once, depth first, and lists every collider proxy, anchor, kit+ * module and port by its semantic role, with the inspection path `kiln_inspect` lists and the+ * node transform relative to the asset root. Lower `MSFT_lod` levels sit outside the scene+ * and are not reached. The diagnostics are advisory and never QA acceptance: a proxy that+ * draws, leaves the drawn bounds or touches no drawn triangle; a port outside its module's+ * footprint; an anchor with children.+ */+import type { Document, Node as GltfNode } from '@gltf-transform/core';+import type { InstancedMesh } from '@gltf-transform/extensions';+import * as THREE from 'three';+import type {+ DeliveryAnchorV1,+ DeliveryColliderV1,+ DeliveryDiagnosticV1,+ DeliveryKitModuleV1,+ DeliveryPortV1,+ DeliveryTransformV1,+} from './contracts/integration';+import { KILN_SEMANTIC_ROLES, readSemanticMetadataV1FromExtras } from './contracts/semantic';+import { KILN_KIT_KEY, kitModuleExtras } from './delivery';+import { isHiddenGltfNode } from './metrics';+import { drawnSceneBounds } from './node-visibility';++/** Upper bound on collider-triangle overlap tests before the check reports itself unmeasured. */+export const DELIVERY_OVERLAP_TEST_LIMIT = 50_000_000;++export interface DeliverySummary {+ colliders: DeliveryColliderV1[];+ anchors: DeliveryAnchorV1[];+ kit?: DeliveryKitModuleV1;+ ports: DeliveryPortV1[];+ diagnostics: DeliveryDiagnosticV1[];+}++interface Visited {+ node: GltfNode;+ path: string;+ roles: string[];+ hidden: boolean;+ /** Path of the nearest kit module at or above this node. */+ module?: { node: GltfNode; path: string };+}++const segment = (name: string, occurrence: number) => `/${encodeURIComponent(name)}[${occurrence}]`;++const roleTail = (role: string, base: string): string | undefined =>+ role.startsWith(`${base}.`) ? role.slice(base.length + 1) : undefined;++function decompose(matrix: THREE.Matrix4): DeliveryTransformV1 {+ const translation = new THREE.Vector3();+ const rotation = new THREE.Quaternion();+ const scale = new THREE.Vector3();+ matrix.decompose(translation, rotation, scale);+ const clean = (value: number) => (Object.is(value, -0) ? 0 : value);+ return {+ translation: translation.toArray().map(clean) as [number, number, number],+ rotation: rotation.toArray().map(clean) as [number, number, number, number],+ scale: scale.toArray().map(clean) as [number, number, number],+ };+}++const worldMatrix = (node: GltfNode) => new THREE.Matrix4().fromArray(node.getWorldMatrix());++/** World triangles of every drawn mesh outside collider proxies, instance copies included. */+function drawnTriangles(visited: readonly Visited[]): Float64Array {+ const values: number[] = [];+ const local = [0, 0, 0];+ const point = new THREE.Vector3();+ for (const { node, roles, hidden } of visited) {+ const mesh = node.getMesh();+ if (!mesh || hidden || roles.some((role) => role.startsWith('collider.'))) continue;+ const base = worldMatrix(node);+ const instances = node.getExtension<InstancedMesh>('EXT_mesh_gpu_instancing');+ const translation = instances?.getAttribute('TRANSLATION');+ const rotation = instances?.getAttribute('ROTATION');+ const scale = instances?.getAttribute('SCALE');+ const copies = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;+ const matrices: THREE.Matrix4[] = [];+ for (let i = 0; i < copies; i++) {+ const instance = new THREE.Matrix4().compose(+ new THREE.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]),+ new THREE.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]),+ new THREE.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]),+ );+ matrices.push(base.clone().multiply(instance));+ }+ for (const primitive of mesh.listPrimitives()) {+ if (primitive.getMode() !== 4) continue;+ const position = primitive.getAttribute('POSITION');+ if (!position) continue;+ const indices = primitive.getIndices();+ const count = indices ? indices.getCount() : position.getCount();+ for (const matrix of matrices)+ for (let i = 0; i + 2 < count; i += 3)+ for (let k = 0; k < 3; k++) {+ position.getElement(indices ? indices.getScalar(i + k) : i + k, local);+ point.fromArray(local).applyMatrix4(matrix);+ values.push(point.x, point.y, point.z);+ }+ }+ }+ return Float64Array.from(values);+}++/** Separating-axis test of a triangle against the box [-h, h] centred at the origin. */+function triangleOverlapsBox(+ a: THREE.Vector3,+ b: THREE.Vector3,+ c: THREE.Vector3,+ h: THREE.Vector3,+ tolerance: number,+): boolean {+ const verts = [a, b, c];+ const he = [h.x + tolerance, h.y + tolerance, h.z + tolerance];+ for (let axis = 0; axis < 3; axis++) {+ const values = verts.map((v) => v.getComponent(axis));+ if (Math.min(...values) > he[axis]! || Math.max(...values) < -he[axis]!) return false;+ }+ const e = [+ new THREE.Vector3().subVectors(b, a),+ new THREE.Vector3().subVectors(c, b),+ new THREE.Vector3().subVectors(a, c),+ ];+ const normal = new THREE.Vector3().crossVectors(e[0]!, e[1]!);+ const axes: THREE.Vector3[] = [normal];+ const units = [+ new THREE.Vector3(1, 0, 0),+ new THREE.Vector3(0, 1, 0),+ new THREE.Vector3(0, 0, 1),+ ];+ for (const unit of units)+ for (const edge of e) axes.push(new THREE.Vector3().crossVectors(unit, edge));+ for (const axis of axes) {+ if (axis.lengthSq() < 1e-24) continue;+ const projections = verts.map((v) => v.dot(axis));+ const radius =+ he[0]! * Math.abs(axis.x) + he[1]! * Math.abs(axis.y) + he[2]! * Math.abs(axis.z);+ if (Math.min(...projections) > radius || Math.max(...projections) < -radius) return false;+ }+ return true;+}++/** Closest point on triangle abc to p (Ericson, Real-Time Collision Detection 5.1.5). */+function closestPointOnTriangle(+ p: THREE.Vector3,+ a: THREE.Vector3,+ b: THREE.Vector3,+ c: THREE.Vector3,+): THREE.Vector3 {+ const ab = new THREE.Vector3().subVectors(b, a);+ const ac = new THREE.Vector3().subVectors(c, a);+ const ap = new THREE.Vector3().subVectors(p, a);+ const d1 = ab.dot(ap);+ const d2 = ac.dot(ap);+ if (d1 <= 0 && d2 <= 0) return a.clone();+ const bp = new THREE.Vector3().subVectors(p, b);+ const d3 = ab.dot(bp);+ const d4 = ac.dot(bp);+ if (d3 >= 0 && d4 <= d3) return b.clone();+ const vc = d1 * d4 - d3 * d2;+ if (vc <= 0 && d1 >= 0 && d3 <= 0) return a.clone().addScaledVector(ab, d1 / (d1 - d3));+ const cp = new THREE.Vector3().subVectors(p, c);+ const d5 = ab.dot(cp);+ const d6 = ac.dot(cp);+ if (d6 >= 0 && d5 <= d6) return c.clone();+ const vb = d5 * d2 - d1 * d6;+ if (vb <= 0 && d2 >= 0 && d6 <= 0) return a.clone().addScaledVector(ac, d2 / (d2 - d6));+ const va = d3 * d6 - d5 * d4;+ if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0)+ return b+ .clone()+ .addScaledVector(new THREE.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));+ const denominator = 1 / (va + vb + vc);+ return a+ .clone()+ .addScaledVector(ab, vb * denominator)+ .addScaledVector(ac, vc * denominator);+}++/** Squared distance between segments p1q1 and p2q2 (Ericson 5.1.9). */+function segmentSegmentDistanceSq(+ p1: THREE.Vector3,+ q1: THREE.Vector3,+ p2: THREE.Vector3,+ q2: THREE.Vector3,+): number {+ const d1 = new THREE.Vector3().subVectors(q1, p1);+ const d2 = new THREE.Vector3().subVectors(q2, p2);+ const r = new THREE.Vector3().subVectors(p1, p2);+ const a = d1.dot(d1);+ const e = d2.dot(d2);+ const f = d2.dot(r);+ let s = 0;+ let t = 0;+ if (a <= 1e-24 && e <= 1e-24) return r.lengthSq();+ if (a <= 1e-24) t = THREE.MathUtils.clamp(f / e, 0, 1);+ else {+ const c = d1.dot(r);+ if (e <= 1e-24) s = THREE.MathUtils.clamp(-c / a, 0, 1);+ else {+ const b = d1.dot(d2);+ const denominator = a * e - b * b;+ s = denominator !== 0 ? THREE.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;+ t = (b * s + f) / e;+ if (t < 0) {+ t = 0;+ s = THREE.MathUtils.clamp(-c / a, 0, 1);+ } else if (t > 1) {+ t = 1;+ s = THREE.MathUtils.clamp((b - c) / a, 0, 1);+ }+ }+ }+ const c1 = p1.clone().addScaledVector(d1, s);+ const c2 = p2.clone().addScaledVector(d2, t);+ return c1.distanceToSquared(c2);+}++/** Whether segment pq passes through triangle abc. */+function segmentCrossesTriangle(+ p: THREE.Vector3,+ q: THREE.Vector3,+ a: THREE.Vector3,+ b: THREE.Vector3,+ c: THREE.Vector3,+): boolean {+ const hit = new THREE.Vector3();+ const ray = new THREE.Ray(p, new THREE.Vector3().subVectors(q, p));+ const length = ray.direction.length();+ if (length === 0) return false;+ ray.direction.divideScalar(length);+ return ray.intersectTriangle(a, b, c, false, hit) !== null && hit.distanceTo(p) <= length;+}++/** Whether triangle abc comes within `radius` of segment pq. */+function triangleTouchesCapsule(+ a: THREE.Vector3,+ b: THREE.Vector3,+ c: THREE.Vector3,+ p: THREE.Vector3,+ q: THREE.Vector3,+ radius: number,+): boolean {+ const r2 = radius * radius;+ if (closestPointOnTriangle(p, a, b, c).distanceToSquared(p) <= r2) return true;+ if (closestPointOnTriangle(q, a, b, c).distanceToSquared(q) <= r2) return true;+ for (const [s, e] of [+ [a, b],+ [b, c],+ [c, a],+ ] as const)+ if (segmentSegmentDistanceSq(p, q, s, e) <= r2) return true;+ return segmentCrossesTriangle(p, q, a, b, c);+}++/** Every delivery record and advisory finding in the default scene of `doc`. */+export function inspectDelivery(doc: Document): DeliverySummary {+ const summary: DeliverySummary = { colliders: [], anchors: [], ports: [], diagnostics: [] };+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ if (!scene) return summary;+ const visited: Visited[] = [];+ const visit = (+ siblings: readonly GltfNode[],+ parentPath: string,+ hidden: boolean,+ module: Visited['module'],+ ): void => {+ const seen = new Map<string, number>();+ for (const node of siblings) {+ const name = node.getName();+ const occurrence = seen.get(name) ?? 0;+ seen.set(name, occurrence + 1);+ const path = `${parentPath}${segment(name, occurrence)}`;+ const roles = readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];+ const nodeHidden = hidden || isHiddenGltfNode(node);+ const nodeModule = roles.includes(KILN_SEMANTIC_ROLES.kitModule) ? { node, path } : module;+ visited.push({ node, path, roles, hidden: nodeHidden, module: nodeModule });+ visit(node.listChildren(), path, nodeHidden, nodeModule);+ }+ };+ visit(scene.listChildren(), segment(scene.getName() || 'Scene', 0), false, undefined);+ const finding = (code: string, path: string, message: string) =>+ summary.diagnostics.push({ code, path, message });++ // Drawn bounds, the same measure the manifest headline uses.+ const { min, max } = drawnSceneBounds(scene);+ const bounds = new THREE.Box3(new THREE.Vector3(...min), new THREE.Vector3(...max));+ const finiteBounds = [...min, ...max].every(Number.isFinite);+ const diagonal = finiteBounds ? bounds.getSize(new THREE.Vector3()).length() : 0;+ const tolerance = Math.max(1e-4, diagonal * 1e-4);++ const colliderNodes: Array<{ visit: Visited; record: DeliveryColliderV1 }> = [];+ for (const entry of visited) {+ const { node, path, roles } = entry;+ for (const role of roles) {+ const matrix = worldMatrix(node);+ const transform = decompose(matrix);+ for (const shape of ['box', 'capsule', 'hull'] as const) {+ const id = roleTail(role, `${KILN_SEMANTIC_ROLES.collider}.${shape}`);+ if (id === undefined) continue;+ const scale = transform.scale;+ const record: DeliveryColliderV1 = {+ role,+ id,+ path,+ name: node.getName(),+ transform,+ shape:+ shape === 'box'+ ? { kind: 'box', size: [...scale] }+ : shape === 'capsule'+ ? { kind: 'capsule', radius: scale[0] / 2, height: scale[1] }+ : {+ kind: 'hull',+ vertices:+ node+ .getMesh()+ ?.listPrimitives()+ .reduce(+ (sum, primitive) =>+ sum + (primitive.getAttribute('POSITION')?.getCount() ?? 0),+ 0,+ ) ?? 0,+ },+ };+ summary.colliders.push(record);+ colliderNodes.push({ visit: entry, record });+ }+ const anchorTail = roleTail(role, KILN_SEMANTIC_ROLES.anchor);+ if (anchorTail !== undefined) {+ const [kind, ...rest] = anchorTail.split('.');+ summary.anchors.push({+ role,+ kind: kind!,+ id: rest.join('.'),+ path,+ name: node.getName(),+ transform,+ });+ }+ const portId = roleTail(role, KILN_SEMANTIC_ROLES.kitPort);+ if (portId !== undefined)+ summary.ports.push({+ role,+ id: portId,+ path,+ name: node.getName(),+ ...(entry.module && entry.module.node !== node ? { module: entry.module.path } : {}),+ transform,+ });+ if (role === KILN_SEMANTIC_ROLES.kitModule) {+ const extras = (node.getExtras() as Record<string, unknown>)[KILN_KIT_KEY];+ let spec: ReturnType<typeof kitModuleExtras> | undefined;+ try {+ const { schemaVersion, ...rest } = (extras ?? {}) as Record<string, unknown>;+ spec = schemaVersion === 1 ? kitModuleExtras(rest) : undefined;+ } catch {+ spec = undefined;+ }+ if (!spec)+ finding(+ 'DELIVERY_KIT_INVALID',+ path,+ `kit module has no valid ${KILN_KIT_KEY} extras; mark it with defineModule.`,+ );+ else if (summary.kit)+ finding(+ 'DELIVERY_KIT_MULTIPLE',+ path,+ `a GLB delivers one kit module; ${summary.kit.path} is listed and this one is not.`,+ );+ else+ summary.kit = {+ role,+ path,+ name: node.getName(),+ footprint: spec.footprint,+ height: spec.height,+ snapAxis: spec.snapAxis,+ origin: spec.origin,+ transform,+ };+ }+ }+ }++ // Collider findings, in scene order.+ const triangles = colliderNodes.some(({ record }) => record.shape.kind !== 'hull')+ ? drawnTriangles(visited)+ : new Float64Array();+ const triangleCount = triangles.length / 9;+ let overlapTests = 0;+ const a = new THREE.Vector3();+ const b = new THREE.Vector3();+ const c = new THREE.Vector3();+ for (const { visit: entry, record } of colliderNodes) {+ if (!entry.hidden)+ finding(+ 'DELIVERY_COLLIDER_NOT_HIDDEN',+ record.path,+ 'collider proxy draws; hide it (the delivery helpers do) so importers that ignore roles draw only the asset.',+ );+ const matrix = worldMatrix(entry.node);+ const proxyBounds = new THREE.Box3();+ const mesh = entry.node.getMesh();+ const local = [0, 0, 0];+ for (const primitive of mesh?.listPrimitives() ?? []) {+ const position = primitive.getAttribute('POSITION');+ for (let i = 0; i < (position?.getCount() ?? 0); i++)+ proxyBounds.expandByPoint(+ new THREE.Vector3().fromArray(position!.getElement(i, local)).applyMatrix4(matrix),+ );+ }+ if (proxyBounds.isEmpty())+ proxyBounds.expandByPoint(new THREE.Vector3().setFromMatrixPosition(matrix));+ const expanded = bounds.clone().expandByScalar(tolerance);+ if (!finiteBounds || !expanded.containsBox(proxyBounds))+ finding(+ 'DELIVERY_COLLIDER_OUTSIDE_BOUNDS',+ record.path,+ 'collider proxy reaches outside the bounds of the drawn asset.',+ );+ if (record.shape.kind === 'hull') continue;+ if (overlapTests + triangleCount > DELIVERY_OVERLAP_TEST_LIMIT) {+ finding(+ 'DELIVERY_COLLIDER_OVERLAP_UNMEASURED',+ record.path,+ `overlap with drawn triangles was not measured: the check stops at ${DELIVERY_OVERLAP_TEST_LIMIT} collider-triangle tests.`,+ );+ continue;+ }+ overlapTests += triangleCount;+ const toLocal = new THREE.Matrix4();+ let touches = false;+ if (record.shape.kind === 'box') {+ // Unit box space: the inverse world matrix maps the box onto [-0.5, 0.5]^3.+ toLocal.copy(matrix).invert();+ const half = new THREE.Vector3(0.5, 0.5, 0.5);+ const scale = Math.max(...record.transform.scale.map(Math.abs), 1e-9);+ for (let t = 0; t < triangleCount && !touches; t++) {+ a.fromArray(triangles, t * 9).applyMatrix4(toLocal);+ b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);+ c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);+ touches = triangleOverlapsBox(a, b, c, half, tolerance / scale);+ }+ } else {+ // Rigid capsule frame: translation and rotation only, so the radius stays metric.+ const { translation, rotation } = record.transform;+ toLocal+ .compose(+ new THREE.Vector3(...translation),+ new THREE.Quaternion(...rotation),+ new THREE.Vector3(1, 1, 1),+ )+ .invert();+ const { radius, height } = record.shape;+ const p = new THREE.Vector3(0, -height / 2 + radius, 0);+ const q = new THREE.Vector3(0, height / 2 - radius, 0);+ for (let t = 0; t < triangleCount && !touches; t++) {+ a.fromArray(triangles, t * 9).applyMatrix4(toLocal);+ b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);+ c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);+ touches = triangleTouchesCapsule(a, b, c, p, q, radius + tolerance);+ }+ }+ if (!touches)+ finding(+ 'DELIVERY_COLLIDER_NO_OVERLAP',+ record.path,+ 'collider proxy overlaps no drawn triangle; a box or capsule normally wraps or crosses the surface it stands for.',+ );+ }++ // Port findings: each port must lie in its module's footprint.+ for (const record of summary.ports) {+ const entry = visited.find((item) => item.path === record.path)!;+ const moduleEntry = entry.module && entry.module.node !== entry.node ? entry.module : undefined;+ const spec = moduleEntry && summary.kit?.path === moduleEntry.path ? summary.kit : undefined;+ if (!spec) {+ finding(+ 'DELIVERY_PORT_WITHOUT_MODULE',+ record.path,+ 'port is not under a valid kit module; place ports under the root defineModule marked.',+ );+ continue;+ }+ const point = new THREE.Vector3(...record.transform.translation).applyMatrix4(+ worldMatrix(moduleEntry!.node).invert(),+ );+ const [width, depth] = spec.footprint;+ const [x0, x1, z0, z1] =+ spec.origin === 'corner'+ ? [0, width, 0, depth]+ : [-width / 2, width / 2, -depth / 2, depth / 2];+ const slack = Math.max(1e-4, Math.max(width, depth, spec.height) * 1e-5);+ if (+ point.x < x0 - slack ||+ point.x > x1 + slack ||+ point.z < z0 - slack ||+ point.z > z1 + slack ||+ point.y < -slack ||+ point.y > spec.height + slack+ )+ finding(+ 'DELIVERY_PORT_OUTSIDE_FOOTPRINT',+ record.path,+ `port lies outside its module footprint (${width} x ${depth} m from the ${spec.origin}, 0..${spec.height} m high).`,+ );+ }++ // Anchor findings: an anchor is a point, so it has no children.+ for (const record of summary.anchors) {+ const entry = visited.find((item) => item.path === record.path)!;+ if (entry.node.listChildren().length > 0)+ finding(+ 'DELIVERY_ANCHOR_NOT_LEAF',+ record.path,+ 'anchor has children; an anchor is an empty leaf node, so attach parts beside it instead.',+ );+ }+ return summary;+}diff --git a/src/delivery.ts b/src/delivery.tsnew file mode 100644index 00000000..ceecd3fb--- /dev/null+++ b/src/delivery.ts@@ -0,0 +1,346 @@+/**+ * Game-delivery authoring helpers (delivery contract item 1).+ *+ * Everything here is plain glTF a consumer can read without Kiln: semantic roles in node+ * extras (`kilnSemantic`), hidden proxy nodes through `KHR_node_visibility`, and one+ * engine-owned extras record (`kilnKit`) on a kit module root. Kiln teaches nothing about+ * physics or collision response; a collider is a shape and a transform, and the consumer+ * decides what to do with it.+ *+ * - `colliderBox(size, { id })` - a hidden unit box (-0.5..0.5); the node scale is the size.+ * - `colliderCapsule(radius, height, { id })` - a hidden unit capsule (radius 0.5, height 1+ * along +Y); the node scale is [2 * radius, height, 2 * radius]. `height` is the total+ * end-to-end height, caps included.+ * - `colliderHull(mesh, { id })` - a hidden convex hull of the mesh's vertices beside it.+ * - `anchor(kind, id)` - a hidden empty leaf: doors, plates, beacons, hardpoints, lights.+ * - `defineModule(root, spec)` - marks a kit module root and records its footprint.+ * - `port(id)` - an empty snap point under a kit module.+ *+ * Proxies and anchors are hidden through the existing hidden-node mechanism, so an importer+ * that ignores roles still draws exactly the asset. Ids and kinds are single role segments.+ */+import * as THREE from 'three';+import { ConvexGeometry } from 'three/addons/geometries/ConvexGeometry.js';+import {+ KILN_SEMANTIC_ROLES,+ readSemanticMetadataV1,+ semanticRole,+ stampSemanticMetadataV1,+ type KitModuleSpecV1,+ type SemanticMetadataV1,+} from './contracts';+import { AuthoringDiagnosticError } from './evaluator/authoring-diagnostic';+import { GEOMETRY_ALLOCATION_LIMITS } from './geometry-budget';++export type { KitModuleSpecV1 } from './contracts';++/** The engine-owned userData and node extras key a kit module root carries. */+export const KILN_KIT_KEY = 'kilnKit';+/** Name of the shared proxy material; proxies are hidden, so its colour never draws. */+export const COLLIDER_PROXY_MATERIAL_NAME = 'KilnColliderProxy';++export interface KitModuleExtrasV1 extends KitModuleSpecV1 {+ schemaVersion: 1;+}++export interface DeliveryPlacementOptions {+ parent?: THREE.Object3D;+ position?: [number, number, number];+ /** Degrees, XYZ order, as in createPart. */+ rotation?: [number, number, number];+}++export interface ColliderOptions extends DeliveryPlacementOptions {+ id: string;+}++export interface ColliderHullOptions {+ id: string;+ /** Defaults to the mesh's parent; the hull takes the mesh's local transform. */+ parent?: THREE.Object3D;+}++/** One role segment: letters, digits, `_` and `-`, starting with a letter or digit. */+const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;++export function fail(helper: string, detail: string): never {+ throw new AuthoringDiagnosticError('DELIVERY_CONTRACT', `${helper}: ${detail}`);+}++function segment(helper: string, label: string, value: unknown): string {+ if (typeof value !== 'string' || !SEGMENT.test(value))+ fail(+ helper,+ `${label} must be 1 to 64 letters, digits, "_" or "-" starting with a letter or digit (no dots), got ${JSON.stringify(value)}.`,+ );+ return value as string;+}++function finitePositive(helper: string, label: string, value: unknown): number {+ if (typeof value !== 'number' || !Number.isFinite(value) || !(value > 0))+ fail(helper, `${label} must be a positive finite number of metres, got ${String(value)}.`);+ return value as number;+}++function triple(helper: string, label: string, value: unknown): [number, number, number] {+ if (+ !Array.isArray(value) ||+ value.length !== 3 ||+ !value.every((item) => typeof item === 'number' && Number.isFinite(item))+ )+ fail(helper, `${label} must be three finite numbers.`);+ return [value[0], value[1], value[2]] as [number, number, number];+}++function isObject3D(value: unknown): value is THREE.Object3D {+ return (value as { isObject3D?: boolean } | null)?.isObject3D === true;+}++function place(helper: string, node: THREE.Object3D, options: DeliveryPlacementOptions): void {+ if (options.position !== undefined)+ node.position.set(...triple(helper, 'position', options.position));+ if (options.rotation !== undefined) {+ const [x, y, z] = triple(helper, 'rotation', options.rotation);+ node.rotation.set(+ THREE.MathUtils.degToRad(x),+ THREE.MathUtils.degToRad(y),+ THREE.MathUtils.degToRad(z),+ );+ }+ if (options.parent !== undefined) {+ if (!isObject3D(options.parent)) fail(helper, 'parent must be a scene node.');+ options.parent.add(node);+ }+}++function options<T extends object>(helper: string, value: unknown): T {+ if (value === undefined) return {} as T;+ if (!value || typeof value !== 'object' || Array.isArray(value))+ fail(helper, 'options must be an object.');+ return value as T;+}++/**+ * Add roles to a node's semantic metadata, keeping what is already there. A node without+ * metadata gets a fresh payload; duplicate roles are not repeated.+ */+export function addSemanticRoles(node: THREE.Object3D, roles: readonly string[]): void {+ const existing: SemanticMetadataV1 | undefined = readSemanticMetadataV1(node);+ const merged = [...(existing?.roles ?? [])];+ for (const role of roles) if (!merged.includes(role)) merged.push(role);+ stampSemanticMetadataV1(node, {+ roles: merged,+ relationships: existing?.relationships ?? [],+ frames: existing?.frames ?? [],+ sockets: existing?.sockets ?? [],+ });+}++function proxyMaterial(): THREE.MeshBasicMaterial {+ return new THREE.MeshBasicMaterial({ name: COLLIDER_PROXY_MATERIAL_NAME, color: 0xff00ff });+}++function proxy(+ shape: 'box' | 'capsule' | 'hull',+ id: string,+ geometry: THREE.BufferGeometry,+): THREE.Mesh {+ const mesh = new THREE.Mesh(geometry, proxyMaterial());+ mesh.name = `Collider_${shape}_${id}`;+ mesh.visible = false;+ addSemanticRoles(mesh, [+ semanticRole(+ shape === 'box'+ ? KILN_SEMANTIC_ROLES.colliderBox+ : shape === 'capsule'+ ? KILN_SEMANTIC_ROLES.colliderCapsule+ : KILN_SEMANTIC_ROLES.colliderHull,+ id,+ ),+ ]);+ return mesh;+}++/**+ * A hidden oriented-box collider. `size` is [width X, height Y, depth Z] in metres, or one+ * number for a cube. The proxy is a unit box under the node, whose scale is the size, so a+ * consumer reads the box from the transform alone: translation is the centre, rotation the+ * orientation (yaw for a yaw-only collider) and scale the size.+ */+export function colliderBox(+ size: number | [number, number, number],+ opts: ColliderOptions,+): THREE.Mesh {+ const helper = 'colliderBox(size, { id })';+ const settings = options<ColliderOptions>(helper, opts);+ const id = segment(helper, 'id', settings.id);+ const dims =+ typeof size === 'number'+ ? [size, size, size]+ : triple(helper, 'size', size).map((value) => value);+ for (const [index, value] of dims.entries())+ finitePositive(helper, `size[${index}]`, value as number);+ const mesh = proxy('box', id, new THREE.BoxGeometry(1, 1, 1));+ mesh.scale.set(dims[0]!, dims[1]!, dims[2]!);+ place(helper, mesh, settings);+ return mesh;+}++/**+ * A hidden capsule collider along the node's local +Y. `height` is the total end-to-end+ * height including both caps (unlike capsuleGeo, whose length is the straight middle), so+ * height must be at least 2 * radius. The proxy is a unit capsule (radius 0.5, height 1)+ * whose node scale is [2 * radius, height, 2 * radius].+ */+export function colliderCapsule(radius: number, height: number, opts: ColliderOptions): THREE.Mesh {+ const helper = 'colliderCapsule(radius, height, { id })';+ const settings = options<ColliderOptions>(helper, opts);+ const id = segment(helper, 'id', settings.id);+ finitePositive(helper, 'radius', radius);+ finitePositive(helper, 'height', height);+ if (height < 2 * radius)+ fail(+ helper,+ `height is the total height including both caps and must be at least 2 * radius (${2 * radius}), got ${height}.`,+ );+ // Build the true shape, then normalise it into the unit box so the node scale restores it.+ const geometry = new THREE.CapsuleGeometry(radius, height - 2 * radius, 4, 12);+ geometry.scale(1 / (2 * radius), 1 / height, 1 / (2 * radius));+ const mesh = proxy('capsule', id, geometry);+ mesh.scale.set(2 * radius, height, 2 * radius);+ place(helper, mesh, settings);+ return mesh;+}++/**+ * A hidden convex-hull collider of `mesh`'s vertices. The hull is built in the mesh's own+ * geometry space and takes the mesh's local transform, under the mesh's parent unless+ * `parent` is given. The input mesh is not changed.+ */+export function colliderHull(mesh: THREE.Object3D, opts: ColliderHullOptions): THREE.Mesh {+ const helper = 'colliderHull(mesh, { id })';+ const settings = options<ColliderHullOptions>(helper, opts);+ const id = segment(helper, 'id', settings.id);+ const source = mesh as THREE.Mesh;+ const position = source?.isMesh ? source.geometry?.getAttribute('position') : undefined;+ if (position?.itemSize !== 3)+ fail(helper, 'mesh must be a mesh with xyz positions, such as createPart returned.');+ if (position!.count > GEOMETRY_ALLOCATION_LIMITS.colliderHullVertices)+ fail(+ helper,+ `mesh has ${position!.count} vertices; a hull proxy reads at most ${GEOMETRY_ALLOCATION_LIMITS.colliderHullVertices}.`,+ );+ const points: THREE.Vector3[] = [];+ for (let i = 0; i < position!.count; i++)+ points.push(new THREE.Vector3().fromBufferAttribute(position!, i));+ let geometry: THREE.BufferGeometry;+ try {+ geometry = new ConvexGeometry(points);+ } catch {+ fail(helper, 'the mesh vertices do not span a volume, so they have no convex hull.');+ }+ if (!geometry!.getAttribute('position')?.count)+ fail(helper, 'the mesh vertices do not span a volume, so they have no convex hull.');+ const hull = proxy('hull', id, geometry!);+ hull.position.copy(source.position);+ hull.quaternion.copy(source.quaternion);+ hull.scale.copy(source.scale);+ const parent = settings.parent ?? source.parent;+ if (parent !== undefined && parent !== null) {+ if (!isObject3D(parent)) fail(helper, 'parent must be a scene node.');+ parent.add(hull);+ }+ return hull;+}++/**+ * A named point with a transform, as a hidden empty leaf node named `Anchor_<kind>_<id>`+ * with role `anchor.<kind>.<id>`: a door, vault plate, beacon, hardpoint, light or spawn.+ */+export function anchor(kind: string, id: string, opts?: DeliveryPlacementOptions): THREE.Object3D {+ const helper = 'anchor(kind, id, opts?)';+ const settings = options<DeliveryPlacementOptions>(helper, opts);+ const kindSegment = segment(helper, 'kind', kind);+ const idSegment = segment(helper, 'id', id);+ const node = new THREE.Object3D();+ node.name = `Anchor_${kindSegment}_${idSegment}`;+ node.visible = false;+ addSemanticRoles(node, [semanticRole(KILN_SEMANTIC_ROLES.anchor, kindSegment, idSegment)]);+ place(helper, node, settings);+ return node;+}++/** Validate a kit module spec into its detached extras record. */+export function kitModuleExtras(+ spec: unknown,+ helper = 'defineModule(root, spec)',+): KitModuleExtrasV1 {+ if (!spec || typeof spec !== 'object' || Array.isArray(spec))+ fail(helper, 'spec must be { footprint: [w, d], height, snapAxis, origin }.');+ const value = spec as Record<string, unknown>;+ const footprint = value.footprint;+ if (!Array.isArray(footprint) || footprint.length !== 2)+ fail(helper, 'footprint must be [width along X, depth along Z] in metres.');+ const [width, depth] = (footprint as unknown[]).map((item, index) =>+ finitePositive(helper, `footprint[${index}]`, item),+ ) as [number, number];+ const height = finitePositive(helper, 'height', value.height);+ if (value.snapAxis !== 'x' && value.snapAxis !== 'y' && value.snapAxis !== 'z')+ fail(helper, `snapAxis must be 'x', 'y' or 'z', got ${JSON.stringify(value.snapAxis)}.`);+ if (value.origin !== 'corner' && value.origin !== 'center')+ fail(helper, `origin must be 'corner' or 'center', got ${JSON.stringify(value.origin)}.`);+ for (const key of Object.keys(value))+ if (!['footprint', 'height', 'snapAxis', 'origin'].includes(key))+ fail(helper, `unknown spec field ${JSON.stringify(key)}.`);+ return {+ schemaVersion: 1,+ footprint: [width, depth],+ height,+ snapAxis: value.snapAxis as KitModuleSpecV1['snapAxis'],+ origin: value.origin as KitModuleSpecV1['origin'],+ };+}++/**+ * Mark `root` as the root of one modular kit piece. The footprint is width along X and depth+ * along Z from the module origin (`corner`: 0..w, 0..d; `center`: -w/2..w/2, -d/2..d/2), and+ * height runs 0..height along Y. Ports placed under the root are its snap points.+ */+export function defineModule<T extends THREE.Object3D>(root: T, spec: KitModuleSpecV1): T {+ const helper = 'defineModule(root, spec)';+ if (!isObject3D(root)) fail(helper, 'root must be a scene node, such as createRoot returned.');+ const extras = kitModuleExtras(spec, helper);+ root.userData[KILN_KIT_KEY] = extras;+ addSemanticRoles(root, [KILN_SEMANTIC_ROLES.kitModule]);+ return root;+}++/** An empty snap point named `Port_<id>` with role `kit.port.<id>`, placed in its parent. */+export function port(id: string, opts?: DeliveryPlacementOptions): THREE.Object3D {+ const helper = 'port(id, opts?)';+ const settings = options<DeliveryPlacementOptions>(helper, opts);+ const idSegment = segment(helper, 'id', id);+ const node = new THREE.Object3D();+ node.name = `Port_${idSegment}`;+ addSemanticRoles(node, [semanticRole(KILN_SEMANTIC_ROLES.kitPort, idSegment)]);+ place(helper, node, settings);+ return node;+}++/**+ * The extras a node's own kit record exports: a detached, validated copy, or nothing. A value+ * under the key that defineModule did not write fails the build rather than export.+ */+export function kitExtras(node: unknown): Record<string, KitModuleExtrasV1> {+ const target = node as { name?: string; userData?: Record<string, unknown> } | null;+ const value = target?.userData?.[KILN_KIT_KEY];+ if (value === undefined) return {};+ const record = value as Record<string, unknown>;+ if (!record || typeof record !== 'object' || record.schemaVersion !== 1)+ fail(+ 'defineModule(root, spec)',+ `userData.${KILN_KIT_KEY} on ${JSON.stringify(target?.name || '(unnamed node)')} is not a record defineModule wrote; set it only through defineModule.`,+ );+ const { schemaVersion: _version, ...spec } = record;+ return { [KILN_KIT_KEY]: kitModuleExtras(spec) };+}diff --git a/src/discovery/helper-contracts.ts b/src/discovery/helper-contracts.tsindex 537b2b49..f9d66b30 100644--- a/src/discovery/helper-contracts.ts+++ b/src/discovery/helper-contracts.ts@@ -789,6 +789,7 @@ define(parameters: ['levels: two or more sibling tier nodes named with one stem and tokens LOD0, LOD1, ... in order.','screenCoverage: one value per level, each from 0 to 1, strictly decreasing, LOD0 first; the last may be 0, which never culls.',+ 'impostor: optional boolean; true gives the last level the lod.impostor role (a card or billboard tier) and the manifest level record impostor: true.',],semantics: ['Level i draws while the asset covers at least screenCoverage[i] of the screen; below the last value it is culled.',@@ -812,6 +813,120 @@ define(related: [{ name: 'createPart', relation: 'companion' }],},);+const deliveryMetadata = {+ references: ['src/delivery.ts', 'src/delivery-inspect.ts', 'docs/delivery-contract.md'],+};+const deliveryPlacement =+ 'Placement options: parent, position [x, y, z] in metres and rotation [x, y, z] in degrees (XYZ), as createPart.';+const deliveryExport = [+ 'Exports as plain glTF: the role in kilnSemantic node extras; proxies and anchors carry KHR_node_visibility visible:false, so loaders that ignore roles draw only the asset.',+ 'The integration manifest lists each record with its inspection path and transform relative to the asset root; advisory DELIVERY_* findings are build warnings, never QA acceptance.',+];+define(+ ['colliderBox', 'colliderCapsule', 'colliderHull'],+ {+ ...nodeFacts,+ origin: 'The proxy node transform is the collider frame relative to its parent.',+ ownership: 'Creates one hidden proxy mesh with its own unit geometry and proxy material.',+ coordinates:+ 'Parent-local placement; the manifest reports the transform relative to the asset root.',+ parameters: [+ 'opts.id: one role segment of letters, digits, _ or -, without dots.',+ 'colliderBox size: three positive metres or one number for a cube; the node scale is the size of a unit box (-0.5..0.5).',+ 'colliderCapsule radius and height: positive metres, height the total end-to-end height along local +Y and at least 2 * radius; the node scale is [2r, height, 2r] over a unit capsule (radius 0.5, height 1).',+ 'colliderHull mesh: a mesh with xyz positions, at most 65536 vertices; the hull takes its local transform under its parent unless parent is given.',+ deliveryPlacement,+ ],+ semantics: [+ ...deliveryExport,+ 'Diagnostics: a proxy that draws, reaches outside the drawn bounds, or (box and capsule) touches no drawn triangle is reported; a box or capsule wholly inside a closed solid touches no triangle and is reported too.',+ 'Invalid arguments are a DELIVERY_CONTRACT build error.',+ ],+ cost: 'One hidden mesh: 12 triangles for a box, about 200 for a capsule, the hull face count for a hull. Hidden triangles are not in the headline.',+ },+ {+ ...deliveryMetadata,+ tags: ['delivery', 'collision', 'export', 'hierarchy'],+ aliases: ['collider', 'collision proxy', 'hitbox', 'physics proxy', 'convex hull collider'],+ intents: ['give the asset collision proxies a game can read'],+ summary:+ 'Hidden collider proxies (box, capsule, convex hull) with roles collider.<shape>.<id>; the consumer reads the shape from the node transform and its own collision code.',+ limitations: [+ 'Kiln adds no physics, collision response or mass; it delivers shapes and transforms.',+ 'Box and capsule overlap is advisory and measured against drawn triangles only.',+ ],+ },+);+define(+ ['anchor', 'port'],+ {+ ...nodeFacts,+ origin: 'The node transform is the anchor or snap frame relative to its parent.',+ ownership: 'Creates one empty node; anchors are hidden, ports are not.',+ coordinates:+ 'Parent-local placement; the manifest reports the transform relative to the asset root.',+ parameters: [+ 'anchor kind and id, port id: one role segment each of letters, digits, _ or -, without dots.',+ deliveryPlacement,+ ],+ semantics: [+ ...deliveryExport,+ 'anchor role anchor.<kind>.<id>, node Anchor_<kind>_<id>; an anchor with children is reported as DELIVERY_ANCHOR_NOT_LEAF.',+ 'port role kit.port.<id>, node Port_<id>; a port outside its kit module footprint, or not under one, is reported.',+ 'Invalid arguments are a DELIVERY_CONTRACT build error.',+ ],+ cost: 'One empty node.',+ },+ {+ ...deliveryMetadata,+ tags: ['delivery', 'hierarchy', 'export', 'kit'],+ aliases: [+ 'attachment point',+ 'hardpoint',+ 'spawn point',+ 'door anchor',+ 'snap point',+ 'kit port',+ ],+ intents: ['mark named points a game attaches behaviour or kit pieces to'],+ summary:+ 'Empty named nodes with delivery roles: anchors (doors, plates, beacons, hardpoints, lights, spawns) and kit ports (snap points under a kit module).',+ limitations: [+ 'No snap solver: ports are delivered as frames, and composition stays in the consumer.',+ ],+ related: [{ name: 'defineModule', relation: 'companion' }],+ },+);+define(+ 'defineModule',+ {+ ...nodeFacts,+ units: 'footprint and height in metres; footprint is [width along X, depth along Z].',+ origin:+ 'corner: footprint spans 0..w and 0..d; center: -w/2..w/2 and -d/2..d/2; height spans 0..height along Y.',+ ownership: 'Writes the role kit.module and validated kilnKit extras on root; creates no nodes.',+ coordinates: 'Module-local footprint.',+ parameters: [+ "spec: { footprint: [w, d] positive, height positive, snapAxis 'x' | 'y' | 'z', origin 'corner' | 'center' } and no other fields.",+ ],+ semantics: [+ 'Exports kilnKit: { schemaVersion: 1, footprint, height, snapAxis, origin } as root node extras, and the role in kilnSemantic.',+ 'The integration manifest kit field lists the first module; a second is reported as DELIVERY_KIT_MULTIPLE.',+ 'The engine owns the kilnKit key; a value defineModule did not write is a DELIVERY_CONTRACT build error.',+ ],+ cost: 'Metadata on one node.',+ },+ {+ ...deliveryMetadata,+ tags: ['delivery', 'kit', 'modular', 'export'],+ aliases: ['modular piece', 'kit module', 'tile set piece', 'snap module'],+ intents: ['deliver a modular kit piece with its footprint and ports'],+ summary:+ 'Marks the root of one modular kit piece and records its footprint, height and snap axis.',+ limitations: ['No snap solver or cross-module validation.'],+ related: [{ name: 'port', relation: 'companion' }],+ },+);define('markOpenShell',{diff --git a/src/discovery/helper-specs.ts b/src/discovery/helper-specs.tsindex 265cfa62..f14c296a 100644--- a/src/discovery/helper-specs.ts+++ b/src/discovery/helper-specs.ts@@ -175,7 +175,8 @@ const PRIMITIVES: HelperSpec[] = [},{name: 'defineLod',- signature: 'defineLod(levels: Object3D[], opts: { screenCoverage: number[] })',+ signature:+ 'defineLod(levels: Object3D[], opts: { screenCoverage: number[], impostor?: boolean })',returns: 'Object3D[] (levels, unchanged)',category: 'structure',description:@@ -183,7 +184,7 @@ const PRIMITIVES: HelperSpec[] = [example:"const tiers = ['Body_LOD0', 'Body_LOD1', 'Body_LOD2'].map((name) => { const g = new THREE.Group(); g.name = name; root.add(g); return g; });\ndefineLod(tiers, { screenCoverage: [0.25, 0.06, 0.01] });",promptNotes:- 'Only when the brief asks for LOD tiers; otherwise build one tier. Tiers are sibling nodes named with one stem and consecutive LOD<n> tokens. screenCoverage has one value per level, strictly decreasing; below the last the asset is culled, and a last value of 0 never culls.',+ 'Only when the brief asks for LOD tiers; otherwise build one tier. Tiers are sibling nodes named with one stem and consecutive LOD<n> tokens. screenCoverage has one value per level, strictly decreasing; below the last the asset is culled, and a last value of 0 never culls. impostor: true marks the last level a card or billboard tier.',},{name: 'markOpenShell',@@ -197,6 +198,71 @@ const PRIMITIVES: HelperSpec[] = [promptNotes:'Only for shells open by design; close a part meant to be solid instead. A mark on a group covers its meshes. Overlap with a marked part stays unmeasured, not clear.',},+ {+ name: 'colliderBox',+ signature:+ 'colliderBox(size: [w, h, d] | number, opts: { id, parent?, position?, rotation?: [xDeg, yDeg, zDeg] })',+ returns: 'THREE.Mesh (hidden proxy named Collider_box_<id>)',+ category: 'structure',+ description:+ 'Adds a hidden oriented-box collider proxy with role collider.box.<id>: a unit box whose node scale is the size, so a consumer reads centre, orientation and size from the transform alone.',+ example: "colliderBox([2, 3, 0.4], { id: 'frame', parent: root, position: [0, 1.5, 0] });",+ promptNotes:+ 'Only when the brief asks for colliders. The proxy never draws; it must wrap or cross the surface it stands for and stay inside the drawn bounds. id is one segment without dots.',+ },+ {+ name: 'colliderCapsule',+ signature:+ 'colliderCapsule(radius: number, height: number, opts: { id, parent?, position?, rotation? })',+ returns: 'THREE.Mesh (hidden proxy named Collider_capsule_<id>)',+ category: 'structure',+ description:+ 'Adds a hidden capsule collider proxy along local +Y with role collider.capsule.<id>. height is the TOTAL end-to-end height including both caps (at least 2 * radius); the node scale is [2r, height, 2r].',+ example: "colliderCapsule(0.15, 1.8, { id: 'post', parent: root, position: [0.8, 0.9, 0] });",+ promptNotes:+ 'height here is total height, unlike capsuleGeo whose height is the straight middle length.',+ },+ {+ name: 'colliderHull',+ signature: 'colliderHull(mesh: Mesh, opts: { id, parent? })',+ returns: 'THREE.Mesh (hidden convex hull named Collider_hull_<id>)',+ category: 'structure',+ description:+ "Adds a hidden convex-hull collider proxy of a mesh's vertices beside it, with the mesh's local transform and role collider.hull.<id>. The input mesh is unchanged.",+ example:+ "const frame = createPart('Frame', boxGeo(2, 3, 0.4), steel, { parent: root });\ncolliderHull(frame, { id: 'frame' });",+ },+ {+ name: 'anchor',+ signature: 'anchor(kind: string, id: string, opts?: { parent?, position?, rotation? })',+ returns: 'THREE.Object3D (hidden empty leaf named Anchor_<kind>_<id>)',+ category: 'structure',+ description:+ 'Adds a named point with a transform and role anchor.<kind>.<id>: a door, vault plate, beacon, hardpoint, light or spawn point the consumer attaches behaviour to.',+ example: "anchor('door', 'main', { parent: root, position: [0, 1, 0.25] });",+ promptNotes: 'An anchor is a leaf: never add parts under it. kind and id are single segments.',+ },+ {+ name: 'defineModule',+ signature:+ "defineModule(root: Object3D, spec: { footprint: [w, d], height, snapAxis: 'x'|'y'|'z', origin: 'corner'|'center' })",+ returns: 'Object3D (root, unchanged)',+ category: 'structure',+ description:+ 'Marks root as one modular kit piece (role kit.module) and records its footprint (width X, depth Z), height and snap axis as kilnKit node extras.',+ example:+ "defineModule(root, { footprint: [4, 4], height: 3, snapAxis: 'x', origin: 'center' });",+ promptNotes: 'Only for modular kit pieces. Place each port inside the footprint.',+ },+ {+ name: 'port',+ signature: 'port(id: string, opts?: { parent?, position?, rotation? })',+ returns: 'THREE.Object3D (empty node named Port_<id>)',+ category: 'structure',+ description:+ 'Adds a kit snap point with role kit.port.<id> under a defineModule root; its transform is the snap frame.',+ example: "port('west', { parent: root, position: [-2, 0, 0], rotation: [0, 180, 0] });",+ },{name: 'beamBetween',signature:diff --git a/src/evaluator/authoring-diagnostic.ts b/src/evaluator/authoring-diagnostic.tsindex 98d9dc1f..09cc71b9 100644--- a/src/evaluator/authoring-diagnostic.ts+++ b/src/evaluator/authoring-diagnostic.ts@@ -34,6 +34,7 @@ export type AuthoringDiagnostic =| 'PROGRAM_RANGE_ERROR'| 'LOD_SET'| 'OPEN_SHELL'+ | 'DELIVERY_CONTRACT'| 'BONE_CHAIN_ARGUMENT'| 'SKIN_BINDING_ARGUMENT'| 'EXPORT_MATERIAL_SIDE_UNSUPPORTED';@@ -73,6 +74,8 @@ export const LOD_SET_ADVICE ='Levels of detail: sibling nodes whose names share a stem and carry LOD0, LOD1, ... tokens (Body_LOD0, Body_LOD1) form one set. A set needs LOD0 and consecutive levels under one parent, outside any other tier, and one defineLod([lod0, lod1, ...], { screenCoverage: [...] }) call listing its tiers in level order with one value per level, each from 0 to 1 and strictly decreasing; the last may be 0, which never culls. Build one tier without LOD tokens unless the brief asks for levels. Call kiln_discover with ids ["defineLod"].';export const OPEN_SHELL_ADVICE ='markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].';+export const DELIVERY_CONTRACT_ADVICE =+ 'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule"].';/*** The advice behind the generic rejection, when no closed cause crossed the boundary.* Engine-owned text only: it states the contract and names the two tools that answer@@ -97,6 +100,7 @@ export function authoringDiagnosticAdvice(diagnostic: AuthoringDiagnostic | undeif (diagnostic === 'UNINITIALIZED_BINDING') return UNINITIALIZED_BINDING_ADVICE;if (diagnostic === 'LOD_SET') return LOD_SET_ADVICE;if (diagnostic === 'OPEN_SHELL') return OPEN_SHELL_ADVICE;+ if (diagnostic === 'DELIVERY_CONTRACT') return DELIVERY_CONTRACT_ADVICE;if (diagnostic === 'BUILD_RESULT') return BUILD_RESULT_ADVICE;if (diagnostic === 'MATERIAL_RECIPE_OVERRIDE') return MATERIAL_RECIPE_OVERRIDE_ADVICE;if (diagnostic === 'PROGRAM_TYPE_ERROR') return PROGRAM_TYPE_ERROR_ADVICE;diff --git a/src/evaluator/protocol.ts b/src/evaluator/protocol.tsindex 35caa4e1..7ee8bd02 100644--- a/src/evaluator/protocol.ts+++ b/src/evaluator/protocol.ts@@ -466,6 +466,7 @@ export function decodeEvaluatorResultV2(value.error.diagnostic !== 'PROGRAM_RANGE_ERROR' &&value.error.diagnostic !== 'LOD_SET' &&value.error.diagnostic !== 'OPEN_SHELL' &&+ value.error.diagnostic !== 'DELIVERY_CONTRACT' &&value.error.diagnostic !== 'EXPORT_MATERIAL_SIDE_UNSUPPORTED' &&value.error.diagnostic !== 'BONE_CHAIN_ARGUMENT' &&value.error.diagnostic !== 'SKIN_BINDING_ARGUMENT'))diff --git a/src/geometry-budget.ts b/src/geometry-budget.tsindex fbbc4926..0b048e40 100644--- a/src/geometry-budget.ts+++ b/src/geometry-budget.ts@@ -15,6 +15,8 @@ export const GEOMETRY_ALLOCATION_LIMITS = Object.freeze({skinBones: 1024,skinVertices: 262_144,skinAttributeBytes: 128 * 1024 * 1024,+ // Delivery contract: colliderHull reads at most this many proxy vertices.+ colliderHullVertices: 65_536,});export function assertDimension(name: string, value: number, allowZero = false): void {if (diff --git a/src/lod-export.ts b/src/lod-export.tsindex b9ac39f3..c130193c 100644--- a/src/lod-export.ts+++ b/src/lod-export.ts@@ -12,6 +12,7 @@import { type Document, type Node as GltfNode, PropertyType } from '@gltf-transform/core';import type * as THREE from 'three';import type { LevelOfDetailChainV1 } from './contracts/integration';+import { KILN_SEMANTIC_ROLES, readSemanticMetadataV1FromExtras } from './contracts/semantic';import { type Lod, MSFT_LOD, MSFTLod } from './gltf-io';import type { LodSet } from './lod';import { drawnNodeTriangles } from './metrics';@@ -102,6 +103,12 @@ export function listLodChainNodes(doc: Document): LodChainNodes[] {return chains;}+/** Whether a level carries the `lod.impostor` role that `defineLod({ impostor: true })` stamps. */+function isImpostorLevel(node: GltfNode): boolean {+ const roles = readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];+ return roles.includes(KILN_SEMANTIC_ROLES.lodImpostor);+}+/** Each chain in {@link listLodChainNodes} order with its thresholds and per-level triangles. */export function summarizeLodChains(doc: Document): LevelOfDetailChainV1[] {return listLodChainNodes(doc).map(({ levels, paths }) => {@@ -114,6 +121,7 @@ export function summarizeLodChains(doc: Document): LevelOfDetailChainV1[] {name: level.getName(),path: paths[number]!,triangles: drawnNodeTriangles(level),+ ...(number > 0 && isImpostorLevel(level) ? { impostor: true as const } : {}),})),};});diff --git a/src/lod.ts b/src/lod.tsindex cf4c6c05..39df5a88 100644--- a/src/lod.ts+++ b/src/lod.ts@@ -11,6 +11,8 @@* guessed: a default could cull an asset in a consumer at a distance nobody chose.*/import type * as THREE from 'three';+import { KILN_SEMANTIC_ROLES } from './contracts/semantic';+import { addSemanticRoles } from './delivery';import { AuthoringDiagnosticError } from './evaluator/authoring-diagnostic';/** An LOD level token such as `LOD0`, `lod1` or `Tree_LOD2`, delimited by the name's ends or non-alphanumerics. */@@ -22,10 +24,14 @@ export const KILN_LOD_KEY = 'kilnLodV1';export interface LodDeclarationV1 {/** Minimum screen coverage (0..1) at which each level draws, LOD0 first. */screenCoverage: number[];+ /** The last level is a card or billboard tier (role `lod.impostor` on that node). */+ impostor?: true;}export interface DefineLodOptions {screenCoverage: number[];+ /** Declare the last level a card or billboard tier: it gets the `lod.impostor` role. */+ impostor?: boolean;}export interface LodSet {@@ -118,8 +124,15 @@ export function defineLod<T extends THREE.Object3D>(levels: T[], options: Defineconst coverage = (options as Partial<DefineLodOptions> | undefined)?.screenCoverage;const problem = coverageProblem(coverage, levels.length);if (problem) fail(`defineLod: ${problem}; got ${format(coverage)}. For example ${EXAMPLE}.`);- const declaration: LodDeclarationV1 = { screenCoverage: [...(coverage as number[])] };+ const impostor = (options as Partial<DefineLodOptions> | undefined)?.impostor;+ if (impostor !== undefined && typeof impostor !== 'boolean')+ fail(`defineLod: impostor must be true or false; got ${format(impostor)}.`);+ const declaration: LodDeclarationV1 = {+ screenCoverage: [...(coverage as number[])],+ ...(impostor ? { impostor: true as const } : {}),+ };levels[0]!.userData[KILN_LOD_KEY] = declaration;+ if (impostor) addSemanticRoles(levels[levels.length - 1]!, [KILN_SEMANTIC_ROLES.lodImpostor]);return levels;}diff --git a/src/primitives.ts b/src/primitives.tsindex 75922208..5e312853 100644--- a/src/primitives.ts+++ b/src/primitives.ts@@ -24,6 +24,7 @@ import { describeAssembly, replicateAssembly } from './assembly';import { defineLod } from './lod';export { defineLod } from './lod';import { markOpenShell } from './open-shell';+import { anchor, colliderBox, colliderCapsule, colliderHull, defineModule, port } from './delivery';import { useCubicSpline } from './animation-cubic';import {CUBIC_INTERPOLATIONS,@@ -2260,6 +2261,12 @@ export function buildSandboxGlobals(createPart: wrap('createPart', createPart),defineLod: wrap('defineLod', defineLod),markOpenShell: wrap('markOpenShell', markOpenShell),+ colliderBox: wrap('colliderBox', colliderBox),+ colliderCapsule: wrap('colliderCapsule', colliderCapsule),+ colliderHull: wrap('colliderHull', colliderHull),+ anchor: wrap('anchor', anchor),+ defineModule: wrap('defineModule', defineModule),+ port: wrap('port', port),capsuleGeo: wrapGeo('capsuleGeo', capsuleGeo),capsuleXGeo: wrapGeo('capsuleXGeo', capsuleXGeo),capsuleYGeo: wrapGeo('capsuleYGeo', capsuleYGeo),diff --git a/src/render.ts b/src/render.tsindex baddbd56..7109bc3c 100644--- a/src/render.ts+++ b/src/render.ts@@ -48,6 +48,8 @@ import {type IndexBufferReceipt,} from './index-policy';import { openShellExtras } from './open-shell';+import { kitExtras } from './delivery';+import { inspectDelivery } from './delivery-inspect';import { rigExtrasForExport } from './rig-export';import { type AuthorExtras, collectAuthorExtras } from './user-data-extras';import {@@ -252,6 +254,7 @@ export async function inspectGlbIntegration(const minY = minTuple[1];const levelsOfDetail = summarizeLodChains(doc);const hiddenNodes = summarizeHiddenNodes(doc);+ const delivery = inspectDelivery(doc);return {schemaVersion: 'kiln.integration-manifest.v1',@@ -291,6 +294,11 @@ export async function inspectGlbIntegration(},...(levelsOfDetail.length ? { levelsOfDetail } : {}),...(hiddenNodes.length ? { hiddenNodes } : {}),+ ...(delivery.colliders.length ? { colliders: delivery.colliders } : {}),+ ...(delivery.anchors.length ? { anchors: delivery.anchors } : {}),+ ...(delivery.kit ? { kit: delivery.kit } : {}),+ ...(delivery.ports.length ? { ports: delivery.ports } : {}),+ ...(delivery.diagnostics.length ? { deliveryDiagnostics: delivery.diagnostics } : {}),structuralQa: {hasDefaultScene: explicitDefault !== null,finiteBounds,@@ -818,6 +826,7 @@ function bridgeNode(...authorExtras?.node(threeObj),...rigExtrasForExport(threeObj),...openShellExtras(threeObj),+ ...kitExtras(threeObj),};let semanticForExport = semanticValue;if ((threeObj as THREE.Object3D & { isSprite?: boolean }).isSprite) {@@ -1877,6 +1886,9 @@ export async function renderSceneToGLB(validation: gltfValidation,});if (!integrationManifest) throw new Error('renderSceneToGLB: final GLB has no measurable scene');+ // Delivery findings are advisory: each is a build warning, never a QA disposition.+ for (const finding of integrationManifest.deliveryDiagnostics ?? [])+ warnings.push(`${finding.code} ${finding.path}: ${finding.message}`);const diagnosticViews: CapturedDiagnosticV1[] = [];const rig = requirements.requirements.requirements.rig;