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.

Stabilize engine exports, scene controls and verified site delivery (#133)

Matthew Kissingera6d2aa3bc54a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index eaf346df..6918096f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -33,10 +33,10 @@ jobs:
- name: Setup Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
- node-version: 22.23.2
+ node-version: 22.23.3
- name: Setup npm
- run: npm install --global [email protected]
+ run: npm install --global [email protected]
- name: Check toolchain metadata
run: bun run check:toolchain
@@ -118,7 +118,7 @@ jobs:
- name: Setup Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
- node-version: 22.23.2
+ node-version: 22.23.3
- name: Check toolchain metadata
run: bun run check:toolchain
@@ -169,10 +169,10 @@ jobs:
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
- node-version: 22.23.2
+ node-version: 22.23.3
- name: Setup npm
- run: npm install --global [email protected]
+ run: npm install --global [email protected]
- name: Install the render service
run: npm ci --ignore-scripts
@@ -193,8 +193,8 @@ jobs:
bun-version: 1.4.2
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
- node-version: 22.23.2
- - run: npm install --global [email protected]
+ node-version: 22.23.3
+ - run: npm install --global [email protected]
- run: bun install --frozen-lockfile
- run: bun run build:runtime
- name: Pack without publishing
@@ -226,9 +226,9 @@ jobs:
# Consumers install only Node/npm. Bun builds the tarball in the separate producer job.
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
- node-version: 22.23.2
+ node-version: 22.23.3
architecture: ${{ matrix.arch }}
- - run: npm install --global [email protected]
+ - run: npm install --global [email protected]
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: node-package-candidate
@@ -326,8 +326,8 @@ jobs:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
- node-version: 22.23.2
- - run: npm install --global [email protected]
+ node-version: 22.23.3
+ - run: npm install --global [email protected]
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: node-package-candidate
@@ -364,7 +364,7 @@ jobs:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
- node-version: 22.23.2
+ node-version: 22.23.3
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: node-package-candidate
diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml
index 0e3d0c42..68bcb633 100644
--- a/.github/workflows/pages.yml
+++ b/.github/workflows/pages.yml
@@ -71,10 +71,10 @@ jobs:
- name: Setup Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
- node-version: 22.23.2
+ node-version: 22.23.3
- name: Pin maintainer npm
- run: npm install --global [email protected]
+ run: npm install --global [email protected]
- name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
diff --git a/.github/workflows/scenes.yml b/.github/workflows/scenes.yml
index e800a558..1bdcf574 100644
--- a/.github/workflows/scenes.yml
+++ b/.github/workflows/scenes.yml
@@ -22,7 +22,7 @@ jobs:
bun-version: 1.4.2
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
- node-version: 22.23.2
+ node-version: 22.23.3
- run: bun install --frozen-lockfile
working-directory: scenes
- run: bun run typecheck && bun run lint && bun run test
diff --git a/AGENTS.md b/AGENTS.md
index 92cdc663..664d2591 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -152,7 +152,7 @@ cache-point blocks. Preserve that and the provider usage fields when changing mo
## Toolchain and validation
-Maintainer toolchain: Bun `1.4.2`; Node `22.23.2`; npm `12.0.2`, pinned in `toolchain.json`.
+Maintainer toolchain: Bun `1.4.2`; Node `22.23.3`; npm `12.2.0`, pinned in `toolchain.json`.
Consumer Node compatibility is defined separately in `src/runtime-support.mjs` and
`engines.node`; do not add Bun or npm maintainer pins to end-user `engines` or use a Bun
canary or implicit latest for a release gate.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0be625de..9f672a7c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,8 +5,47 @@ separate milestones. The package is not published on the npm registry.
## Unreleased
-On `main` after the 0.10.0 release; the package version stays 0.10.0 until the next one.
-
+Changes since the 0.10.0 tagged package release. The package version stays 0.10.0
+until the next package release; source/main and website deployment are separate
+from publishing a new installable package.
+
+- **Breaking (planned 0.11):** `optimize: 'full'` replaces flatten/join with rigid-group
+ merging. Its rigid-merge pass preserves node names, hierarchy and transforms, including animated targets,
+ named joint pivots, semantic nodes, composition placements and LOD levels. Ordinary
+ named mesh nodes can become empty or hold merged geometry. When geometry must remain
+ on every named part, use `optimize: 'off'` or `'palette'` with `instance: 'off'`;
+ the separate GPU-instancing pass can remove named instance nodes. Shared-buffer expansion is limited
+ to 4 KiB per saved draw, and merged buckets split at 65,534 vertices. Results expose
+ boundary, lock and rejection diagnostics. New builds record `rigid-v1`; exact
+ rebuilds of older unversioned full-mode revisions require their original engine
+ or an explicit new authoring revision. Original saved GLBs remain exportable.
+- ORM packing isolates shared images per metallic-roughness/occlusion pair. Materials
+ with different AO maps and consumers in other texture slots retain their original
+ pixels, UVs and samplers; identical packing pairs reuse the packed image.
+- Scene browser tools share portable executable discovery and clean up temporary
+ profiles on launch failure and close. The normal portable scene gate includes
+ script tests, and the static server identifies WebP images correctly.
+- Cloudflare Pages deployment has a portable Node preflight that verifies the exact
+ launch-mode artifact inventory, sizes and hashes against a clean checkout before
+ upload. The PowerShell entry delegates to the same implementation.
+- Inspection and export summaries add bounded per-anchor draw counts, a qualified
+ rigid-merge estimate, and sampled mirrored-tangent/coplanar-part observations.
+ Compact render output and tool input schemas stay unchanged; estimates and flags
+ are advisory, not GPU timings or QA acceptance.
+- Compatible dependency updates include glTF Transform 4.5.1, manifold 3.5.4,
+ MCP client/server 2.3.0, Strands 1.19.0 with the compatible AI SDK 6/provider 3
+ family, image libraries and tooling. Site/scenes use Vite 8.3.2. Maintainer pins
+ move to Node 22.23.3/npm 12.2.0, retaining Bun 1.4.2 and consumer Node compatibility.
+- The exact-input scene release gate verifies public pack hashes and cannot pass
+ through missing-fixture skips. Shadow caches observe morph weights, Farm's economy
+ tier retains its trailer casters, and Golden Gate reflections exclude dynamic
+ traffic/player/fog while preserving vegetation; diagnostic fog hiding persists.
+
+- The scenes' dependency pin check resolves the engine, site and render service
+ from the integrated checkout instead of hard-coded Windows worktrees. It now
+ runs on the Linux hub and relocated checkouts; a filesystem regression test
+ verifies collection and detection of an engine pin mismatch. Contributor and
+ Troy resume instructions name the current validation and workspace setup commands.
- The kit pass (`applyKitContract`, `packKitGlb`) no longer folds an occlusion map into the
metallic-roughness image when the two are read through different UV sets or
`KHR_texture_transform` values. It used to point the occlusion slot at the
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 07e4ef29..c6512cad 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -8,7 +8,7 @@ used CPU or GPU. Remove credentials and private paths from shared logs.
## Work on the engine
Read [AGENTS.md](AGENTS.md) and the [README](README.md). Contributor checks use Bun
-1.4.2, Node 22.23.2 and npm 12.0.2. End users only need Node/npm for a built package.
+1.4.2, Node 22.23.3 and npm 12.2.0. End users only need Node/npm for a built package.
```sh
bun install --frozen-lockfile
@@ -24,9 +24,25 @@ bun run test:coverage
`bun run test` is `bun test src scripts`, so it never reaches `render-service/` -- a
separate npm project with its own lockfile and a native dependency.
`bun run test:render-service` does, after `npm --prefix render-service ci
---ignore-scripts` once. All 37 of those tests are pure, so none of them needs a GPU or
-the Dawn build; CI requires the job, and before this the only way to find a break in it
-was a red pull request.
+--ignore-scripts` once. This suite needs no GPU or Dawn build; CI requires it.
+
+The maintained scenes have a separate lockfile and validation commands:
+
+```sh
+cd scenes
+bun install --frozen-lockfile
+bun run check:toolchain
+bun run check:pins
+bun run typecheck
+bun run lint
+bun run test
+bun test ./scripts/tests --timeout 20000
+```
+
+The pin check reads the engine, render service and site from the same checkout.
+The portable test runner covers scene source contracts; the separate script-test
+command covers the validation and evidence tooling. Asset and browser qualification
+require staged inputs; see [scenes/README.md](scenes/README.md).
`lint` reports **nothing** on a clean tree, and a warning fails it. There is no
tolerated baseline to compare against, so any diagnostic your change produces is
@@ -41,11 +57,12 @@ count read off the output is a floor.
### Version
-`version` in `package.json` moves with every change that ships. It sat at `0.6.0`
-through 21 shipped changes while CI named every tarball from it, so two people could
-hold `kiln-engine-0.6.0.tgz` and have materially different software. Patch for a fix,
-minor for changed or added capability; this package is pre-1.0 and unpublished, so a
-minor is the normal case.
+`version` in `package.json` identifies the installable release. Changes on `main`
+ahead of that release go in the changelog's `Unreleased` section and can retain the
+released version until the next release is prepared. A new release must bump the
+version before producing its tarball: two different releases must never share a
+package version. Patch for a fix, minor for changed or added capability; this
+package is pre-1.0 and unpublished, so a minor is the normal case.
Bumping it means rebuilding: `runtimeBuildIdentity` hashes the version into each
entry's `identity` in `dist/build.json`, which is the value a build receipt cites. Run
diff --git a/README.md b/README.md
index 27c22158..0de43e97 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@ the model; Kiln does not require a separate model API key for its tools.
Walk the [Farm](https://kilnstudio.tools/scenes/farm/), drive across
[Golden Gate](https://kilnstudio.tools/scenes/golden-gate/), or explore the
-[Foundry Floor preview](https://kilnstudio.tools/scenes/foundry-floor/).
+[Foundry Floor](https://kilnstudio.tools/scenes/foundry-floor/).
The scenes put Kiln assets to work with animation, levels of detail and interactive controls.
| Farm | Golden Gate |
@@ -27,9 +27,8 @@ The scenes put Kiln assets to work with animation, levels of detail and interact
| --- | --- |
| [![Foundry campus exterior](assets/readme/foundry-campus-v09.png)](https://kilnstudio.tools/scenes/foundry-floor/) | [![Container transport inside the Foundry Floor](assets/readme/foundry-floor-v09.png)](https://kilnstudio.tools/scenes/foundry-floor/) |
-The Foundry preview pairs a factory campus with a representative floor in its southwest
+Foundry Floor pairs a factory campus with a representative floor in its southwest
building. AMRs, robot arms and overhead transport move containers through the fab.
-This scene is still in production.
Six reusable vehicles, shown with the gallery's live body-paint controls:
diff --git a/ROADMAP.md b/ROADMAP.md
index 07987726..a20b501c 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,5 +1,12 @@
# Kiln roadmap
+**Release direction, 3 October:** Matt confirmed the farmer hand fixes and could not
+reproduce the water jump locally. He authorized final performance review, commits,
+main integration and Cloudflare deployment. The focused performance investigation is
+settled for release with its original failures and limits preserved. See the
+[release disposition](docs/reviews/2026-10-03-release-disposition.md). Bridge stills are refreshed; physical-device
+promotion, Troy construction and npm publication remain deferred.
+
Kiln **0.10.0** is the current release, the v1 readiness release: the stdio server serves
protocol revision 2026-07-28 beside the 2025 handshakes and answers before the engine
loads, the three record tools are flat objects with an `action` field, every tool result is
@@ -15,32 +22,129 @@ dogfooding and stabilisation work is in [dogfooding](docs/dogfooding.md),
[headless harnesses](docs/harnesses.md) and Phase 17 of the
[engine ledger](docs/plans/repo-size-and-r2-migration-2026-09-10.md).
+The large scene optimization pass landed in **#131 (`b1ac6ee`)**: Farm hero/shadow
+work, Golden Gate bridge/shadow/reflection work and Foundry planting/MSAA work,
+with count baselines and parity evidence. It did not rewrite saved assets. Optimized
+Farm is live; local Golden Gate `g9-code5` and Foundry `ff3-review2-code5` deliveries
+are now prepared, while production retains its previous seals. #132
+(`ac8456c`) then fixed ORM UV/transform handling. The remaining work below does
+not restart that completed pass.
+
## Next
-1. **Farm pilot.** Begin the [Farm pilot](docs/plans/2026-09-26-farm-pilot-brief.md) as a
- production step in a separate asset workspace: its 23-asset inventory and individual
- references, a project profile and scale lineup, then a qualified shared material and
- shape slice before production expands. The assembled Farm scene needs its own artistic
- and performance acceptance.
-2. **Later.** Ten-pack production, engine-specific importer qualification and a public
- Commons/package launch.
+The owner's current direction is to stabilize existing core, assets and scenes,
+review behavior, implementation and cycle intent adversarially, and qualify exact
+local artifacts with explicit issues and evidence limits. Troy brainstorming is not
+an adopted specification or task; its construction awaits direct Matt discussion,
+and its pack stays off the public site. No release actions are authorized. The
+[alignment plan](docs/plans/2026-10-02-core-scenes-site-alignment.md) is the current
+work queue and acceptance contract; the [current backlog](docs/backlog.md) tracks
+individual dispositions. The September Farm pilot and October landing plans retain
+their historical scope.
+
+The 3 October local candidate implements ORM isolation, rigid full optimization,
+rebuild versioning, bounded inspection/export diagnostics, compatible dependencies
+and the adopted scene/control repairs. These planned 0.11 changes remain local and
+unreleased. The fresh current-source corpus passes **224/224** at identity
+`58b1b178…`: 86 examples, 113 scene GLBs and 25 saved Troy regression inputs. Every
+per-input result and optimized hash matches the earlier run; 20 compressed terrain
+inputs remain explicitly decoded derivatives. Separate installed-package checks
+qualify the frozen runtime bundles. Root coverage passes 3,187 tests; the complete
+scene-script gate records 108 tests / 615 assertions, and the motion3 portable gate
+passes 713 tests with 18 historical skips. Typecheck and lint pass.
+
+The bounded [stabilization adversarial review](docs/reviews/2026-10-03-stabilization-adversarial-review.md)
+found no new concrete implementation blocker in its reviewed surfaces. Farm pose,
+blend, warming, orbit/pinch and shared first-key ownership repairs pass their focused
+and compiled both-backend checks. Golden Gate water continuity and startup contact
+pipeline preparation have bounded browser/native evidence. These do not establish
+every clipping pose, physical-device behavior, owner appearance or performance.
+Earlier image/count matrices retain their tested build scopes: Farm 160 direct,
+32 paired and 32 settled-count cases; Foundry 120 default images and 56 exact static
+count rows; Golden Gate 78 depth-reference cases per backend. Four shared Farm pilot
+differences and Golden Gate's 17 WebGPU / 11 WebGL2 original strict flags remain.
+
+The code5 local site **`26ecd2b2…`** now qualifies the changed public deliveries:
+564 tests with two historical skips, all 70 Astro files without diagnostics, static
+checks, six NVIDIA control scenarios / 34 checks and nine lifecycle/viewer/failure
+areas pass. Fresh accessibility passes 396 widths and 44 keyboard tours with zero
+issues. Served checks cover 116 downloads, 520 linked files, 89 pages and three
+checksum endpoints. Revision reconciliation covers 292 records / 882 checks with
+zero mismatches; saved model/data/source revisions remain unchanged. The actual
+public Farm diagnostic also passes orbit, pinch and first keyboard movement after
+touch on NVIDIA WebGPU and WebGL2; its earlier warning-classification failure stays
+recorded. Current fresh/managed skills qualify KIT-6 guidance. The final skill-only
+site **`978664da…`** passes fresh static, delivery and HTTP checks. Its strict
+continuity proof establishes 2,721 unchanged product files, including all 200 HTML
+and 243 scene files, against `26ecd2b2…`; earlier browser measurements retain their
+original artifact and scope. Current skill archives match the maintained guidance.
+After documentation freezes, the final offline package byte audit is separately
+recorded at `tmp/alignment-20261003/package-stabilization-final/receipt.json`; the
+qualification ledger records its result. No result is claimed in advance.
+
+Matt selected **focused checks, expanding only if a failure needs investigation**.
+All **18 intended focused runs / 20.5 measured minutes** are collection-valid.
+Raw D41 is **17 pass / 1 fail**, retaining candidate Golden Gate balanced flyover's
+50.1 ms interval at 56.9993 s. The Farm minimal 135-second pair passes D41 with
+original/candidate maxima of 25.0/33.4 ms. Strict post-run quiet checks fail for
+both blocks: CPU maxima of 16.473% and 16.159%, sampled 18.125 s and 6.326 s after
+their respective blocks. The overall focused audit therefore remains **FAIL**.
+One additional unchanged flyover A/B pair completes two measured minutes with
+50.0/16.7 ms maxima, both D41 and all quiet checks passing, with complete cleanup.
+Its earlier 12.694% CPU preflight failure stopped before browser launch and is preserved.
+The candidate's later 50.1 ms miss did not recur; no actionable cause or new runtime
+repair is established. The passing repeat does not erase the original failures.
+All intended focused measurement work is complete; no further benchmark expansion
+is presently justified. The prepared 18-cell / 108-run campaign
+is preserved, deferred and unrun; no all-tier, repeated-run or desktop-speedup claim follows.
+The prior UI3 balanced block stays 7/18 cells and 42/108 runs, with 37 D41 passes and
+five failures; it does not qualify the changed candidate. Golden Gate's separate
+58.3 ms drive event remains distinct from the identified flyover pipeline cause.
+Farm's four allocation observations are complete: neither current observation has
+a natural interval above 40 ms, compared with original intervals of 50.0 and 41.7 ms.
+Current late major GC still takes about 36 ms; source allocation/retainer ownership
+remains unresolved, so no speculative repair or hitch-fixed claim is justified.
+Functional implementation is complete within its tested scope. Strict desktop
+performance acceptance remains open; physical-device and owner appearance review
+are deferred, with owner farmer/water review after the development goals. No desktop
+margin, tablet promotion, full-goal completion, owner approval or deployment is claimed.
+
+1. **Core correctness and upgrades.** Implementation, fresh final-source corpus and
+ core/package gates pass. Retain named/LOD, draw/byte and saved-revision contracts
+ through final package binding and release review.
+2. **Focused scene follow-ups and asset checks.** Motion3 and code5 functional
+ qualification and bounded Farm allocation diagnosis are complete within the recorded
+ scope. Intended focused measurements are complete; retain the failed strict
+ performance audit and unresolved cause without speculative repairs or further
+ benchmark expansion. Do not promote incomplete acceptance evidence.
+3. **Site delivery.** Code5 seals and the exact local launch artifact are qualified.
+ Skill-only rebuild and product continuity pass. Record the separate final package
+ byte audit after documentation freezes, then review the exact clean artifact before
+ any authorized Cloudflare release.
+ GitHub validation does not deploy it.
+4. **Troy remains deferred.** Discuss it directly with Matt after the stabilization
+ report. Earlier ideas and the [handoff](packs/troy/HANDOFF.md) are reference only,
+ not adopted construction/refinement tasks. Keep the pack off the public site.
+5. **Later product milestones.** Ten-pack production, broader importer qualification and
+ the v1 public package launch remain separate milestones.
Projects remain optional for every other kind of standalone authoring.
-## Requests not adopted in 0.9
+## Disposition of earlier author requests
-Authors asked for these while using 0.8. Each is a new contract that needs an owner
-decision before it is built:
+The former "not adopted in 0.9" list was stale. Current implementations and
+[CHANGELOG.md](CHANGELOG.md) establish these dispositions:
-- per-part transforms in `listParts` output;
-- `userData` exported as glTF `extras`, and a node-visibility extension (core glTF has none);
-- easing curves for `createClip`;
-- a choice of index policy for exported buffers;
-- a self-intersection check for `sweepProfile`;
-- a hide-node option in versioned captures (`visibility: "isolate"` covers subject-only shots);
-- a per-part "intentionally open" annotation for overlap QA;
-- a level-of-detail authoring workflow, including which level a default sheet shows;
-- an output path on MCP render tools (CLI `--views` and `--capture` write files).
+| Request | Current state |
+| --- | --- |
+| Per-part transforms | Available through requested `listParts` placement output |
+| `userData` and visibility | Bounded JSON extras and `KHR_node_visibility` shipped |
+| Easing and index policy | Cubic animation samplers and indexed/as-built policies shipped; as-built requires optimization off |
+| Sweep self-intersection | Bounded local/adjacent-ring analysis shipped; general distant self-intersections remain outside its guarantee |
+| Hide-node captures | Available in `kiln.capture.v2` |
+| Intentionally open parts | `markOpenShell` shipped; it does not suppress measured overlap failures |
+| LOD authoring and review | `defineLod`, `MSFT_lod`, LOD0 default views and per-level inspection shipped; destination support must still be verified |
+| MCP render output path | Still unadopted; CLI views/capture write files and MCP returns media/receipts |
## Deferred
@@ -53,7 +157,12 @@ decision before it is built:
| Family | State |
|---|---|
-| `three` r186 + `@types/three` 0.186.0 | **Taken.** Both are pinned at 0.186.0 in every manifest that uses them |
-| `webgpu` 0.6.1 in `render-service/` | **Taken** after the GPU smoke it was gated on passed: `dawn-vulkan` on a GTX 1660 Ti boots and renders through the engine |
-| `zod` 4.6.4 | **Taken** |
-| `ai` 6→7, `@ai-sdk/provider` 3→4, `@openrouter/ai-sdk-provider` 2→3, `openai` 6→7 | **Blocked upstream, not by money.** `@strands-agents/[email protected]` peer-requires `@ai-sdk/provider: ^3.0.0`, while `@openrouter/ai-sdk-provider@3` requires `ai: ^7`, which depends on provider 4 |
+| Three.js/types and webgpu | Local candidate uses 0.186.1 / 0.186.0 / 0.6.2 with synchronized locks and identities. Native GPU/material/display, fresh 58b1 source corpus, motion3 both-backend controls and code5 site gates pass within their scopes. Intended focused timing is collected: 18 valid runs, raw 17 D41 pass / one fail and two failed post-run quiet gates; a separate unchanged flyover pair passes but does not erase failures. Strict desktop acceptance remains open; the 108-run preparation stays deferred/unrun and owner/device/release boundaries remain |
+| glTF Transform, MCP, material/runtime and site tooling | Compatible updates are installed locally and pass the full core and package gates. Exact versions and evidence are in the alignment plan; production has not changed |
+| Maintainer Node/Bun/npm | Local pins and active hub tools are 22.23.3 / 1.4.2 / 12.2.0; the former Node/npm prefix is retained |
+| TypeScript | Root/scenes use 7.0.2; site and the scene compiler-API alias retain 6.0.3 intentionally |
+| AI SDK/provider/OpenRouter/OpenAI majors | Held by Strands compatibility: installed candidate Strands 1.19.0 requires provider 3 and OpenAI 6. Its Anthropic peer also excludes the newest Anthropic family |
+
+Versions were checked on 2 October and the compatible updates were installed and
+qualified on 3 October 2026. Keep exact release inputs; unresolved scene evidence
+and incompatible major families are not silently accepted by the core test results.
diff --git a/biome.json b/biome.json
index 02b96d4e..58d4ff51 100644
--- a/biome.json
+++ b/biome.json
@@ -1,5 +1,5 @@
{
- "$schema": "https://biomejs.dev/schemas/2.5.13/schema.json",
+ "$schema": "https://biomejs.dev/schemas/2.5.15/schema.json",
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
"files": {
"includes": [
diff --git a/bun.lock b/bun.lock
index e1ee1170..0e3ad2fb 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5,41 +5,41 @@
"": {
"name": "@kiln/engine",
"dependencies": {
- "@gltf-transform/core": "4.5.0",
- "@gltf-transform/extensions": "4.5.0",
- "@gltf-transform/functions": "4.5.0",
- "@modelcontextprotocol/client": "^2.2.0",
+ "@gltf-transform/core": "4.5.1",
+ "@gltf-transform/extensions": "4.5.1",
+ "@gltf-transform/functions": "4.5.1",
+ "@modelcontextprotocol/client": "^2.3.0",
"@modelcontextprotocol/ext-apps": "2.0.3",
- "@modelcontextprotocol/server": "^2.2.0",
+ "@modelcontextprotocol/server": "^2.3.0",
"@types/three": "^0.186.0",
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
- "manifold-3d": "^3.5.3",
+ "manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
- "sharp": "^0.35.4",
- "three": "0.186.0",
+ "sharp": "^0.35.5",
+ "three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
- "zod": "^4.6.4",
+ "zod": "^4.6.5",
},
"devDependencies": {
- "@ai-sdk/provider": "^3.0.16",
+ "@ai-sdk/provider": "^3.0.18",
"@anthropic-ai/sdk": "0.109.1",
- "@aws-sdk/client-bedrock-runtime": "^3.1131.0",
- "@biomejs/biome": "^2.5.13",
- "@google/genai": "^2.22.0",
+ "@aws-sdk/client-bedrock-runtime": "^3.1146.0",
+ "@biomejs/biome": "^2.5.15",
+ "@google/genai": "^2.27.0",
"@openrouter/ai-sdk-provider": "^2.10.0",
- "@strands-agents/sdk": "1.18.0",
+ "@strands-agents/sdk": "1.19.0",
"@types/bun": "^1.4.2",
- "ai": "^6.0.282",
+ "ai": "^6.0.300",
"openai": "^6.49.0",
"typescript": "^7.0.2",
},
"optionalDependencies": {
- "@napi-rs/canvas": "1.0.9",
- "webgpu": "0.6.1",
+ "@napi-rs/canvas": "1.0.10",
+ "webgpu": "0.6.2",
},
"peerDependencies": {
"@ai-sdk/provider": "^3.0.0",
@@ -54,142 +54,142 @@
},
},
"overrides": {
- "sharp": "^0.35.4",
+ "sharp": "^0.35.5",
},
"packages": {
- "@ai-sdk/gateway": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.16", "@ai-sdk/provider-utils": "4.0.51", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-T2vq1EKPhbFF2Sk2MUFL/RmCg/2mp1LGbCZZSx5vh0M6Sr1EAj3wRr1EnpcwCV3/Imj2q56pT89XLiUFnB+ZgQ=="],
+ "@ai-sdk/gateway": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.18", "@ai-sdk/provider-utils": "4.0.57", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-CjCBzC35lRZ0LnUYLDfTB92p0Fr1Fu9Wrivc+LI0u3ox/DyZ0wPOHjt8DKBKHD/R4aZ86+JCFFuD9f8MFjAQFg=="],
- "@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-9Av6kg0t/IN/dcYAAmEJ4B9OPhcEJqwSR+GfHEA8olRkindXpUHadc3p3cyvgFUQFTVm1G5thtsmgZ9yVb2w3A=="],
+ "@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-IpefF5ssZVOZCD4Wu7zxt6PwZoGT2HLVjxpJ10Bjx6EAmRfLYJPjyrfxb0RYDlwvXnDb9nkQ7Do/oJVDuRFzew=="],
- "@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.16", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8", "undici": "^6.28.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ukLTs9x1Xm6lxSIwbJIxYQxbZHmVeIczNntARZrBcOa6pjdBhqeZnATNnJMHa7M9dZ8Ji5NJbpKpvz7o5XyBtg=="],
+ "@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.18", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8", "undici": "^6.28.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-89a7sPvZqXsP3PigcAQLWntu/duIVEcN/RyChAB+j6p3C7NwW767sVttvL8r0+BetTg63uAXQoYHCZZueQKBSw=="],
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9OnEKLr5H9nxSuXdgDgJhxfYMiE+AaUEBze2Gk91UcaaLnsN+Lx5fbCYywiqurU/APLdwv23x03Wm6WN3EBsg=="],
- "@aws-sdk/client-bedrock-runtime": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.0", "@aws-sdk/credential-provider-node": "^3.972.83", "@aws-sdk/eventstream-handler-node": "^3.972.34", "@aws-sdk/middleware-eventstream": "^3.972.29", "@aws-sdk/middleware-websocket": "^3.972.53", "@aws-sdk/token-providers": "3.1131.0", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/fetch-http-handler": "^5.7.2", "@smithy/node-http-handler": "^4.11.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-q0MTJy3yknOJDt7RfX156CZ/RMkp9X0dWUNBkhEaPU3l+rLV5VYkjsbucF1397UD4eKu1AiMKfP62yE08zblBg=="],
+ "@aws-sdk/client-bedrock-runtime": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/credential-provider-node": "^3.972.84", "@aws-sdk/eventstream-handler-node": "^3.972.35", "@aws-sdk/middleware-eventstream": "^3.972.30", "@aws-sdk/middleware-websocket": "^3.972.54", "@aws-sdk/token-providers": "3.1146.0", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.12.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-FPg7W8TtLGv6ruAjkfjhX02ks6ozhwQ12tBp0hdc9DPBx7stsJbwQunejwQhF5dfdOtShkTJuXQKNR7BqZGjlg=="],
- "@aws-sdk/core": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.5", "@aws-sdk/xml-builder": "^3.972.40", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.33.3", "@smithy/signature-v4": "^5.6.12", "@smithy/types": "^4.17.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-2yX9LUmxPklVjSGTb8dfnWRJSiFQ3TeH2nn7G1mdKHTfnabzF0+gfrS8rYfLWmZrQ8A3mEcxMJjRc51dL5KWaA=="],
+ "@aws-sdk/core": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.6", "@aws-sdk/xml-builder": "^3.972.41", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.35.0", "@smithy/signature-v4": "^5.7.3", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-LbY9aGsEiznDWmUc30Nwv3aIX/+dbwTx8KfS0yOC3NPYMO+O91e6jkT1azf34FwjOndq8/Q+RcVVZz5xnerwdg=="],
- "@aws-sdk/credential-provider-env": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.0", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-JN+JHruYZw3GUZB8YGAlDk4wTDPOEAEEdEzj5nS0xodWR4smzHsN7PnK2j6IeOsDIj2aqua5DSbhXl9Gtf90FQ=="],
+ "@aws-sdk/credential-provider-env": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-xTKO/FWJPozTIXbozVnVGoNBhaGba8TBcx+KyUjRVeOlXE+dUc7GTR1cLvu0uTdIdmemzaFbqqCshXeZA1fZew=="],
- "@aws-sdk/credential-provider-http": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.0", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/fetch-http-handler": "^5.7.2", "@smithy/node-http-handler": "^4.11.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-uyYYnJOnlis8uQzaYGPd7N1JoioCoNpXgnkXYixsWJXHXgXyYi8WXJSDfofxJeWfQIGWLe2Nwyq60Uc7MZdVOg=="],
+ "@aws-sdk/credential-provider-http": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.12.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-u91E/hT8f4d1xy0Jl7VG4nVKJ3lxbrZkoBTeSVoJdWBiSEUMwMS/9+e0H/aJVQV//Lt5wuzP+E69v4aRSsNTmw=="],
- "@aws-sdk/credential-provider-ini": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.0", "@aws-sdk/credential-provider-env": "^3.972.71", "@aws-sdk/credential-provider-http": "^3.972.73", "@aws-sdk/credential-provider-login": "^3.972.78", "@aws-sdk/credential-provider-process": "^3.972.71", "@aws-sdk/credential-provider-sso": "^3.973.15", "@aws-sdk/credential-provider-web-identity": "^3.972.77", "@aws-sdk/nested-clients": "^3.997.45", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/credential-provider-imds": "^4.4.16", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-i++ly+0Uxa+u3ebSSyr0S/3CFhFJDxCXT3+Zj+mW2bXenEx5bKGCdTIKFu39SgXBNhWDjex/8cXUx9MUTMCrTw=="],
+ "@aws-sdk/credential-provider-ini": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/credential-provider-env": "^3.972.72", "@aws-sdk/credential-provider-http": "^3.972.74", "@aws-sdk/credential-provider-login": "^3.972.79", "@aws-sdk/credential-provider-process": "^3.972.72", "@aws-sdk/credential-provider-sso": "^3.973.16", "@aws-sdk/credential-provider-web-identity": "^3.972.78", "@aws-sdk/nested-clients": "^3.997.46", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-ged4KXdBkvIC81bLvNHHuQKdKak/VXhQTR1NWYTTqW0474nlmsxy9O/vlgTIohDDWH3xpBdtVMZRyjb+DnocDA=="],
- "@aws-sdk/credential-provider-login": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.0", "@aws-sdk/nested-clients": "^3.997.45", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-eUtswnXu0+Ii9ieRK+0L7aPFV3Z/dnW2VntJzjBP9xs8s+8p5nBNuymIXtXwZ+5r5+XJP3e32nMkuZ/r0HozEA=="],
+ "@aws-sdk/credential-provider-login": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/nested-clients": "^3.997.46", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-L+Z85anONJd8MaiuraO4wRxATCdEejBZ3K3eymzWI5JPXa9sOS9CkIm72PBKqXKX+Z9p9NGMX5AIMXm0LEflgw=="],
- "@aws-sdk/credential-provider-node": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.71", "@aws-sdk/credential-provider-http": "^3.972.73", "@aws-sdk/credential-provider-ini": "^3.973.16", "@aws-sdk/credential-provider-process": "^3.972.71", "@aws-sdk/credential-provider-sso": "^3.973.15", "@aws-sdk/credential-provider-web-identity": "^3.972.77", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/credential-provider-imds": "^4.4.16", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-jdso7ejzfRnatxMUZK4S/U6KbaDPCvfIV4XL+IQAPFDBt5rj5Fq595euqlK8Le4lNCMFR9oUpt+1l0aMgaayOQ=="],
+ "@aws-sdk/credential-provider-node": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.72", "@aws-sdk/credential-provider-http": "^3.972.74", "@aws-sdk/credential-provider-ini": "^3.973.17", "@aws-sdk/credential-provider-process": "^3.972.72", "@aws-sdk/credential-provider-sso": "^3.973.16", "@aws-sdk/credential-provider-web-identity": "^3.972.78", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-oHt854odINVwzwsh+c5x69j0ajm4DbqqqVJ+O1ECsCIZeMDAbzFpXItaqP7UZstJj/ATdTk/KFSH0LaNAgV+kA=="],
- "@aws-sdk/credential-provider-process": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.0", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-lYmXJa4gvq4xN1lrT5NiP5vIYYKcGWAdj8y+8o6dlcateB5eF3Dn8DtmjjHKfMBrTPAMr2pebIiX/UOj8c1/UA=="],
+ "@aws-sdk/credential-provider-process": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-rLIp2xbMjX/k9/od7APpqq1ZgXXnV0pOL1Th3ZsL8Wu0TRtBsDTVS8iPqcfRFcHakFxPvR04OSTv2ka2qOb/2A=="],
- "@aws-sdk/credential-provider-sso": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.0", "@aws-sdk/nested-clients": "^3.997.45", "@aws-sdk/token-providers": "3.1129.0", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-6Jhcf4v0pSFdjk1EW2kvzuEBKD+UZ2uNcHUIglKKLndD20YhvkL2kdmDOV5/j4mYuWWwe/a1FQ1aomU86/Cg5Q=="],
+ "@aws-sdk/credential-provider-sso": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/nested-clients": "^3.997.46", "@aws-sdk/token-providers": "3.1138.0", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-IGihaJfFZYacJJr/odqILCoK7W/mvrZ7cuK7ECn3sAu4vLC6u0V8bS7mCGbdugJ8Aum2tnvqmx0F2MRFp2rn9g=="],
- "@aws-sdk/credential-provider-web-identity": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.0", "@aws-sdk/nested-clients": "^3.997.45", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-uylIQSUWpfLuH2LovxEEfwzJGM/SabLOfLMg6YXu/E8jJEKUdpdILCVCQCdFvHyu/7dLJOHPMfrSwduxO56NkQ=="],
+ "@aws-sdk/credential-provider-web-identity": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/nested-clients": "^3.997.46", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/y9WvNtlcPBGLR0qc1a+9J/xtYZfVczvLUOuXaVWylzttH7ewsxwHtjmiJSolNrVSDorIxHGHMU61CbonRkmwA=="],
- "@aws-sdk/eventstream-handler-node": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-cTeVzpu1xEAkryTZBYhGwnQ6gOGyp8ZYZvmn0Sg/nI/ABmy/CRHHxPDJDUi9PxwxUtGGaatvfRUB3FCgT/rSWw=="],
+ "@aws-sdk/eventstream-handler-node": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-a8xilRoRaalvSPZdfrs0VY3/BPc0uYhXW56Z/k6nmZ5Vk430LHeowf9APIPq8utM3tMJSNGSSuJMlB9YrPsN+A=="],
- "@aws-sdk/middleware-eventstream": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-dlRzHCgyB8W6hLuDC5pcT5q+ziPt00n4QGgGBE17ucLVU4zMa6lsbuUdQ2Pm75Z5VA8GF+R/+SgrRcaTdIzSIQ=="],
+ "@aws-sdk/middleware-eventstream": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-B6gvZlcnRBNWraKgyEjKsbhv+VjtbyHmpU7hmtTHzXpDSxHPpCJnYLpglEOOsF+SFne20DbZC5IVC1aNr2Pb4A=="],
- "@aws-sdk/middleware-websocket": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.0", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/fetch-http-handler": "^5.7.2", "@smithy/signature-v4": "^5.6.12", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-bIrDaMENQmYRBHntOiOheqkiw5+fhKW4Lqb+mS1uqF0VwvdWI22fW2HFgWrng66CmYd+4k8ePlpj38sEfTuMLQ=="],
+ "@aws-sdk/middleware-websocket": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/signature-v4": "^5.7.3", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-bhESdru8u8KosziH8jcVta/NM/dNreeRz2+2aU86si5bfBYOiJ6IiqD+9U4URUcU5WJO3Yw+jO3GLDIHlscXMQ=="],
- "@aws-sdk/nested-clients": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.0", "@aws-sdk/signature-v4-multi-region": "^3.996.46", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/fetch-http-handler": "^5.7.2", "@smithy/node-http-handler": "^4.11.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-mooq9Q+jLa18VoM7HouczmslZU60iiB0aKc/Ztnq/luIL1ud0z4DnYprLR/ZO1gp331S9tJctM1HZr7u6YKBXQ=="],
+ "@aws-sdk/nested-clients": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/signature-v4-multi-region": "^3.996.47", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.12.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-oRxtBcka/JGHGs9l9p9IVajGoTP8vTPmoAzdHGy4Qcy9P5vPnDf6nhIeM/COQNY9k/OahImTRaLkHftoXvfcmQ=="],
- "@aws-sdk/signature-v4-multi-region": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.5", "@smithy/signature-v4": "^5.6.12", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-L+2xZTye/2T96f3lwCws0Zw6GG2JHZW9e8FpVgGBeeExSKyeoZ6CWRpBml/7DNiK/O26jrgPM9F+Ay8VkgzUWQ=="],
+ "@aws-sdk/signature-v4-multi-region": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.6", "@smithy/signature-v4": "^5.7.3", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-Zk08macMvQTHzQJCLJVkOlviVoqwYMrpXv4lmLN7b7sAbiMoOK7Go0NYdR5UeF+MW8LIbRmwrNy9u/5VvX1U5g=="],
- "@aws-sdk/token-providers": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.0", "@aws-sdk/nested-clients": "^3.997.45", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-csUjJ+GsvyjPJhtTURYP2yzZKduVw7VA8L1OpTm39RiA1VYR1eiO7uihOcvXXVOgbaL2GoH4FTGx6X+6s1p6tA=="],
+ "@aws-sdk/token-providers": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/nested-clients": "^3.997.46", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-ocX29IyTSK/9y25lZ7X7E/1v04BIZ3kfu9DDDYr/c9aJxFik53kvzJao5T25lh/Uob9VkVAbgXRN776nr1EI3Q=="],
- "@aws-sdk/types": ["@aws-sdk/[email protected]", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-LkwLL2BLbC6wNNm4JaH9mbEqBMdOZCct6VAYqhdN4U1xrWM+fUJQEfbHwQgDypapOWTRtlk25akb5afM0P8CIQ=="],
+ "@aws-sdk/types": ["@aws-sdk/[email protected]", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-v/clNZzZnDxGyvpHMOGpJKVXFAExJzUNAAjaWGdcx8QAcXLGwTaOkw33p5SHAi0YAioK32xB3hWwOekRVfmfKg=="],
- "@aws-sdk/xml-builder": ["@aws-sdk/[email protected]", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-wlFmCIGUlwF4zx/kncw+bmxTQh1HeSJq4mYV/V5cZUSJadDP3kXvGW8Rn21cimj/7y9ju+47oYWXi97vF7czaA=="],
+ "@aws-sdk/xml-builder": ["@aws-sdk/[email protected]", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-ctjVSyCMegrWfXlx6VqzSBFI6UqmQ5ZlnfMhdLIiWmhoH8UAQxSCP5N3OpG7X3k4LnS7ou74C4mt20+bfTW2aQ=="],
"@aws/lambda-invoke-store": ["@aws/[email protected]", "", {}, "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ=="],
"@babel/runtime": ["@babel/[email protected]", "", {}, "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw=="],
- "@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.5.13", "@biomejs/cli-darwin-x64": "2.5.13", "@biomejs/cli-linux-arm64": "2.5.13", "@biomejs/cli-linux-arm64-musl": "2.5.13", "@biomejs/cli-linux-x64": "2.5.13", "@biomejs/cli-linux-x64-musl": "2.5.13", "@biomejs/cli-win32-arm64": "2.5.13", "@biomejs/cli-win32-x64": "2.5.13" }, "bin": { "biome": "bin/biome" } }, "sha512-+SEC/mFk1a+5mvUANZgbZTaiZXs1nj4iMhL/PHiqDT5TPUEPFIlliEtkKKZB4N862yylHC3UI+/Sj2I0HJEqhA=="],
+ "@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.5.15", "@biomejs/cli-darwin-x64": "2.5.15", "@biomejs/cli-linux-arm64": "2.5.15", "@biomejs/cli-linux-arm64-musl": "2.5.15", "@biomejs/cli-linux-x64": "2.5.15", "@biomejs/cli-linux-x64-musl": "2.5.15", "@biomejs/cli-win32-arm64": "2.5.15", "@biomejs/cli-win32-x64": "2.5.15" }, "bin": { "biome": "bin/biome" } }, "sha512-WZTW4slm/pdkh92K6t/3aEN++44JD1PQ7squ7RCMLI1flHGl43DVOIGXvCjHiZgBMO1V4uYxoFNtqrIA4qGuIQ=="],
- "@biomejs/cli-darwin-arm64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-nYSuDJ6zgVqZUkAkJkvhXxsF2PYIrUk/g638K4voCXz7foI9f7b6C2/7+oAihsHQlivZNMUrm/y8ywlcHQtZOw=="],
+ "@biomejs/cli-darwin-arm64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BZVzFhJ/mUvTLMYbc9x6el0o2Uv5zP7bACYyhFb6fSc1giroXm7PL0a5KqMJ9F+/BnkYRjagD/ROSDVOZ6eapg=="],
- "@biomejs/cli-darwin-x64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-KVy1ceEDuJ3AzFxjT9kkxbVy+UANw1pjEMUS6lvKfxjJ+fmkRvc7sQn1Xo6ETgseEI7wUQoV03KSga3XfE8YRQ=="],
+ "@biomejs/cli-darwin-x64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-V5Kw63V+fVGNFhFrizDxMbGXAzZCh8kYzJpy3GI6gTapWDg7bZK9oYC9CbVgQSEdTnupz0U5Efz8Ev+5vdBBXw=="],
- "@biomejs/cli-linux-arm64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-VlNMtoxOqs0dUR6drxxHr18SNUvI7xxAuHZlH4s/dstYSf3g6RaqVgo8JRnhcOhKz9afWrvtJTboNG1JuYlIDQ=="],
+ "@biomejs/cli-linux-arm64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-XaG7P7eeSLYETD3K9grfB0mQmpLQZjygdbsxekWBJAg4am79fGAtRpfRyNnTvXB2fZFNnJZG3nXm7HBat0+VUw=="],
- "@biomejs/cli-linux-arm64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-CH32xpep3dNS5EVJpAHlYchkBYznxyVZQrx0b6YYYlPL9u9ZeD2NtqiK/6s64+HFS2a7hGnryLlqqZAOh8ax5g=="],
+ "@biomejs/cli-linux-arm64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-tGzZUTcJCV7tj5Adh/Gn6nR4MycqA3iohq2LEcrarAgRBkU0h0OKd2UzCRkOsOYOuUGaUJb4YmqRqyy2feGGSw=="],
- "@biomejs/cli-linux-x64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-Fi6gIxbUaJ3ZCIXeG3ggIBPF76O2DjDN67WrPX/ODRv54GeXPm2gbEPC96Yb0yrJoiH0Eax1JLx1Pi0XbsNFZQ=="],
+ "@biomejs/cli-linux-x64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-xE4iEW/3LqlYj9GFgGrFsFSH51dEEpUbYWBfeOv0q87WkUDxK2o/HhreSb7qMJqck70RVM6Lg96hgedcAYcOkA=="],
- "@biomejs/cli-linux-x64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-F3pmwl+VHoUuVJN/tbNLKeLt0SVK3EIyN1jXlMcNyQGYRQQTVqXF+GgkP0/CjGXFN87e/mv0sBfUnWqWza5PKQ=="],
+ "@biomejs/cli-linux-x64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-IlxUcyxilVGPsE008x13pWdkTbU3nQpP2i9b5UrbOYj6goBkKsRX1XB7yJLcV+O1H9LBchIIm4adOaVLZBX0ZQ=="],
- "@biomejs/cli-win32-arm64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-+WD13qshXrr0Icv4BfsAdzm8Fs3TL+nZ59zEQxsYNd8lcgZJ0A5+OrlwsL1PipVCmWeRpxgIPD6DAcEd7smkCQ=="],
+ "@biomejs/cli-win32-arm64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-2kPKzhNlm8C+Ru3GcO0Me2ODkCBLrVOUNuyi84RJyWDVKAA4+Kjj3jMjL938lF6BRfvltC4vB2nPY9SvN51Ovg=="],
- "@biomejs/cli-win32-x64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-VOofU/nW761XWzUeUNE8zzYNyPrxuMuNFMizL0qz7J75yeV8N7WFheUlk1/K6dOkaFpH9wJ+lDKlwjAbw0346w=="],
+ "@biomejs/cli-win32-x64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-yAzh4UqEImV6Hcy0zjUqNfJAsUhoD64FBQCdTG8Md/Z2wQeVP/ZmJ3XRYAs1g8J9fjTFyl2fCtc5FB5til47+g=="],
"@dimforge/rapier3d-compat": ["@dimforge/[email protected]", "", {}, "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow=="],
"@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
- "@gltf-transform/core": ["@gltf-transform/[email protected]", "", { "dependencies": { "property-graph": "^4.1.0" } }, "sha512-JlvShvnB4AtfGZqjnESS/wfPJbpVnyHhTwJBbWN4qXqkB3C5HIoxxpu/orwGBge6Pc0zObeWj70lVf+4gbuu0A=="],
+ "@gltf-transform/core": ["@gltf-transform/[email protected]", "", { "dependencies": { "property-graph": "^4.1.0" } }, "sha512-OWgBYssKHKoXMIrMb2N20jXqWRnMP9HdtcTFQBEAJtz4P+OOxx5fozl5eAeK7nktIs5uDE/lu4NbkE5VCZaR9g=="],
- "@gltf-transform/extensions": ["@gltf-transform/[email protected]", "", { "dependencies": { "@gltf-transform/core": "^4.5.0", "ktx-parse": "^1.1.0" } }, "sha512-J4cKzrmEr75YkrtdI4cKosBg2vDC4rT56aq/QoijW7GT1Y9gSEMJbqyFO9xcFO3FNpZaZiDrHWUqE5Okrl5nOQ=="],
+ "@gltf-transform/extensions": ["@gltf-transform/[email protected]", "", { "dependencies": { "@gltf-transform/core": "^4.5.1", "ktx-parse": "^1.1.0" } }, "sha512-3jTe+GWRy4fj1TU790LPsO+rpO/4byUWPTpNkjy6M6h8RvrUivRf12Mptc0770K4ZczibpJDNHXZFkFsFMRDLA=="],
- "@gltf-transform/functions": ["@gltf-transform/[email protected]", "", { "dependencies": { "@gltf-transform/core": "^4.5.0", "@gltf-transform/extensions": "^4.5.0", "ktx-parse": "^1.1.0", "ndarray": "^1.0.19", "ndarray-lanczos": "^0.3.0", "ndarray-pixels": "^5.2.0" } }, "sha512-7sMOuEfksMyF+/NTwUnEOgh7djohJ5XfeYg8rzXDG+9JIdbGVUpvJUY3XVBJCUJJ04dusDvcTHloOi1wfM8lnw=="],
+ "@gltf-transform/functions": ["@gltf-transform/[email protected]", "", { "dependencies": { "@gltf-transform/core": "^4.5.1", "@gltf-transform/extensions": "^4.5.1", "ktx-parse": "^1.1.0", "ndarray": "^1.0.19", "ndarray-lanczos": "^0.3.0", "ndarray-pixels": "^5.2.0" } }, "sha512-rfm4nQY2DJ+ip1e15xp7YfQwhRno3kPLcGw4EZiRk1dVwMV3cdFMcF08glYcO/+oLyYkUEs3xXMJYXa0cPgcTg=="],
- "@google/genai": ["@google/[email protected]", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-NE90Nl0AP75YZ2tGxXjQQs6Gkunma7a1JmPCx5g5CxvjHXshmuI2aNoPJ1xLrRixjkNxog898oylM+MyNudUQw=="],
+ "@google/genai": ["@google/[email protected]", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-W6F9Y9d4h7cVQNa85IPCOVVP9PiUzve/ZQPBvQnBmnBJcLvxstEw+R2X/RyCH0SOe0HVDQzeKDpDUf6ZRtbmdQ=="],
"@hono/node-server": ["@hono/[email protected]", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],
"@img/colour": ["@img/[email protected]", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
- "@img/sharp-darwin-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.3" }, "os": "darwin", "cpu": "arm64" }, "sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA=="],
+ "@img/sharp-darwin-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg=="],
- "@img/sharp-darwin-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.3" }, "os": "darwin", "cpu": "x64" }, "sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw=="],
+ "@img/sharp-darwin-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.4" }, "os": "darwin", "cpu": "x64" }, "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw=="],
- "@img/sharp-freebsd-wasm32": ["@img/[email protected]", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "os": "freebsd" }, "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA=="],
+ "@img/sharp-freebsd-wasm32": ["@img/[email protected]", "", { "dependencies": { "@img/sharp-wasm32": "0.35.5" }, "os": "freebsd" }, "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw=="],
- "@img/sharp-libvips-darwin-arm64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg=="],
+ "@img/sharp-libvips-darwin-arm64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw=="],
- "@img/sharp-libvips-darwin-x64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw=="],
+ "@img/sharp-libvips-darwin-x64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ=="],
- "@img/sharp-libvips-linux-arm": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA=="],
+ "@img/sharp-libvips-linux-arm": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw=="],
- "@img/sharp-libvips-linux-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A=="],
+ "@img/sharp-libvips-linux-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A=="],
- "@img/sharp-libvips-linux-ppc64": ["@img/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w=="],
+ "@img/sharp-libvips-linux-ppc64": ["@img/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ=="],
- "@img/sharp-libvips-linux-riscv64": ["@img/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ=="],
+ "@img/sharp-libvips-linux-riscv64": ["@img/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q=="],
- "@img/sharp-libvips-linux-s390x": ["@img/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q=="],
+ "@img/sharp-libvips-linux-s390x": ["@img/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ=="],
- "@img/sharp-libvips-linux-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA=="],
+ "@img/sharp-libvips-linux-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw=="],
- "@img/sharp-libvips-linuxmusl-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw=="],
+ "@img/sharp-libvips-linuxmusl-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA=="],
- "@img/sharp-libvips-linuxmusl-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw=="],
+ "@img/sharp-libvips-linuxmusl-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg=="],
- "@img/sharp-linux-arm": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.3" }, "os": "linux", "cpu": "arm" }, "sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A=="],
+ "@img/sharp-linux-arm": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.4" }, "os": "linux", "cpu": "arm" }, "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ=="],
- "@img/sharp-linux-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64" }, "sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ=="],
+ "@img/sharp-linux-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64" }, "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ=="],
- "@img/sharp-linux-ppc64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.3" }, "os": "linux", "cpu": "ppc64" }, "sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ=="],
+ "@img/sharp-linux-ppc64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.4" }, "os": "linux", "cpu": "ppc64" }, "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA=="],
- "@img/sharp-linux-riscv64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.3" }, "os": "linux", "cpu": "none" }, "sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA=="],
+ "@img/sharp-linux-riscv64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.4" }, "os": "linux", "cpu": "none" }, "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ=="],
- "@img/sharp-linux-s390x": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.3" }, "os": "linux", "cpu": "s390x" }, "sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ=="],
+ "@img/sharp-linux-s390x": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.4" }, "os": "linux", "cpu": "s390x" }, "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA=="],
- "@img/sharp-linux-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.3" }, "os": "linux", "cpu": "x64" }, "sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA=="],
+ "@img/sharp-linux-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.4" }, "os": "linux", "cpu": "x64" }, "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog=="],
- "@img/sharp-linuxmusl-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64" }, "sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA=="],
+ "@img/sharp-linuxmusl-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64" }, "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg=="],
- "@img/sharp-linuxmusl-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.3" }, "os": "linux", "cpu": "x64" }, "sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg=="],
+ "@img/sharp-linuxmusl-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.4" }, "os": "linux", "cpu": "x64" }, "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A=="],
- "@img/sharp-wasm32": ["@img/[email protected]", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA=="],
+ "@img/sharp-wasm32": ["@img/[email protected]", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ=="],
- "@img/sharp-webcontainers-wasm32": ["@img/[email protected]", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "cpu": "none" }, "sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA=="],
+ "@img/sharp-webcontainers-wasm32": ["@img/[email protected]", "", { "dependencies": { "@img/sharp-wasm32": "0.35.5" }, "cpu": "none" }, "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA=="],
- "@img/sharp-win32-arm64": ["@img/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw=="],
+ "@img/sharp-win32-arm64": ["@img/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q=="],
- "@img/sharp-win32-ia32": ["@img/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw=="],
+ "@img/sharp-win32-ia32": ["@img/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A=="],
- "@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg=="],
+ "@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg=="],
"@jridgewell/resolve-uri": ["@jridgewell/[email protected]", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
@@ -199,39 +199,39 @@
"@jscadui/3mf-export": ["@jscadui/[email protected]", "", {}, "sha512-y5vZktqCjyi7wA38zqNlLIdZUIRZoOO9vCjLzwmL4bR0hk7B/Zm1IeffzJPFe1vFc0C1IEv3hm8caDv3doRk9g=="],
- "@modelcontextprotocol/client": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@modelcontextprotocol/core": "2.2.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-LxCou/CSYQ6dwEnjhLZY0KnEuc8V4UJ3IEQCl/uR2yHobSQIEdJKUlKLRYRF5i5FqRGHy1eK7une3aAWDHLtig=="],
+ "@modelcontextprotocol/client": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@modelcontextprotocol/core": "2.3.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.8", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-pbHtGj6EeFCHngFE8gtNPaKrsj8Mb1IMw45BLcaPML/m2WTxI7pyYmeNQvaux88Lw8BSO5r7nyRbUyIkICmGrg=="],
- "@modelcontextprotocol/core": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-iLhmprRmWI8EcosOA3wVvww22z02NkgqhV4fBH6f/odQBsi7xnJc0HGmi21yWO+/iKw2yzqVE127Zhna5/+JXw=="],
+ "@modelcontextprotocol/core": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-09BHFaNVBe5pB2AhzCfLj0cqmsKLERvZQ4FblzP90UMGLaXVqdZPByFjURwsUYCmxonUW2yAwgTTvle+8O2/8w=="],
"@modelcontextprotocol/ext-apps": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0" }, "peerDependencies": { "@modelcontextprotocol/client": "^2.0.0", "@modelcontextprotocol/core": "^2.0.0", "@modelcontextprotocol/server": "^2.0.0", "react": "^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0", "zod": "^4.2.0" }, "optionalPeers": ["@modelcontextprotocol/server", "react", "react-dom"] }, "sha512-Tn+4+cyhO4f4cQSDxNyLiIfEE+qlTTuIbWBJB8JTinEXOhDYgCT4wDTQplxD9MBYZH5pCYGC59GaxiwIT4bu8w=="],
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA=="],
- "@modelcontextprotocol/server": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@modelcontextprotocol/core": "2.2.0", "zod": "^4.2.0" } }, "sha512-qFnltjus6Gk8Lx6J1w2RXmr3YPN22MNT6qD6zjAkaiWIlFIFxWClz0rXHNuJF/KSUyn5YGhkSvXkWDbQHVLFEQ=="],
+ "@modelcontextprotocol/server": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@modelcontextprotocol/core": "2.3.0", "zod": "^4.2.0" } }, "sha512-+6b0LdsQLmHsvS7J6sQJ4weTpzUn61fU1JKS+321/+IyDYoHW5CR2Tgqcs6GgAAQvlesCo6yX3xttgmx+XGtJw=="],
- "@napi-rs/canvas": ["@napi-rs/[email protected]", "", { "optionalDependencies": { "@napi-rs/canvas-android-arm64": "1.0.9", "@napi-rs/canvas-darwin-arm64": "1.0.9", "@napi-rs/canvas-darwin-x64": "1.0.9", "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.9", "@napi-rs/canvas-linux-arm64-gnu": "1.0.9", "@napi-rs/canvas-linux-arm64-musl": "1.0.9", "@napi-rs/canvas-linux-riscv64-gnu": "1.0.9", "@napi-rs/canvas-linux-x64-gnu": "1.0.9", "@napi-rs/canvas-linux-x64-musl": "1.0.9", "@napi-rs/canvas-win32-arm64-msvc": "1.0.9", "@napi-rs/canvas-win32-x64-msvc": "1.0.9" } }, "sha512-QviPdJImDi/jMAvBfqaw+19BndMd/sizXVW3NnpMd3VJGz++QXkOHcP9kWR/smHG0hNjHeyuHFyrx/5lD0oNcQ=="],
+ "@napi-rs/canvas": ["@napi-rs/[email protected]", "", { "optionalDependencies": { "@napi-rs/canvas-android-arm64": "1.0.10", "@napi-rs/canvas-darwin-arm64": "1.0.10", "@napi-rs/canvas-darwin-x64": "1.0.10", "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.10", "@napi-rs/canvas-linux-arm64-gnu": "1.0.10", "@napi-rs/canvas-linux-arm64-musl": "1.0.10", "@napi-rs/canvas-linux-riscv64-gnu": "1.0.10", "@napi-rs/canvas-linux-x64-gnu": "1.0.10", "@napi-rs/canvas-linux-x64-musl": "1.0.10", "@napi-rs/canvas-win32-arm64-msvc": "1.0.10", "@napi-rs/canvas-win32-x64-msvc": "1.0.10" } }, "sha512-V+qptzsGnPMFxEbhwc6eDNMe5eDrfiBIp8qGpuRjAVIX4Kn2zxvwQ1Xco6Fwe+3tYIe3iLW8LM9D+SvjyJhqbQ=="],
- "@napi-rs/canvas-android-arm64": ["@napi-rs/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-4LGXk2/0HVzE29K8SzML5WubgCp++B1FH3qgl35XmSZE+lLdr6P9VRQEnZ0MCLZMTSuJP41yyhtoiVNEuvrTIA=="],
+ "@napi-rs/canvas-android-arm64": ["@napi-rs/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-0sDMvme+7fj6bHERUaBs5SvEyWaORc91VUkaB4RrtG7p6dBrBNGy1of8cyEKDxygd1FlHtW+Thunj8lSixzY7A=="],
- "@napi-rs/canvas-darwin-arm64": ["@napi-rs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-YNdfLBzY0W/Pep9fo2L6RmoNlNksnn05LRnX66W63R3ij58S25QOTcjdtEt2v8+PnCESzqZsYzUo+QPeIR44NA=="],
+ "@napi-rs/canvas-darwin-arm64": ["@napi-rs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-pdHL1TEfFMrnchRYqmPWXKN7hR4XtOYmzJqnh4XhpfWD4/eeSokOGVzrdFP/iQ3sfr2rf0939gOGq9uCp8BGmg=="],
- "@napi-rs/canvas-darwin-x64": ["@napi-rs/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-ceZQSknTEcy3dOXoekv59LTCkXjvnLsq+VW5PeNNDHEPQbRS5Ervkm1EaDa7WLAjiYWMLuSQTRTHao1dEX4prg=="],
+ "@napi-rs/canvas-darwin-x64": ["@napi-rs/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-iuuk5plGxAcxurxv2ycF2yR20y5zvaBZ4heQdhPpg3EMFD21PhlY1V+YwSRmYRWzbvKL474UYdw3WIg2qfafyw=="],
- "@napi-rs/canvas-linux-arm-gnueabihf": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-XhfI0Wwv4llhd6nnWDtY3kQKjq0r+y1i91PlJlJI24ag2U9WrnwbG1qS3+fDLEyouwEVFchiKkTEHozK+5iUNA=="],
+ "@napi-rs/canvas-linux-arm-gnueabihf": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-kH7GFR5Unpm77pKSEsmkqvzeQCRD7/MQ7upmeLLjg4XpQ62dX/R6THFsp6vkF1Pkco2aKUq9KhoLM4W5twdk7g=="],
- "@napi-rs/canvas-linux-arm64-gnu": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-012oiYtKaE7i9oxc8q7nraT7kDOpLcaCmFLzVe9Ty34RHDdoDzbWLrVh827CNxYh/EADX1eSikA3ymLjo/nNuw=="],
+ "@napi-rs/canvas-linux-arm64-gnu": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-0/Hj7IwM9pmzdwxiqkp4YLJ8dKqASBrWQ3Y7dWUSU/4dgvCL9O6YNvX7xVUJjonQvdD3IE9ESS/nXa5srQqoVw=="],
- "@napi-rs/canvas-linux-arm64-musl": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Ls5UWYFFn63casTZEczbeyEg3vRDRkv9lscuGwfchtY5yLLQhgOB8SN4YGxmfJ5vTaBwZ2YUxBS3NtmjJmFXdA=="],
+ "@napi-rs/canvas-linux-arm64-musl": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-fmjKM0P2MLF9O6XzCQsRjhB+jlLzaf6tFQU36hMPMsYup+VThYvpjjhqNLOc/Ee3tHUE3r13H2BSJx/yXz4pFA=="],
- "@napi-rs/canvas-linux-riscv64-gnu": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-hLKEGxV7ZiRHqndePTokgDMdBlo/rDfzg7P4p4QIv9pUhuYobnu3R2NIFLCRghG0nwfo+s2sw+c1xZFeCmEAsw=="],
+ "@napi-rs/canvas-linux-riscv64-gnu": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-O/BUrGwrs3pVP9PpD/3++ZiOpjHMJlmiB7aBgswP8rbe4egPfiFkFxmcCczoLvZa72TaQX5lJ8Udedb6rc/Hvg=="],
- "@napi-rs/canvas-linux-x64-gnu": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-6kaz3w0QMy77PDWk6rJ1ksIihdad3qzEyX2o2oGT8GwCaypfT5mhjr8buOO5hstyLxcWXDScuz56RsINLtBPIQ=="],
+ "@napi-rs/canvas-linux-x64-gnu": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-48HkZPQeAN/R+9NPpY64tceoyCUW5xYYtHKZnC+BG11qiihXJCbH+xfbgGU+OdYp1Q4s84HDl9ILU0KBK6SBOQ=="],
- "@napi-rs/canvas-linux-x64-musl": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-xrGvmS3v55hmZ86ls/kBLVNMUTYio3f6Ik0DireemG994VfPAwiA3ZXA0Uf1bByctkB3NQ1Sfb+H5bkdUnnzfQ=="],
+ "@napi-rs/canvas-linux-x64-musl": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-QYHVi7WZ9v+Wm9OQyHLMTnJ8QiBPVX94BgbCHFJC/4bCFMfvX7fRzo4FJPgkRP0ISz3ulYNow/FCbQOPjzhYjg=="],
- "@napi-rs/canvas-win32-arm64-msvc": ["@napi-rs/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-yjmVS3ArZeRVCP7jqbPq4rpZa/BhTeI7ELE2XqJg3snICQBDevLZyArxswHkiTnT34KRic33/4fLirrHI+SY8A=="],
+ "@napi-rs/canvas-win32-arm64-msvc": ["@napi-rs/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-bWK+YajM/8sL0mMgLtug2s063FVBPzFV4QAn987CQomMKlmzrBY6Trz43KY+24hq7IOa3qNhUAgP/XMEF50ZEQ=="],
- "@napi-rs/canvas-win32-x64-msvc": ["@napi-rs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-QlSYQdMQslB81nlABo9wNfQ6npFhE7/O+saCZdqVGueGanyRk4jCogD5EwQenfP3kIq9e+mm6GreQBjX5MrA8g=="],
+ "@napi-rs/canvas-win32-x64-msvc": ["@napi-rs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-9WtzW85PaIhtB27iXaR/9RrLCqHLbqD3Z8Q+kh17NjFxwQXFXU5vWbYH4vEH+drM307TTyK3hidZgpt09G5T3g=="],
"@nodable/entities": ["@nodable/[email protected]", "", {}, "sha512-9uGyhaQavEUMC8AIddIjau4NsnsXhou+j5sBAGojCM1oxmQpVKTWR/9JxABD6UAv12vpIms55fPZKFQEhG6uBg=="],
@@ -257,23 +257,23 @@
"@protobufjs/utf8": ["@protobufjs/[email protected]", "", {}, "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg=="],
- "@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-YvlfAEyHmuWpwjEKgq4FBaXhLEoSEwS/nNbyCF/ef05ZvSuwMDB4NIMgXqkJojzYyQWjhVDapPHXfhkz/tZYlg=="],
+ "@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-i4YPS4B6ts7bjn7UwLnGjiZdprOvHvgGobFZsYK3GIY3E5hIqtj0rReU69BcTpGp+fvtraSNXeG1l+jtJvF55w=="],
- "@smithy/credential-provider-imds": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/core": "^3.32.0", "@smithy/types": "^4.17.0", "tslib": "^2.6.2" } }, "sha512-2jsPi+7Zv2hSzD9IXR9D7DTqSn7mv4XalzRm+bESh53jiaUS3NKEUbpQFTJP0HhQy9qzZvluxQ3yS24zdRrqsA=="],
+ "@smithy/credential-provider-imds": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/core": "^3.33.2", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg=="],
"@smithy/fetch-http-handler": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA=="],
"@smithy/node-http-handler": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw=="],
- "@smithy/signature-v4": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/core": "^3.32.0", "@smithy/types": "^4.17.0", "tslib": "^2.6.2" } }, "sha512-hCynhm22wMJ8wTF9crcwu8mxggtUrSLLJgDcGUvYFBqpofxycYJCGKOMYg4xtPPFtgNiDJSYmhsWLTrcU/g59Q=="],
+ "@smithy/signature-v4": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-tHy0K0VtqNd5Y7Y41h0a0Lhh0L1GzC08dTWg0F7vRJWFtTENg7IZikf3wQkanYIRdb7ngoIPMTmqgUi401fEeQ=="],
- "@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-CgB6HHWer/vrKps24ulRIbpcpb7K4xAU7SkZ7YHzBPlwHsvsrCJFEXK421s+cJzX+ZrqtA/TuU5w1HzI7k9N8A=="],
+ "@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
"@stablelib/base64": ["@stablelib/[email protected]", "", {}, "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ=="],
"@standard-schema/spec": ["@standard-schema/[email protected]", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
- "@strands-agents/sdk": ["@strands-agents/[email protected]", "", { "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.1112.0", "@smithy/fetch-http-handler": "^5.7.2", "@types/json-schema": "^7.0.15", "uuid": "^14.0.2", "yaml": "^2.8.3" }, "peerDependencies": { "@a2a-js/sdk": "^0.3.10", "@ai-sdk/provider": "^3.0.0", "@anthropic-ai/sdk": "^0.109.1", "@aws-sdk/client-bedrock-agent": "^3.1078.0", "@aws-sdk/client-bedrock-agent-runtime": "^3.1078.0", "@aws-sdk/client-s3": "^3.1078.0", "@aws/bedrock-token-generator": "^1.1.0", "@cedar-policy/cedar-wasm": "^4.0.0", "@cedar-policy/mcp-schema-generator-wasm": "^0.6.0", "@google/genai": "^2.6.0", "@modelcontextprotocol/sdk": "^1.25.2", "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-metrics-otlp-http": "^0.219.0", "@opentelemetry/exporter-trace-otlp-http": "^0.219.0", "@opentelemetry/resources": "^2.8.0", "@opentelemetry/sdk-metrics": "^2.6.1", "@opentelemetry/sdk-trace-base": "^2.6.1", "@opentelemetry/sdk-trace-node": "^2.6.1", "@smithy/types": "^4.15.1", "@tobilu/qmd": "^2.8.0", "express": "^5.1.0", "openai": "^6.45.0", "turndown": "^7.2.4", "zod": "^4.1.12" }, "optionalPeers": ["@a2a-js/sdk", "@ai-sdk/provider", "@anthropic-ai/sdk", "@aws-sdk/client-bedrock-agent", "@aws-sdk/client-bedrock-agent-runtime", "@aws-sdk/client-s3", "@aws/bedrock-token-generator", "@cedar-policy/cedar-wasm", "@cedar-policy/mcp-schema-generator-wasm", "@google/genai", "@opentelemetry/exporter-metrics-otlp-http", "@opentelemetry/exporter-trace-otlp-http", "@opentelemetry/resources", "@opentelemetry/sdk-metrics", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-trace-node", "@smithy/types", "@tobilu/qmd", "express", "openai", "turndown"] }, "sha512-YDaYA4MvYhzKdwu0aL7jZI8GHQkKAmqvmLMxFnywBwaSkTYE/DPiDFeAzI61U10pUGFwXKLbcRFIbjQ3iEMGsw=="],
+ "@strands-agents/sdk": ["@strands-agents/[email protected]", "", { "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.1132.0", "@smithy/fetch-http-handler": "^5.8.0", "@types/json-schema": "^7.0.15", "uuid": "^14.0.2", "yaml": "^2.9.1" }, "peerDependencies": { "@a2a-js/sdk": "^0.3.10", "@ai-sdk/provider": "^3.0.0", "@anthropic-ai/sdk": "^0.109.1", "@aws-sdk/client-bedrock-agent": "^3.1078.0", "@aws-sdk/client-bedrock-agent-runtime": "^3.1078.0", "@aws-sdk/client-s3": "^3.1078.0", "@aws/bedrock-token-generator": "^1.1.0", "@cedar-policy/cedar-wasm": "^4.0.0", "@cedar-policy/mcp-schema-generator-wasm": "^0.6.0", "@google/genai": "^2.6.0", "@modelcontextprotocol/sdk": "^1.25.2", "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-metrics-otlp-http": "^0.219.0", "@opentelemetry/exporter-trace-otlp-http": "^0.219.0", "@opentelemetry/resources": "^2.8.0", "@opentelemetry/sdk-metrics": "^2.6.1", "@opentelemetry/sdk-trace-base": "^2.6.1", "@opentelemetry/sdk-trace-node": "^2.6.1", "@smithy/types": "^4.15.1", "@tobilu/qmd": "^2.8.0", "express": "^5.1.0", "openai": "^6.45.0", "turndown": "^7.2.4", "zod": "^4.1.12" }, "optionalPeers": ["@a2a-js/sdk", "@ai-sdk/provider", "@anthropic-ai/sdk", "@aws-sdk/client-bedrock-agent", "@aws-sdk/client-bedrock-agent-runtime", "@aws-sdk/client-s3", "@aws/bedrock-token-generator", "@cedar-policy/cedar-wasm", "@cedar-policy/mcp-schema-generator-wasm", "@google/genai", "@opentelemetry/exporter-metrics-otlp-http", "@opentelemetry/exporter-trace-otlp-http", "@opentelemetry/resources", "@opentelemetry/sdk-metrics", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-trace-node", "@smithy/types", "@tobilu/qmd", "express", "openai", "turndown"] }, "sha512-pYBv1x0Vbt+/nPsvD3jyF4Re0ljTWK5iiuh4sdvuZs+DnXVsRhqbHXRhdsTh3X8f+mvk2XF6YadJzsmscXOBkg=="],
"@tweenjs/tween.js": ["@tweenjs/[email protected]", "", {}, "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="],
@@ -345,7 +345,7 @@
"agent-base": ["[email protected]", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],
- "ai": ["[email protected]", "", { "dependencies": { "@ai-sdk/gateway": "3.0.193", "@ai-sdk/provider": "3.0.16", "@ai-sdk/provider-utils": "4.0.51", "@opentelemetry/api": "^1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-fdzEzSppVTYlgyW/Gp6tMAFIU88yv7k86x77m5vAJo7hXV31hDJCsAkq/aIpE3tP3k4LjrrLcUANPHcBZ0YWsw=="],
+ "ai": ["[email protected]", "", { "dependencies": { "@ai-sdk/gateway": "3.0.209", "@ai-sdk/provider": "3.0.18", "@ai-sdk/provider-utils": "4.0.57", "@opentelemetry/api": "^1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ZBT30eQTy6exP+EWJJxm3DMb34m9td8STy+hfnvKdjhyEQoM8vQN5YfFLTRVVTCONHoM+y5K+Tudb6PTFrpikA=="],
"ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
@@ -519,7 +519,7 @@
"magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
- "manifold-3d": ["[email protected]", "", { "dependencies": { "@gltf-transform/core": "^4.2.0", "@gltf-transform/extensions": "^4.2.0", "@gltf-transform/functions": "^4.2.0", "@jridgewell/resolve-uri": "^3.1.2", "@jridgewell/trace-mapping": "^0.3.31", "@jscadui/3mf-export": "^0.5.0", "commander": "^13.1.0", "convert-source-map": "^2.0.0", "fast-xml-parser": "^5.4.2", "fflate": "^0.8.0", "magic-string": "^0.30.21" }, "peerDependencies": { "esbuild-wasm": "^0.27.3" }, "bin": { "manifold-cad": "bin/manifold-cad" } }, "sha512-u00Dc4IKm6W6VyVCAs6eFWNOW9V1w9/QM+xdwS/0TQKXLDtMIauxH5RXUwhOGDnvXa9uciKKYMUD2At76ffsaA=="],
+ "manifold-3d": ["[email protected]", "", { "dependencies": { "@gltf-transform/core": "^4.2.0", "@gltf-transform/extensions": "^4.2.0", "@gltf-transform/functions": "^4.2.0", "@jridgewell/resolve-uri": "^3.1.2", "@jridgewell/trace-mapping": "^0.3.31", "@jscadui/3mf-export": "^0.5.0", "commander": "^13.1.0", "convert-source-map": "^2.0.0", "fast-xml-parser": "^5.4.2", "fflate": "^0.8.0", "magic-string": "^0.30.21" }, "peerDependencies": { "esbuild-wasm": "^0.27.3" }, "bin": { "manifold-cad": "bin/manifold-cad" } }, "sha512-WWsme5HabwLHVcWPHT9m+s7mdmDVSEvCny+uXH1E7jEc8FbFUgM75C3Dh6NVw57Eeh3Ow7+xHCuXfxDMOemi9A=="],
"math-intrinsics": ["[email protected]", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
@@ -605,7 +605,7 @@
"setprototypeof": ["[email protected]", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
- "sharp": ["[email protected]", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.4", "@img/sharp-darwin-x64": "0.35.4", "@img/sharp-freebsd-wasm32": "0.35.4", "@img/sharp-libvips-darwin-arm64": "1.3.3", "@img/sharp-libvips-darwin-x64": "1.3.3", "@img/sharp-libvips-linux-arm": "1.3.3", "@img/sharp-libvips-linux-arm64": "1.3.3", "@img/sharp-libvips-linux-ppc64": "1.3.3", "@img/sharp-libvips-linux-riscv64": "1.3.3", "@img/sharp-libvips-linux-s390x": "1.3.3", "@img/sharp-libvips-linux-x64": "1.3.3", "@img/sharp-libvips-linuxmusl-arm64": "1.3.3", "@img/sharp-libvips-linuxmusl-x64": "1.3.3", "@img/sharp-linux-arm": "0.35.4", "@img/sharp-linux-arm64": "0.35.4", "@img/sharp-linux-ppc64": "0.35.4", "@img/sharp-linux-riscv64": "0.35.4", "@img/sharp-linux-s390x": "0.35.4", "@img/sharp-linux-x64": "0.35.4", "@img/sharp-linuxmusl-arm64": "0.35.4", "@img/sharp-linuxmusl-x64": "0.35.4", "@img/sharp-webcontainers-wasm32": "0.35.4", "@img/sharp-win32-arm64": "0.35.4", "@img/sharp-win32-ia32": "0.35.4", "@img/sharp-win32-x64": "0.35.4" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA=="],
+ "sharp": ["[email protected]", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.5", "@img/sharp-darwin-x64": "0.35.5", "@img/sharp-freebsd-wasm32": "0.35.5", "@img/sharp-libvips-darwin-arm64": "1.3.4", "@img/sharp-libvips-darwin-x64": "1.3.4", "@img/sharp-libvips-linux-arm": "1.3.4", "@img/sharp-libvips-linux-arm64": "1.3.4", "@img/sharp-libvips-linux-ppc64": "1.3.4", "@img/sharp-libvips-linux-riscv64": "1.3.4", "@img/sharp-libvips-linux-s390x": "1.3.4", "@img/sharp-libvips-linux-x64": "1.3.4", "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", "@img/sharp-libvips-linuxmusl-x64": "1.3.4", "@img/sharp-linux-arm": "0.35.5", "@img/sharp-linux-arm64": "0.35.5", "@img/sharp-linux-ppc64": "0.35.5", "@img/sharp-linux-riscv64": "0.35.5", "@img/sharp-linux-s390x": "0.35.5", "@img/sharp-linux-x64": "0.35.5", "@img/sharp-linuxmusl-arm64": "0.35.5", "@img/sharp-linuxmusl-x64": "0.35.5", "@img/sharp-webcontainers-wasm32": "0.35.5", "@img/sharp-win32-arm64": "0.35.5", "@img/sharp-win32-ia32": "0.35.5", "@img/sharp-win32-x64": "0.35.5" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g=="],
"shebang-command": ["[email protected]", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
@@ -625,7 +625,7 @@
"strnum": ["[email protected]", "", { "dependencies": { "anynum": "^1.0.1" } }, "sha512-M9eUSMT2dCB2cTNPG7UYj6KuK7RJR2SN2+yCV/fTW3xzTCS6EaGZ5pSMgDIjB7r8zSfTGk+dvvn9rTjpVS9Mwg=="],
- "three": ["[email protected]", "", {}, "sha512-cr/fIM2ddMSVbYVgkfD4jLJv7Fh/8ZTjvo+7gQeSVGUZHxpx9FDwoL5iC7hUz/LiRA8wMbqfnb90xKfm1/HHkQ=="],
+ "three": ["[email protected]", "", {}, "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA=="],
"three-subdivide": ["[email protected]", "", { "peerDependencies": { "three": ">= 0.125.0" } }, "sha512-eEWMevrsHIMnC1xbsZSQZIB8QBr8XeXZhTSAdYrLm3ZC/yTdR4ocOZ2Qi+gEyPJFOt3iirQ+SQR0jCamk7e6FQ=="],
@@ -653,7 +653,7 @@
"web-streams-polyfill": ["[email protected]", "", {}, "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw=="],
- "webgpu": ["[email protected]", "", { "dependencies": { "@webgpu/types": "^0.1.72", "debug": "^4.4.0" } }, "sha512-T+B65/j2jhyFjbWHsVZ4TJw0nk0RVT27lG+nL3V5IIYMsvuVYKYOUli/yJhMpwvXAwqVPZehakWvTjxk+mK8LQ=="],
+ "webgpu": ["[email protected]", "", { "dependencies": { "@webgpu/types": "^0.1.72", "debug": "^4.4.0" } }, "sha512-3L4GfmqJLvYUIEWJngEQY+2HQiUlAFkg8+P8NDDj3Xx5hHHIFO/r8JW+ynfqBj7kHN4mbnwO74uB+lrRtLhp4Q=="],
"which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
@@ -665,21 +665,21 @@
"xml-naming": ["[email protected]", "", {}, "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw=="],
- "yaml": ["[email protected]", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
+ "yaml": ["[email protected]", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="],
- "zod": ["[email protected]", "", {}, "sha512-AXSD6hvGdvRjajG/l1cC+d6IrhH+sjmPKtYeQdJIK8MFJl3LyClzS+o/YsVC+zQZPupAaeH5skwwm8YqYH7BqA=="],
+ "zod": ["[email protected]", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="],
"zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
- "@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.0", "@aws-sdk/nested-clients": "^3.997.45", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-Sbl3rpzQdsG4ZK2zh0JWUYyZPKKorJlVOddA2T0DVbKJFrsW8J6wgnslxxUH04+WaBMr4A1HzJZvZX0xUvkniA=="],
+ "@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/nested-clients": "^3.997.46", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-GpyAr0DD63YOEmYFM6Df+gJuIgC92MMTiBK4FTKfxii5MJ9ge20epR7LyroulscYlG89J+ZB2ivFDPjvfQhzdw=="],
- "@smithy/credential-provider-imds/@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.17.0", "tslib": "^2.6.2" } }, "sha512-uKbkxgqLyepQDZoq8aRSdUqD1ID//rOqG96ixBhp++O7vBtmwYM6fwldGhr9HJP0iYrdc7GP/AlgzPWEZIrNRg=="],
+ "@smithy/fetch-http-handler/@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-YvlfAEyHmuWpwjEKgq4FBaXhLEoSEwS/nNbyCF/ef05ZvSuwMDB4NIMgXqkJojzYyQWjhVDapPHXfhkz/tZYlg=="],
- "@smithy/credential-provider-imds/@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-Aw4joiM0ZdErpo39lCj8phT2lxoiKZV+KZzBxnnQhWVtU2Is/WffQSL04uUWRcXUse9Ln8vXZK6V/FwqRVnQpg=="],
+ "@smithy/fetch-http-handler/@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-CgB6HHWer/vrKps24ulRIbpcpb7K4xAU7SkZ7YHzBPlwHsvsrCJFEXK421s+cJzX+ZrqtA/TuU5w1HzI7k9N8A=="],
- "@smithy/signature-v4/@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.17.0", "tslib": "^2.6.2" } }, "sha512-uKbkxgqLyepQDZoq8aRSdUqD1ID//rOqG96ixBhp++O7vBtmwYM6fwldGhr9HJP0iYrdc7GP/AlgzPWEZIrNRg=="],
+ "@smithy/node-http-handler/@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.18.0", "tslib": "^2.6.2" } }, "sha512-YvlfAEyHmuWpwjEKgq4FBaXhLEoSEwS/nNbyCF/ef05ZvSuwMDB4NIMgXqkJojzYyQWjhVDapPHXfhkz/tZYlg=="],
- "@smithy/signature-v4/@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-Aw4joiM0ZdErpo39lCj8phT2lxoiKZV+KZzBxnnQhWVtU2Is/WffQSL04uUWRcXUse9Ln8vXZK6V/FwqRVnQpg=="],
+ "@smithy/node-http-handler/@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-CgB6HHWer/vrKps24ulRIbpcpb7K4xAU7SkZ7YHzBPlwHsvsrCJFEXK421s+cJzX+ZrqtA/TuU5w1HzI7k9N8A=="],
"body-parser/content-type": ["[email protected]", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjs
index 6f4c4ce8..ae8dfa88 100644
--- a/dist/agent-run.mjs
+++ b/dist/agent-run.mjs
@@ -9313,13 +9313,14 @@ var init_material_library_node = __esm(() => {
// src/rebuild-options.ts
import { z as z12 } from "zod";
-var rebuildOptionsSchema;
+var FULL_OPTIMIZATION_PIPELINE = "rigid-v1", rebuildOptionsSchema;
var init_rebuild_options = __esm(() => {
rebuildOptionsSchema = z12.object({
indexPolicy: z12.enum(["indexed", "asBuilt"]).optional(),
gltfExporter: z12.enum(["legacy", "three"]),
geometryPolicy: z12.enum(["warn", "strict"]),
optimize: z12.enum(["off", "auto", "palette", "full"]),
+ optimizationPipeline: z12.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
instance: z12.enum(["off", "auto", "on"])
});
});
@@ -17598,7 +17599,7 @@ var init_architecture = __esm(() => {
scope: { kind: "category", category: "architecture" },
ruleClass: "exact",
owner: KILN_ENGINE_QA_OWNER,
- promotion: conformancePromotionAuthorization("architecture-qa-v1", "src/qa/architecture.test.ts", "c3a3bdc764c62238cede39813995fcaa428131d0aa3774bcd86cfc8b60f36671"),
+ promotion: conformancePromotionAuthorization("architecture-qa-v1", "src/qa/architecture.test.ts", "ce42ab6baef737d109f272413d902ea0903bd66c4da13ea723a52aff2f9e6c66", KILN_ENGINE_QA_OWNER, "2026-10-03T05:45:42.000Z", "enforce", "cpu-raster:0.10.0"),
defaultMode: "enforce",
evaluate: (context) => evaluateArchitectureQa(context).filter((finding) => finding.disposition === "block")
};
@@ -24807,6 +24808,507 @@ var init_material_metrics = __esm(() => {
});
});
+// src/rigid-merge.ts
+import {
+ ComponentTypeToTypedArray,
+ Primitive,
+ PropertyType as PropertyType3
+} from "@gltf-transform/core";
+import { createTransform, dequantizePrimitive, joinPrimitives } from "@gltf-transform/functions";
+import * as THREE37 from "three";
+function isSingular(matrix) {
+ const e = matrix.elements;
+ const scale = Math.hypot(e[0], e[1], e[2]) * Math.hypot(e[4], e[5], e[6]) * Math.hypot(e[8], e[9], e[10]);
+ const det = matrix.determinant();
+ return !Number.isFinite(det) || Math.abs(det) <= 0.000000001 * scale;
+}
+function findRigidBoundaries(doc, keep) {
+ const root = doc.getRoot();
+ const found = new Map;
+ const add = (node, reason) => {
+ const reasons = found.get(node) ?? [];
+ if (!reasons.includes(reason))
+ reasons.push(reason);
+ found.set(node, reasons);
+ };
+ for (const animation of root.listAnimations())
+ for (const channel of animation.listChannels()) {
+ const target = channel.getTargetNode();
+ if (target)
+ add(target, "animated");
+ }
+ for (const skin of root.listSkins())
+ for (const joint of skin.listJoints())
+ add(joint, "skin-joint");
+ const targets = new Set;
+ for (const node of root.listNodes()) {
+ const semantic = node.getExtras()[KILN_SEMANTIC_EXTRAS_KEY];
+ if (Array.isArray(semantic?.relationships)) {
+ for (const relationship of semantic.relationships)
+ if (relationship?.targetType === "node" && typeof relationship.target === "string")
+ targets.add(relationship.target);
+ }
+ }
+ for (const node of root.listNodes()) {
+ const name = node.getName();
+ const sceneParents = node.listParents().filter((parent) => parent.propertyType === PropertyType3.SCENE).length;
+ if (sceneParents > 1)
+ add(node, "shared-scene");
+ if (JOINT_PIVOT.test(name))
+ add(node, "joint-pivot");
+ if (hasKeys(node.getExtras()))
+ add(node, "extras");
+ if (targets.has(name))
+ add(node, "relationship-target");
+ if (node.getExtension("KHR_node_visibility"))
+ add(node, "visibility");
+ const lod = node.getExtension(MSFT_LOD);
+ if (lod) {
+ add(node, "lod");
+ for (const level of lod.listLevels())
+ if (level.propertyType === PropertyType3.NODE)
+ add(level, "lod");
+ }
+ if (keep.has(name))
+ add(node, "kept");
+ }
+ return found;
+}
+function nodeLock(node, mesh, world, expandShared) {
+ if (node.getSkin())
+ return "skinned";
+ if (node.getExtension("EXT_mesh_gpu_instancing"))
+ return "instanced";
+ if (hasKeys(mesh.getExtras()))
+ return "mesh-extras";
+ if (!expandShared && nodeUsers(mesh) > 1)
+ return "shared-mesh";
+ if (isSingular(world))
+ return "singular-matrix";
+ return;
+}
+function primLock(prim, mergeTransparent) {
+ if (prim.listTargets().length > 0)
+ return "morph-targets";
+ if (RESTART_MODES.has(prim.getMode()))
+ return "primitive-mode";
+ if (prim.listExtensions().length > 0)
+ return "primitive-extensions";
+ if (hasKeys(prim.getExtras()))
+ return "primitive-extras";
+ if (!prim.getAttribute("POSITION"))
+ return "no-position";
+ const material = prim.getMaterial();
+ if (material?.getExtension("KHR_materials_volume"))
+ return "volume";
+ if (!mergeTransparent && material && (material.getAlphaMode() === "BLEND" || material.getExtension("KHR_materials_transmission") || material.getExtension("KHR_materials_diffuse_transmission")))
+ return "transparent";
+ return;
+}
+function bucketKey(prim, materials, handedness) {
+ const layout = prim.listSemantics().sort().map((semantic) => {
+ const a = prim.getAttribute(semantic);
+ return `${semantic}:${a.getElementSize()}:${a.getComponentType()}:${a.getNormalized()}`;
+ }).join("+");
+ const hand = handedness !== null && prim.getAttribute("TANGENT") ? `|${handedness}` : "";
+ return `${materials.get(prim.getMaterial()) ?? -1}|${prim.getMode()}|${!!prim.getIndices()}|${layout}${hand}`;
+}
+function reverseWinding(prim) {
+ const indices = prim.getIndices()?.getArray();
+ const swap = (array, size, i) => {
+ for (let k = 0;k < size; k++) {
+ const [j, l] = [(i + 1) * size + k, (i + 2) * size + k];
+ [array[j], array[l]] = [array[l], array[j]];
+ }
+ };
+ if (indices) {
+ for (let i = 0;i + 2 < indices.length; i += 3)
+ swap(indices, 1, i);
+ return;
+ }
+ for (const semantic of prim.listSemantics()) {
+ const attribute = prim.getAttribute(semantic);
+ for (let i = 0;i + 2 < attribute.getCount(); i += 3)
+ swap(attribute.getArray(), attribute.getElementSize(), i);
+ }
+}
+function bake(prim, matrix) {
+ const linear = new THREE37.Matrix3().setFromMatrix4(matrix);
+ const normalMatrix = new THREE37.Matrix3().getNormalMatrix(matrix);
+ const mirrored = matrix.determinant() < 0;
+ const v = new THREE37.Vector3;
+ const each = (semantic, apply) => {
+ const attribute = prim.getAttribute(semantic);
+ const element = [];
+ for (let i = 0;i < (attribute?.getCount() ?? 0); i++) {
+ apply(attribute.getElement(i, element));
+ attribute.setElement(i, element);
+ }
+ };
+ each("POSITION", (e) => v.fromArray(e).applyMatrix4(matrix).toArray(e));
+ each("NORMAL", (e) => v.fromArray(e).applyMatrix3(normalMatrix).normalize().toArray(e));
+ each("TANGENT", (e) => {
+ v.fromArray(e).applyMatrix3(linear).normalize().toArray(e);
+ if (mirrored)
+ e[3] = -e[3];
+ });
+ if (mirrored && prim.getMode() === Primitive.Mode.TRIANGLES)
+ reverseWinding(prim);
+}
+function destinationOf(entries) {
+ let chosen = entries[0].node;
+ let best = Infinity;
+ let bestScale = Infinity;
+ for (const { node } of entries) {
+ const linear = new THREE37.Matrix3().setFromMatrix4(worldOf(node));
+ const norm = Math.hypot(...linear.elements);
+ const inverseNorm = Math.hypot(...linear.clone().invert().elements);
+ const condition = norm * inverseNorm;
+ const scale = Math.max(norm, inverseNorm);
+ if (condition < best * (1 - 0.000000000001) || Math.abs(condition - best) <= best * 0.000000000001 && scale < bestScale) {
+ chosen = node;
+ best = condition;
+ bestScale = scale;
+ }
+ }
+ return chosen;
+}
+function checkPositionPrecision(input, output, sourceWorld, destinationWorld, reversed) {
+ const expected = new THREE37.Vector3;
+ const actual = new THREE37.Vector3;
+ const bounds = new THREE37.Box3;
+ const element = [];
+ let error = 0;
+ let magnitude = 0;
+ for (let i = 0;i < input.getCount(); i++) {
+ const out = reversed ? i % 3 === 1 ? i + 1 : i % 3 === 2 ? i - 1 : i : i;
+ expected.fromArray(input.getElement(i, element)).applyMatrix4(sourceWorld);
+ actual.fromArray(output.getElement(out, element)).applyMatrix4(destinationWorld);
+ bounds.expandByPoint(expected);
+ error = Math.max(error, expected.distanceTo(actual));
+ magnitude = Math.max(magnitude, expected.length());
+ }
+ const tolerance = Math.max(bounds.getSize(expected).length() * 0.000001, magnitude * Number.EPSILON * 32, Number.EPSILON);
+ if (error > tolerance)
+ throw new Error("rigid merge: destination frame loses position precision");
+}
+function splitVertices(prim, created) {
+ if (prim.getAttribute("POSITION").getCount() <= MAX_VERTICES)
+ return [prim];
+ const width = prim.getMode() === Primitive.Mode.POINTS ? 1 : prim.getMode() === Primitive.Mode.LINES ? 2 : 3;
+ const sourceIndices = prim.getIndices()?.getArray();
+ const count = sourceIndices?.length ?? prim.getAttribute("POSITION").getCount();
+ if (count % width !== 0)
+ throw new Error("rigid merge: incomplete primitive element");
+ const chunks = [];
+ let remap = new Map;
+ let indices = [];
+ const flush = () => {
+ if (!indices.length)
+ return;
+ const chunk = prim.clone();
+ created.push(chunk);
+ const vertices = [...remap.keys()];
+ for (const semantic of prim.listSemantics()) {
+ const source = prim.getAttribute(semantic);
+ const size = source.getElementSize();
+ const ArrayType = ComponentTypeToTypedArray[source.getComponentType()];
+ if (!ArrayType)
+ throw new Error(`rigid merge: unsupported component type for ${semantic}`);
+ const data = new ArrayType(vertices.length * size);
+ const sourceData = source.getArray();
+ for (const [out, input] of vertices.entries())
+ data.set(sourceData.subarray(input * size, (input + 1) * size), out * size);
+ const attribute = source.clone().setArray(data);
+ created.push(attribute);
+ chunk.setAttribute(semantic, attribute);
+ }
+ if (prim.getIndices()) {
+ const accessor = prim.getIndices().clone().setArray(new Uint16Array(indices));
+ created.push(accessor);
+ chunk.setIndices(accessor);
+ }
+ chunks.push(chunk);
+ remap = new Map;
+ indices = [];
+ };
+ for (let offset = 0;offset < count; offset += width) {
+ const element = Array.from({ length: width }, (_, i) => sourceIndices?.[offset + i] ?? offset + i);
+ const extra = new Set(element.filter((index) => !remap.has(index))).size;
+ if (remap.size + extra > MAX_VERTICES)
+ flush();
+ for (const index of element) {
+ if (!remap.has(index))
+ remap.set(index, remap.size);
+ indices.push(remap.get(index));
+ }
+ }
+ flush();
+ for (const property of [prim, ...accessorsOf(prim)])
+ property.dispose();
+ return chunks;
+}
+function prepare(entries, dst, created) {
+ const destinationWorld = worldOf(dst);
+ const inverse = destinationWorld.clone().invert();
+ const copies = entries.map(({ node, prim }) => {
+ const copy = prim.clone();
+ created.push(copy);
+ for (const semantic of copy.listSemantics()) {
+ const attribute = copy.getAttribute(semantic).clone();
+ created.push(attribute);
+ copy.setAttribute(semantic, attribute);
+ }
+ const indices = copy.getIndices()?.clone();
+ if (indices) {
+ created.push(indices);
+ copy.setIndices(indices);
+ }
+ dequantizePrimitive(copy, { pattern: BAKED });
+ if (node !== dst) {
+ const sourceWorld = worldOf(node);
+ const matrix = inverse.clone().multiply(sourceWorld);
+ bake(copy, matrix);
+ const reversed = !copy.getIndices() && copy.getMode() === Primitive.Mode.TRIANGLES && matrix.determinant() < 0;
+ checkPositionPrecision(prim.getAttribute("POSITION"), copy.getAttribute("POSITION"), sourceWorld, destinationWorld, reversed);
+ }
+ return copy;
+ });
+ const merged = joinPrimitives(copies);
+ created.push(merged, ...accessorsOf(merged));
+ for (const semantic of ["POSITION", "NORMAL", "TANGENT"]) {
+ const array = merged.getAttribute(semantic)?.getArray();
+ if (array && !array.every(Number.isFinite))
+ throw new Error(`rigid merge: non-finite ${semantic} in the joined primitive`);
+ }
+ const elements = (p) => p.getIndices()?.getCount() ?? p.getAttribute("POSITION").getCount();
+ const expected = copies.reduce((sum, copy) => sum + elements(copy), 0);
+ if (elements(merged) !== expected)
+ throw new Error(`rigid merge: joined ${elements(merged)} of ${expected} elements`);
+ for (const copy of copies)
+ for (const property of [copy, ...accessorsOf(copy)])
+ property.dispose();
+ return splitVertices(merged, created);
+}
+function removableBytes(entries) {
+ const uses = new Map;
+ for (const { node, prim } of entries) {
+ const nodes = uses.get(prim) ?? new Set;
+ nodes.add(node);
+ uses.set(prim, nodes);
+ }
+ const removed = new Set;
+ for (const [prim, nodes] of uses) {
+ const retained = prim.listParents().some((parent) => {
+ if (parent.propertyType === PropertyType3.ROOT)
+ return false;
+ if (parent.propertyType !== PropertyType3.MESH)
+ return true;
+ return parent.listParents().some((user) => user.propertyType !== PropertyType3.ROOT && (user.propertyType !== PropertyType3.NODE || !nodes.has(user)));
+ });
+ if (!retained)
+ removed.add(prim);
+ }
+ const accessors = new Set([...removed].flatMap(accessorsOf));
+ let bytes = 0;
+ for (const accessor of accessors)
+ if (accessor.listParents().every((parent) => parent.propertyType === PropertyType3.ROOT || removed.has(parent)))
+ bytes += accessor.getArray()?.byteLength ?? 0;
+ return bytes;
+}
+function sceneNodes2(doc) {
+ const seen = new Set;
+ const visit = (node) => {
+ if (seen.has(node))
+ return;
+ seen.add(node);
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const scene of doc.getRoot().listScenes())
+ for (const child of scene.listChildren())
+ visit(child);
+ return seen;
+}
+function mergeRigidGroups(doc, options = {}) {
+ const root = doc.getRoot();
+ const keep = new Set(options.keep ?? []);
+ const nodes = sceneNodes2(doc);
+ const names = new Set([...nodes].map((node) => node.getName()));
+ const summary = {
+ primitivesBefore: countPrimitives(nodes),
+ primitivesAfter: 0,
+ groups: 0,
+ merges: 0,
+ boundaries: [],
+ locked: [],
+ rejected: [],
+ unmatchedKeep: [...keep].filter((name) => !names.has(name))
+ };
+ if (root.listAnimations().some((a) => a.listChannels().some((c) => !c.getTargetNode()))) {
+ summary.skipped = "unbounded-animation";
+ summary.primitivesAfter = summary.primitivesBefore;
+ return summary;
+ }
+ const boundaries = findRigidBoundaries(doc, keep);
+ const materials = new Map(root.listMaterials().map((m, i) => [m, i]));
+ const groups = [];
+ const locks = new Map;
+ const lock = (node, reason, primitives) => {
+ const key = `${node.getName()}|${reason}`;
+ const known = locks.get(key);
+ if (known)
+ known.primitives += primitives;
+ else {
+ const entry = { node: node.getName(), reason, primitives };
+ locks.set(key, entry);
+ summary.locked.push(entry);
+ }
+ };
+ const seen = new Set;
+ const visit = (node, parentGroup) => {
+ if (seen.has(node))
+ return;
+ seen.add(node);
+ const reasons = boundaries.get(node);
+ let group = parentGroup;
+ if (reasons) {
+ summary.boundaries.push({ node: node.getName(), reasons });
+ group = new Map;
+ groups.push(group);
+ }
+ const mesh = node.getMesh();
+ if (mesh) {
+ const world = worldOf(node);
+ const nodeReason = reasons ? "boundary" : nodeLock(node, mesh, world, options.expandSharedMeshes !== false);
+ const handedness = options.mergeMirroredTangents ? null : Math.sign(world.determinant());
+ if (nodeReason)
+ lock(node, nodeReason, mesh.listPrimitives().length);
+ else
+ for (const prim of mesh.listPrimitives()) {
+ const primReason = primLock(prim, options.mergeTransparent === true);
+ if (primReason)
+ lock(node, primReason, 1);
+ else {
+ const key = bucketKey(prim, materials, handedness);
+ const list = group.get(key);
+ if (list)
+ list.push({ node, prim });
+ else
+ group.set(key, [{ node, prim }]);
+ }
+ }
+ }
+ for (const child of node.listChildren())
+ visit(child, group);
+ };
+ for (const scene of root.listScenes()) {
+ const group = new Map;
+ groups.push(group);
+ for (const child of scene.listChildren())
+ visit(child, group);
+ }
+ summary.groups = groups.length;
+ const plans = [];
+ for (const group of groups)
+ for (const bucket of group.values()) {
+ let entries = bucket;
+ while (entries.length >= 2) {
+ const created = [];
+ const track = (event) => created.push(event.target);
+ doc.getGraph().addEventListener("node:create", track);
+ try {
+ const destination = destinationOf(entries);
+ const merged = prepare(entries, destination, created);
+ const savedDraws = entries.length - merged.length;
+ const shared = entries.filter((entry) => removableBytes([entry]) < primitiveBytes([entry.prim]));
+ const addedBytes = Math.max(0, primitiveBytes(merged) - removableBytes(entries));
+ if (savedDraws > 0 && addedBytes <= savedDraws * MAX_BYTES_PER_SAVED_DRAW) {
+ plans.push({ entries, destination, merged });
+ break;
+ }
+ for (const property of created)
+ property.dispose();
+ if (!shared.length || savedDraws <= 0)
+ break;
+ const costly = shared.reduce((best, entry) => primitiveBytes(entry.node.getMesh().listPrimitives()) > primitiveBytes(best.node.getMesh().listPrimitives()) ? entry : best);
+ const mesh = costly.node.getMesh();
+ for (const entry of entries.filter((entry) => entry.node.getMesh() === mesh))
+ lock(entry.node, "shared-byte-budget", 1);
+ entries = entries.filter((entry) => entry.node.getMesh() !== mesh);
+ } catch (error) {
+ for (const property of created)
+ property.dispose();
+ summary.rejected.push({
+ node: entries[0].node.getName(),
+ primitives: entries.length,
+ error: error instanceof Error ? error.message : String(error)
+ });
+ break;
+ } finally {
+ doc.getGraph().removeEventListener("node:create", track);
+ }
+ }
+ }
+ const owned = new Map;
+ const ownMesh = (node) => {
+ let mesh = owned.get(node);
+ if (mesh)
+ return mesh;
+ mesh = node.getMesh();
+ if (nodeUsers(mesh) > 1) {
+ mesh = mesh.clone();
+ node.setMesh(mesh);
+ }
+ owned.set(node, mesh);
+ return mesh;
+ };
+ const removed = new Set;
+ for (const { entries, destination, merged } of plans) {
+ for (const { node, prim } of entries) {
+ ownMesh(node).removePrimitive(prim);
+ removed.add(prim);
+ }
+ for (const primitive of merged)
+ ownMesh(destination).addPrimitive(primitive);
+ }
+ for (const [node, mesh] of owned)
+ if (mesh.listPrimitives().length === 0) {
+ node.setMesh(null);
+ if (nodeUsers(mesh) === 0)
+ mesh.dispose();
+ }
+ for (const prim of removed) {
+ if (prim.listParents().some((parent) => parent.propertyType === PropertyType3.MESH))
+ continue;
+ const accessors = accessorsOf(prim);
+ prim.dispose();
+ for (const accessor of accessors)
+ if (accessor.listParents().every((parent) => parent.propertyType === PropertyType3.ROOT))
+ accessor.dispose();
+ }
+ summary.merges = plans.length;
+ summary.primitivesAfter = countPrimitives(nodes);
+ return summary;
+}
+function rigidMerge(options = {}, onSummary) {
+ return createTransform("kilnRigidMerge", (doc) => {
+ const summary = mergeRigidGroups(doc, options);
+ onSummary?.(summary);
+ });
+}
+var JOINT_PIVOT, RESTART_MODES, BAKED, MAX_VERTICES = 65534, MAX_BYTES_PER_SAVED_DRAW = 4096, hasKeys = (value) => Object.keys(value).length > 0, worldOf = (node) => new THREE37.Matrix4().fromArray(node.getWorldMatrix()), nodeUsers = (mesh) => mesh.listParents().filter((parent) => parent.propertyType === PropertyType3.NODE).length, accessorsOf = (prim) => {
+ const indices = prim.getIndices();
+ return indices ? [...prim.listAttributes(), indices] : prim.listAttributes();
+}, primitiveBytes = (primitives) => [...new Set(primitives.flatMap(accessorsOf))].reduce((sum, a) => sum + (a.getArray()?.byteLength ?? 0), 0), countPrimitives = (nodes) => [...nodes].reduce((sum, node) => sum + (node.getMesh()?.listPrimitives().length ?? 0), 0);
+var init_rigid_merge = __esm(() => {
+ init_semantic();
+ init_gltf_io();
+ JOINT_PIVOT = /^joint[_-]/i;
+ RESTART_MODES = new Set([2, 3, 5, 6]);
+ BAKED = /^(POSITION|NORMAL|TANGENT)$/;
+});
+
// src/source-bindings.ts
import * as walk from "acorn-walk";
function sourceBindings(ast) {
@@ -26145,7 +26647,7 @@ var init_kit = __esm(() => {
// src/texture-bake.ts
import { createHash as createHash8 } from "node:crypto";
-import * as THREE37 from "three";
+import * as THREE38 from "three";
function readPixels(texture) {
const image = texture.image;
if (!image)
@@ -26237,7 +26739,7 @@ async function bakeSceneTextures(root, warnings) {
mime: "image/png",
bytes
};
- const colorSpace = entry.texture.colorSpace === THREE37.SRGBColorSpace ? "srgb" : "linear";
+ const colorSpace = entry.texture.colorSpace === THREE38.SRGBColorSpace ? "srgb" : "linear";
const recipe = entry.texture.userData["kilnProcedural"];
const primaryUsage = recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");
entry.texture.userData["kilnTexture"] = {
@@ -26318,10 +26820,10 @@ function computeTangentBasis(geometry) {
}
}
const out = new Float32Array(vertexCount * 4);
- const n = new THREE37.Vector3;
- const t = new THREE37.Vector3;
- const tmp = new THREE37.Vector3;
- const tmp2 = new THREE37.Vector3;
+ const n = new THREE38.Vector3;
+ const t = new THREE38.Vector3;
+ const tmp = new THREE38.Vector3;
+ const tmp2 = new THREE38.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]);
@@ -26341,7 +26843,7 @@ function computeTangentBasis(geometry) {
out[v * 4 + 2] = tmp.z;
out[v * 4 + 3] = w;
}
- geometry.setAttribute("tangent", new THREE37.BufferAttribute(out, 4));
+ geometry.setAttribute("tangent", new THREE38.BufferAttribute(out, 4));
}
function ensureNormalMapTangents(root, warnings) {
let count = 0;
@@ -26452,7 +26954,7 @@ var init_exporter_node = __esm(() => {
});
// src/views/character.ts
-import * as THREE38 from "three";
+import * as THREE39 from "three";
function rounded(value) {
const result = Math.round(value * 1e9) / 1e9;
return Object.is(result, -0) ? 0 : result;
@@ -26494,9 +26996,9 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {
const invalidPaths = new Set(invalidFindingNodePaths);
const joints = evidence.map((joint) => {
const relative = rootInverse.clone().multiply(joint.node.matrixWorld);
- const position = new THREE38.Vector3().setFromMatrixPosition(relative);
- const forward = new THREE38.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
- const bend = new THREE38.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const position = new THREE39.Vector3().setFromMatrixPosition(relative);
+ const forward = new THREE39.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const bend = new THREE39.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
const chainId = chainIdFor(joint.descriptor, descriptorByRole);
return {
role: joint.descriptor.role,
@@ -27457,13 +27959,13 @@ var init_architecture3 = __esm(() => {
// src/views/glb.ts
import {
- Primitive
+ Primitive as Primitive2
} from "@gltf-transform/core";
import {
BufferAttribute as BufferAttribute8,
BufferGeometry as BufferGeometry15,
Group as Group4,
- Matrix4 as Matrix413,
+ Matrix4 as Matrix414,
Mesh as Mesh12,
MeshStandardMaterial as MeshStandardMaterial5,
NoColorSpace as NoColorSpace4,
@@ -27473,7 +27975,7 @@ import {
QuaternionKeyframeTrack as QuaternionKeyframeTrack2,
VectorKeyframeTrack as VectorKeyframeTrack2,
Quaternion as Quaternion17,
- Vector3 as Vector331,
+ Vector3 as Vector332,
InterpolateDiscrete as InterpolateDiscrete2,
InterpolateLinear as InterpolateLinear2
} from "three";
@@ -27538,16 +28040,16 @@ 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:
+ case Primitive2.Mode.TRIANGLES:
return Uint32Array.from(source);
- case Primitive.Mode.TRIANGLE_STRIP: {
+ case Primitive2.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: {
+ case Primitive2.Mode.TRIANGLE_FAN: {
const triangles = [];
for (let index = 1;index + 1 < source.length; index++) {
triangles.push(source[index], source[index + 1], source[0]);
@@ -27625,7 +28127,7 @@ function noteMaterialTextures(material, reasons) {
}
}
function instanceMatrices(node) {
- const world = new Matrix413().fromArray(node.getWorldMatrix());
+ const world = new Matrix414().fromArray(node.getWorldMatrix());
const extension = node.getExtension("EXT_mesh_gpu_instancing");
if (!extension)
return { matrices: [world], count: 1 };
@@ -27648,7 +28150,7 @@ function instanceMatrices(node) {
translations?.getElement(index, translation);
rotations?.getElement(index, rotation);
scales?.getElement(index, scale);
- const local = new Matrix413().compose(new Vector331(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion17(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector331(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));
+ const local = new Matrix414().compose(new Vector332(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion17(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector332(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));
matrices.push(world.clone().multiply(local));
}
return { matrices, count };
@@ -27736,7 +28238,7 @@ async function loadGlbGeometryFlatScene(bytes) {
function localInstanceMatrices(node) {
const extension = node.getExtension("EXT_mesh_gpu_instancing");
if (!extension)
- return [new Matrix413];
+ return [new Matrix414];
const attributes = extension.listAttributes();
if (attributes.length === 0) {
throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", "Invalid empty instancing data.");
@@ -27755,7 +28257,7 @@ function localInstanceMatrices(node) {
translations?.getElement(index, translation);
rotations?.getElement(index, rotation);
scales?.getElement(index, scale);
- return new Matrix413().compose(new Vector331(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion17(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector331(...scales ? scale.slice(0, 3) : [1, 1, 1]));
+ return new Matrix414().compose(new Vector332(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion17(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector332(...scales ? scale.slice(0, 3) : [1, 1, 1]));
});
}
async function loadGlbReviewScene(bytes) {
@@ -28001,7 +28503,7 @@ var init_renderer_id = __esm(() => {
});
// src/views/scene-raster.ts
-import * as THREE39 from "three";
+import * as THREE40 from "three";
var DEG2;
var init_scene_raster = __esm(() => {
init_evaluator();
@@ -28012,18 +28514,18 @@ var init_scene_raster = __esm(() => {
});
// src/views/vehicle.ts
-import * as THREE40 from "three";
+import * as THREE41 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 THREE40.Box3;
+ const bounds = new THREE41.Box3;
let found = false;
root.traverse((node) => {
if (!hasRole2(node, "chassis"))
return;
node.traverse((part) => {
- if (!(part instanceof THREE40.Mesh) || !(part.geometry instanceof THREE40.BufferGeometry))
+ if (!(part instanceof THREE41.Mesh) || !(part.geometry instanceof THREE41.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const box = part.geometry.boundingBox;
@@ -28033,7 +28535,7 @@ function chassisBounds(root, inverse) {
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 THREE40.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE41.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -28101,33 +28603,33 @@ function tagDiagnostic(node, role) {
stampSemanticMetadataV1(node, { roles: [role] });
}
function rod(name, start, end, radius, color, role) {
- const from = new THREE40.Vector3(...start);
- const to = new THREE40.Vector3(...end);
+ const from = new THREE41.Vector3(...start);
+ const to = new THREE41.Vector3(...end);
const direction = to.clone().sub(from);
const length = direction.length();
- const geometry = length > 0.000000001 ? new THREE40.CylinderGeometry(radius, radius, length, 8) : new THREE40.SphereGeometry(radius, 8, 6);
- const result = new THREE40.Mesh(geometry, new THREE40.MeshBasicMaterial({ color }));
+ const geometry = length > 0.000000001 ? new THREE41.CylinderGeometry(radius, radius, length, 8) : new THREE41.SphereGeometry(radius, 8, 6);
+ const result = new THREE41.Mesh(geometry, new THREE41.MeshBasicMaterial({ color }));
result.name = name;
result.position.copy(from).add(to).multiplyScalar(0.5);
if (length > 0.000000001) {
- result.quaternion.setFromUnitVectors(new THREE40.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
+ result.quaternion.setFromUnitVectors(new THREE41.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
}
tagDiagnostic(result, role);
return result;
}
function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {
- const overlay = new THREE40.Group;
+ const overlay = new THREE41.Group;
overlay.name = "VehicleDiagnosticOverlay";
const chassisSpan = descriptor.chassisBox ? Math.max(descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0], descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1], descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2]) : 1;
const thickness = Math.max(0.01, chassisSpan * 0.008);
- const arrow = new THREE40.Group;
+ const arrow = new THREE41.Group;
arrow.name = "Diagnostic_Forward_+X";
tagDiagnostic(arrow, "diagnostic.vehicle.forward");
arrow.add(rod("Diagnostic_Forward_Shaft", descriptor.forwardArrow.start, [descriptor.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));
- const arrowHead = new THREE40.Mesh(new THREE40.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE40.MeshBasicMaterial({ color: 16724804 }));
+ const arrowHead = new THREE41.Mesh(new THREE41.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE41.MeshBasicMaterial({ color: 16724804 }));
arrowHead.name = "Diagnostic_Forward_Head";
arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);
- arrowHead.quaternion.setFromUnitVectors(new THREE40.Vector3(0, 1, 0), new THREE40.Vector3(1, 0, 0));
+ arrowHead.quaternion.setFromUnitVectors(new THREE41.Vector3(0, 1, 0), new THREE41.Vector3(1, 0, 0));
tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");
arrow.add(arrowHead);
overlay.add(arrow);
@@ -28135,18 +28637,18 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));
}
for (const wheel of descriptor.wheels) {
- const ring = new THREE40.Mesh(new THREE40.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE40.MeshBasicMaterial({ color: 16763955 }));
+ const ring = new THREE41.Mesh(new THREE41.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE41.MeshBasicMaterial({ color: 16763955 }));
ring.name = `Diagnostic_Wheel_${wheel.id}`;
ring.position.set(...wheel.center);
- const axle = new THREE40.Vector3(...wheel.axle);
+ const axle = new THREE41.Vector3(...wheel.axle);
if (axle.lengthSq() > 0.000000000001) {
- ring.quaternion.setFromUnitVectors(new THREE40.Vector3(0, 0, 1), axle.normalize());
+ ring.quaternion.setFromUnitVectors(new THREE41.Vector3(0, 0, 1), axle.normalize());
}
tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);
overlay.add(ring);
}
if (descriptor.chassisBox) {
- const chassis = new THREE40.Group;
+ const chassis = new THREE41.Group;
chassis.name = "Diagnostic_ChassisBox";
tagDiagnostic(chassis, "diagnostic.vehicle.chassis");
const { min, max } = descriptor.chassisBox;
@@ -28180,7 +28682,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(chassis);
}
if (descriptor.supportPlaneY !== undefined) {
- const plane = new THREE40.Group;
+ const plane = new THREE41.Group;
plane.name = "Diagnostic_SupportPlane";
tagDiagnostic(plane, "diagnostic.vehicle.support-plane");
const halfX = Math.max(1, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;
@@ -28778,7 +29280,7 @@ var init_views = __esm(() => {
});
// src/views/character-capture.ts
-import * as THREE41 from "three";
+import * as THREE42 from "three";
function drawLine2(rgb, width, height, from, to, color) {
let x0 = Math.round(from[0]);
let y0 = Math.round(from[1]);
@@ -28815,22 +29317,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {
}
function projector(root, cameraId, size) {
root.updateMatrixWorld(true);
- const bounds = new THREE41.Box3().setFromObject(root);
+ const bounds = new THREE42.Box3().setFromObject(root);
if (bounds.isEmpty())
- bounds.set(new THREE41.Vector3(-0.5, 0, -0.5), new THREE41.Vector3(0.5, 1, 0.5));
- const center = bounds.getCenter(new THREE41.Vector3);
- const camera = cameraId === "front" ? new THREE41.Vector3(1, 0, 0) : new THREE41.Vector3(0, 0, 1);
- const upHint = new THREE41.Vector3(0, 1, 0);
- const xAxis = new THREE41.Vector3().crossVectors(upHint, camera).normalize();
- const yAxis = new THREE41.Vector3().crossVectors(camera, xAxis).normalize();
+ bounds.set(new THREE42.Vector3(-0.5, 0, -0.5), new THREE42.Vector3(0.5, 1, 0.5));
+ const center = bounds.getCenter(new THREE42.Vector3);
+ const camera = cameraId === "front" ? new THREE42.Vector3(1, 0, 0) : new THREE42.Vector3(0, 0, 1);
+ const upHint = new THREE42.Vector3(0, 1, 0);
+ const xAxis = new THREE42.Vector3().crossVectors(upHint, camera).normalize();
+ const yAxis = new THREE42.Vector3().crossVectors(camera, xAxis).normalize();
let extent = 0.000001;
for (let corner = 0;corner < 8; corner++) {
- const point = new THREE41.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);
+ const point = new THREE42.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);
extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));
}
const scale = size * 0.45 / extent;
return (assetPoint) => {
- const world = new THREE41.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
+ const world = new THREE42.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];
};
}
@@ -28956,19 +29458,10 @@ var init_character_capture = __esm(() => {
});
// src/render.ts
-import * as THREE42 from "three";
-import { Document } from "@gltf-transform/core";
+import * as THREE43 from "three";
+import { Document, Logger } from "@gltf-transform/core";
import { KHRMaterialsEmissiveStrength } from "@gltf-transform/extensions";
-import {
- dedup,
- instance,
- palette,
- flatten,
- join,
- weld,
- prune,
- mergeDocuments
-} from "@gltf-transform/functions";
+import { dedup, instance, palette, weld, prune, mergeDocuments } from "@gltf-transform/functions";
function hiddenTriangles(root, lowerLevels) {
let hidden = 0;
const visit = (node) => {
@@ -29129,7 +29622,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras) {
} else if (stdMat.transparent) {
mat.setAlphaMode("BLEND");
}
- if (stdMat.side === THREE42.DoubleSide) {
+ if (stdMat.side === THREE43.DoubleSide) {
mat.setDoubleSided(true);
}
if (stdMat.map) {
@@ -29196,7 +29689,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras) {
} else if (common.transparent || (common.opacity ?? 1) < 1) {
mat.setAlphaMode("BLEND");
}
- if (threeMat.side === THREE42.DoubleSide)
+ if (threeMat.side === THREE43.DoubleSide)
mat.setDoubleSided(true);
if (common.map && !mat.getBaseColorTexture()) {
const texture = bridgeTexture(doc, common.map, textureCache);
@@ -29331,7 +29824,7 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache,
const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;
let gtMesh = meshCache.get(cacheKey);
if (!gtMesh) {
- const geometry = new THREE42.PlaneGeometry(1, 1);
+ const geometry = new THREE43.PlaneGeometry(1, 1);
if (centerX !== 0.5 || centerY !== 0.5) {
geometry.translate(0.5 - centerX, 0.5 - centerY, 0);
}
@@ -29355,9 +29848,9 @@ function animationInterpolation(track) {
if (isCubicSplineTrack(track))
return "CUBICSPLINE";
const mode = track.getInterpolation();
- if (mode === THREE42.InterpolateDiscrete)
+ if (mode === THREE43.InterpolateDiscrete)
return "STEP";
- if (mode === THREE42.InterpolateLinear)
+ if (mode === THREE43.InterpolateLinear)
return "LINEAR";
throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);
}
@@ -29521,27 +30014,41 @@ async function applyGpuInstancing(doc, mode, role) {
const after = collectGlbMetrics(doc);
return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };
}
-async function consolidateMaterials(doc, mode) {
+async function consolidateMaterials(doc, mode, keep = []) {
+ doc.setLogger(new Logger(Logger.Verbosity.WARN));
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 || hasNodeLevelsOfDetail(doc) || hasPreservedNodeState(doc)) ? "palette" : mode;
const steps = root.listMaterials().some((material) => Object.keys(material.getExtras()).length > 0) ? [] : [palette({ min: PALETTE_MIN })];
- if (effective === "full") {
- steps.push(flatten(), join({ keepNamed: true }));
- }
+ let merge;
+ if (mode === "full")
+ steps.push(rigidMerge({ keep }, (summary) => {
+ merge = summary;
+ }));
steps.push(weld(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));
await doc.transform(...steps);
const after = collectGlbMetrics(doc);
return {
- mode: effective,
+ mode,
materialsBefore: before.uniqueMaterials,
materialsAfter: after.uniqueMaterials,
drawsBefore: before.drawCalls,
- drawsAfter: after.drawCalls
+ drawsAfter: after.drawCalls,
+ ...merge ? { rigidMerge: merge } : {}
};
}
+function optimizeWarnings(summary) {
+ const merge = summary.rigidMerge;
+ if (!merge)
+ return [];
+ const warnings = [];
+ if (merge.skipped)
+ warnings.push(`Rigid merge skipped: ${merge.skipped}; geometry left separate.`);
+ if (merge.rejected.length)
+ warnings.push(`Rigid merge retained ${merge.rejected.length} rejected buckets; first: ${merge.rejected[0].error}`);
+ if (merge.unmatchedKeep.length)
+ warnings.push(`Rigid merge did not find ${merge.unmatchedKeep.length} requested boundary names.`);
+ return warnings;
+}
async function renderSceneToGLB(root, opts = {}) {
assertNoLegacyRuntimePolicy(opts);
const requirements = resolveRequirementsContext(opts.requirements);
@@ -29637,6 +30144,7 @@ async function renderSceneToGLB(root, opts = {}) {
if (effectiveOptimize !== "off") {
try {
optimize = await consolidateMaterials(doc, effectiveOptimize);
+ warnings.push(...optimizeWarnings(optimize));
} catch (err) {
warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);
}
@@ -29740,6 +30248,7 @@ async function renderGLBInProcess(code, opts = {}) {
gltfExporter: resolveGltfExporter(opts.gltfExporter),
geometryPolicy: opts.geometryPolicy ?? "warn",
optimize: resolveOptimize(opts.optimize),
+ ...resolveOptimize(opts.optimize) === "full" ? { optimizationPipeline: FULL_OPTIMIZATION_PIPELINE } : {},
instance: resolveInstance(opts.instance)
};
let materialLibraryDependencies;
@@ -29855,8 +30364,8 @@ function collectMeshStats(root) {
if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {
return;
}
- const center = new THREE42.Vector3;
- const size = new THREE42.Vector3;
+ const center = new THREE43.Vector3;
+ const size = new THREE43.Vector3;
box.getCenter(center);
box.getSize(size);
out.push({
@@ -29871,7 +30380,7 @@ function collectMeshStats(root) {
return out;
}
function minimalGapVector(a, b) {
- const v = new THREE42.Vector3;
+ const v = new THREE43.Vector3;
for (const axis of ["x", "y", "z"]) {
if (a.min[axis] > b.max[axis])
v[axis] = b.max[axis] - a.min[axis];
@@ -29889,10 +30398,10 @@ function inspectSceneStructure(root, opts = {}) {
return warnings;
const cat = opts.category?.toLowerCase();
if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {
- const all = new THREE42.Box3;
+ const all = new THREE43.Box3;
for (const m of meshes)
all.union(m.box);
- const size = new THREE42.Vector3;
+ const size = new THREE43.Vector3;
all.getSize(size);
if (cat === "aircraft") {
if (size.y > size.x * 1.2) {
@@ -29985,6 +30494,8 @@ var init_render = __esm(() => {
init_material_recipe_runtime();
init_material_resources();
init_texture_resolver();
+ init_rebuild_options();
+ init_rigid_merge();
init_validation();
init_kit();
init_texture_bake();
@@ -30055,6 +30566,10 @@ var init_protocol = __esm(() => {
});
// src/asset-export.ts
+var exports_asset_export = {};
+__export(exports_asset_export, {
+ exportAssetGlb: () => exportAssetGlb
+});
async function sha2562(bytes) {
const digest = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));
return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
@@ -30408,12 +30923,12 @@ var exports_part_placement = {};
__export(exports_part_placement, {
createPartPlacementReader: () => createPartPlacementReader
});
-import * as THREE43 from "three";
+import * as THREE44 from "three";
function createPartPlacementReader(root) {
const bounds = createPartBoundsReader(root);
- const position = new THREE43.Vector3;
- const quaternion = new THREE43.Quaternion;
- const scale = new THREE43.Vector3;
+ const position = new THREE44.Vector3;
+ const quaternion = new THREE44.Quaternion;
+ const scale = new THREE44.Vector3;
return (node) => {
node.matrixWorld.decompose(position, quaternion, scale);
const box = bounds(node);
@@ -30564,13 +31079,13 @@ var init_inspect = __esm(() => {
});
// src/views/measurement.ts
-import { Box3 as Box322, Vector3 as Vector336 } from "three";
+import { Box3 as Box323, Vector3 as Vector337 } from "three";
function describeSubjectFrame(root, subject) {
const selected = selectCameraSubject(root, subject);
selected.node.updateWorldMatrix(true, true);
const matrix = selected.node.matrixWorld;
- const bounds = new Box322().setFromObject(selected.node);
- const local = new Box322;
+ const bounds = new Box323().setFromObject(selected.node);
+ const local = new Box323;
const invertible = matrix.determinant() !== 0;
const inverse = matrix.clone().invert();
selected.node.traverse((node) => {
@@ -30581,10 +31096,10 @@ function describeSubjectFrame(root, subject) {
if (!attr)
return;
for (let i = 0;i < attr.count; i++)
- local.expandByPoint(new Vector336().fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse));
+ local.expandByPoint(new Vector337().fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse));
});
const box = (b) => b.isEmpty() ? null : { min: b.min.toArray(), max: b.max.toArray() };
- const axis = (i) => new Vector336().setFromMatrixColumn(matrix, i).normalize().toArray();
+ const axis = (i) => new Vector337().setFromMatrixColumn(matrix, i).normalize().toArray();
return {
path: selected.path,
name: selected.name,
@@ -30594,7 +31109,7 @@ function describeSubjectFrame(root, subject) {
invertible,
worldMatrix: matrix.toArray(),
axes: { frame: "world", x: axis(0), y: axis(1), z: axis(2) },
- origin: new Vector336().setFromMatrixPosition(matrix).toArray()
+ origin: new Vector337().setFromMatrixPosition(matrix).toArray()
};
}
function measureAttachment(root, input) {
@@ -30607,7 +31122,7 @@ function measureAttachment(root, input) {
return {
path: selected.path,
local: [...local],
- world: new Vector336(...local).applyMatrix4(selected.node.matrixWorld).toArray()
+ world: new Vector337(...local).applyMatrix4(selected.node.matrixWorld).toArray()
};
};
const from = endpoint(input.from), to = endpoint(input.to);
@@ -30617,7 +31132,7 @@ function measureAttachment(root, input) {
method: "straight-line anchor distance",
from,
to,
- distance: new Vector336(...from.world).distanceTo(new Vector336(...to.world))
+ distance: new Vector337(...from.world).distanceTo(new Vector337(...to.world))
};
}
var init_measurement = __esm(() => {
@@ -30626,10 +31141,10 @@ var init_measurement = __esm(() => {
// src/revision-comparison.ts
import {
- PropertyType as PropertyType3
+ PropertyType as PropertyType4
} from "@gltf-transform/core";
import { ALL_EXTENSIONS as ALL_EXTENSIONS2 } from "@gltf-transform/extensions";
-import { Box3 as Box323, Matrix4 as Matrix414, Vector3 as Vector337 } from "three";
+import { Box3 as Box324, Matrix4 as Matrix415, Vector3 as Vector338 } from "three";
async function accessorFingerprint(accessor) {
const array = accessor?.getArray();
if (!accessor || !array)
@@ -30642,13 +31157,13 @@ async function accessorFingerprint(accessor) {
];
}
function lowerLevels(node) {
- return (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType3.NODE);
+ return (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType4.NODE);
}
function bounds(box) {
return box.isEmpty() ? null : {
min: box.min.toArray(),
max: box.max.toArray(),
- size: box.getSize(new Vector337).toArray()
+ size: box.getSize(new Vector338).toArray()
};
}
async function digest3(bytes) {
@@ -30682,7 +31197,7 @@ async function snapshot3(bytes) {
if (depth > 128)
throw new Error("Revision comparison hierarchy exceeds 128 levels.");
const names = new Set;
- const combined = new Box323;
+ const combined = new Box324;
const placed = siblings.flatMap((node) => [
{ node, drawn: true },
...lowerLevels(node).map((level) => ({ node: level, drawn: false }))
@@ -30699,8 +31214,8 @@ async function snapshot3(bytes) {
if (node.listExtensions().some((extension) => extension.extensionName !== MSFT_LOD && extension.extensionName !== "KHR_node_visibility") || mesh?.listExtensions().length)
throw new Error("Revision comparison does not support node/mesh extensions (including instancing).");
const primitives = mesh?.listPrimitives() ?? [];
- const own = new Box323;
- const matrix = parentWorld.clone().multiply(new Matrix414().fromArray(node.getMatrix()));
+ const own = new Box324;
+ const matrix = parentWorld.clone().multiply(new Matrix415().fromArray(node.getMatrix()));
if (matrix.elements.some((value) => !Number.isFinite(value)))
throw new Error("Revision comparison requires finite transforms.");
for (const primitive of primitives) {
@@ -30712,7 +31227,7 @@ async function snapshot3(bytes) {
const indices = primitive.getIndices();
const count = indices?.getCount() ?? position.getCount();
vertices += count;
- if (vertices > MAX_VERTICES)
+ if (vertices > MAX_VERTICES2)
throw new Error("Revision comparison exceeds 2,000,000 placed vertices.");
const element = [0, 0, 0];
for (let index = 0;index < count; index++) {
@@ -30720,7 +31235,7 @@ async function snapshot3(bytes) {
if (!Number.isInteger(vertex) || vertex < 0 || vertex >= position.getCount())
throw new Error("Revision comparison found an invalid vertex index.");
position.getElement(vertex, element);
- const point = new Vector337(...element).applyMatrix4(matrix);
+ const point = new Vector338(...element).applyMatrix4(matrix);
if (point.toArray().some((value) => !Number.isFinite(value)))
throw new Error("Revision comparison requires finite positions.");
own.expandByPoint(point);
@@ -30739,7 +31254,7 @@ async function snapshot3(bytes) {
if (scenes[0].listExtensions().length)
throw new Error("Revision comparison does not support scene extensions.");
const scenePath = `/${encodeURIComponent(scenes[0].getName() || "Scene")}[0]`;
- const box = visit(scenes[0].listChildren(), "", 0, new Matrix414);
+ const box = visit(scenes[0].listChildren(), "", 0, new Matrix415);
const nodePaths = new Map([...parts].map(([path, part]) => [part.node, path]));
const animation = new Map;
const clipNames = new Set;
@@ -30899,7 +31414,7 @@ async function compareRevisionGlbs(before, after, page = {}) {
nextOffset: offset + limit < changes.length ? offset + limit : null
};
}
-var MAX_GLB_BYTES, MAX_NODES = 1e4, MAX_VERTICES = 2000000, ACCESSOR_IGNORED, MATERIAL_IGNORED;
+var MAX_GLB_BYTES, MAX_NODES = 1e4, MAX_VERTICES2 = 2000000, ACCESSOR_IGNORED, MATERIAL_IGNORED;
var init_revision_comparison = __esm(() => {
init_gltf_io();
init_metrics();
@@ -30910,20 +31425,20 @@ var init_revision_comparison = __esm(() => {
// src/views/surface-distance.ts
import {
- Box3 as Box324,
- Matrix4 as Matrix415,
+ Box3 as Box325,
+ Matrix4 as Matrix416,
Ray,
Triangle as Triangle2,
- Vector3 as Vector338
+ Vector3 as Vector339
} from "three";
function hierarchy(triangles) {
- const box = new Box324;
+ const box = new Box325;
for (const triangle of triangles)
box.union(triangle.box);
const count = triangles.length;
if (count <= 4)
return { box, count, triangles };
- const size = box.getSize(new Vector338);
+ const size = box.getSize(new Vector339);
const axis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";
const center = (triangle) => triangle.box.min[axis] / 2 + triangle.box.max[axis] / 2;
triangles.sort((a, b) => center(a) - center(b));
@@ -30942,7 +31457,7 @@ function boxDistanceSquared(a, b) {
}
function collect(node, paths) {
const triangles = [];
- const bounds = new Box324;
+ const bounds = new Box325;
node.updateWorldMatrix(true, true);
node.traverseVisible((child) => {
const mesh = child;
@@ -30966,7 +31481,7 @@ function collect(node, paths) {
for (let instance = 0;instance < instances; instance++) {
const matrix = mesh.matrixWorld.clone();
if (instanced.isInstancedMesh) {
- const local = new Matrix415;
+ const local = new Matrix416;
instanced.getMatrixAt(instance, local);
matrix.multiply(local);
}
@@ -30975,13 +31490,13 @@ function collect(node, paths) {
const id = index ? index.getX(i + offset) : i + offset;
if (!Number.isSafeInteger(id) || id < 0 || id >= position.count)
throw new Error("Surface distance encountered an invalid triangle index.");
- const point = new Vector338().fromBufferAttribute(position, id).applyMatrix4(matrix);
+ const point = new Vector339().fromBufferAttribute(position, id).applyMatrix4(matrix);
if (![point.x, point.y, point.z].every(Number.isFinite))
throw new Error("Surface distance encountered a non-finite world position.");
return point;
};
const triangle = new Triangle2(vertex(0), vertex(1), vertex(2));
- const box = new Box324().setFromPoints([triangle.a, triangle.b, triangle.c]);
+ const box = new Box325().setFromPoints([triangle.a, triangle.b, triangle.c]);
bounds.union(box);
triangles.push({
triangle,
@@ -31034,10 +31549,10 @@ function trianglePair(a, b) {
const av = [a.a, a.b, a.c], bv = [b.a, b.b, b.c];
if (b.getArea() > 0)
for (const p of av)
- record(p, b.closestPointToPoint(p, new Vector338));
+ record(p, b.closestPointToPoint(p, new Vector339));
if (a.getArea() > 0)
for (const q of bv)
- record(a.closestPointToPoint(q, new Vector338), q);
+ record(a.closestPointToPoint(q, new Vector339), q);
for (let i = 0;i < 3; i++) {
const p = av[i], q = av[(i + 1) % 3];
for (let j = 0;j < 3; j++)
@@ -31050,9 +31565,9 @@ function trianglePair(a, b) {
const length = delta.length();
if (length === 0)
continue;
- const hit = new Ray(origin, delta.divideScalar(length)).intersectTriangle(target.a, target.b, target.c, false, new Vector338);
+ const hit = new Ray(origin, delta.divideScalar(length)).intersectTriangle(target.a, target.b, target.c, false, new Vector339);
if (hit && origin.distanceTo(hit) <= length) {
- const onFace = target.closestPointToPoint(hit, new Vector338);
+ const onFace = target.closestPointToPoint(hit, new Vector339);
if (vertices === av)
record(hit, onFace);
else
@@ -31211,6 +31726,221 @@ var init_surface_distance = __esm(() => {
init_camera();
});
+// src/draw-diagnostics.ts
+var exports_draw_diagnostics = {};
+__export(exports_draw_diagnostics, {
+ inspectDrawDiagnostics: () => inspectDrawDiagnostics
+});
+import { Primitive as Primitive3 } from "@gltf-transform/core";
+import { cloneDocument } from "@gltf-transform/functions";
+import * as THREE45 from "three";
+function withinLimits(doc) {
+ const root = doc.getRoot();
+ if (root.listNodes().length > MAX_NODES2 || root.listAccessors().length > 4096 || root.listMaterials().length > 2048 || root.listTextures().length > 256 || root.listScenes().length > 32 || doc.getGraph().listEdges().length > 32768)
+ return false;
+ let bytes = root.listAccessors().reduce((n, a) => n + (a.getArray()?.byteLength ?? 0), 0) + root.listTextures().reduce((n, t) => n + (t.getImage()?.byteLength ?? 0), 0);
+ let uses = 0;
+ let vertices = 0;
+ const walk = (node, depth) => {
+ if (depth > 128)
+ return false;
+ for (const p of node.getMesh()?.listPrimitives() ?? []) {
+ uses++;
+ vertices += p.getAttribute("POSITION")?.getCount() ?? 0;
+ bytes += p.listAttributes().reduce((n, a) => n + (a.getArray()?.byteLength ?? 0), 0) + (p.getIndices()?.getArray()?.byteLength ?? 0);
+ }
+ return uses <= MAX_USES && vertices <= MAX_VERTICES3 && bytes <= MAX_BYTES && node.listChildren().every((n) => walk(n, depth + 1));
+ };
+ return bytes <= MAX_BYTES && root.listScenes().every((s) => s.listChildren().every((n) => walk(n, 0)));
+}
+function collect2(doc, keep) {
+ const root = doc.getRoot();
+ const boundaries = findRigidBoundaries(doc, new Set(keep));
+ const nodeIds = new Map(root.listNodes().map((n, i) => [n, i]));
+ const anchors = new Map;
+ const uses = [];
+ for (const [sceneIndex, scene] of root.listScenes().entries()) {
+ const id = `scene:${sceneIndex}`;
+ const initial = { id, name: nameOf(scene.getName() || "Scene"), draws: 0, afterRigidMerge: 0 };
+ anchors.set(id, initial);
+ const walk = (node, anchor) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const part = { id: `${id}/node:${nodeIds.get(node)}`, name: nameOf(node.getName()) };
+ if (boundaries.has(node)) {
+ anchor = { ...part, draws: 0, afterRigidMerge: 0 };
+ anchors.set(part.id, anchor);
+ }
+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
+ anchor.draws++;
+ uses.push({ node, primitive, part });
+ }
+ for (const child of node.listChildren())
+ walk(child, anchor);
+ };
+ for (const child of scene.listChildren())
+ walk(child, initial);
+ }
+ return { anchors, uses };
+}
+function overlaps(a, b) {
+ if (Math.abs(a.normal.dot(b.normal)) < 1 - 0.00000001 || !a.bounds.intersectsBox(b.bounds))
+ return false;
+ const tolerance = Math.max(a.bounds.getSize(new THREE45.Vector3).length(), b.bounds.getSize(new THREE45.Vector3).length(), 0.000000000001) * 0.000001;
+ if (b.points.some((p) => Math.abs(a.normal.dot(p.clone().sub(a.points[0]))) > tolerance))
+ return false;
+ const normal = a.normal.toArray().map(Math.abs);
+ const drop = normal.indexOf(Math.max(...normal));
+ const project = (p) => p.toArray().filter((_, i) => i !== drop);
+ const clip = a.points.map(project);
+ if (cross22(clip[0], clip[1], clip[2]) < 0)
+ clip.reverse();
+ let polygon = b.points.map(project);
+ for (let i = 0;i < 3 && polygon.length; i++) {
+ const x = clip[i], y = clip[(i + 1) % 3];
+ const output = [];
+ for (let j = 0;j < polygon.length; j++) {
+ const p = polygon[j], q = polygon[(j + 1) % polygon.length];
+ const dp = cross22(x, y, p), dq = cross22(x, y, q);
+ if (dp >= 0)
+ output.push(p);
+ if (dp >= 0 !== dq >= 0) {
+ const t = dp / (dp - dq);
+ output.push([p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])]);
+ }
+ }
+ polygon = output;
+ }
+ let area = 0;
+ for (let i = 0;i < polygon.length; i++) {
+ const p = polygon[i], q = polygon[(i + 1) % polygon.length];
+ area += p[0] * q[1] - p[1] * q[0];
+ }
+ return Math.abs(area) / 2 > tolerance * tolerance;
+}
+function observe(uses) {
+ const mirrored = new Map;
+ const samples = [];
+ let eligibleTriangles = 0;
+ let unexaminedPrimitiveUses = 0;
+ for (const { node, primitive, part } of uses) {
+ if (node.getSkin() || node.getExtension("EXT_mesh_gpu_instancing") || primitive.listTargets().length) {
+ unexaminedPrimitiveUses++;
+ continue;
+ }
+ const matrix = new THREE45.Matrix4().fromArray(node.getWorldMatrix());
+ if (primitive.getAttribute("TANGENT") && matrix.determinant() < 0)
+ mirrored.set(part.id, part);
+ const position = primitive.getAttribute("POSITION");
+ if (!position || primitive.getMode() !== Primitive3.Mode.TRIANGLES) {
+ unexaminedPrimitiveUses++;
+ continue;
+ }
+ const indices = primitive.getIndices();
+ const count = Math.floor((indices?.getCount() ?? position.getCount()) / 3);
+ eligibleTriangles += count;
+ const amount = Math.min(count, 8, MAX_SAMPLES - samples.length);
+ for (let i = 0;i < amount; i++) {
+ const start = Math.floor(i * count / amount) * 3;
+ const points = [0, 1, 2].map((j) => new THREE45.Vector3().fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, [])).applyMatrix4(matrix));
+ const normal = points[1].clone().sub(points[0]).cross(points[2].clone().sub(points[0]));
+ if (!Number.isFinite(normal.lengthSq()) || normal.lengthSq() === 0)
+ continue;
+ samples.push({
+ points,
+ normal: normal.normalize(),
+ bounds: new THREE45.Box3().setFromPoints(points),
+ part
+ });
+ }
+ }
+ const pairs = new Map;
+ for (let i = 0;i < samples.length; i++)
+ for (let j = i + 1;j < samples.length; j++) {
+ const a = samples[i], b = samples[j];
+ if (a.part.id === b.part.id || a.part.id.split("/")[0] !== b.part.id.split("/")[0])
+ continue;
+ const key = [a.part.id, b.part.id].sort().join("|");
+ if (!pairs.has(key) && overlaps(a, b))
+ pairs.set(key, { parts: [a.part, b.part] });
+ }
+ return {
+ mirroredTangents: {
+ count: mirrored.size,
+ omitted: Math.max(0, mirrored.size - MAX_FINDINGS),
+ parts: [...mirrored.values()].slice(0, MAX_FINDINGS),
+ evidence: "Visible static nodes with tangent attributes and negative world determinant; not proof of a shading defect. Skinned, morphed and GPU-instanced uses are not assessed."
+ },
+ coplanarParts: {
+ sampledTriangles: samples.length,
+ eligibleTriangles,
+ unexaminedPrimitiveUses,
+ candidatePairs: pairs.size,
+ omitted: Math.max(0, pairs.size - MAX_FINDINGS),
+ candidates: [...pairs.values()].slice(0, MAX_FINDINGS),
+ evidence: "Sampled overlapping coplanar triangles in separate static nodes; not proof of visible z-fighting. At most 8 triangles per primitive and 256 total; unexamined faces may contain other candidates."
+ }
+ };
+}
+function analyzeDrawDiagnostics(doc, options = {}) {
+ try {
+ if (!withinLimits(doc))
+ return skipped("input-limit");
+ const keep = options.keep ?? [];
+ const before = collect2(doc, keep);
+ const copy = cloneDocument(doc);
+ const merge = mergeRigidGroups(copy, { keep });
+ const after = collect2(copy, keep);
+ const all = [...before.anchors.values()].map((anchor) => ({
+ ...anchor,
+ afterRigidMerge: after.anchors.get(anchor.id)?.draws ?? 0
+ }));
+ const currentDraws = before.uses.length;
+ return {
+ version: "kiln.draw-diagnostics.v1",
+ status: "assessed",
+ scope: SCOPE,
+ currentDraws,
+ mergeEstimate: {
+ method: METHOD,
+ draws: after.uses.length,
+ saved: currentDraws - after.uses.length,
+ rejectedBuckets: merge.rejected.length,
+ ...merge.skipped ? { skipped: merge.skipped } : {}
+ },
+ anchors: {
+ total: all.length,
+ omitted: Math.max(0, all.length - MAX_ANCHORS),
+ items: all.slice(0, MAX_ANCHORS)
+ },
+ observations: observe(before.uses)
+ };
+ } catch {
+ return skipped("analysis-failed");
+ }
+}
+async function inspectDrawDiagnostics(bytes, options = {}) {
+ if (bytes.byteLength > MAX_BYTES)
+ return skipped("input-limit");
+ try {
+ return analyzeDrawDiagnostics(await createGltfIO().readBinary(bytes), options);
+ } catch {
+ return skipped("unreadable-glb");
+ }
+}
+var MAX_NODES2 = 2048, MAX_USES = 256, MAX_VERTICES3 = 262144, MAX_BYTES, MAX_ANCHORS = 16, MAX_SAMPLES = 256, MAX_FINDINGS = 4, SCOPE = "Static single-pass primitive draws across document scenes, respecting node visibility. Excludes culling, alternate LOD selections, shadow, reflection and depth passes, and renderer-specific extra passes; GPU instances count once per primitive. IDs use scene/node indices; names are bounded labels.", METHOD = "Current rigid-merge policy on a bounded clone with existing materials: includes layouts, boundaries, locks, shared-byte budget and vertex splits. Excludes palette consolidation and instancing; not a full-mode or GPU performance prediction.", nameOf = (name) => name.length <= 80 ? name : `${name.slice(0, 79)}…`, skipped = (reason) => ({
+ version: "kiln.draw-diagnostics.v1",
+ status: "skipped",
+ scope: SCOPE,
+ reason
+}), cross22 = (a, b, p) => (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]);
+var init_draw_diagnostics = __esm(() => {
+ init_gltf_io();
+ init_metrics();
+ init_rigid_merge();
+ MAX_BYTES = 32 * 1024 * 1024;
+});
+
// src/assets-resources.ts
var exports_assets_resources = {};
__export(exports_assets_resources, {
@@ -31234,8 +31964,8 @@ function assetLinks(collection, manifest) {
function assetMime(name) {
return name.endsWith(".glb") ? "model/gltf-binary" : name.endsWith(".png") ? "image/png" : name.endsWith(".zip") ? "application/zip" : name.endsWith(".json") ? "application/json" : "text/javascript";
}
-async function runtimeAssetLinks(collection, record) {
- const output = await exportAssetGlb(record, { profile: "runtime" });
+async function runtimeAssetLinks(collection, record, derived) {
+ const output = derived ?? await exportAssetGlb(record, { profile: "runtime" });
if (output.profile !== "runtime")
throw new Error("Expected runtime export");
return [
@@ -36964,7 +37694,7 @@ function createCachedEvaluatorPort(evaluator, options) {
// src/tools/registry.ts
init_validation();
-import * as THREE44 from "three";
+import * as THREE46 from "three";
// src/evaluator/source-check.ts
init_validation();
@@ -37322,7 +38052,7 @@ async function renderDerivativeCell(input, context) {
return;
const prepare = (material) => {
const copy = material.clone();
- copy.side = THREE44.DoubleSide;
+ copy.side = THREE46.DoubleSide;
return copy;
};
mesh.material = Array.isArray(mesh.material) ? mesh.material.map(prepare) : prepare(mesh.material);
@@ -37572,8 +38302,8 @@ function collectSceneMetrics(root) {
let meshes = 0;
const materialSet = new Set;
let lowestPart;
- const box = new THREE44.Box3;
- const point = new THREE44.Vector3;
+ const box = new THREE46.Box3;
+ const point = new THREE46.Vector3;
root.updateWorldMatrix(true, true);
root.traverseVisible((node) => {
const n = node;
@@ -37589,7 +38319,7 @@ function collectSceneMetrics(root) {
const mesh = node;
const position = mesh.geometry.getAttribute("position");
const index = mesh.geometry.index;
- const mb = new THREE44.Box3;
+ const mb = new THREE46.Box3;
if (position) {
for (let i = 0;i < (index?.count ?? position.count); i++) {
point.fromBufferAttribute(position, index ? index.getX(i) : i);
@@ -37604,7 +38334,7 @@ function collectSceneMetrics(root) {
});
let bbox;
if (!box.isEmpty()) {
- const size = new THREE44.Vector3;
+ const size = new THREE46.Vector3;
box.getSize(size);
bbox = {
min: [box.min.x, box.min.y, box.min.z],
@@ -38068,6 +38798,7 @@ async function runInspect(input, context) {
if (input.measure && input.measure.mode !== "surface")
measurement = measureAttachment(root, input.measure);
const measurements = {
+ drawDiagnostics: await (await Promise.resolve().then(() => (init_draw_diagnostics(), exports_draw_diagnostics))).inspectDrawDiagnostics(evaluated.glb),
...input.listParts ? { partListing: await listPartPage(root, input.listParts) } : {},
...measurement ? { measurement } : {},
...surfaceMeasurements ? { surfaceMeasurements } : {},
@@ -38825,10 +39556,17 @@ function createKilnAssetDefs(context) {
inputSchema: profileExportInput,
run: async (raw) => {
const input = profileExportInput.parse(raw);
+ const record = await readSavedRevision(library(), input.collection, input.assetId, input.revisionId);
+ await Promise.resolve().then(() => init_draw_diagnostics());
if (input.profile === "runtime") {
- const record = await readSavedRevision(library(), input.collection, input.assetId, input.revisionId);
+ const output = await (await Promise.resolve().then(() => (init_asset_export(), exports_asset_export))).exportAssetGlb(record, {
+ profile: "runtime"
+ });
+ if (output.profile !== "runtime")
+ throw new Error("Expected runtime export");
return {
ok: true,
+ drawDiagnostics: await inspectDrawDiagnostics(output.glb),
profile: input.profile,
collection: input.collection,
asset: {
@@ -38836,10 +39574,13 @@ function createKilnAssetDefs(context) {
revisionId: input.revisionId,
name: record.manifest.name
},
- resources: await (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).runtimeAssetLinks(input.collection, record)
+ resources: await (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).runtimeAssetLinks(input.collection, record, output)
};
}
- return links(input.collection, (await readSavedRevision(library(), input.collection, input.assetId, input.revisionId)).manifest);
+ return {
+ ...await links(input.collection, record.manifest),
+ drawDiagnostics: await inspectDrawDiagnostics(record.files["asset.glb"])
+ };
}
},
{
@@ -39300,7 +40041,7 @@ ${JSON.stringify(options.requirements)}`);
// src/agent/skill-resources.ts
import { lstat, open, readdir, realpath, stat } from "node:fs/promises";
-import { basename, dirname, extname, join as join2, relative, resolve, sep } from "node:path";
+import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
import { createHash as createHash10 } from "node:crypto";
import { Skill } from "@strands-agents/sdk/vended-plugins/skills";
var MAX_FILE_BYTES = 256 * 1024;
@@ -39314,7 +40055,7 @@ async function loadNativeSkills(selected) {
throw new Error(`Native skill directory is unavailable: ${selected}`);
});
const info = await stat(root);
- const directories = info.isFile() && basename(root) === "SKILL.md" ? [dirname(root)] : info.isDirectory() && await stat(join2(root, "SKILL.md")).then((s) => s.isFile(), () => false) ? [root] : info.isDirectory() ? (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => join2(root, e.name)).sort() : [];
+ const directories = info.isFile() && basename(root) === "SKILL.md" ? [dirname(root)] : info.isDirectory() && await stat(join(root, "SKILL.md")).then((s) => s.isFile(), () => false) ? [root] : info.isDirectory() ? (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => join(root, e.name)).sort() : [];
const snapshots = new Map;
const skills = [];
const referenceCollections = [];
@@ -39346,7 +40087,7 @@ async function loadNativeSkills(selected) {
return new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, size));
}
for (const directory of directories) {
- const file = join2(directory, "SKILL.md");
+ const file = join(directory, "SKILL.md");
if (!await stat(file).then((s) => s.isFile(), () => false))
continue;
const parsed = Skill.fromContent(await textFile(file), { strict: true, path: directory });
@@ -39365,7 +40106,7 @@ async function loadNativeSkills(selected) {
if (entries.length > 128)
throw new Error("Native skill reference directory exceeds 128 entries.");
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
- const path = join2(folder, entry.name);
+ const path = join(folder, entry.name);
if (entry.isSymbolicLink())
throw new Error(`Symlinked native skill reference is unsupported: ${entry.name}`);
if (entry.isDirectory()) {
@@ -39389,7 +40130,7 @@ async function loadNativeSkills(selected) {
});
}
}
- const referenceDir = join2(directory, "references");
+ const referenceDir = join(directory, "references");
const referenceInfo = await lstat(referenceDir).catch(() => {
return;
});
diff --git a/dist/build.json b/dist/build.json
index d1816b92..6d97166a 100644
--- a/dist/build.json
+++ b/dist/build.json
@@ -2,214 +2,214 @@
"schemaVersion": 1,
"entries": {
"worker": {
- "identity": "sha256:e998e55ac15e0ff3dd98484975724258c08932bf4a050199f3f1f490917c7a71",
+ "identity": "sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295",
"engineVersion": "0.10.0",
"toolchain": "[email protected]",
- "sourceHash": "1cdf0d9097fc093acbd552c0d14a7106a19987fc12d7b4c5ea3f98f017a73229",
- "rendererSourceHash": "27a01f842fffb183ce0da5044a100c172109bf791b0701da1cf56b6bc74db442",
- "dependencyHash": "da9e9142ff49f835d5438b770d065358aba655fb38e9dd453220d31b65ec17e9",
+ "sourceHash": "2df6b1cf2efc215f4659b520147ce014d887360be61bbb2f8cb8f7d76285d903",
+ "rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
+ "dependencyHash": "bc5b0968ad7298be37eaf7db2585ba6168c0cfcd8f33114dfd2d93ed4749a933",
"dependencies": {
- "@gltf-transform/core": "4.5.0",
- "@gltf-transform/extensions": "4.5.0",
- "@gltf-transform/functions": "4.5.0",
- "@modelcontextprotocol/client": "^2.2.0",
+ "@gltf-transform/core": "4.5.1",
+ "@gltf-transform/extensions": "4.5.1",
+ "@gltf-transform/functions": "4.5.1",
+ "@modelcontextprotocol/client": "^2.3.0",
"@modelcontextprotocol/ext-apps": "2.0.3",
- "@modelcontextprotocol/server": "^2.2.0",
+ "@modelcontextprotocol/server": "^2.3.0",
"@types/three": "^0.186.0",
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
- "manifold-3d": "^3.5.3",
+ "manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
- "sharp": "^0.35.4",
- "three": "0.186.0",
+ "sharp": "^0.35.5",
+ "three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
- "zod": "^4.6.4"
+ "zod": "^4.6.5"
},
"optionalDependencies": {
- "@napi-rs/canvas": "1.0.9",
- "webgpu": "0.6.1"
+ "@napi-rs/canvas": "1.0.10",
+ "webgpu": "0.6.2"
},
"target": "node",
"file": "evaluator-worker.mjs",
- "bundleHash": "sha256:2b59a716045f271f1b4d1588d10e6021bf7b61d2f487de738f47cf20fe64472f"
+ "bundleHash": "sha256:efb67be70d07325ecd824a451e2852ed50b50f2a8c1516b529ea66d5074577ab"
},
"agent-run": {
- "identity": "sha256:e998e55ac15e0ff3dd98484975724258c08932bf4a050199f3f1f490917c7a71",
+ "identity": "sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295",
"engineVersion": "0.10.0",
"toolchain": "[email protected]",
- "sourceHash": "1cdf0d9097fc093acbd552c0d14a7106a19987fc12d7b4c5ea3f98f017a73229",
- "rendererSourceHash": "27a01f842fffb183ce0da5044a100c172109bf791b0701da1cf56b6bc74db442",
- "dependencyHash": "da9e9142ff49f835d5438b770d065358aba655fb38e9dd453220d31b65ec17e9",
+ "sourceHash": "2df6b1cf2efc215f4659b520147ce014d887360be61bbb2f8cb8f7d76285d903",
+ "rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
+ "dependencyHash": "bc5b0968ad7298be37eaf7db2585ba6168c0cfcd8f33114dfd2d93ed4749a933",
"dependencies": {
- "@gltf-transform/core": "4.5.0",
- "@gltf-transform/extensions": "4.5.0",
- "@gltf-transform/functions": "4.5.0",
- "@modelcontextprotocol/client": "^2.2.0",
+ "@gltf-transform/core": "4.5.1",
+ "@gltf-transform/extensions": "4.5.1",
+ "@gltf-transform/functions": "4.5.1",
+ "@modelcontextprotocol/client": "^2.3.0",
"@modelcontextprotocol/ext-apps": "2.0.3",
- "@modelcontextprotocol/server": "^2.2.0",
+ "@modelcontextprotocol/server": "^2.3.0",
"@types/three": "^0.186.0",
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
- "manifold-3d": "^3.5.3",
+ "manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
- "sharp": "^0.35.4",
- "three": "0.186.0",
+ "sharp": "^0.35.5",
+ "three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
- "zod": "^4.6.4"
+ "zod": "^4.6.5"
},
"optionalDependencies": {
- "@napi-rs/canvas": "1.0.9",
- "webgpu": "0.6.1"
+ "@napi-rs/canvas": "1.0.10",
+ "webgpu": "0.6.2"
},
"target": "node",
"file": "agent-run.mjs",
- "bundleHash": "sha256:7b458dd2b0156445ac01721bd977532f12ba6c7ef7f12298fa717f9aa1474709"
+ "bundleHash": "sha256:a9228e007de71e69dc8cff8ccc38d244631d49854745acc667a4a5bcfea7a035"
},
"agent-providers": {
- "identity": "sha256:e998e55ac15e0ff3dd98484975724258c08932bf4a050199f3f1f490917c7a71",
+ "identity": "sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295",
"engineVersion": "0.10.0",
"toolchain": "[email protected]",
- "sourceHash": "1cdf0d9097fc093acbd552c0d14a7106a19987fc12d7b4c5ea3f98f017a73229",
- "rendererSourceHash": "27a01f842fffb183ce0da5044a100c172109bf791b0701da1cf56b6bc74db442",
- "dependencyHash": "da9e9142ff49f835d5438b770d065358aba655fb38e9dd453220d31b65ec17e9",
+ "sourceHash": "2df6b1cf2efc215f4659b520147ce014d887360be61bbb2f8cb8f7d76285d903",
+ "rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
+ "dependencyHash": "bc5b0968ad7298be37eaf7db2585ba6168c0cfcd8f33114dfd2d93ed4749a933",
"dependencies": {
- "@gltf-transform/core": "4.5.0",
- "@gltf-transform/extensions": "4.5.0",
- "@gltf-transform/functions": "4.5.0",
- "@modelcontextprotocol/client": "^2.2.0",
+ "@gltf-transform/core": "4.5.1",
+ "@gltf-transform/extensions": "4.5.1",
+ "@gltf-transform/functions": "4.5.1",
+ "@modelcontextprotocol/client": "^2.3.0",
"@modelcontextprotocol/ext-apps": "2.0.3",
- "@modelcontextprotocol/server": "^2.2.0",
+ "@modelcontextprotocol/server": "^2.3.0",
"@types/three": "^0.186.0",
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
- "manifold-3d": "^3.5.3",
+ "manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
- "sharp": "^0.35.4",
- "three": "0.186.0",
+ "sharp": "^0.35.5",
+ "three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
- "zod": "^4.6.4"
+ "zod": "^4.6.5"
},
"optionalDependencies": {
- "@napi-rs/canvas": "1.0.9",
- "webgpu": "0.6.1"
+ "@napi-rs/canvas": "1.0.10",
+ "webgpu": "0.6.2"
},
"target": "node",
"file": "agent-providers.mjs",
"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"
},
"mcp": {
- "identity": "sha256:e998e55ac15e0ff3dd98484975724258c08932bf4a050199f3f1f490917c7a71",
+ "identity": "sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295",
"engineVersion": "0.10.0",
"toolchain": "[email protected]",
- "sourceHash": "1cdf0d9097fc093acbd552c0d14a7106a19987fc12d7b4c5ea3f98f017a73229",
- "rendererSourceHash": "27a01f842fffb183ce0da5044a100c172109bf791b0701da1cf56b6bc74db442",
- "dependencyHash": "da9e9142ff49f835d5438b770d065358aba655fb38e9dd453220d31b65ec17e9",
+ "sourceHash": "2df6b1cf2efc215f4659b520147ce014d887360be61bbb2f8cb8f7d76285d903",
+ "rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
+ "dependencyHash": "bc5b0968ad7298be37eaf7db2585ba6168c0cfcd8f33114dfd2d93ed4749a933",
"dependencies": {
- "@gltf-transform/core": "4.5.0",
- "@gltf-transform/extensions": "4.5.0",
- "@gltf-transform/functions": "4.5.0",
- "@modelcontextprotocol/client": "^2.2.0",
+ "@gltf-transform/core": "4.5.1",
+ "@gltf-transform/extensions": "4.5.1",
+ "@gltf-transform/functions": "4.5.1",
+ "@modelcontextprotocol/client": "^2.3.0",
"@modelcontextprotocol/ext-apps": "2.0.3",
- "@modelcontextprotocol/server": "^2.2.0",
+ "@modelcontextprotocol/server": "^2.3.0",
"@types/three": "^0.186.0",
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
- "manifold-3d": "^3.5.3",
+ "manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
- "sharp": "^0.35.4",
- "three": "0.186.0",
+ "sharp": "^0.35.5",
+ "three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
- "zod": "^4.6.4"
+ "zod": "^4.6.5"
},
"optionalDependencies": {
- "@napi-rs/canvas": "1.0.9",
- "webgpu": "0.6.1"
+ "@napi-rs/canvas": "1.0.10",
+ "webgpu": "0.6.2"
},
"target": "node",
"file": "mcp-server.mjs",
"bundleHash": "sha256:aff8b03e5146a9e7bc32f0fcb7dea5e46d1e47634046b1df09b86f4cdc73b772"
},
"cli": {
- "identity": "sha256:e998e55ac15e0ff3dd98484975724258c08932bf4a050199f3f1f490917c7a71",
+ "identity": "sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295",
"engineVersion": "0.10.0",
"toolchain": "[email protected]",
- "sourceHash": "1cdf0d9097fc093acbd552c0d14a7106a19987fc12d7b4c5ea3f98f017a73229",
- "rendererSourceHash": "27a01f842fffb183ce0da5044a100c172109bf791b0701da1cf56b6bc74db442",
- "dependencyHash": "da9e9142ff49f835d5438b770d065358aba655fb38e9dd453220d31b65ec17e9",
+ "sourceHash": "2df6b1cf2efc215f4659b520147ce014d887360be61bbb2f8cb8f7d76285d903",
+ "rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
+ "dependencyHash": "bc5b0968ad7298be37eaf7db2585ba6168c0cfcd8f33114dfd2d93ed4749a933",
"dependencies": {
- "@gltf-transform/core": "4.5.0",
- "@gltf-transform/extensions": "4.5.0",
- "@gltf-transform/functions": "4.5.0",
- "@modelcontextprotocol/client": "^2.2.0",
+ "@gltf-transform/core": "4.5.1",
+ "@gltf-transform/extensions": "4.5.1",
+ "@gltf-transform/functions": "4.5.1",
+ "@modelcontextprotocol/client": "^2.3.0",
"@modelcontextprotocol/ext-apps": "2.0.3",
- "@modelcontextprotocol/server": "^2.2.0",
+ "@modelcontextprotocol/server": "^2.3.0",
"@types/three": "^0.186.0",
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
- "manifold-3d": "^3.5.3",
+ "manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
- "sharp": "^0.35.4",
- "three": "0.186.0",
+ "sharp": "^0.35.5",
+ "three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
- "zod": "^4.6.4"
+ "zod": "^4.6.5"
},
"optionalDependencies": {
- "@napi-rs/canvas": "1.0.9",
- "webgpu": "0.6.1"
+ "@napi-rs/canvas": "1.0.10",
+ "webgpu": "0.6.2"
},
"target": "node",
"file": "cli.mjs",
- "bundleHash": "sha256:8f7369895732aaf38879b8ea3f5003625f0b0fe114ec1f7e010c83c5fab15908"
+ "bundleHash": "sha256:e09ee8f1d6808c29903f3da884062955742b0a6fb3a0e8da4ddcef4eb8278a06"
},
"engine": {
- "identity": "sha256:e998e55ac15e0ff3dd98484975724258c08932bf4a050199f3f1f490917c7a71",
+ "identity": "sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295",
"engineVersion": "0.10.0",
"toolchain": "[email protected]",
- "sourceHash": "1cdf0d9097fc093acbd552c0d14a7106a19987fc12d7b4c5ea3f98f017a73229",
- "rendererSourceHash": "27a01f842fffb183ce0da5044a100c172109bf791b0701da1cf56b6bc74db442",
- "dependencyHash": "da9e9142ff49f835d5438b770d065358aba655fb38e9dd453220d31b65ec17e9",
+ "sourceHash": "2df6b1cf2efc215f4659b520147ce014d887360be61bbb2f8cb8f7d76285d903",
+ "rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
+ "dependencyHash": "bc5b0968ad7298be37eaf7db2585ba6168c0cfcd8f33114dfd2d93ed4749a933",
"dependencies": {
- "@gltf-transform/core": "4.5.0",
- "@gltf-transform/extensions": "4.5.0",
- "@gltf-transform/functions": "4.5.0",
- "@modelcontextprotocol/client": "^2.2.0",
+ "@gltf-transform/core": "4.5.1",
+ "@gltf-transform/extensions": "4.5.1",
+ "@gltf-transform/functions": "4.5.1",
+ "@modelcontextprotocol/client": "^2.3.0",
"@modelcontextprotocol/ext-apps": "2.0.3",
- "@modelcontextprotocol/server": "^2.2.0",
+ "@modelcontextprotocol/server": "^2.3.0",
"@types/three": "^0.186.0",
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
- "manifold-3d": "^3.5.3",
+ "manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
- "sharp": "^0.35.4",
- "three": "0.186.0",
+ "sharp": "^0.35.5",
+ "three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
- "zod": "^4.6.4"
+ "zod": "^4.6.5"
},
"optionalDependencies": {
- "@napi-rs/canvas": "1.0.9",
- "webgpu": "0.6.1"
+ "@napi-rs/canvas": "1.0.10",
+ "webgpu": "0.6.2"
},
"target": "node",
"file": "mcp-engine.mjs",
- "bundleHash": "sha256:76df0fd371e5b1da8f3f94f087791a043738e3169364cc2653f6df25359d00fc"
+ "bundleHash": "sha256:8dd44a83867607428b548fe2deb78208dde50e70dfe83092fd97ce4cad0fcfc7"
}
}
}
diff --git a/dist/cli.mjs b/dist/cli.mjs
index 0d77244e..422138d3 100644
--- a/dist/cli.mjs
+++ b/dist/cli.mjs
@@ -3577,7 +3577,7 @@ var init_architecture = __esm(() => {
scope: { kind: "category", category: "architecture" },
ruleClass: "exact",
owner: KILN_ENGINE_QA_OWNER,
- promotion: conformancePromotionAuthorization("architecture-qa-v1", "src/qa/architecture.test.ts", "c3a3bdc764c62238cede39813995fcaa428131d0aa3774bcd86cfc8b60f36671"),
+ promotion: conformancePromotionAuthorization("architecture-qa-v1", "src/qa/architecture.test.ts", "ce42ab6baef737d109f272413d902ea0903bd66c4da13ea723a52aff2f9e6c66", KILN_ENGINE_QA_OWNER, "2026-10-03T05:45:42.000Z", "enforce", "cpu-raster:0.10.0"),
defaultMode: "enforce",
evaluate: (context) => evaluateArchitectureQa(context).filter((finding) => finding.disposition === "block")
};
@@ -16076,13 +16076,14 @@ var init_requirements_report = __esm(() => {
// src/rebuild-options.ts
import { z as z4 } from "zod";
-var rebuildOptionsSchema;
+var FULL_OPTIMIZATION_PIPELINE = "rigid-v1", rebuildOptionsSchema;
var init_rebuild_options = __esm(() => {
rebuildOptionsSchema = z4.object({
indexPolicy: z4.enum(["indexed", "asBuilt"]).optional(),
gltfExporter: z4.enum(["legacy", "three"]),
geometryPolicy: z4.enum(["warn", "strict"]),
optimize: z4.enum(["off", "auto", "palette", "full"]),
+ optimizationPipeline: z4.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
instance: z4.enum(["off", "auto", "on"])
});
});
@@ -22855,6 +22856,507 @@ var init_material_metrics = __esm(() => {
});
});
+// src/rigid-merge.ts
+import {
+ ComponentTypeToTypedArray,
+ Primitive,
+ PropertyType as PropertyType3
+} from "@gltf-transform/core";
+import { createTransform, dequantizePrimitive, joinPrimitives } from "@gltf-transform/functions";
+import * as THREE37 from "three";
+function isSingular(matrix) {
+ const e = matrix.elements;
+ const scale = Math.hypot(e[0], e[1], e[2]) * Math.hypot(e[4], e[5], e[6]) * Math.hypot(e[8], e[9], e[10]);
+ const det = matrix.determinant();
+ return !Number.isFinite(det) || Math.abs(det) <= 0.000000001 * scale;
+}
+function findRigidBoundaries(doc, keep) {
+ const root = doc.getRoot();
+ const found = new Map;
+ const add = (node, reason) => {
+ const reasons = found.get(node) ?? [];
+ if (!reasons.includes(reason))
+ reasons.push(reason);
+ found.set(node, reasons);
+ };
+ for (const animation of root.listAnimations())
+ for (const channel of animation.listChannels()) {
+ const target = channel.getTargetNode();
+ if (target)
+ add(target, "animated");
+ }
+ for (const skin of root.listSkins())
+ for (const joint of skin.listJoints())
+ add(joint, "skin-joint");
+ const targets = new Set;
+ for (const node of root.listNodes()) {
+ const semantic = node.getExtras()[KILN_SEMANTIC_EXTRAS_KEY];
+ if (Array.isArray(semantic?.relationships)) {
+ for (const relationship of semantic.relationships)
+ if (relationship?.targetType === "node" && typeof relationship.target === "string")
+ targets.add(relationship.target);
+ }
+ }
+ for (const node of root.listNodes()) {
+ const name = node.getName();
+ const sceneParents = node.listParents().filter((parent) => parent.propertyType === PropertyType3.SCENE).length;
+ if (sceneParents > 1)
+ add(node, "shared-scene");
+ if (JOINT_PIVOT.test(name))
+ add(node, "joint-pivot");
+ if (hasKeys(node.getExtras()))
+ add(node, "extras");
+ if (targets.has(name))
+ add(node, "relationship-target");
+ if (node.getExtension("KHR_node_visibility"))
+ add(node, "visibility");
+ const lod = node.getExtension(MSFT_LOD);
+ if (lod) {
+ add(node, "lod");
+ for (const level of lod.listLevels())
+ if (level.propertyType === PropertyType3.NODE)
+ add(level, "lod");
+ }
+ if (keep.has(name))
+ add(node, "kept");
+ }
+ return found;
+}
+function nodeLock(node, mesh, world, expandShared) {
+ if (node.getSkin())
+ return "skinned";
+ if (node.getExtension("EXT_mesh_gpu_instancing"))
+ return "instanced";
+ if (hasKeys(mesh.getExtras()))
+ return "mesh-extras";
+ if (!expandShared && nodeUsers(mesh) > 1)
+ return "shared-mesh";
+ if (isSingular(world))
+ return "singular-matrix";
+ return;
+}
+function primLock(prim, mergeTransparent) {
+ if (prim.listTargets().length > 0)
+ return "morph-targets";
+ if (RESTART_MODES.has(prim.getMode()))
+ return "primitive-mode";
+ if (prim.listExtensions().length > 0)
+ return "primitive-extensions";
+ if (hasKeys(prim.getExtras()))
+ return "primitive-extras";
+ if (!prim.getAttribute("POSITION"))
+ return "no-position";
+ const material = prim.getMaterial();
+ if (material?.getExtension("KHR_materials_volume"))
+ return "volume";
+ if (!mergeTransparent && material && (material.getAlphaMode() === "BLEND" || material.getExtension("KHR_materials_transmission") || material.getExtension("KHR_materials_diffuse_transmission")))
+ return "transparent";
+ return;
+}
+function bucketKey(prim, materials, handedness) {
+ const layout = prim.listSemantics().sort().map((semantic) => {
+ const a = prim.getAttribute(semantic);
+ return `${semantic}:${a.getElementSize()}:${a.getComponentType()}:${a.getNormalized()}`;
+ }).join("+");
+ const hand = handedness !== null && prim.getAttribute("TANGENT") ? `|${handedness}` : "";
+ return `${materials.get(prim.getMaterial()) ?? -1}|${prim.getMode()}|${!!prim.getIndices()}|${layout}${hand}`;
+}
+function reverseWinding(prim) {
+ const indices = prim.getIndices()?.getArray();
+ const swap = (array, size, i) => {
+ for (let k = 0;k < size; k++) {
+ const [j, l] = [(i + 1) * size + k, (i + 2) * size + k];
+ [array[j], array[l]] = [array[l], array[j]];
+ }
+ };
+ if (indices) {
+ for (let i = 0;i + 2 < indices.length; i += 3)
+ swap(indices, 1, i);
+ return;
+ }
+ for (const semantic of prim.listSemantics()) {
+ const attribute = prim.getAttribute(semantic);
+ for (let i = 0;i + 2 < attribute.getCount(); i += 3)
+ swap(attribute.getArray(), attribute.getElementSize(), i);
+ }
+}
+function bake(prim, matrix) {
+ const linear = new THREE37.Matrix3().setFromMatrix4(matrix);
+ const normalMatrix = new THREE37.Matrix3().getNormalMatrix(matrix);
+ const mirrored = matrix.determinant() < 0;
+ const v = new THREE37.Vector3;
+ const each = (semantic, apply) => {
+ const attribute = prim.getAttribute(semantic);
+ const element = [];
+ for (let i = 0;i < (attribute?.getCount() ?? 0); i++) {
+ apply(attribute.getElement(i, element));
+ attribute.setElement(i, element);
+ }
+ };
+ each("POSITION", (e) => v.fromArray(e).applyMatrix4(matrix).toArray(e));
+ each("NORMAL", (e) => v.fromArray(e).applyMatrix3(normalMatrix).normalize().toArray(e));
+ each("TANGENT", (e) => {
+ v.fromArray(e).applyMatrix3(linear).normalize().toArray(e);
+ if (mirrored)
+ e[3] = -e[3];
+ });
+ if (mirrored && prim.getMode() === Primitive.Mode.TRIANGLES)
+ reverseWinding(prim);
+}
+function destinationOf(entries) {
+ let chosen = entries[0].node;
+ let best = Infinity;
+ let bestScale = Infinity;
+ for (const { node } of entries) {
+ const linear = new THREE37.Matrix3().setFromMatrix4(worldOf(node));
+ const norm = Math.hypot(...linear.elements);
+ const inverseNorm = Math.hypot(...linear.clone().invert().elements);
+ const condition = norm * inverseNorm;
+ const scale = Math.max(norm, inverseNorm);
+ if (condition < best * (1 - 0.000000000001) || Math.abs(condition - best) <= best * 0.000000000001 && scale < bestScale) {
+ chosen = node;
+ best = condition;
+ bestScale = scale;
+ }
+ }
+ return chosen;
+}
+function checkPositionPrecision(input, output, sourceWorld, destinationWorld, reversed) {
+ const expected = new THREE37.Vector3;
+ const actual = new THREE37.Vector3;
+ const bounds = new THREE37.Box3;
+ const element = [];
+ let error = 0;
+ let magnitude = 0;
+ for (let i = 0;i < input.getCount(); i++) {
+ const out = reversed ? i % 3 === 1 ? i + 1 : i % 3 === 2 ? i - 1 : i : i;
+ expected.fromArray(input.getElement(i, element)).applyMatrix4(sourceWorld);
+ actual.fromArray(output.getElement(out, element)).applyMatrix4(destinationWorld);
+ bounds.expandByPoint(expected);
+ error = Math.max(error, expected.distanceTo(actual));
+ magnitude = Math.max(magnitude, expected.length());
+ }
+ const tolerance = Math.max(bounds.getSize(expected).length() * 0.000001, magnitude * Number.EPSILON * 32, Number.EPSILON);
+ if (error > tolerance)
+ throw new Error("rigid merge: destination frame loses position precision");
+}
+function splitVertices(prim, created) {
+ if (prim.getAttribute("POSITION").getCount() <= MAX_VERTICES)
+ return [prim];
+ const width = prim.getMode() === Primitive.Mode.POINTS ? 1 : prim.getMode() === Primitive.Mode.LINES ? 2 : 3;
+ const sourceIndices = prim.getIndices()?.getArray();
+ const count = sourceIndices?.length ?? prim.getAttribute("POSITION").getCount();
+ if (count % width !== 0)
+ throw new Error("rigid merge: incomplete primitive element");
+ const chunks = [];
+ let remap = new Map;
+ let indices = [];
+ const flush = () => {
+ if (!indices.length)
+ return;
+ const chunk = prim.clone();
+ created.push(chunk);
+ const vertices = [...remap.keys()];
+ for (const semantic of prim.listSemantics()) {
+ const source = prim.getAttribute(semantic);
+ const size = source.getElementSize();
+ const ArrayType = ComponentTypeToTypedArray[source.getComponentType()];
+ if (!ArrayType)
+ throw new Error(`rigid merge: unsupported component type for ${semantic}`);
+ const data = new ArrayType(vertices.length * size);
+ const sourceData = source.getArray();
+ for (const [out, input] of vertices.entries())
+ data.set(sourceData.subarray(input * size, (input + 1) * size), out * size);
+ const attribute = source.clone().setArray(data);
+ created.push(attribute);
+ chunk.setAttribute(semantic, attribute);
+ }
+ if (prim.getIndices()) {
+ const accessor = prim.getIndices().clone().setArray(new Uint16Array(indices));
+ created.push(accessor);
+ chunk.setIndices(accessor);
+ }
+ chunks.push(chunk);
+ remap = new Map;
+ indices = [];
+ };
+ for (let offset = 0;offset < count; offset += width) {
+ const element = Array.from({ length: width }, (_, i) => sourceIndices?.[offset + i] ?? offset + i);
+ const extra = new Set(element.filter((index) => !remap.has(index))).size;
+ if (remap.size + extra > MAX_VERTICES)
+ flush();
+ for (const index of element) {
+ if (!remap.has(index))
+ remap.set(index, remap.size);
+ indices.push(remap.get(index));
+ }
+ }
+ flush();
+ for (const property of [prim, ...accessorsOf(prim)])
+ property.dispose();
+ return chunks;
+}
+function prepare(entries, dst, created) {
+ const destinationWorld = worldOf(dst);
+ const inverse = destinationWorld.clone().invert();
+ const copies = entries.map(({ node, prim }) => {
+ const copy = prim.clone();
+ created.push(copy);
+ for (const semantic of copy.listSemantics()) {
+ const attribute = copy.getAttribute(semantic).clone();
+ created.push(attribute);
+ copy.setAttribute(semantic, attribute);
+ }
+ const indices = copy.getIndices()?.clone();
+ if (indices) {
+ created.push(indices);
+ copy.setIndices(indices);
+ }
+ dequantizePrimitive(copy, { pattern: BAKED });
+ if (node !== dst) {
+ const sourceWorld = worldOf(node);
+ const matrix = inverse.clone().multiply(sourceWorld);
+ bake(copy, matrix);
+ const reversed = !copy.getIndices() && copy.getMode() === Primitive.Mode.TRIANGLES && matrix.determinant() < 0;
+ checkPositionPrecision(prim.getAttribute("POSITION"), copy.getAttribute("POSITION"), sourceWorld, destinationWorld, reversed);
+ }
+ return copy;
+ });
+ const merged = joinPrimitives(copies);
+ created.push(merged, ...accessorsOf(merged));
+ for (const semantic of ["POSITION", "NORMAL", "TANGENT"]) {
+ const array = merged.getAttribute(semantic)?.getArray();
+ if (array && !array.every(Number.isFinite))
+ throw new Error(`rigid merge: non-finite ${semantic} in the joined primitive`);
+ }
+ const elements = (p) => p.getIndices()?.getCount() ?? p.getAttribute("POSITION").getCount();
+ const expected = copies.reduce((sum, copy) => sum + elements(copy), 0);
+ if (elements(merged) !== expected)
+ throw new Error(`rigid merge: joined ${elements(merged)} of ${expected} elements`);
+ for (const copy of copies)
+ for (const property of [copy, ...accessorsOf(copy)])
+ property.dispose();
+ return splitVertices(merged, created);
+}
+function removableBytes(entries) {
+ const uses = new Map;
+ for (const { node, prim } of entries) {
+ const nodes = uses.get(prim) ?? new Set;
+ nodes.add(node);
+ uses.set(prim, nodes);
+ }
+ const removed = new Set;
+ for (const [prim, nodes] of uses) {
+ const retained = prim.listParents().some((parent) => {
+ if (parent.propertyType === PropertyType3.ROOT)
+ return false;
+ if (parent.propertyType !== PropertyType3.MESH)
+ return true;
+ return parent.listParents().some((user) => user.propertyType !== PropertyType3.ROOT && (user.propertyType !== PropertyType3.NODE || !nodes.has(user)));
+ });
+ if (!retained)
+ removed.add(prim);
+ }
+ const accessors = new Set([...removed].flatMap(accessorsOf));
+ let bytes = 0;
+ for (const accessor of accessors)
+ if (accessor.listParents().every((parent) => parent.propertyType === PropertyType3.ROOT || removed.has(parent)))
+ bytes += accessor.getArray()?.byteLength ?? 0;
+ return bytes;
+}
+function sceneNodes2(doc) {
+ const seen = new Set;
+ const visit = (node) => {
+ if (seen.has(node))
+ return;
+ seen.add(node);
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const scene of doc.getRoot().listScenes())
+ for (const child of scene.listChildren())
+ visit(child);
+ return seen;
+}
+function mergeRigidGroups(doc, options = {}) {
+ const root = doc.getRoot();
+ const keep = new Set(options.keep ?? []);
+ const nodes = sceneNodes2(doc);
+ const names = new Set([...nodes].map((node) => node.getName()));
+ const summary = {
+ primitivesBefore: countPrimitives(nodes),
+ primitivesAfter: 0,
+ groups: 0,
+ merges: 0,
+ boundaries: [],
+ locked: [],
+ rejected: [],
+ unmatchedKeep: [...keep].filter((name) => !names.has(name))
+ };
+ if (root.listAnimations().some((a) => a.listChannels().some((c) => !c.getTargetNode()))) {
+ summary.skipped = "unbounded-animation";
+ summary.primitivesAfter = summary.primitivesBefore;
+ return summary;
+ }
+ const boundaries = findRigidBoundaries(doc, keep);
+ const materials = new Map(root.listMaterials().map((m, i) => [m, i]));
+ const groups = [];
+ const locks = new Map;
+ const lock = (node, reason, primitives) => {
+ const key = `${node.getName()}|${reason}`;
+ const known = locks.get(key);
+ if (known)
+ known.primitives += primitives;
+ else {
+ const entry = { node: node.getName(), reason, primitives };
+ locks.set(key, entry);
+ summary.locked.push(entry);
+ }
+ };
+ const seen = new Set;
+ const visit = (node, parentGroup) => {
+ if (seen.has(node))
+ return;
+ seen.add(node);
+ const reasons = boundaries.get(node);
+ let group = parentGroup;
+ if (reasons) {
+ summary.boundaries.push({ node: node.getName(), reasons });
+ group = new Map;
+ groups.push(group);
+ }
+ const mesh = node.getMesh();
+ if (mesh) {
+ const world = worldOf(node);
+ const nodeReason = reasons ? "boundary" : nodeLock(node, mesh, world, options.expandSharedMeshes !== false);
+ const handedness = options.mergeMirroredTangents ? null : Math.sign(world.determinant());
+ if (nodeReason)
+ lock(node, nodeReason, mesh.listPrimitives().length);
+ else
+ for (const prim of mesh.listPrimitives()) {
+ const primReason = primLock(prim, options.mergeTransparent === true);
+ if (primReason)
+ lock(node, primReason, 1);
+ else {
+ const key = bucketKey(prim, materials, handedness);
+ const list = group.get(key);
+ if (list)
+ list.push({ node, prim });
+ else
+ group.set(key, [{ node, prim }]);
+ }
+ }
+ }
+ for (const child of node.listChildren())
+ visit(child, group);
+ };
+ for (const scene of root.listScenes()) {
+ const group = new Map;
+ groups.push(group);
+ for (const child of scene.listChildren())
+ visit(child, group);
+ }
+ summary.groups = groups.length;
+ const plans = [];
+ for (const group of groups)
+ for (const bucket of group.values()) {
+ let entries = bucket;
+ while (entries.length >= 2) {
+ const created = [];
+ const track = (event) => created.push(event.target);
+ doc.getGraph().addEventListener("node:create", track);
+ try {
+ const destination = destinationOf(entries);
+ const merged = prepare(entries, destination, created);
+ const savedDraws = entries.length - merged.length;
+ const shared = entries.filter((entry) => removableBytes([entry]) < primitiveBytes([entry.prim]));
+ const addedBytes = Math.max(0, primitiveBytes(merged) - removableBytes(entries));
+ if (savedDraws > 0 && addedBytes <= savedDraws * MAX_BYTES_PER_SAVED_DRAW) {
+ plans.push({ entries, destination, merged });
+ break;
+ }
+ for (const property of created)
+ property.dispose();
+ if (!shared.length || savedDraws <= 0)
+ break;
+ const costly = shared.reduce((best, entry) => primitiveBytes(entry.node.getMesh().listPrimitives()) > primitiveBytes(best.node.getMesh().listPrimitives()) ? entry : best);
+ const mesh = costly.node.getMesh();
+ for (const entry of entries.filter((entry) => entry.node.getMesh() === mesh))
+ lock(entry.node, "shared-byte-budget", 1);
+ entries = entries.filter((entry) => entry.node.getMesh() !== mesh);
+ } catch (error) {
+ for (const property of created)
+ property.dispose();
+ summary.rejected.push({
+ node: entries[0].node.getName(),
+ primitives: entries.length,
+ error: error instanceof Error ? error.message : String(error)
+ });
+ break;
+ } finally {
+ doc.getGraph().removeEventListener("node:create", track);
+ }
+ }
+ }
+ const owned = new Map;
+ const ownMesh = (node) => {
+ let mesh = owned.get(node);
+ if (mesh)
+ return mesh;
+ mesh = node.getMesh();
+ if (nodeUsers(mesh) > 1) {
+ mesh = mesh.clone();
+ node.setMesh(mesh);
+ }
+ owned.set(node, mesh);
+ return mesh;
+ };
+ const removed = new Set;
+ for (const { entries, destination, merged } of plans) {
+ for (const { node, prim } of entries) {
+ ownMesh(node).removePrimitive(prim);
+ removed.add(prim);
+ }
+ for (const primitive of merged)
+ ownMesh(destination).addPrimitive(primitive);
+ }
+ for (const [node, mesh] of owned)
+ if (mesh.listPrimitives().length === 0) {
+ node.setMesh(null);
+ if (nodeUsers(mesh) === 0)
+ mesh.dispose();
+ }
+ for (const prim of removed) {
+ if (prim.listParents().some((parent) => parent.propertyType === PropertyType3.MESH))
+ continue;
+ const accessors = accessorsOf(prim);
+ prim.dispose();
+ for (const accessor of accessors)
+ if (accessor.listParents().every((parent) => parent.propertyType === PropertyType3.ROOT))
+ accessor.dispose();
+ }
+ summary.merges = plans.length;
+ summary.primitivesAfter = countPrimitives(nodes);
+ return summary;
+}
+function rigidMerge(options = {}, onSummary) {
+ return createTransform("kilnRigidMerge", (doc) => {
+ const summary = mergeRigidGroups(doc, options);
+ onSummary?.(summary);
+ });
+}
+var JOINT_PIVOT, RESTART_MODES, BAKED, MAX_VERTICES = 65534, MAX_BYTES_PER_SAVED_DRAW = 4096, hasKeys = (value) => Object.keys(value).length > 0, worldOf = (node) => new THREE37.Matrix4().fromArray(node.getWorldMatrix()), nodeUsers = (mesh) => mesh.listParents().filter((parent) => parent.propertyType === PropertyType3.NODE).length, accessorsOf = (prim) => {
+ const indices = prim.getIndices();
+ return indices ? [...prim.listAttributes(), indices] : prim.listAttributes();
+}, primitiveBytes = (primitives) => [...new Set(primitives.flatMap(accessorsOf))].reduce((sum, a) => sum + (a.getArray()?.byteLength ?? 0), 0), countPrimitives = (nodes) => [...nodes].reduce((sum, node) => sum + (node.getMesh()?.listPrimitives().length ?? 0), 0);
+var init_rigid_merge = __esm(() => {
+ init_semantic();
+ init_gltf_io();
+ JOINT_PIVOT = /^joint[_-]/i;
+ RESTART_MODES = new Set([2, 3, 5, 6]);
+ BAKED = /^(POSITION|NORMAL|TANGENT)$/;
+});
+
// src/geometry-catalog.ts
var REMOVED_AUTHORING_HELPERS, geometryPrimitives;
var init_geometry_catalog = __esm(() => {
@@ -25137,7 +25639,7 @@ var init_kit = __esm(() => {
// src/texture-bake.ts
import { createHash as createHash6 } from "node:crypto";
-import * as THREE37 from "three";
+import * as THREE38 from "three";
function readPixels(texture) {
const image = texture.image;
if (!image)
@@ -25229,7 +25731,7 @@ async function bakeSceneTextures(root, warnings) {
mime: "image/png",
bytes
};
- const colorSpace = entry.texture.colorSpace === THREE37.SRGBColorSpace ? "srgb" : "linear";
+ const colorSpace = entry.texture.colorSpace === THREE38.SRGBColorSpace ? "srgb" : "linear";
const recipe = entry.texture.userData["kilnProcedural"];
const primaryUsage = recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");
entry.texture.userData["kilnTexture"] = {
@@ -25310,10 +25812,10 @@ function computeTangentBasis(geometry) {
}
}
const out = new Float32Array(vertexCount * 4);
- const n = new THREE37.Vector3;
- const t = new THREE37.Vector3;
- const tmp = new THREE37.Vector3;
- const tmp2 = new THREE37.Vector3;
+ const n = new THREE38.Vector3;
+ const t = new THREE38.Vector3;
+ const tmp = new THREE38.Vector3;
+ const tmp2 = new THREE38.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]);
@@ -25333,7 +25835,7 @@ function computeTangentBasis(geometry) {
out[v * 4 + 2] = tmp.z;
out[v * 4 + 3] = w;
}
- geometry.setAttribute("tangent", new THREE37.BufferAttribute(out, 4));
+ geometry.setAttribute("tangent", new THREE38.BufferAttribute(out, 4));
}
function ensureNormalMapTangents(root, warnings) {
let count = 0;
@@ -25444,7 +25946,7 @@ var init_exporter_node = __esm(() => {
});
// src/views/character.ts
-import * as THREE38 from "three";
+import * as THREE39 from "three";
function rounded(value) {
const result = Math.round(value * 1e9) / 1e9;
return Object.is(result, -0) ? 0 : result;
@@ -25486,9 +25988,9 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {
const invalidPaths = new Set(invalidFindingNodePaths);
const joints = evidence.map((joint) => {
const relative = rootInverse.clone().multiply(joint.node.matrixWorld);
- const position = new THREE38.Vector3().setFromMatrixPosition(relative);
- const forward = new THREE38.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
- const bend = new THREE38.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const position = new THREE39.Vector3().setFromMatrixPosition(relative);
+ const forward = new THREE39.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const bend = new THREE39.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
const chainId = chainIdFor(joint.descriptor, descriptorByRole);
return {
role: joint.descriptor.role,
@@ -27177,7 +27679,7 @@ var init_raster = __esm(() => {
});
// src/views/camera.ts
-import { Vector3 as Vector330, Matrix4 as Matrix412, Euler as Euler4, Group as Group3 } from "three";
+import { Vector3 as Vector331, Matrix4 as Matrix413, Euler as Euler4, Group as Group3 } from "three";
function strict(value, keys, label) {
for (const key of Object.keys(value))
if (!keys.includes(key)) {
@@ -27271,14 +27773,14 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {
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 Vector330(0, 0, -1) : new Vector330(0, 1, 0);
+ const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector331(0, 0, -1) : new Vector331(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 extent = 0.000001;
for (let i = 0;i < 8; i++) {
- const p = new Vector330((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);
+ const p = new Vector331((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);
extent = Math.max(extent, Math.abs(p.dot(x)), Math.abs(p.dot(y)));
}
const depthMin = bounds.min.map((v, i) => Math.min(v, sceneBounds.min[i]));
@@ -27359,7 +27861,7 @@ function resolveAssetCamera(root, shot = {}) {
if (relative !== "world") {
const node = relative === "part" ? selected.node : rootNode;
dir.transformDirection(node.matrixWorld);
- up = tuple5(new Vector330(0, 1, 0).transformDirection(node.matrixWorld));
+ up = tuple5(new Vector331(0, 1, 0).transformDirection(node.matrixWorld));
}
camera = cameraFromBounds(bounds, tuple5(dir), request.padding ?? 1.2, up, measureBounds(root));
} else if (request.type === "explicit") {
@@ -27394,7 +27896,7 @@ function resolveAssetCamera(root, shot = {}) {
throw new Error("padding requires bounds framing");
if (request.framing === "bounds" && request.halfHeight !== undefined)
throw new Error("bounds framing derives halfHeight");
- let matrix = new Matrix412;
+ let matrix = new Matrix413;
if (relative === "asset" || relative === "part")
matrix = (relative === "asset" ? rootNode : selected.node).matrixWorld;
if (request.frame) {
@@ -27406,7 +27908,7 @@ function resolveAssetCamera(root, shot = {}) {
const position = vec(triple(request.position, "position")).applyMatrix4(matrix);
const target = request.target ? vec(triple(request.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);
const up = vec(triple(request.up ?? [0, 1, 0], "up")).transformDirection(matrix);
- const offset = vec(triple(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector330().setFromMatrixPosition(matrix));
+ const offset = vec(triple(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector331().setFromMatrixPosition(matrix));
const radius = vec(bounds.max).sub(vec(bounds.min)).length();
camera = {
version: "kiln.camera.v1",
@@ -27534,11 +28036,11 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)
}
return result;
};
- const key = new Vector330(1.5, 2, 1).normalize();
+ const key = new Vector331(1.5, 2, 1).normalize();
const srgb = (n) => n <= 0.0031308 ? n * 12.92 : 1.055 * n ** (1 / 2.4) - 0.055;
const ordered = compositingOrder(collectTriangles(root).tris, (px, py, pz) => camera.projection === "perspective" ? Math.hypot(px - position.x, py - position.y, pz - position.z) : (position.x - px) * z.x + (position.y - py) * z.y + (position.z - pz) * z.z);
for (const tri of ordered) {
- const world = [0, 1, 2].map((i) => new Vector330(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));
+ const world = [0, 1, 2].map((i) => new Vector331(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;
@@ -27548,7 +28050,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)
const color = tri.color.map((c) => Math.round(srgb(c * light) * 255));
let polygon = world.map((p) => {
const d = p.clone().sub(position);
- return new Vector330(d.dot(x), d.dot(y), -d.dot(z));
+ return new Vector331(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++) {
@@ -27581,7 +28083,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)
}
return out;
}
-var vec = (a) => new Vector330(...a), tuple5 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;
+var vec = (a) => new Vector331(...a), tuple5 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;
var init_camera = __esm(() => {
init_raster();
init_background();
@@ -28330,13 +28832,13 @@ var init_architecture3 = __esm(() => {
// src/views/glb.ts
import {
- Primitive
+ Primitive as Primitive2
} from "@gltf-transform/core";
import {
BufferAttribute as BufferAttribute8,
BufferGeometry as BufferGeometry15,
Group as Group4,
- Matrix4 as Matrix413,
+ Matrix4 as Matrix414,
Mesh as Mesh12,
MeshStandardMaterial as MeshStandardMaterial5,
NoColorSpace as NoColorSpace4,
@@ -28346,7 +28848,7 @@ import {
QuaternionKeyframeTrack as QuaternionKeyframeTrack2,
VectorKeyframeTrack as VectorKeyframeTrack2,
Quaternion as Quaternion17,
- Vector3 as Vector331,
+ Vector3 as Vector332,
InterpolateDiscrete as InterpolateDiscrete2,
InterpolateLinear as InterpolateLinear2
} from "three";
@@ -28411,16 +28913,16 @@ 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:
+ case Primitive2.Mode.TRIANGLES:
return Uint32Array.from(source);
- case Primitive.Mode.TRIANGLE_STRIP: {
+ case Primitive2.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: {
+ case Primitive2.Mode.TRIANGLE_FAN: {
const triangles = [];
for (let index = 1;index + 1 < source.length; index++) {
triangles.push(source[index], source[index + 1], source[0]);
@@ -28498,7 +29000,7 @@ function noteMaterialTextures(material, reasons) {
}
}
function instanceMatrices(node) {
- const world = new Matrix413().fromArray(node.getWorldMatrix());
+ const world = new Matrix414().fromArray(node.getWorldMatrix());
const extension = node.getExtension("EXT_mesh_gpu_instancing");
if (!extension)
return { matrices: [world], count: 1 };
@@ -28521,7 +29023,7 @@ function instanceMatrices(node) {
translations?.getElement(index, translation);
rotations?.getElement(index, rotation);
scales?.getElement(index, scale);
- const local = new Matrix413().compose(new Vector331(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion17(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector331(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));
+ const local = new Matrix414().compose(new Vector332(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion17(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector332(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));
matrices.push(world.clone().multiply(local));
}
return { matrices, count };
@@ -28609,7 +29111,7 @@ async function loadGlbGeometryFlatScene(bytes) {
function localInstanceMatrices(node) {
const extension = node.getExtension("EXT_mesh_gpu_instancing");
if (!extension)
- return [new Matrix413];
+ return [new Matrix414];
const attributes = extension.listAttributes();
if (attributes.length === 0) {
throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", "Invalid empty instancing data.");
@@ -28628,7 +29130,7 @@ function localInstanceMatrices(node) {
translations?.getElement(index, translation);
rotations?.getElement(index, rotation);
scales?.getElement(index, scale);
- return new Matrix413().compose(new Vector331(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion17(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector331(...scales ? scale.slice(0, 3) : [1, 1, 1]));
+ return new Matrix414().compose(new Vector332(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion17(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector332(...scales ? scale.slice(0, 3) : [1, 1, 1]));
});
}
async function loadGlbReviewScene(bytes) {
@@ -29084,7 +29586,7 @@ var init_renderer_id = __esm(() => {
});
// src/views/scene-raster.ts
-import * as THREE39 from "three";
+import * as THREE40 from "three";
var DEG2;
var init_scene_raster = __esm(() => {
init_evaluator();
@@ -29095,18 +29597,18 @@ var init_scene_raster = __esm(() => {
});
// src/views/vehicle.ts
-import * as THREE40 from "three";
+import * as THREE41 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 THREE40.Box3;
+ const bounds = new THREE41.Box3;
let found = false;
root.traverse((node) => {
if (!hasRole2(node, "chassis"))
return;
node.traverse((part) => {
- if (!(part instanceof THREE40.Mesh) || !(part.geometry instanceof THREE40.BufferGeometry))
+ if (!(part instanceof THREE41.Mesh) || !(part.geometry instanceof THREE41.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const box = part.geometry.boundingBox;
@@ -29116,7 +29618,7 @@ function chassisBounds(root, inverse) {
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 THREE40.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE41.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -29184,33 +29686,33 @@ function tagDiagnostic(node, role) {
stampSemanticMetadataV1(node, { roles: [role] });
}
function rod(name, start, end, radius, color, role) {
- const from = new THREE40.Vector3(...start);
- const to = new THREE40.Vector3(...end);
+ const from = new THREE41.Vector3(...start);
+ const to = new THREE41.Vector3(...end);
const direction = to.clone().sub(from);
const length = direction.length();
- const geometry = length > 0.000000001 ? new THREE40.CylinderGeometry(radius, radius, length, 8) : new THREE40.SphereGeometry(radius, 8, 6);
- const result = new THREE40.Mesh(geometry, new THREE40.MeshBasicMaterial({ color }));
+ const geometry = length > 0.000000001 ? new THREE41.CylinderGeometry(radius, radius, length, 8) : new THREE41.SphereGeometry(radius, 8, 6);
+ const result = new THREE41.Mesh(geometry, new THREE41.MeshBasicMaterial({ color }));
result.name = name;
result.position.copy(from).add(to).multiplyScalar(0.5);
if (length > 0.000000001) {
- result.quaternion.setFromUnitVectors(new THREE40.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
+ result.quaternion.setFromUnitVectors(new THREE41.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
}
tagDiagnostic(result, role);
return result;
}
function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {
- const overlay = new THREE40.Group;
+ const overlay = new THREE41.Group;
overlay.name = "VehicleDiagnosticOverlay";
const chassisSpan = descriptor.chassisBox ? Math.max(descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0], descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1], descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2]) : 1;
const thickness = Math.max(0.01, chassisSpan * 0.008);
- const arrow = new THREE40.Group;
+ const arrow = new THREE41.Group;
arrow.name = "Diagnostic_Forward_+X";
tagDiagnostic(arrow, "diagnostic.vehicle.forward");
arrow.add(rod("Diagnostic_Forward_Shaft", descriptor.forwardArrow.start, [descriptor.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));
- const arrowHead = new THREE40.Mesh(new THREE40.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE40.MeshBasicMaterial({ color: 16724804 }));
+ const arrowHead = new THREE41.Mesh(new THREE41.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE41.MeshBasicMaterial({ color: 16724804 }));
arrowHead.name = "Diagnostic_Forward_Head";
arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);
- arrowHead.quaternion.setFromUnitVectors(new THREE40.Vector3(0, 1, 0), new THREE40.Vector3(1, 0, 0));
+ arrowHead.quaternion.setFromUnitVectors(new THREE41.Vector3(0, 1, 0), new THREE41.Vector3(1, 0, 0));
tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");
arrow.add(arrowHead);
overlay.add(arrow);
@@ -29218,18 +29720,18 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));
}
for (const wheel of descriptor.wheels) {
- const ring = new THREE40.Mesh(new THREE40.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE40.MeshBasicMaterial({ color: 16763955 }));
+ const ring = new THREE41.Mesh(new THREE41.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE41.MeshBasicMaterial({ color: 16763955 }));
ring.name = `Diagnostic_Wheel_${wheel.id}`;
ring.position.set(...wheel.center);
- const axle = new THREE40.Vector3(...wheel.axle);
+ const axle = new THREE41.Vector3(...wheel.axle);
if (axle.lengthSq() > 0.000000000001) {
- ring.quaternion.setFromUnitVectors(new THREE40.Vector3(0, 0, 1), axle.normalize());
+ ring.quaternion.setFromUnitVectors(new THREE41.Vector3(0, 0, 1), axle.normalize());
}
tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);
overlay.add(ring);
}
if (descriptor.chassisBox) {
- const chassis = new THREE40.Group;
+ const chassis = new THREE41.Group;
chassis.name = "Diagnostic_ChassisBox";
tagDiagnostic(chassis, "diagnostic.vehicle.chassis");
const { min, max } = descriptor.chassisBox;
@@ -29263,7 +29765,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(chassis);
}
if (descriptor.supportPlaneY !== undefined) {
- const plane = new THREE40.Group;
+ const plane = new THREE41.Group;
plane.name = "Diagnostic_SupportPlane";
tagDiagnostic(plane, "diagnostic.vehicle.support-plane");
const halfX = Math.max(1, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;
@@ -29861,7 +30363,7 @@ var init_views = __esm(() => {
});
// src/views/character-capture.ts
-import * as THREE41 from "three";
+import * as THREE42 from "three";
function drawLine2(rgb, width, height, from, to, color) {
let x0 = Math.round(from[0]);
let y0 = Math.round(from[1]);
@@ -29898,22 +30400,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {
}
function projector(root, cameraId, size) {
root.updateMatrixWorld(true);
- const bounds = new THREE41.Box3().setFromObject(root);
+ const bounds = new THREE42.Box3().setFromObject(root);
if (bounds.isEmpty())
- bounds.set(new THREE41.Vector3(-0.5, 0, -0.5), new THREE41.Vector3(0.5, 1, 0.5));
- const center = bounds.getCenter(new THREE41.Vector3);
- const camera = cameraId === "front" ? new THREE41.Vector3(1, 0, 0) : new THREE41.Vector3(0, 0, 1);
- const upHint = new THREE41.Vector3(0, 1, 0);
- const xAxis = new THREE41.Vector3().crossVectors(upHint, camera).normalize();
- const yAxis = new THREE41.Vector3().crossVectors(camera, xAxis).normalize();
+ bounds.set(new THREE42.Vector3(-0.5, 0, -0.5), new THREE42.Vector3(0.5, 1, 0.5));
+ const center = bounds.getCenter(new THREE42.Vector3);
+ const camera = cameraId === "front" ? new THREE42.Vector3(1, 0, 0) : new THREE42.Vector3(0, 0, 1);
+ const upHint = new THREE42.Vector3(0, 1, 0);
+ const xAxis = new THREE42.Vector3().crossVectors(upHint, camera).normalize();
+ const yAxis = new THREE42.Vector3().crossVectors(camera, xAxis).normalize();
let extent = 0.000001;
for (let corner = 0;corner < 8; corner++) {
- const point = new THREE41.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);
+ const point = new THREE42.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);
extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));
}
const scale = size * 0.45 / extent;
return (assetPoint) => {
- const world = new THREE41.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
+ const world = new THREE42.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];
};
}
@@ -30039,19 +30541,10 @@ var init_character_capture = __esm(() => {
});
// src/render.ts
-import * as THREE42 from "three";
-import { Document } from "@gltf-transform/core";
+import * as THREE43 from "three";
+import { Document, Logger } from "@gltf-transform/core";
import { KHRMaterialsEmissiveStrength } from "@gltf-transform/extensions";
-import {
- dedup,
- instance,
- palette,
- flatten,
- join as join3,
- weld,
- prune,
- mergeDocuments
-} from "@gltf-transform/functions";
+import { dedup, instance, palette, weld, prune, mergeDocuments } from "@gltf-transform/functions";
function hiddenTriangles(root, lowerLevels) {
let hidden = 0;
const visit = (node) => {
@@ -30212,7 +30705,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras) {
} else if (stdMat.transparent) {
mat.setAlphaMode("BLEND");
}
- if (stdMat.side === THREE42.DoubleSide) {
+ if (stdMat.side === THREE43.DoubleSide) {
mat.setDoubleSided(true);
}
if (stdMat.map) {
@@ -30279,7 +30772,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras) {
} else if (common.transparent || (common.opacity ?? 1) < 1) {
mat.setAlphaMode("BLEND");
}
- if (threeMat.side === THREE42.DoubleSide)
+ if (threeMat.side === THREE43.DoubleSide)
mat.setDoubleSided(true);
if (common.map && !mat.getBaseColorTexture()) {
const texture = bridgeTexture(doc, common.map, textureCache);
@@ -30414,7 +30907,7 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache,
const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;
let gtMesh = meshCache.get(cacheKey);
if (!gtMesh) {
- const geometry = new THREE42.PlaneGeometry(1, 1);
+ const geometry = new THREE43.PlaneGeometry(1, 1);
if (centerX !== 0.5 || centerY !== 0.5) {
geometry.translate(0.5 - centerX, 0.5 - centerY, 0);
}
@@ -30438,9 +30931,9 @@ function animationInterpolation(track) {
if (isCubicSplineTrack(track))
return "CUBICSPLINE";
const mode = track.getInterpolation();
- if (mode === THREE42.InterpolateDiscrete)
+ if (mode === THREE43.InterpolateDiscrete)
return "STEP";
- if (mode === THREE42.InterpolateLinear)
+ if (mode === THREE43.InterpolateLinear)
return "LINEAR";
throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);
}
@@ -30604,27 +31097,41 @@ async function applyGpuInstancing(doc, mode, role) {
const after = collectGlbMetrics(doc);
return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };
}
-async function consolidateMaterials(doc, mode) {
+async function consolidateMaterials(doc, mode, keep = []) {
+ doc.setLogger(new Logger(Logger.Verbosity.WARN));
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 || hasNodeLevelsOfDetail(doc) || hasPreservedNodeState(doc)) ? "palette" : mode;
const steps = root.listMaterials().some((material) => Object.keys(material.getExtras()).length > 0) ? [] : [palette({ min: PALETTE_MIN })];
- if (effective === "full") {
- steps.push(flatten(), join3({ keepNamed: true }));
- }
+ let merge;
+ if (mode === "full")
+ steps.push(rigidMerge({ keep }, (summary) => {
+ merge = summary;
+ }));
steps.push(weld(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));
await doc.transform(...steps);
const after = collectGlbMetrics(doc);
return {
- mode: effective,
+ mode,
materialsBefore: before.uniqueMaterials,
materialsAfter: after.uniqueMaterials,
drawsBefore: before.drawCalls,
- drawsAfter: after.drawCalls
+ drawsAfter: after.drawCalls,
+ ...merge ? { rigidMerge: merge } : {}
};
}
+function optimizeWarnings(summary) {
+ const merge = summary.rigidMerge;
+ if (!merge)
+ return [];
+ const warnings = [];
+ if (merge.skipped)
+ warnings.push(`Rigid merge skipped: ${merge.skipped}; geometry left separate.`);
+ if (merge.rejected.length)
+ warnings.push(`Rigid merge retained ${merge.rejected.length} rejected buckets; first: ${merge.rejected[0].error}`);
+ if (merge.unmatchedKeep.length)
+ warnings.push(`Rigid merge did not find ${merge.unmatchedKeep.length} requested boundary names.`);
+ return warnings;
+}
async function renderSceneToGLB(root, opts = {}) {
assertNoLegacyRuntimePolicy(opts);
const requirements = resolveRequirementsContext(opts.requirements);
@@ -30720,6 +31227,7 @@ async function renderSceneToGLB(root, opts = {}) {
if (effectiveOptimize !== "off") {
try {
optimize = await consolidateMaterials(doc, effectiveOptimize);
+ warnings.push(...optimizeWarnings(optimize));
} catch (err) {
warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);
}
@@ -30823,6 +31331,7 @@ async function renderGLBInProcess(code, opts = {}) {
gltfExporter: resolveGltfExporter(opts.gltfExporter),
geometryPolicy: opts.geometryPolicy ?? "warn",
optimize: resolveOptimize(opts.optimize),
+ ...resolveOptimize(opts.optimize) === "full" ? { optimizationPipeline: FULL_OPTIMIZATION_PIPELINE } : {},
instance: resolveInstance(opts.instance)
};
let materialLibraryDependencies;
@@ -30948,8 +31457,8 @@ function collectMeshStats(root) {
if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {
return;
}
- const center = new THREE42.Vector3;
- const size = new THREE42.Vector3;
+ const center = new THREE43.Vector3;
+ const size = new THREE43.Vector3;
box.getCenter(center);
box.getSize(size);
out.push({
@@ -30964,7 +31473,7 @@ function collectMeshStats(root) {
return out;
}
function minimalGapVector(a, b) {
- const v = new THREE42.Vector3;
+ const v = new THREE43.Vector3;
for (const axis of ["x", "y", "z"]) {
if (a.min[axis] > b.max[axis])
v[axis] = b.max[axis] - a.min[axis];
@@ -30982,10 +31491,10 @@ function inspectSceneStructure(root, opts = {}) {
return warnings;
const cat = opts.category?.toLowerCase();
if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {
- const all = new THREE42.Box3;
+ const all = new THREE43.Box3;
for (const m of meshes)
all.union(m.box);
- const size = new THREE42.Vector3;
+ const size = new THREE43.Vector3;
all.getSize(size);
if (cat === "aircraft") {
if (size.y > size.x * 1.2) {
@@ -31078,6 +31587,8 @@ var init_render = __esm(() => {
init_material_recipe_runtime();
init_material_resources();
init_texture_resolver();
+ init_rebuild_options();
+ init_rigid_merge();
init_validation();
init_kit();
init_texture_bake();
@@ -31528,12 +32039,12 @@ var init_subprocess = __esm(() => {
});
// src/workspace-location.ts
-import { dirname as dirname3, join as join4, resolve as resolve5 } from "node:path";
+import { dirname as dirname3, join as join3, resolve as resolve5 } from "node:path";
function localWorkspaceRoot(env = process.env) {
return env.KILN_WORKSPACE ? resolve5(env.KILN_WORKSPACE) : env.KILN_PROGRAM_STORE ? dirname3(dirname3(resolve5(env.KILN_PROGRAM_STORE))) : process.cwd();
}
function localProgramStoreDirectory(env = process.env) {
- return env.KILN_PROGRAM_STORE ? resolve5(env.KILN_PROGRAM_STORE) : join4(localWorkspaceRoot(env), ".kiln", "programs");
+ return env.KILN_PROGRAM_STORE ? resolve5(env.KILN_PROGRAM_STORE) : join3(localWorkspaceRoot(env), ".kiln", "programs");
}
var init_workspace_location = () => {};
@@ -31633,7 +32144,7 @@ __export(exports_program_store_node, {
});
import { link as link2, lstat as lstat3, mkdir as mkdir3, readFile as readFile2, readdir as readdir2, stat as stat2, unlink as unlink2, writeFile as writeFile3 } from "node:fs/promises";
import { randomUUID as randomUUID3 } from "node:crypto";
-import { join as join5 } from "node:path";
+import { join as join4 } from "node:path";
class FileProgramStore {
directory;
@@ -31649,7 +32160,7 @@ class FileProgramStore {
if (!entry.isFile() || !/^[a-f0-9]{64}\.js$/.test(entry.name))
continue;
try {
- bytes += (await stat2(join5(this.directory, entry.name))).size;
+ bytes += (await stat2(join4(this.directory, entry.name))).size;
entries++;
} catch (error) {
if (error.code !== "ENOENT")
@@ -31667,7 +32178,7 @@ class FileProgramStore {
const canonical = ref.startsWith("p_") ? await this.readHandle(ref) : ref;
if (canonical === undefined)
throw this.notFound(ref);
- const path = join5(this.directory, `${canonical.slice(7)}.js`);
+ const path = join4(this.directory, `${canonical.slice(7)}.js`);
let code;
try {
if ((await stat2(path)).size > MAX_PROGRAM_BYTES)
@@ -31686,7 +32197,7 @@ class FileProgramStore {
return programNotFound(ref, "This program store has no such reference; it was issued by another store (KILN_PROGRAM_STORE selects which) or its store was removed.");
}
async readHandle(handle) {
- const path = join5(this.directory, "refs", `${handle}.ref`);
+ const path = join4(this.directory, "refs", `${handle}.ref`);
try {
const info = await lstat3(path);
if (!info.isFile() || info.size !== 71)
@@ -31705,7 +32216,7 @@ class FileProgramStore {
await this.get(ref);
if (ref.startsWith("p_"))
return ref;
- const directory = join5(this.directory, "refs");
+ const directory = join4(this.directory, "refs");
await mkdir3(directory, { recursive: true });
for (const handle of shortProgramRefCandidates(ref)) {
const owner = await this.readHandle(handle);
@@ -31713,11 +32224,11 @@ class FileProgramStore {
return handle;
if (owner !== undefined)
continue;
- const temporary = join5(directory, `.write-${randomUUID3()}`);
+ const temporary = join4(directory, `.write-${randomUUID3()}`);
await writeFile3(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });
try {
try {
- await link2(temporary, join5(directory, `${handle}.ref`));
+ await link2(temporary, join4(directory, `${handle}.ref`));
return handle;
} catch (error) {
if (error.code !== "EEXIST")
@@ -31734,8 +32245,8 @@ class FileProgramStore {
async put(code) {
const ref = await programReference(code);
await mkdir3(this.directory, { recursive: true });
- const target = join5(this.directory, `${ref.slice(7)}.js`);
- const temporary = join5(this.directory, `.write-${randomUUID3()}`);
+ const target = join4(this.directory, `${ref.slice(7)}.js`);
+ const temporary = join4(this.directory, `.write-${randomUUID3()}`);
await writeFile3(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });
try {
try {
@@ -31968,7 +32479,7 @@ import {
utimes,
writeFile as writeFile4
} from "node:fs/promises";
-import { join as join6, resolve as resolve6 } from "node:path";
+import { join as join5, resolve as resolve6 } from "node:path";
class FileBuildCache {
maxBytes;
@@ -31982,7 +32493,7 @@ class FileBuildCache {
path(key) {
if (!keyPattern.test(key))
throw new Error("Invalid build cache key.");
- return join6(this.directory, `${key.slice(7)}.json`);
+ return join5(this.directory, `${key.slice(7)}.json`);
}
async get(key) {
const path = this.path(key);
@@ -32010,7 +32521,7 @@ class FileBuildCache {
if (Buffer.byteLength(bytes) > Math.min(this.maxBytes, 96 * 1024 * 1024))
return;
await mkdir4(this.directory, { recursive: true });
- const temporary = join6(this.directory, `.write-${randomUUID4()}`);
+ const temporary = join5(this.directory, `.write-${randomUUID4()}`);
await writeFile4(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });
try {
await rename3(temporary, path);
@@ -32024,7 +32535,7 @@ class FileBuildCache {
for (const name of await readdir3(this.directory)) {
if (!filePattern.test(name))
continue;
- const path = join6(this.directory, name);
+ const path = join5(this.directory, name);
try {
const item = await stat3(path);
entries.push({ path, size: item.size, used: item.mtimeMs });
@@ -32051,14 +32562,14 @@ var init_build_cache_node = __esm(() => {
import { createHash as createHash11 } from "node:crypto";
import { lstat as lstat4, readFile as readFile4, readdir as readdir4, realpath as realpath3, stat as stat4 } from "node:fs/promises";
import { createRequire } from "node:module";
-import { dirname as dirname4, join as join7, relative as relative2 } from "node:path";
+import { dirname as dirname4, join as join6, relative as relative2 } from "node:path";
async function installedRuntimeIdentity(root, limits = {}) {
let bytes = 0;
let files = 0;
const absentPackages = [];
const maxBytes = limits.maxBytes ?? 512 * 1024 * 1024;
const maxFiles = limits.maxFiles ?? 40000;
- const manifest = async (directory) => JSON.parse(await readFile4(join7(directory, "package.json"), "utf8"));
+ const manifest = async (directory) => JSON.parse(await readFile4(join6(directory, "package.json"), "utf8"));
let readers = 0;
const waiting = [];
const read = async (path) => {
@@ -32084,17 +32595,17 @@ async function installedRuntimeIdentity(root, limits = {}) {
const pkg = await manifest(root);
if (pkg.name !== "@kiln/engine")
throw new Error("Not a Kiln installation.");
- const build = JSON.parse(await readFile4(join7(root, "dist", "build.json"), "utf8"));
+ const build = JSON.parse(await readFile4(join6(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:${digest4(await read(join7(root, "dist", worker.file)))}`;
+ const workerHash = `sha256:${digest4(await read(join6(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 = createRequire(join7(parent, "package.json"));
+ const require2 = createRequire(join6(parent, "package.json"));
let found;
try {
found = require2.resolve(`${name}/package.json`);
@@ -32103,7 +32614,7 @@ async function installedRuntimeIdentity(root, limits = {}) {
found = require2.resolve(name);
} catch {
for (const modules of require2.resolve.paths(name) ?? []) {
- const candidate = join7(modules, name);
+ const candidate = join6(modules, name);
try {
await lstat4(candidate);
} catch (error) {
@@ -32135,7 +32646,7 @@ async function installedRuntimeIdentity(root, limits = {}) {
return (await Promise.all(entries.map(async (entry) => {
if (entry.name === "node_modules" || entry.name === ".git")
return [];
- const path = join7(directory, entry.name);
+ const path = join6(directory, entry.name);
if (entry.isSymbolicLink())
throw new Error("Dependency contains an untracked internal symlink.");
if (entry.isDirectory())
@@ -32384,7 +32895,7 @@ var init_projects = __esm(() => {
// src/projects-node.ts
import { createHash as createHash12, randomUUID as randomUUID5 } from "node:crypto";
import { link as link3, lstat as lstat5, mkdir as mkdir5, open as open3, readdir as readdir5, realpath as realpath4, unlink as unlink4 } from "node:fs/promises";
-import { join as join8, relative as relative3, resolve as resolve7, sep as sep2 } from "node:path";
+import { join as join7, relative as relative3, resolve as resolve7, sep as sep2 } from "node:path";
function sequenceOf(revisionId) {
projectRevisionIdSchema.parse(revisionId);
const sequence = Number(revisionId.slice(2, 12));
@@ -32404,7 +32915,7 @@ class FileProjectStore {
if (!workspace.trim())
throw new Error("A workspace directory is required");
this.workspace = resolve7(workspace);
- this.directory = join8(this.workspace, ".kiln", "projects");
+ this.directory = join7(this.workspace, ".kiln", "projects");
}
async path(projectId, create = false) {
if (projectId !== undefined)
@@ -32414,7 +32925,7 @@ class FileProjectStore {
const canonical = await realpath4(this.workspace);
let path = this.workspace;
for (const part of [".kiln", "projects", ...projectId ? [projectId, "revisions"] : []]) {
- path = join8(path, part);
+ path = join7(path, part);
if (create)
await mkdir5(path).catch((error) => {
if (!exists(error))
@@ -32446,7 +32957,7 @@ class FileProjectStore {
return latest;
}
async load(projectId, directory, sequence) {
- const path = join8(directory, filename(sequence));
+ const path = join7(directory, filename(sequence));
const info = await lstat5(path);
if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_PROJECT_BYTES)
throw new Error("Invalid or oversized project revision file");
@@ -32529,7 +33040,7 @@ class FileProjectStore {
for (const revision of new Set(record.reviews.map((review) => review.projectRevisionId)))
await this.read(record.projectId, revision);
const directory = await this.path(record.projectId, true);
- const temporary = join8(directory, `.write-${randomUUID5()}`);
+ const temporary = join7(directory, `.write-${randomUUID5()}`);
const handle = await open3(temporary, "wx", 384);
try {
try {
@@ -32539,7 +33050,7 @@ class FileProjectStore {
await handle.close();
}
try {
- await link3(temporary, join8(directory, filename(sequenceOf(record.revisionId))));
+ await link3(temporary, join7(directory, filename(sequenceOf(record.revisionId))));
} catch (error) {
if (!exists(error))
throw error;
@@ -32617,7 +33128,7 @@ var init_workspace = __esm(() => {
// src/workspace-node.ts
import { AsyncLocalStorage } from "node:async_hooks";
-import { join as join9 } from "node:path";
+import { join as join8 } from "node:path";
class FileWorkspace {
root;
@@ -32629,7 +33140,7 @@ class FileWorkspace {
this.root = root;
this.defaultProjectId = defaultProjectId;
this.projects = new FileProjectStore(root);
- this.materials = new FileMaterialLibrary(join9(root, ".kiln", "materials"));
+ this.materials = new FileMaterialLibrary(join8(root, ".kiln", "materials"));
}
current() {
return this.active.getStore();
@@ -32879,7 +33390,7 @@ import {
writeFile as writeFile5,
realpath as realpath5
} from "node:fs/promises";
-import { join as join10, resolve as resolve8, relative as relative4, sep as sep3 } from "node:path";
+import { join as join9, resolve as resolve8, relative as relative4, sep as sep3 } from "node:path";
import { z as z8 } from "zod";
function notify(run) {
try {
@@ -33052,7 +33563,7 @@ class FileLiveReview {
unreportedIssues = [];
constructor(workspace, options = {}) {
this.workspace = resolve8(workspace);
- this.directory = join10(this.workspace, ".kiln", "review");
+ this.directory = join9(this.workspace, ".kiln", "review");
this.maxOperations = options.maxOperations ?? 200;
this.maxBytes = options.maxBytes ?? 256 * 1024 * 1024;
this.maxQueuedBytes = options.maxQueuedBytes ?? 128 * 1024 * 1024;
@@ -33075,7 +33586,7 @@ class FileLiveReview {
path(operationId, file) {
if (!operationPattern.test(operationId))
throw new Error("Invalid operation ID");
- return join10(this.directory, operationId, ...file ? [file] : []);
+ return join9(this.directory, operationId, ...file ? [file] : []);
}
async root(create = false) {
if (create)
@@ -33083,7 +33594,7 @@ class FileLiveReview {
const canonical = await realpath5(this.workspace);
let path = this.workspace;
for (const part of [".kiln", "review"]) {
- path = join10(path, part);
+ path = join9(path, part);
if (create)
await mkdir6(path).catch((error) => {
if (!collision(error))
@@ -33121,7 +33632,7 @@ class FileLiveReview {
async locked(run) {
await this.root(true);
const token = randomUUID6();
- const directory = join10(this.directory, ".locks");
+ const directory = join9(this.directory, ".locks");
await mkdir6(directory).catch((error) => {
if (!collision(error))
throw error;
@@ -33129,7 +33640,7 @@ class FileLiveReview {
const info = await lstat6(directory);
if (!info.isDirectory() || info.isSymbolicLink())
throw new Error("Unsafe live lock directory");
- const candidate = join10(directory, `.candidate-${process.pid}-${token}.tmp`);
+ const candidate = join9(directory, `.candidate-${process.pid}-${token}.tmp`);
const owner = JSON.stringify({ pid: process.pid, token });
await writeFile5(candidate, owner, { flag: "wx", mode: 384 });
const generations = async () => (await readdir6(directory)).filter((name) => /^[0-9]{16}\.lock$/.test(name)).sort();
@@ -33146,8 +33657,8 @@ class FileLiveReview {
throw new Error("Live lock generation exhausted");
if (latest) {
try {
- const prior = z8.object({ pid: z8.number().int().positive(), token: z8.string().uuid() }).strict().parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join10(directory, latest), 1024))));
- const released = await lstat6(join10(directory, `${latest}.released`)).then((entry) => {
+ const prior = z8.object({ pid: z8.number().int().positive(), token: z8.string().uuid() }).strict().parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join9(directory, latest), 1024))));
+ const released = await lstat6(join9(directory, `${latest}.released`)).then((entry) => {
if (!entry.isFile() || entry.isSymbolicLink() || entry.size !== 0)
throw new Error("Invalid lock release");
return true;
@@ -33168,9 +33679,9 @@ class FileLiveReview {
}
const name = `${String(sequence).padStart(16, "0")}.lock`;
try {
- await link4(candidate, join10(directory, name));
+ await link4(candidate, join9(directory, name));
if ((await generations()).at(-1) !== name) {
- await unlink5(join10(directory, name));
+ await unlink5(join9(directory, name));
continue;
}
acquired = name;
@@ -33180,8 +33691,8 @@ class FileLiveReview {
}
}
for (const name of (await generations()).slice(0, -3)) {
- await unlink5(join10(directory, name));
- await unlink5(join10(directory, `${name}.released`)).catch((error) => {
+ await unlink5(join9(directory, name));
+ await unlink5(join9(directory, `${name}.released`)).catch((error) => {
if (!missing2(error))
throw error;
});
@@ -33189,18 +33700,18 @@ class FileLiveReview {
for (const name of await readdir6(directory)) {
const match = /^\.candidate-([0-9]+)-[a-f0-9-]+\.tmp$/.exec(name);
if (match && dead(Number(match[1])))
- await unlink5(join10(directory, name)).catch(() => {});
+ await unlink5(join9(directory, name)).catch(() => {});
}
await this.limits(true);
return await run();
} finally {
if (acquired)
- await writeFile5(join10(directory, `${acquired}.released`), "", { flag: "wx", mode: 384 });
+ await writeFile5(join9(directory, `${acquired}.released`), "", { flag: "wx", mode: 384 });
await unlink5(candidate).catch(() => {});
}
}
async limits(create = false) {
- const path = join10(this.directory, "limits.json");
+ const path = join9(this.directory, "limits.json");
try {
const value = JSON.parse(new TextDecoder().decode(await this.boundedFile(path, 1024)));
const parsed = z8.object({
@@ -33274,7 +33785,7 @@ class FileLiveReview {
try {
await this.locked(async () => {
const previous = await this.health();
- await this.atomic(join10(this.directory, "health.json"), JSON.stringify([...new Set([...previous, ...issues])].slice(-20)));
+ await this.atomic(join9(this.directory, "health.json"), JSON.stringify([...new Set([...previous, ...issues])].slice(-20)));
});
this.unreportedIssues = this.unreportedIssues.filter((value) => !issues.includes(value));
} catch {}
@@ -33437,7 +33948,7 @@ class FileLiveReview {
const info = await lstat6(directory);
if (!info.isDirectory() || info.isSymbolicLink())
throw new Error("Unsafe live directory");
- const raw = JSON.parse(new TextDecoder().decode(await this.boundedFile(join10(directory, "record.json"), metadataLimit)));
+ const raw = JSON.parse(new TextDecoder().decode(await this.boundedFile(join9(directory, "record.json"), metadataLimit)));
const state = stateSchema.parse(jsonValue(raw, metadataLimit));
if (state.operation.operationId !== operationId)
throw new Error("Invalid live identity");
@@ -33456,7 +33967,7 @@ class FileLiveReview {
throw new Error("Invalid artifact descriptor");
if (state.operation.captures.some((file) => !/^capture-\d{1,2}\.png$/.test(file.name)))
throw new Error("Invalid capture descriptor");
- state.operation.pinned = await lstat6(join10(directory, "pinned")).then((s) => {
+ state.operation.pinned = await lstat6(join9(directory, "pinned")).then((s) => {
if (!s.isFile() || s.isSymbolicLink())
throw new Error("Invalid live pin");
return true;
@@ -33478,7 +33989,7 @@ class FileLiveReview {
for (const entry of await readdir6(directory, { withFileTypes: true })) {
if (!entry.isFile() || entry.isSymbolicLink())
throw new Error("Invalid live directory entry");
- bytes += (await lstat6(join10(directory, entry.name))).size;
+ bytes += (await lstat6(join9(directory, entry.name))).size;
}
this.storedSizes.set(state, bytes);
return state;
@@ -33529,7 +34040,7 @@ class FileLiveReview {
}
async health() {
try {
- return z8.array(z8.string().max(500)).max(20).parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join10(this.directory, "health.json"), 16384))));
+ return z8.array(z8.string().max(500)).max(20).parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join9(this.directory, "health.json"), 16384))));
} catch (error) {
if (missing2(error))
return [];
@@ -33596,8 +34107,8 @@ class FileLiveReview {
if ((await lstat6(directory)).isSymbolicLink())
throw new Error("Unsafe live directory");
for (const [name, data] of Object.entries(blobs))
- await this.atomic(join10(directory, name), data);
- await this.atomic(join10(directory, "record.json"), JSON.stringify(state));
+ await this.atomic(join9(directory, name), data);
+ await this.atomic(join9(directory, "record.json"), JSON.stringify(state));
await this.cleanupRecord(await this.record(state.operation.operationId));
}
async remove(operationId) {
@@ -33785,7 +34296,7 @@ import {
writeFile as writeFile6
} from "node:fs/promises";
import { homedir, platform } from "node:os";
-import { dirname as dirname5, join as join11, relative as relative5, resolve as resolve9, sep as sep4, win32 } from "node:path";
+import { dirname as dirname5, join as join10, relative as relative5, resolve as resolve9, sep as sep4, win32 } from "node:path";
function assertMaterialAllocation(records) {
let bytes = 0;
for (const record of records)
@@ -33829,7 +34340,7 @@ class FileAssetLibrary {
return root;
}
revisionDirectory(collection, assetId, revisionId) {
- return join11(this.directory(collection), assetIdSchema.parse(assetId), "revisions", assetIdSchema.parse(revisionId));
+ return join10(this.directory(collection), assetIdSchema.parse(assetId), "revisions", assetIdSchema.parse(revisionId));
}
async path(collection, ...parts) {
const root = this.directory(collection);
@@ -33838,7 +34349,7 @@ class FileAssetLibrary {
let path = root;
for (const part of parts) {
assetIdSchema.parse(part);
- path = join11(path, part);
+ path = join10(path, part);
try {
const entry = await lstat7(path);
if (entry.isSymbolicLink())
@@ -33881,7 +34392,7 @@ class FileAssetLibrary {
return records.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.revisionId.localeCompare(b.revisionId));
}
async file(dir, name, limit = ASSET_LIMIT) {
- const path = join11(dir, name);
+ const path = join10(dir, name);
const info = await lstat7(path);
if (!info.isFile() || info.isSymbolicLink() || info.size > limit)
throw new Error("Invalid collection file");
@@ -33997,14 +34508,14 @@ class FileAssetLibrary {
const dest = await this.path(collection, manifest.assetId, "revisions", manifest.revisionId);
const parent = dirname5(dest);
await mkdir7(parent, { recursive: true });
- const stage = join11(parent, `.write-${randomUUID7()}`);
+ const stage = join10(parent, `.write-${randomUUID7()}`);
await mkdir7(stage);
try {
for (const [name, bytes] of Object.entries(files))
- await writeFile6(join11(stage, name), bytes, { flag: "wx" });
+ await writeFile6(join10(stage, name), bytes, { flag: "wx" });
if (record.materialResources)
- await writeFile6(join11(stage, ASSET_MATERIAL_FILE), JSON.stringify(record.materialResources), { flag: "wx" });
- await writeFile6(join11(stage, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
+ await writeFile6(join10(stage, ASSET_MATERIAL_FILE), JSON.stringify(record.materialResources), { flag: "wx" });
+ await writeFile6(join10(stage, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
`, {
flag: "wx"
});
@@ -34018,7 +34529,7 @@ class FileAssetLibrary {
throw error;
if (record.materialResources && !existing.materialResources) {
try {
- await link5(join11(stage, ASSET_MATERIAL_FILE), join11(dest, ASSET_MATERIAL_FILE));
+ await link5(join10(stage, ASSET_MATERIAL_FILE), join10(dest, ASSET_MATERIAL_FILE));
} catch (enrichmentError) {
if (enrichmentError.code !== "EEXIST")
throw enrichmentError;
@@ -34036,17 +34547,17 @@ class FileAssetLibrary {
}
}
function collectionConfigPath(env = process.env) {
- return join11(localWorkspaceRoot(env), ".kiln", "collections.json");
+ return join10(localWorkspaceRoot(env), ".kiln", "collections.json");
}
function defaultUserLibraryRoot(env = process.env, home = homedir(), operatingSystem = platform()) {
const dataRoot = env.XDG_DATA_HOME?.trim();
if (dataRoot)
- return join11(dataRoot, "kiln", "library");
+ return join10(dataRoot, "kiln", "library");
if (operatingSystem === "darwin")
- return join11(home, "Library", "Application Support", "Kiln", "library");
+ return join10(home, "Library", "Application Support", "Kiln", "library");
if (operatingSystem === "win32")
- return join11(env.LOCALAPPDATA?.trim() || join11(home, "AppData", "Local"), "Kiln", "library");
- return join11(home, ".local", "share", "kiln", "library");
+ return join10(env.LOCALAPPDATA?.trim() || join10(home, "AppData", "Local"), "Kiln", "library");
+ return join10(home, ".local", "share", "kiln", "library");
}
function assertCollectionRoot(id, path, operatingSystem = platform(), source) {
if (operatingSystem !== "win32" || windowsDrivePath.test(path) || windowsSharePath.test(path))
@@ -34065,10 +34576,10 @@ function configuredRoots(text, source, operatingSystem) {
}
function localAssetLibrary(env = process.env, operatingSystem = platform()) {
if (env.KILN_COLLECTIONS)
- return new FileAssetLibrary(configuredRoots(env.KILN_COLLECTIONS, "KILN_COLLECTIONS", operatingSystem), new FileMaterialLibrary(join11(localWorkspaceRoot(env), ".kiln", "materials")));
+ return new FileAssetLibrary(configuredRoots(env.KILN_COLLECTIONS, "KILN_COLLECTIONS", operatingSystem), new FileMaterialLibrary(join10(localWorkspaceRoot(env), ".kiln", "materials")));
const config = collectionConfigPath(env);
const workspace = dirname5(dirname5(config));
- const materials = new FileMaterialLibrary(join11(workspace, ".kiln", "materials"));
+ const materials = new FileMaterialLibrary(join10(workspace, ".kiln", "materials"));
let text;
try {
text = readFileSync2(config, "utf8");
@@ -34082,7 +34593,7 @@ function localAssetLibrary(env = process.env, operatingSystem = platform()) {
return new FileAssetLibrary(configuredRoots(text, config, operatingSystem), materials);
}
return new FileAssetLibrary({
- project: join11(workspace, "assets", "kiln"),
+ project: join10(workspace, "assets", "kiln"),
library: defaultUserLibraryRoot(env, homedir(), operatingSystem)
}, materials);
}
@@ -34097,6 +34608,10 @@ var init_assets_node = __esm(() => {
});
// src/asset-export.ts
+var exports_asset_export = {};
+__export(exports_asset_export, {
+ exportAssetGlb: () => exportAssetGlb
+});
async function sha2562(bytes) {
const digest = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));
return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
@@ -34476,7 +34991,7 @@ var init_project_bundle = __esm(() => {
// src/project-bundle-node.ts
import { randomUUID as randomUUID8 } from "node:crypto";
import { link as link6, lstat as lstat8, mkdir as mkdir8, readFile as readFile7, realpath as realpath7, unlink as unlink6, writeFile as writeFile7 } from "node:fs/promises";
-import { join as join12, relative as relative6, resolve as resolve10, sep as sep5 } from "node:path";
+import { join as join11, relative as relative6, resolve as resolve10, sep as sep5 } from "node:path";
async function assetMaterials(workspace, asset) {
return resolveSavedAssetMaterials(asset, workspace.materials);
}
@@ -34526,7 +35041,7 @@ async function retainArchive(workspace, bytes, digest) {
const canonical = await realpath7(root);
let directory = root;
for (const part of [".kiln", "imports"]) {
- directory = join12(directory, part);
+ directory = join11(directory, part);
await mkdir8(directory).catch((error) => {
if (error.code !== "EEXIST")
throw error;
@@ -34536,8 +35051,8 @@ async function retainArchive(workspace, bytes, digest) {
if (!info.isDirectory() || info.isSymbolicLink() || rel === ".." || rel.startsWith(`..${sep5}`))
throw new Error("Unsafe project import directory");
}
- const file = join12(directory, `${digest.slice(7)}.zip`);
- const temporary = join12(directory, `.import-${randomUUID8()}.tmp`);
+ const file = join11(directory, `${digest.slice(7)}.zip`);
+ const temporary = join11(directory, `.import-${randomUUID8()}.tmp`);
await writeFile7(temporary, bytes, { flag: "wx", mode: 384 });
try {
try {
@@ -34689,7 +35204,7 @@ var init_source_check = __esm(() => {
// src/local-runtime.ts
import { readFile as readFile8, stat as stat5 } from "node:fs/promises";
-import { dirname as dirname6, isAbsolute, join as join13, resolve as resolve11 } from "node:path";
+import { dirname as dirname6, isAbsolute, join as join12, resolve as resolve11 } from "node:path";
import { fileURLToPath as fileURLToPath4 } from "node:url";
import { Console } from "node:console";
function workspaceSourceReader(root) {
@@ -34880,7 +35395,7 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst
}
const cacheBytes = integer2(env, "KILN_BUILD_CACHE_MB", 128, 0, 1024) * 1024 * 1024;
const store = context.programStore;
- const directory = resolve11(env.KILN_BUILD_CACHE_DIR ?? join13(store instanceof FileProgramStore ? dirname6(store.directory) : ".kiln", "cache", "builds"));
+ const directory = resolve11(env.KILN_BUILD_CACHE_DIR ?? join12(store instanceof FileProgramStore ? dirname6(store.directory) : ".kiln", "cache", "builds"));
context.buildCache = new FileBuildCache(directory, cacheBytes);
context.evaluatorCacheIdentity = `${identity.identity}:${JSON.stringify({
execution: context.localExecution,
@@ -40656,12 +41171,12 @@ var exports_part_placement = {};
__export(exports_part_placement, {
createPartPlacementReader: () => createPartPlacementReader
});
-import * as THREE43 from "three";
+import * as THREE44 from "three";
function createPartPlacementReader(root) {
const bounds = createPartBoundsReader(root);
- const position = new THREE43.Vector3;
- const quaternion = new THREE43.Quaternion;
- const scale = new THREE43.Vector3;
+ const position = new THREE44.Vector3;
+ const quaternion = new THREE44.Quaternion;
+ const scale = new THREE44.Vector3;
return (node) => {
node.matrixWorld.decompose(position, quaternion, scale);
const box = bounds(node);
@@ -40812,13 +41327,13 @@ var init_inspect = __esm(() => {
});
// src/views/measurement.ts
-import { Box3 as Box322, Vector3 as Vector336 } from "three";
+import { Box3 as Box323, Vector3 as Vector337 } from "three";
function describeSubjectFrame(root, subject) {
const selected = selectCameraSubject(root, subject);
selected.node.updateWorldMatrix(true, true);
const matrix = selected.node.matrixWorld;
- const bounds = new Box322().setFromObject(selected.node);
- const local = new Box322;
+ const bounds = new Box323().setFromObject(selected.node);
+ const local = new Box323;
const invertible = matrix.determinant() !== 0;
const inverse = matrix.clone().invert();
selected.node.traverse((node) => {
@@ -40829,10 +41344,10 @@ function describeSubjectFrame(root, subject) {
if (!attr)
return;
for (let i = 0;i < attr.count; i++)
- local.expandByPoint(new Vector336().fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse));
+ local.expandByPoint(new Vector337().fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse));
});
const box = (b) => b.isEmpty() ? null : { min: b.min.toArray(), max: b.max.toArray() };
- const axis = (i) => new Vector336().setFromMatrixColumn(matrix, i).normalize().toArray();
+ const axis = (i) => new Vector337().setFromMatrixColumn(matrix, i).normalize().toArray();
return {
path: selected.path,
name: selected.name,
@@ -40842,7 +41357,7 @@ function describeSubjectFrame(root, subject) {
invertible,
worldMatrix: matrix.toArray(),
axes: { frame: "world", x: axis(0), y: axis(1), z: axis(2) },
- origin: new Vector336().setFromMatrixPosition(matrix).toArray()
+ origin: new Vector337().setFromMatrixPosition(matrix).toArray()
};
}
function measureAttachment(root, input) {
@@ -40855,7 +41370,7 @@ function measureAttachment(root, input) {
return {
path: selected.path,
local: [...local],
- world: new Vector336(...local).applyMatrix4(selected.node.matrixWorld).toArray()
+ world: new Vector337(...local).applyMatrix4(selected.node.matrixWorld).toArray()
};
};
const from = endpoint(input.from), to = endpoint(input.to);
@@ -40865,7 +41380,7 @@ function measureAttachment(root, input) {
method: "straight-line anchor distance",
from,
to,
- distance: new Vector336(...from.world).distanceTo(new Vector336(...to.world))
+ distance: new Vector337(...from.world).distanceTo(new Vector337(...to.world))
};
}
var init_measurement = __esm(() => {
@@ -40874,10 +41389,10 @@ var init_measurement = __esm(() => {
// src/revision-comparison.ts
import {
- PropertyType as PropertyType3
+ PropertyType as PropertyType4
} from "@gltf-transform/core";
import { ALL_EXTENSIONS as ALL_EXTENSIONS2 } from "@gltf-transform/extensions";
-import { Box3 as Box323, Matrix4 as Matrix414, Vector3 as Vector337 } from "three";
+import { Box3 as Box324, Matrix4 as Matrix415, Vector3 as Vector338 } from "three";
async function accessorFingerprint(accessor) {
const array = accessor?.getArray();
if (!accessor || !array)
@@ -40890,13 +41405,13 @@ async function accessorFingerprint(accessor) {
];
}
function lowerLevels(node) {
- return (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType3.NODE);
+ return (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType4.NODE);
}
function bounds(box) {
return box.isEmpty() ? null : {
min: box.min.toArray(),
max: box.max.toArray(),
- size: box.getSize(new Vector337).toArray()
+ size: box.getSize(new Vector338).toArray()
};
}
async function digest7(bytes) {
@@ -40930,7 +41445,7 @@ async function snapshot3(bytes) {
if (depth > 128)
throw new Error("Revision comparison hierarchy exceeds 128 levels.");
const names = new Set;
- const combined = new Box323;
+ const combined = new Box324;
const placed = siblings.flatMap((node) => [
{ node, drawn: true },
...lowerLevels(node).map((level) => ({ node: level, drawn: false }))
@@ -40947,8 +41462,8 @@ async function snapshot3(bytes) {
if (node.listExtensions().some((extension) => extension.extensionName !== MSFT_LOD && extension.extensionName !== "KHR_node_visibility") || mesh?.listExtensions().length)
throw new Error("Revision comparison does not support node/mesh extensions (including instancing).");
const primitives = mesh?.listPrimitives() ?? [];
- const own = new Box323;
- const matrix = parentWorld.clone().multiply(new Matrix414().fromArray(node.getMatrix()));
+ const own = new Box324;
+ const matrix = parentWorld.clone().multiply(new Matrix415().fromArray(node.getMatrix()));
if (matrix.elements.some((value) => !Number.isFinite(value)))
throw new Error("Revision comparison requires finite transforms.");
for (const primitive of primitives) {
@@ -40960,7 +41475,7 @@ async function snapshot3(bytes) {
const indices = primitive.getIndices();
const count = indices?.getCount() ?? position.getCount();
vertices += count;
- if (vertices > MAX_VERTICES)
+ if (vertices > MAX_VERTICES2)
throw new Error("Revision comparison exceeds 2,000,000 placed vertices.");
const element = [0, 0, 0];
for (let index = 0;index < count; index++) {
@@ -40968,7 +41483,7 @@ async function snapshot3(bytes) {
if (!Number.isInteger(vertex) || vertex < 0 || vertex >= position.getCount())
throw new Error("Revision comparison found an invalid vertex index.");
position.getElement(vertex, element);
- const point = new Vector337(...element).applyMatrix4(matrix);
+ const point = new Vector338(...element).applyMatrix4(matrix);
if (point.toArray().some((value) => !Number.isFinite(value)))
throw new Error("Revision comparison requires finite positions.");
own.expandByPoint(point);
@@ -40987,7 +41502,7 @@ async function snapshot3(bytes) {
if (scenes[0].listExtensions().length)
throw new Error("Revision comparison does not support scene extensions.");
const scenePath = `/${encodeURIComponent(scenes[0].getName() || "Scene")}[0]`;
- const box = visit(scenes[0].listChildren(), "", 0, new Matrix414);
+ const box = visit(scenes[0].listChildren(), "", 0, new Matrix415);
const nodePaths = new Map([...parts].map(([path, part]) => [part.node, path]));
const animation = new Map;
const clipNames = new Set;
@@ -41147,7 +41662,7 @@ async function compareRevisionGlbs(before, after, page = {}) {
nextOffset: offset + limit < changes.length ? offset + limit : null
};
}
-var MAX_GLB_BYTES, MAX_NODES = 1e4, MAX_VERTICES = 2000000, ACCESSOR_IGNORED, MATERIAL_IGNORED;
+var MAX_GLB_BYTES, MAX_NODES = 1e4, MAX_VERTICES2 = 2000000, ACCESSOR_IGNORED, MATERIAL_IGNORED;
var init_revision_comparison = __esm(() => {
init_gltf_io();
init_metrics();
@@ -41158,20 +41673,20 @@ var init_revision_comparison = __esm(() => {
// src/views/surface-distance.ts
import {
- Box3 as Box324,
- Matrix4 as Matrix415,
+ Box3 as Box325,
+ Matrix4 as Matrix416,
Ray,
Triangle as Triangle2,
- Vector3 as Vector338
+ Vector3 as Vector339
} from "three";
function hierarchy(triangles) {
- const box = new Box324;
+ const box = new Box325;
for (const triangle of triangles)
box.union(triangle.box);
const count = triangles.length;
if (count <= 4)
return { box, count, triangles };
- const size = box.getSize(new Vector338);
+ const size = box.getSize(new Vector339);
const axis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";
const center = (triangle) => triangle.box.min[axis] / 2 + triangle.box.max[axis] / 2;
triangles.sort((a, b) => center(a) - center(b));
@@ -41190,7 +41705,7 @@ function boxDistanceSquared(a, b) {
}
function collect(node, paths) {
const triangles = [];
- const bounds = new Box324;
+ const bounds = new Box325;
node.updateWorldMatrix(true, true);
node.traverseVisible((child) => {
const mesh = child;
@@ -41214,7 +41729,7 @@ function collect(node, paths) {
for (let instance = 0;instance < instances; instance++) {
const matrix = mesh.matrixWorld.clone();
if (instanced.isInstancedMesh) {
- const local = new Matrix415;
+ const local = new Matrix416;
instanced.getMatrixAt(instance, local);
matrix.multiply(local);
}
@@ -41223,13 +41738,13 @@ function collect(node, paths) {
const id = index ? index.getX(i + offset) : i + offset;
if (!Number.isSafeInteger(id) || id < 0 || id >= position.count)
throw new Error("Surface distance encountered an invalid triangle index.");
- const point = new Vector338().fromBufferAttribute(position, id).applyMatrix4(matrix);
+ const point = new Vector339().fromBufferAttribute(position, id).applyMatrix4(matrix);
if (![point.x, point.y, point.z].every(Number.isFinite))
throw new Error("Surface distance encountered a non-finite world position.");
return point;
};
const triangle = new Triangle2(vertex(0), vertex(1), vertex(2));
- const box = new Box324().setFromPoints([triangle.a, triangle.b, triangle.c]);
+ const box = new Box325().setFromPoints([triangle.a, triangle.b, triangle.c]);
bounds.union(box);
triangles.push({
triangle,
@@ -41282,10 +41797,10 @@ function trianglePair(a, b) {
const av = [a.a, a.b, a.c], bv = [b.a, b.b, b.c];
if (b.getArea() > 0)
for (const p of av)
- record(p, b.closestPointToPoint(p, new Vector338));
+ record(p, b.closestPointToPoint(p, new Vector339));
if (a.getArea() > 0)
for (const q of bv)
- record(a.closestPointToPoint(q, new Vector338), q);
+ record(a.closestPointToPoint(q, new Vector339), q);
for (let i = 0;i < 3; i++) {
const p = av[i], q = av[(i + 1) % 3];
for (let j = 0;j < 3; j++)
@@ -41298,9 +41813,9 @@ function trianglePair(a, b) {
const length = delta.length();
if (length === 0)
continue;
- const hit = new Ray(origin, delta.divideScalar(length)).intersectTriangle(target.a, target.b, target.c, false, new Vector338);
+ const hit = new Ray(origin, delta.divideScalar(length)).intersectTriangle(target.a, target.b, target.c, false, new Vector339);
if (hit && origin.distanceTo(hit) <= length) {
- const onFace = target.closestPointToPoint(hit, new Vector338);
+ const onFace = target.closestPointToPoint(hit, new Vector339);
if (vertices === av)
record(hit, onFace);
else
@@ -41459,6 +41974,221 @@ var init_surface_distance = __esm(() => {
init_camera();
});
+// src/draw-diagnostics.ts
+var exports_draw_diagnostics = {};
+__export(exports_draw_diagnostics, {
+ inspectDrawDiagnostics: () => inspectDrawDiagnostics
+});
+import { Primitive as Primitive3 } from "@gltf-transform/core";
+import { cloneDocument } from "@gltf-transform/functions";
+import * as THREE45 from "three";
+function withinLimits(doc) {
+ const root = doc.getRoot();
+ if (root.listNodes().length > MAX_NODES2 || root.listAccessors().length > 4096 || root.listMaterials().length > 2048 || root.listTextures().length > 256 || root.listScenes().length > 32 || doc.getGraph().listEdges().length > 32768)
+ return false;
+ let bytes = root.listAccessors().reduce((n, a) => n + (a.getArray()?.byteLength ?? 0), 0) + root.listTextures().reduce((n, t) => n + (t.getImage()?.byteLength ?? 0), 0);
+ let uses = 0;
+ let vertices = 0;
+ const walk = (node, depth) => {
+ if (depth > 128)
+ return false;
+ for (const p of node.getMesh()?.listPrimitives() ?? []) {
+ uses++;
+ vertices += p.getAttribute("POSITION")?.getCount() ?? 0;
+ bytes += p.listAttributes().reduce((n, a) => n + (a.getArray()?.byteLength ?? 0), 0) + (p.getIndices()?.getArray()?.byteLength ?? 0);
+ }
+ return uses <= MAX_USES && vertices <= MAX_VERTICES3 && bytes <= MAX_BYTES && node.listChildren().every((n) => walk(n, depth + 1));
+ };
+ return bytes <= MAX_BYTES && root.listScenes().every((s) => s.listChildren().every((n) => walk(n, 0)));
+}
+function collect2(doc, keep) {
+ const root = doc.getRoot();
+ const boundaries = findRigidBoundaries(doc, new Set(keep));
+ const nodeIds = new Map(root.listNodes().map((n, i) => [n, i]));
+ const anchors = new Map;
+ const uses = [];
+ for (const [sceneIndex, scene] of root.listScenes().entries()) {
+ const id = `scene:${sceneIndex}`;
+ const initial = { id, name: nameOf(scene.getName() || "Scene"), draws: 0, afterRigidMerge: 0 };
+ anchors.set(id, initial);
+ const walk = (node, anchor) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const part = { id: `${id}/node:${nodeIds.get(node)}`, name: nameOf(node.getName()) };
+ if (boundaries.has(node)) {
+ anchor = { ...part, draws: 0, afterRigidMerge: 0 };
+ anchors.set(part.id, anchor);
+ }
+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
+ anchor.draws++;
+ uses.push({ node, primitive, part });
+ }
+ for (const child of node.listChildren())
+ walk(child, anchor);
+ };
+ for (const child of scene.listChildren())
+ walk(child, initial);
+ }
+ return { anchors, uses };
+}
+function overlaps(a, b) {
+ if (Math.abs(a.normal.dot(b.normal)) < 1 - 0.00000001 || !a.bounds.intersectsBox(b.bounds))
+ return false;
+ const tolerance = Math.max(a.bounds.getSize(new THREE45.Vector3).length(), b.bounds.getSize(new THREE45.Vector3).length(), 0.000000000001) * 0.000001;
+ if (b.points.some((p) => Math.abs(a.normal.dot(p.clone().sub(a.points[0]))) > tolerance))
+ return false;
+ const normal = a.normal.toArray().map(Math.abs);
+ const drop = normal.indexOf(Math.max(...normal));
+ const project = (p) => p.toArray().filter((_, i) => i !== drop);
+ const clip = a.points.map(project);
+ if (cross22(clip[0], clip[1], clip[2]) < 0)
+ clip.reverse();
+ let polygon = b.points.map(project);
+ for (let i = 0;i < 3 && polygon.length; i++) {
+ const x = clip[i], y = clip[(i + 1) % 3];
+ const output = [];
+ for (let j = 0;j < polygon.length; j++) {
+ const p = polygon[j], q = polygon[(j + 1) % polygon.length];
+ const dp = cross22(x, y, p), dq = cross22(x, y, q);
+ if (dp >= 0)
+ output.push(p);
+ if (dp >= 0 !== dq >= 0) {
+ const t = dp / (dp - dq);
+ output.push([p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])]);
+ }
+ }
+ polygon = output;
+ }
+ let area = 0;
+ for (let i = 0;i < polygon.length; i++) {
+ const p = polygon[i], q = polygon[(i + 1) % polygon.length];
+ area += p[0] * q[1] - p[1] * q[0];
+ }
+ return Math.abs(area) / 2 > tolerance * tolerance;
+}
+function observe(uses) {
+ const mirrored = new Map;
+ const samples = [];
+ let eligibleTriangles = 0;
+ let unexaminedPrimitiveUses = 0;
+ for (const { node, primitive, part } of uses) {
+ if (node.getSkin() || node.getExtension("EXT_mesh_gpu_instancing") || primitive.listTargets().length) {
+ unexaminedPrimitiveUses++;
+ continue;
+ }
+ const matrix = new THREE45.Matrix4().fromArray(node.getWorldMatrix());
+ if (primitive.getAttribute("TANGENT") && matrix.determinant() < 0)
+ mirrored.set(part.id, part);
+ const position = primitive.getAttribute("POSITION");
+ if (!position || primitive.getMode() !== Primitive3.Mode.TRIANGLES) {
+ unexaminedPrimitiveUses++;
+ continue;
+ }
+ const indices = primitive.getIndices();
+ const count = Math.floor((indices?.getCount() ?? position.getCount()) / 3);
+ eligibleTriangles += count;
+ const amount = Math.min(count, 8, MAX_SAMPLES - samples.length);
+ for (let i = 0;i < amount; i++) {
+ const start = Math.floor(i * count / amount) * 3;
+ const points = [0, 1, 2].map((j) => new THREE45.Vector3().fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, [])).applyMatrix4(matrix));
+ const normal = points[1].clone().sub(points[0]).cross(points[2].clone().sub(points[0]));
+ if (!Number.isFinite(normal.lengthSq()) || normal.lengthSq() === 0)
+ continue;
+ samples.push({
+ points,
+ normal: normal.normalize(),
+ bounds: new THREE45.Box3().setFromPoints(points),
+ part
+ });
+ }
+ }
+ const pairs = new Map;
+ for (let i = 0;i < samples.length; i++)
+ for (let j = i + 1;j < samples.length; j++) {
+ const a = samples[i], b = samples[j];
+ if (a.part.id === b.part.id || a.part.id.split("/")[0] !== b.part.id.split("/")[0])
+ continue;
+ const key = [a.part.id, b.part.id].sort().join("|");
+ if (!pairs.has(key) && overlaps(a, b))
+ pairs.set(key, { parts: [a.part, b.part] });
+ }
+ return {
+ mirroredTangents: {
+ count: mirrored.size,
+ omitted: Math.max(0, mirrored.size - MAX_FINDINGS),
+ parts: [...mirrored.values()].slice(0, MAX_FINDINGS),
+ evidence: "Visible static nodes with tangent attributes and negative world determinant; not proof of a shading defect. Skinned, morphed and GPU-instanced uses are not assessed."
+ },
+ coplanarParts: {
+ sampledTriangles: samples.length,
+ eligibleTriangles,
+ unexaminedPrimitiveUses,
+ candidatePairs: pairs.size,
+ omitted: Math.max(0, pairs.size - MAX_FINDINGS),
+ candidates: [...pairs.values()].slice(0, MAX_FINDINGS),
+ evidence: "Sampled overlapping coplanar triangles in separate static nodes; not proof of visible z-fighting. At most 8 triangles per primitive and 256 total; unexamined faces may contain other candidates."
+ }
+ };
+}
+function analyzeDrawDiagnostics(doc, options = {}) {
+ try {
+ if (!withinLimits(doc))
+ return skipped("input-limit");
+ const keep = options.keep ?? [];
+ const before = collect2(doc, keep);
+ const copy = cloneDocument(doc);
+ const merge = mergeRigidGroups(copy, { keep });
+ const after = collect2(copy, keep);
+ const all = [...before.anchors.values()].map((anchor) => ({
+ ...anchor,
+ afterRigidMerge: after.anchors.get(anchor.id)?.draws ?? 0
+ }));
+ const currentDraws = before.uses.length;
+ return {
+ version: "kiln.draw-diagnostics.v1",
+ status: "assessed",
+ scope: SCOPE,
+ currentDraws,
+ mergeEstimate: {
+ method: METHOD,
+ draws: after.uses.length,
+ saved: currentDraws - after.uses.length,
+ rejectedBuckets: merge.rejected.length,
+ ...merge.skipped ? { skipped: merge.skipped } : {}
+ },
+ anchors: {
+ total: all.length,
+ omitted: Math.max(0, all.length - MAX_ANCHORS),
+ items: all.slice(0, MAX_ANCHORS)
+ },
+ observations: observe(before.uses)
+ };
+ } catch {
+ return skipped("analysis-failed");
+ }
+}
+async function inspectDrawDiagnostics(bytes, options = {}) {
+ if (bytes.byteLength > MAX_BYTES)
+ return skipped("input-limit");
+ try {
+ return analyzeDrawDiagnostics(await createGltfIO().readBinary(bytes), options);
+ } catch {
+ return skipped("unreadable-glb");
+ }
+}
+var MAX_NODES2 = 2048, MAX_USES = 256, MAX_VERTICES3 = 262144, MAX_BYTES, MAX_ANCHORS = 16, MAX_SAMPLES = 256, MAX_FINDINGS = 4, SCOPE = "Static single-pass primitive draws across document scenes, respecting node visibility. Excludes culling, alternate LOD selections, shadow, reflection and depth passes, and renderer-specific extra passes; GPU instances count once per primitive. IDs use scene/node indices; names are bounded labels.", METHOD = "Current rigid-merge policy on a bounded clone with existing materials: includes layouts, boundaries, locks, shared-byte budget and vertex splits. Excludes palette consolidation and instancing; not a full-mode or GPU performance prediction.", nameOf = (name) => name.length <= 80 ? name : `${name.slice(0, 79)}…`, skipped = (reason) => ({
+ version: "kiln.draw-diagnostics.v1",
+ status: "skipped",
+ scope: SCOPE,
+ reason
+}), cross22 = (a, b, p) => (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]);
+var init_draw_diagnostics = __esm(() => {
+ init_gltf_io();
+ init_metrics();
+ init_rigid_merge();
+ MAX_BYTES = 32 * 1024 * 1024;
+});
+
// src/assets-resources.ts
var exports_assets_resources = {};
__export(exports_assets_resources, {
@@ -41484,8 +42214,8 @@ function assetLinks(collection, manifest) {
function assetMime(name) {
return name.endsWith(".glb") ? "model/gltf-binary" : name.endsWith(".png") ? "image/png" : name.endsWith(".zip") ? "application/zip" : name.endsWith(".json") ? "application/json" : "text/javascript";
}
-async function runtimeAssetLinks(collection, record) {
- const output = await exportAssetGlb(record, { profile: "runtime" });
+async function runtimeAssetLinks(collection, record, derived) {
+ const output = derived ?? await exportAssetGlb(record, { profile: "runtime" });
if (output.profile !== "runtime")
throw new Error("Expected runtime export");
return [
@@ -41601,7 +42331,7 @@ var init_asset_widget = __esm(() => {
// src/tools/registry.ts
import { z as z21 } from "zod";
-import * as THREE44 from "three";
+import * as THREE46 from "three";
function proceduralTextureMaterialContract(rendered, context) {
const required = [...new Set(context.requiredProceduralTextureUsages ?? [])];
if (required.length === 0)
@@ -41687,7 +42417,7 @@ async function renderDerivativeCell(input, context) {
return;
const prepare = (material) => {
const copy = material.clone();
- copy.side = THREE44.DoubleSide;
+ copy.side = THREE46.DoubleSide;
return copy;
};
mesh.material = Array.isArray(mesh.material) ? mesh.material.map(prepare) : prepare(mesh.material);
@@ -41891,8 +42621,8 @@ function collectSceneMetrics(root) {
let meshes = 0;
const materialSet = new Set;
let lowestPart;
- const box = new THREE44.Box3;
- const point = new THREE44.Vector3;
+ const box = new THREE46.Box3;
+ const point = new THREE46.Vector3;
root.updateWorldMatrix(true, true);
root.traverseVisible((node) => {
const n = node;
@@ -41908,7 +42638,7 @@ function collectSceneMetrics(root) {
const mesh = node;
const position = mesh.geometry.getAttribute("position");
const index = mesh.geometry.index;
- const mb = new THREE44.Box3;
+ const mb = new THREE46.Box3;
if (position) {
for (let i = 0;i < (index?.count ?? position.count); i++) {
point.fromBufferAttribute(position, index ? index.getX(i) : i);
@@ -41923,7 +42653,7 @@ function collectSceneMetrics(root) {
});
let bbox;
if (!box.isEmpty()) {
- const size = new THREE44.Vector3;
+ const size = new THREE46.Vector3;
box.getSize(size);
bbox = {
min: [box.min.x, box.min.y, box.min.z],
@@ -42348,6 +43078,7 @@ async function runInspect(input, context) {
if (input.measure && input.measure.mode !== "surface")
measurement = measureAttachment(root, input.measure);
const measurements = {
+ drawDiagnostics: await (await Promise.resolve().then(() => (init_draw_diagnostics(), exports_draw_diagnostics))).inspectDrawDiagnostics(evaluated.glb),
...input.listParts ? { partListing: await listPartPage(root, input.listParts) } : {},
...measurement ? { measurement } : {},
...surfaceMeasurements ? { surfaceMeasurements } : {},
@@ -43010,10 +43741,17 @@ function createKilnAssetDefs(context) {
inputSchema: profileExportInput,
run: async (raw) => {
const input = profileExportInput.parse(raw);
+ const record = await readSavedRevision(library(), input.collection, input.assetId, input.revisionId);
+ await Promise.resolve().then(() => init_draw_diagnostics());
if (input.profile === "runtime") {
- const record = await readSavedRevision(library(), input.collection, input.assetId, input.revisionId);
+ const output = await (await Promise.resolve().then(() => (init_asset_export(), exports_asset_export))).exportAssetGlb(record, {
+ profile: "runtime"
+ });
+ if (output.profile !== "runtime")
+ throw new Error("Expected runtime export");
return {
ok: true,
+ drawDiagnostics: await inspectDrawDiagnostics(output.glb),
profile: input.profile,
collection: input.collection,
asset: {
@@ -43021,10 +43759,13 @@ function createKilnAssetDefs(context) {
revisionId: input.revisionId,
name: record.manifest.name
},
- resources: await (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).runtimeAssetLinks(input.collection, record)
+ resources: await (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).runtimeAssetLinks(input.collection, record, output)
};
}
- return links(input.collection, (await readSavedRevision(library(), input.collection, input.assetId, input.revisionId)).manifest);
+ return {
+ ...await links(input.collection, record.manifest),
+ drawDiagnostics: await inspectDrawDiagnostics(record.files["asset.glb"])
+ };
}
},
{
@@ -43183,7 +43924,7 @@ var init_registry2 = __esm(() => {
// render-service/src/instance.mjs
import { createHash as createHash15 } from "node:crypto";
import { readFileSync as readFileSync3, readdirSync, statSync } from "node:fs";
-import { join as join14, relative as relative7 } from "node:path";
+import { join as join13, relative as relative7 } from "node:path";
function fingerprintSourceDir(dir) {
const hash = createHash15("sha256");
hash.update("kiln.render-service-source.v1");
@@ -43192,7 +43933,7 @@ function fingerprintSourceDir(dir) {
for (const name of readdirSync(path).sort()) {
if (name === "node_modules")
continue;
- visit(join14(path, name));
+ visit(join13(path, name));
}
return;
}
@@ -43208,7 +43949,7 @@ var init_instance = () => {};
// render-service/src/build-identity.mjs
import { createHash as createHash16 } from "node:crypto";
import { readFileSync as readFileSync4 } from "node:fs";
-import { dirname as dirname7, join as join15 } from "node:path";
+import { dirname as dirname7, join as join14 } from "node:path";
import { createRequire as createRequire2 } from "node:module";
function compatibilityFingerprint({ sourceFingerprint, dependencies }) {
if (typeof sourceFingerprint !== "string" || !/^sha256:[a-f0-9]{64}$/.test(sourceFingerprint))
@@ -43236,7 +43977,7 @@ function resolvedRendererDependencies(anchorUrl = import.meta.url) {
let found;
for (;; ) {
try {
- const pkg = JSON.parse(readFileSync4(join15(dir, "package.json"), "utf8"));
+ const pkg = JSON.parse(readFileSync4(join14(dir, "package.json"), "utf8"));
if (pkg.name === name) {
found = pkg.version;
break;
@@ -43256,8 +43997,8 @@ var RENDER_SERVICE_PROTOCOL = "kiln.render-service.v2", RENDER_SERVICE_DEPENDENC
var init_build_identity = __esm(() => {
init_instance();
RENDER_SERVICE_DEPENDENCIES = Object.freeze({
- three: "0.186.0",
- webgpu: "0.6.1",
+ three: "0.186.1",
+ webgpu: "0.6.2",
pngjs: "7.0.0"
});
REQUIRED_RENDER_CAPABILITIES = Object.freeze([
@@ -43413,7 +44154,7 @@ var init_render_service_client = __esm(() => {
// src/render-service-windows.ts
import { spawn as spawn2 } from "node:child_process";
-import { join as join16 } from "node:path";
+import { join as join15 } from "node:path";
function powerShellLiteral(value) {
return `'${value.replaceAll("'", "''")}'`;
}
@@ -43428,7 +44169,7 @@ function launchWindowsRenderService(executable, args, directory, env) {
].join(`
`);
const systemRoot = env.SystemRoot ?? env.SYSTEMROOT;
- const powerShell = systemRoot ? join16(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";
+ const powerShell = systemRoot ? join15(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";
const child = spawn2(powerShell, [
"-NoProfile",
"-NonInteractive",
@@ -43479,7 +44220,7 @@ var init_render_service_windows = () => {};
import { spawn as spawn3, spawnSync } from "node:child_process";
import { existsSync as existsSync3 } from "node:fs";
import { fileURLToPath as fileURLToPath6, pathToFileURL } from "node:url";
-import { join as join17 } from "node:path";
+import { join as join16 } from "node:path";
function localRenderServicePort(env = process.env) {
const raw = Number(env["KILN_RENDER_SERVICE_PORT"]);
return Number.isInteger(raw) && raw > 0 && raw < 65536 ? raw : DEFAULT_LOCAL_RENDER_SERVICE_PORT;
@@ -43497,18 +44238,18 @@ function namesLocalRenderService(url, env = process.env) {
function renderServiceNodeArguments(dir) {
return [
"--import",
- pathToFileURL(join17(dir, "src/register-hooks.mjs")).href,
- join17(dir, "src/server.mjs")
+ pathToFileURL(join16(dir, "src/register-hooks.mjs")).href,
+ join16(dir, "src/server.mjs")
];
}
function renderServiceDir() {
return process.env["KILN_RENDER_SERVICE_DIR"] || fileURLToPath6(new URL("../render-service", import.meta.url));
}
function localRenderServiceState(dir = renderServiceDir()) {
- if (!existsSync3(join17(dir, "src/server.mjs")) || !existsSync3(join17(dir, "package.json")))
+ if (!existsSync3(join16(dir, "src/server.mjs")) || !existsSync3(join16(dir, "package.json")))
return "not-packaged";
try {
- const anchor = pathToFileURL(join17(dir, "src/server.mjs")).href;
+ const anchor = pathToFileURL(join16(dir, "src/server.mjs")).href;
if (process.versions.bun) {
const moduleUrl = new URL("../render-service/src/build-identity.mjs", import.meta.url).href;
const result = spawnSync(nodeBinary(), [
@@ -43539,7 +44280,7 @@ function explainRenderServiceState(state, dir) {
return "renderer dependencies are missing; reinstall the official Kiln package with optional dependencies enabled";
}
function renderServiceSourceFingerprint(dir) {
- const source = join17(dir, "src");
+ const source = join16(dir, "src");
return existsSync3(source) ? fingerprintSourceDir(source) : undefined;
}
async function inspectLocalRenderService(url, dir = renderServiceDir(), timeoutMs = 1500) {
@@ -44152,7 +44893,7 @@ var init_workspace_http = __esm(() => {
// src/asset-viewer.ts
import { createServer } from "node:http";
import { readFile as readFile9 } from "node:fs/promises";
-import { dirname as dirname8, join as join18 } from "node:path";
+import { dirname as dirname8, join as join17 } from "node:path";
import { fileURLToPath as fileURLToPath7 } from "node:url";
function quoted(value) {
if (value === undefined)
@@ -44165,7 +44906,7 @@ function refuse(res, message) {
`);
}
async function startAssetViewer(library, options = {}) {
- const staticDirectory = options.staticDirectory ?? (import.meta.url.endsWith(".ts") ? join18(dirname8(fileURLToPath7(import.meta.url)), "..", "dist", "viewer") : join18(dirname8(fileURLToPath7(import.meta.url)), "viewer"));
+ const staticDirectory = options.staticDirectory ?? (import.meta.url.endsWith(".ts") ? join17(dirname8(fileURLToPath7(import.meta.url)), "..", "dist", "viewer") : join17(dirname8(fileURLToPath7(import.meta.url)), "viewer"));
const server = createServer(async (req, res) => {
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Referrer-Policy", "no-referrer");
@@ -44235,7 +44976,7 @@ async function startAssetViewer(library, options = {}) {
return;
}
res.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; connect-src 'self' blob: data:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'");
- return send(await readFile9(join18(staticDirectory, file[0])), file[1]);
+ return send(await readFile9(join17(staticDirectory, file[0])), file[1]);
} catch (error) {
res.statusCode = error instanceof WorkspaceHttpError ? error.status : error && typeof error === "object" && ("code" in error) && error.code === "PROJECT_CONFLICT" ? 409 : 400;
send(JSON.stringify({ error: error instanceof Error ? error.message : "Asset unavailable" }));
@@ -44473,10 +45214,13 @@ async function assetMain(argv) {
const parsed = rebuildOptionsSchema.safeParse(record.manifest.build?.options);
if (!parsed.success)
throw new Error("Saved exporter settings are incomplete; use an explicit new authoring run instead of an exact rebuild.");
+ if (parsed.data.optimize === "full" && parsed.data.optimizationPipeline !== FULL_OPTIMIZATION_PIPELINE)
+ throw new Error("Saved revision uses an unversioned full optimization pipeline; rebuild with its original pinned engine, or explicitly author and save a new child revision to migrate.");
+ const { optimizationPipeline: _pipeline, ...renderOptions } = parsed.data;
const materialResources = await resolveAssetMaterialPayload(new FileWorkspace(localWorkspaceRoot()), record);
const code = new TextDecoder().decode(source);
const rendered = await context.evaluatorPort.render(code, {
- ...parsed.data,
+ ...renderOptions,
materialResources,
requirements
});
@@ -44562,6 +45306,9 @@ async function assetMain(argv) {
revisionId,
profile,
format,
+ ...format !== "source" ? {
+ drawDiagnostics: await inspectDrawDiagnostics(written.find(({ kind }) => kind === "glb")?.data ?? record.files["asset.glb"])
+ } : {},
files: written.map(({ kind, path, data }) => ({
kind,
path,
@@ -44644,6 +45391,7 @@ var init_asset_cli = __esm(() => {
init_registry2();
init_cli_output();
init_asset_export();
+ init_draw_diagnostics();
init_local_runtime();
init_cli_render_mode();
init_asset_viewer();
diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjs
index 5acc1140..7d7674a3 100644
--- a/dist/evaluator-worker.mjs
+++ b/dist/evaluator-worker.mjs
@@ -10290,7 +10290,7 @@ var init_architecture = __esm(() => {
scope: { kind: "category", category: "architecture" },
ruleClass: "exact",
owner: KILN_ENGINE_QA_OWNER,
- promotion: conformancePromotionAuthorization("architecture-qa-v1", "src/qa/architecture.test.ts", "c3a3bdc764c62238cede39813995fcaa428131d0aa3774bcd86cfc8b60f36671"),
+ promotion: conformancePromotionAuthorization("architecture-qa-v1", "src/qa/architecture.test.ts", "ce42ab6baef737d109f272413d902ea0903bd66c4da13ea723a52aff2f9e6c66", KILN_ENGINE_QA_OWNER, "2026-10-03T05:45:42.000Z", "enforce", "cpu-raster:0.10.0"),
defaultMode: "enforce",
evaluate: (context) => evaluateArchitectureQa(context).filter((finding) => finding.disposition === "block")
};
@@ -20742,6 +20742,521 @@ var init_material_metrics = __esm(() => {
});
});
+// src/rebuild-options.ts
+import { z as z3 } from "zod";
+var FULL_OPTIMIZATION_PIPELINE = "rigid-v1", rebuildOptionsSchema;
+var init_rebuild_options = __esm(() => {
+ rebuildOptionsSchema = z3.object({
+ indexPolicy: z3.enum(["indexed", "asBuilt"]).optional(),
+ gltfExporter: z3.enum(["legacy", "three"]),
+ geometryPolicy: z3.enum(["warn", "strict"]),
+ optimize: z3.enum(["off", "auto", "palette", "full"]),
+ optimizationPipeline: z3.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
+ instance: z3.enum(["off", "auto", "on"])
+ });
+});
+
+// src/rigid-merge.ts
+import {
+ ComponentTypeToTypedArray,
+ Primitive,
+ PropertyType as PropertyType3
+} from "@gltf-transform/core";
+import { createTransform, dequantizePrimitive, joinPrimitives } from "@gltf-transform/functions";
+import * as THREE37 from "three";
+function isSingular(matrix) {
+ const e = matrix.elements;
+ const scale = Math.hypot(e[0], e[1], e[2]) * Math.hypot(e[4], e[5], e[6]) * Math.hypot(e[8], e[9], e[10]);
+ const det = matrix.determinant();
+ return !Number.isFinite(det) || Math.abs(det) <= 0.000000001 * scale;
+}
+function findRigidBoundaries(doc, keep) {
+ const root = doc.getRoot();
+ const found = new Map;
+ const add = (node, reason) => {
+ const reasons = found.get(node) ?? [];
+ if (!reasons.includes(reason))
+ reasons.push(reason);
+ found.set(node, reasons);
+ };
+ for (const animation of root.listAnimations())
+ for (const channel of animation.listChannels()) {
+ const target = channel.getTargetNode();
+ if (target)
+ add(target, "animated");
+ }
+ for (const skin of root.listSkins())
+ for (const joint of skin.listJoints())
+ add(joint, "skin-joint");
+ const targets = new Set;
+ for (const node of root.listNodes()) {
+ const semantic = node.getExtras()[KILN_SEMANTIC_EXTRAS_KEY];
+ if (Array.isArray(semantic?.relationships)) {
+ for (const relationship of semantic.relationships)
+ if (relationship?.targetType === "node" && typeof relationship.target === "string")
+ targets.add(relationship.target);
+ }
+ }
+ for (const node of root.listNodes()) {
+ const name = node.getName();
+ const sceneParents = node.listParents().filter((parent) => parent.propertyType === PropertyType3.SCENE).length;
+ if (sceneParents > 1)
+ add(node, "shared-scene");
+ if (JOINT_PIVOT.test(name))
+ add(node, "joint-pivot");
+ if (hasKeys(node.getExtras()))
+ add(node, "extras");
+ if (targets.has(name))
+ add(node, "relationship-target");
+ if (node.getExtension("KHR_node_visibility"))
+ add(node, "visibility");
+ const lod = node.getExtension(MSFT_LOD);
+ if (lod) {
+ add(node, "lod");
+ for (const level of lod.listLevels())
+ if (level.propertyType === PropertyType3.NODE)
+ add(level, "lod");
+ }
+ if (keep.has(name))
+ add(node, "kept");
+ }
+ return found;
+}
+function nodeLock(node, mesh, world, expandShared) {
+ if (node.getSkin())
+ return "skinned";
+ if (node.getExtension("EXT_mesh_gpu_instancing"))
+ return "instanced";
+ if (hasKeys(mesh.getExtras()))
+ return "mesh-extras";
+ if (!expandShared && nodeUsers(mesh) > 1)
+ return "shared-mesh";
+ if (isSingular(world))
+ return "singular-matrix";
+ return;
+}
+function primLock(prim, mergeTransparent) {
+ if (prim.listTargets().length > 0)
+ return "morph-targets";
+ if (RESTART_MODES.has(prim.getMode()))
+ return "primitive-mode";
+ if (prim.listExtensions().length > 0)
+ return "primitive-extensions";
+ if (hasKeys(prim.getExtras()))
+ return "primitive-extras";
+ if (!prim.getAttribute("POSITION"))
+ return "no-position";
+ const material = prim.getMaterial();
+ if (material?.getExtension("KHR_materials_volume"))
+ return "volume";
+ if (!mergeTransparent && material && (material.getAlphaMode() === "BLEND" || material.getExtension("KHR_materials_transmission") || material.getExtension("KHR_materials_diffuse_transmission")))
+ return "transparent";
+ return;
+}
+function bucketKey(prim, materials, handedness) {
+ const layout = prim.listSemantics().sort().map((semantic) => {
+ const a = prim.getAttribute(semantic);
+ return `${semantic}:${a.getElementSize()}:${a.getComponentType()}:${a.getNormalized()}`;
+ }).join("+");
+ const hand = handedness !== null && prim.getAttribute("TANGENT") ? `|${handedness}` : "";
+ return `${materials.get(prim.getMaterial()) ?? -1}|${prim.getMode()}|${!!prim.getIndices()}|${layout}${hand}`;
+}
+function reverseWinding(prim) {
+ const indices = prim.getIndices()?.getArray();
+ const swap = (array, size, i) => {
+ for (let k = 0;k < size; k++) {
+ const [j, l] = [(i + 1) * size + k, (i + 2) * size + k];
+ [array[j], array[l]] = [array[l], array[j]];
+ }
+ };
+ if (indices) {
+ for (let i = 0;i + 2 < indices.length; i += 3)
+ swap(indices, 1, i);
+ return;
+ }
+ for (const semantic of prim.listSemantics()) {
+ const attribute = prim.getAttribute(semantic);
+ for (let i = 0;i + 2 < attribute.getCount(); i += 3)
+ swap(attribute.getArray(), attribute.getElementSize(), i);
+ }
+}
+function bake(prim, matrix) {
+ const linear = new THREE37.Matrix3().setFromMatrix4(matrix);
+ const normalMatrix = new THREE37.Matrix3().getNormalMatrix(matrix);
+ const mirrored = matrix.determinant() < 0;
+ const v = new THREE37.Vector3;
+ const each = (semantic, apply) => {
+ const attribute = prim.getAttribute(semantic);
+ const element = [];
+ for (let i = 0;i < (attribute?.getCount() ?? 0); i++) {
+ apply(attribute.getElement(i, element));
+ attribute.setElement(i, element);
+ }
+ };
+ each("POSITION", (e) => v.fromArray(e).applyMatrix4(matrix).toArray(e));
+ each("NORMAL", (e) => v.fromArray(e).applyMatrix3(normalMatrix).normalize().toArray(e));
+ each("TANGENT", (e) => {
+ v.fromArray(e).applyMatrix3(linear).normalize().toArray(e);
+ if (mirrored)
+ e[3] = -e[3];
+ });
+ if (mirrored && prim.getMode() === Primitive.Mode.TRIANGLES)
+ reverseWinding(prim);
+}
+function destinationOf(entries) {
+ let chosen = entries[0].node;
+ let best = Infinity;
+ let bestScale = Infinity;
+ for (const { node } of entries) {
+ const linear = new THREE37.Matrix3().setFromMatrix4(worldOf(node));
+ const norm = Math.hypot(...linear.elements);
+ const inverseNorm = Math.hypot(...linear.clone().invert().elements);
+ const condition = norm * inverseNorm;
+ const scale = Math.max(norm, inverseNorm);
+ if (condition < best * (1 - 0.000000000001) || Math.abs(condition - best) <= best * 0.000000000001 && scale < bestScale) {
+ chosen = node;
+ best = condition;
+ bestScale = scale;
+ }
+ }
+ return chosen;
+}
+function checkPositionPrecision(input, output, sourceWorld, destinationWorld, reversed) {
+ const expected = new THREE37.Vector3;
+ const actual = new THREE37.Vector3;
+ const bounds = new THREE37.Box3;
+ const element = [];
+ let error = 0;
+ let magnitude = 0;
+ for (let i = 0;i < input.getCount(); i++) {
+ const out = reversed ? i % 3 === 1 ? i + 1 : i % 3 === 2 ? i - 1 : i : i;
+ expected.fromArray(input.getElement(i, element)).applyMatrix4(sourceWorld);
+ actual.fromArray(output.getElement(out, element)).applyMatrix4(destinationWorld);
+ bounds.expandByPoint(expected);
+ error = Math.max(error, expected.distanceTo(actual));
+ magnitude = Math.max(magnitude, expected.length());
+ }
+ const tolerance = Math.max(bounds.getSize(expected).length() * 0.000001, magnitude * Number.EPSILON * 32, Number.EPSILON);
+ if (error > tolerance)
+ throw new Error("rigid merge: destination frame loses position precision");
+}
+function splitVertices(prim, created) {
+ if (prim.getAttribute("POSITION").getCount() <= MAX_VERTICES)
+ return [prim];
+ const width = prim.getMode() === Primitive.Mode.POINTS ? 1 : prim.getMode() === Primitive.Mode.LINES ? 2 : 3;
+ const sourceIndices = prim.getIndices()?.getArray();
+ const count = sourceIndices?.length ?? prim.getAttribute("POSITION").getCount();
+ if (count % width !== 0)
+ throw new Error("rigid merge: incomplete primitive element");
+ const chunks = [];
+ let remap = new Map;
+ let indices = [];
+ const flush = () => {
+ if (!indices.length)
+ return;
+ const chunk = prim.clone();
+ created.push(chunk);
+ const vertices = [...remap.keys()];
+ for (const semantic of prim.listSemantics()) {
+ const source = prim.getAttribute(semantic);
+ const size = source.getElementSize();
+ const ArrayType = ComponentTypeToTypedArray[source.getComponentType()];
+ if (!ArrayType)
+ throw new Error(`rigid merge: unsupported component type for ${semantic}`);
+ const data = new ArrayType(vertices.length * size);
+ const sourceData = source.getArray();
+ for (const [out, input] of vertices.entries())
+ data.set(sourceData.subarray(input * size, (input + 1) * size), out * size);
+ const attribute = source.clone().setArray(data);
+ created.push(attribute);
+ chunk.setAttribute(semantic, attribute);
+ }
+ if (prim.getIndices()) {
+ const accessor = prim.getIndices().clone().setArray(new Uint16Array(indices));
+ created.push(accessor);
+ chunk.setIndices(accessor);
+ }
+ chunks.push(chunk);
+ remap = new Map;
+ indices = [];
+ };
+ for (let offset = 0;offset < count; offset += width) {
+ const element = Array.from({ length: width }, (_, i) => sourceIndices?.[offset + i] ?? offset + i);
+ const extra = new Set(element.filter((index) => !remap.has(index))).size;
+ if (remap.size + extra > MAX_VERTICES)
+ flush();
+ for (const index of element) {
+ if (!remap.has(index))
+ remap.set(index, remap.size);
+ indices.push(remap.get(index));
+ }
+ }
+ flush();
+ for (const property of [prim, ...accessorsOf(prim)])
+ property.dispose();
+ return chunks;
+}
+function prepare(entries, dst, created) {
+ const destinationWorld = worldOf(dst);
+ const inverse = destinationWorld.clone().invert();
+ const copies = entries.map(({ node, prim }) => {
+ const copy = prim.clone();
+ created.push(copy);
+ for (const semantic of copy.listSemantics()) {
+ const attribute = copy.getAttribute(semantic).clone();
+ created.push(attribute);
+ copy.setAttribute(semantic, attribute);
+ }
+ const indices = copy.getIndices()?.clone();
+ if (indices) {
+ created.push(indices);
+ copy.setIndices(indices);
+ }
+ dequantizePrimitive(copy, { pattern: BAKED });
+ if (node !== dst) {
+ const sourceWorld = worldOf(node);
+ const matrix = inverse.clone().multiply(sourceWorld);
+ bake(copy, matrix);
+ const reversed = !copy.getIndices() && copy.getMode() === Primitive.Mode.TRIANGLES && matrix.determinant() < 0;
+ checkPositionPrecision(prim.getAttribute("POSITION"), copy.getAttribute("POSITION"), sourceWorld, destinationWorld, reversed);
+ }
+ return copy;
+ });
+ const merged = joinPrimitives(copies);
+ created.push(merged, ...accessorsOf(merged));
+ for (const semantic of ["POSITION", "NORMAL", "TANGENT"]) {
+ const array = merged.getAttribute(semantic)?.getArray();
+ if (array && !array.every(Number.isFinite))
+ throw new Error(`rigid merge: non-finite ${semantic} in the joined primitive`);
+ }
+ const elements = (p) => p.getIndices()?.getCount() ?? p.getAttribute("POSITION").getCount();
+ const expected = copies.reduce((sum, copy) => sum + elements(copy), 0);
+ if (elements(merged) !== expected)
+ throw new Error(`rigid merge: joined ${elements(merged)} of ${expected} elements`);
+ for (const copy of copies)
+ for (const property of [copy, ...accessorsOf(copy)])
+ property.dispose();
+ return splitVertices(merged, created);
+}
+function removableBytes(entries) {
+ const uses = new Map;
+ for (const { node, prim } of entries) {
+ const nodes = uses.get(prim) ?? new Set;
+ nodes.add(node);
+ uses.set(prim, nodes);
+ }
+ const removed = new Set;
+ for (const [prim, nodes] of uses) {
+ const retained = prim.listParents().some((parent) => {
+ if (parent.propertyType === PropertyType3.ROOT)
+ return false;
+ if (parent.propertyType !== PropertyType3.MESH)
+ return true;
+ return parent.listParents().some((user) => user.propertyType !== PropertyType3.ROOT && (user.propertyType !== PropertyType3.NODE || !nodes.has(user)));
+ });
+ if (!retained)
+ removed.add(prim);
+ }
+ const accessors = new Set([...removed].flatMap(accessorsOf));
+ let bytes = 0;
+ for (const accessor of accessors)
+ if (accessor.listParents().every((parent) => parent.propertyType === PropertyType3.ROOT || removed.has(parent)))
+ bytes += accessor.getArray()?.byteLength ?? 0;
+ return bytes;
+}
+function sceneNodes2(doc) {
+ const seen = new Set;
+ const visit = (node) => {
+ if (seen.has(node))
+ return;
+ seen.add(node);
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const scene of doc.getRoot().listScenes())
+ for (const child of scene.listChildren())
+ visit(child);
+ return seen;
+}
+function mergeRigidGroups(doc, options = {}) {
+ const root = doc.getRoot();
+ const keep = new Set(options.keep ?? []);
+ const nodes = sceneNodes2(doc);
+ const names = new Set([...nodes].map((node) => node.getName()));
+ const summary = {
+ primitivesBefore: countPrimitives(nodes),
+ primitivesAfter: 0,
+ groups: 0,
+ merges: 0,
+ boundaries: [],
+ locked: [],
+ rejected: [],
+ unmatchedKeep: [...keep].filter((name) => !names.has(name))
+ };
+ if (root.listAnimations().some((a) => a.listChannels().some((c) => !c.getTargetNode()))) {
+ summary.skipped = "unbounded-animation";
+ summary.primitivesAfter = summary.primitivesBefore;
+ return summary;
+ }
+ const boundaries = findRigidBoundaries(doc, keep);
+ const materials = new Map(root.listMaterials().map((m, i) => [m, i]));
+ const groups = [];
+ const locks = new Map;
+ const lock = (node, reason, primitives) => {
+ const key = `${node.getName()}|${reason}`;
+ const known = locks.get(key);
+ if (known)
+ known.primitives += primitives;
+ else {
+ const entry = { node: node.getName(), reason, primitives };
+ locks.set(key, entry);
+ summary.locked.push(entry);
+ }
+ };
+ const seen = new Set;
+ const visit = (node, parentGroup) => {
+ if (seen.has(node))
+ return;
+ seen.add(node);
+ const reasons = boundaries.get(node);
+ let group = parentGroup;
+ if (reasons) {
+ summary.boundaries.push({ node: node.getName(), reasons });
+ group = new Map;
+ groups.push(group);
+ }
+ const mesh = node.getMesh();
+ if (mesh) {
+ const world = worldOf(node);
+ const nodeReason = reasons ? "boundary" : nodeLock(node, mesh, world, options.expandSharedMeshes !== false);
+ const handedness = options.mergeMirroredTangents ? null : Math.sign(world.determinant());
+ if (nodeReason)
+ lock(node, nodeReason, mesh.listPrimitives().length);
+ else
+ for (const prim of mesh.listPrimitives()) {
+ const primReason = primLock(prim, options.mergeTransparent === true);
+ if (primReason)
+ lock(node, primReason, 1);
+ else {
+ const key = bucketKey(prim, materials, handedness);
+ const list = group.get(key);
+ if (list)
+ list.push({ node, prim });
+ else
+ group.set(key, [{ node, prim }]);
+ }
+ }
+ }
+ for (const child of node.listChildren())
+ visit(child, group);
+ };
+ for (const scene of root.listScenes()) {
+ const group = new Map;
+ groups.push(group);
+ for (const child of scene.listChildren())
+ visit(child, group);
+ }
+ summary.groups = groups.length;
+ const plans = [];
+ for (const group of groups)
+ for (const bucket of group.values()) {
+ let entries = bucket;
+ while (entries.length >= 2) {
+ const created = [];
+ const track = (event) => created.push(event.target);
+ doc.getGraph().addEventListener("node:create", track);
+ try {
+ const destination = destinationOf(entries);
+ const merged = prepare(entries, destination, created);
+ const savedDraws = entries.length - merged.length;
+ const shared = entries.filter((entry) => removableBytes([entry]) < primitiveBytes([entry.prim]));
+ const addedBytes = Math.max(0, primitiveBytes(merged) - removableBytes(entries));
+ if (savedDraws > 0 && addedBytes <= savedDraws * MAX_BYTES_PER_SAVED_DRAW) {
+ plans.push({ entries, destination, merged });
+ break;
+ }
+ for (const property of created)
+ property.dispose();
+ if (!shared.length || savedDraws <= 0)
+ break;
+ const costly = shared.reduce((best, entry) => primitiveBytes(entry.node.getMesh().listPrimitives()) > primitiveBytes(best.node.getMesh().listPrimitives()) ? entry : best);
+ const mesh = costly.node.getMesh();
+ for (const entry of entries.filter((entry) => entry.node.getMesh() === mesh))
+ lock(entry.node, "shared-byte-budget", 1);
+ entries = entries.filter((entry) => entry.node.getMesh() !== mesh);
+ } catch (error) {
+ for (const property of created)
+ property.dispose();
+ summary.rejected.push({
+ node: entries[0].node.getName(),
+ primitives: entries.length,
+ error: error instanceof Error ? error.message : String(error)
+ });
+ break;
+ } finally {
+ doc.getGraph().removeEventListener("node:create", track);
+ }
+ }
+ }
+ const owned = new Map;
+ const ownMesh = (node) => {
+ let mesh = owned.get(node);
+ if (mesh)
+ return mesh;
+ mesh = node.getMesh();
+ if (nodeUsers(mesh) > 1) {
+ mesh = mesh.clone();
+ node.setMesh(mesh);
+ }
+ owned.set(node, mesh);
+ return mesh;
+ };
+ const removed = new Set;
+ for (const { entries, destination, merged } of plans) {
+ for (const { node, prim } of entries) {
+ ownMesh(node).removePrimitive(prim);
+ removed.add(prim);
+ }
+ for (const primitive of merged)
+ ownMesh(destination).addPrimitive(primitive);
+ }
+ for (const [node, mesh] of owned)
+ if (mesh.listPrimitives().length === 0) {
+ node.setMesh(null);
+ if (nodeUsers(mesh) === 0)
+ mesh.dispose();
+ }
+ for (const prim of removed) {
+ if (prim.listParents().some((parent) => parent.propertyType === PropertyType3.MESH))
+ continue;
+ const accessors = accessorsOf(prim);
+ prim.dispose();
+ for (const accessor of accessors)
+ if (accessor.listParents().every((parent) => parent.propertyType === PropertyType3.ROOT))
+ accessor.dispose();
+ }
+ summary.merges = plans.length;
+ summary.primitivesAfter = countPrimitives(nodes);
+ return summary;
+}
+function rigidMerge(options = {}, onSummary) {
+ return createTransform("kilnRigidMerge", (doc) => {
+ const summary = mergeRigidGroups(doc, options);
+ onSummary?.(summary);
+ });
+}
+var JOINT_PIVOT, RESTART_MODES, BAKED, MAX_VERTICES = 65534, MAX_BYTES_PER_SAVED_DRAW = 4096, hasKeys = (value) => Object.keys(value).length > 0, worldOf = (node) => new THREE37.Matrix4().fromArray(node.getWorldMatrix()), nodeUsers = (mesh) => mesh.listParents().filter((parent) => parent.propertyType === PropertyType3.NODE).length, accessorsOf = (prim) => {
+ const indices = prim.getIndices();
+ return indices ? [...prim.listAttributes(), indices] : prim.listAttributes();
+}, primitiveBytes = (primitives) => [...new Set(primitives.flatMap(accessorsOf))].reduce((sum, a) => sum + (a.getArray()?.byteLength ?? 0), 0), countPrimitives = (nodes) => [...nodes].reduce((sum, node) => sum + (node.getMesh()?.listPrimitives().length ?? 0), 0);
+var init_rigid_merge = __esm(() => {
+ init_semantic();
+ init_gltf_io();
+ JOINT_PIVOT = /^joint[_-]/i;
+ RESTART_MODES = new Set([2, 3, 5, 6]);
+ BAKED = /^(POSITION|NORMAL|TANGENT)$/;
+});
+
// src/geometry-catalog.ts
var REMOVED_AUTHORING_HELPERS, geometryPrimitives;
var init_geometry_catalog = __esm(() => {
@@ -22226,7 +22741,7 @@ var init_kit = __esm(() => {
// src/texture-bake.ts
import { createHash as createHash5 } from "node:crypto";
-import * as THREE37 from "three";
+import * as THREE38 from "three";
function readPixels(texture) {
const image = texture.image;
if (!image)
@@ -22318,7 +22833,7 @@ async function bakeSceneTextures(root, warnings) {
mime: "image/png",
bytes
};
- const colorSpace = entry.texture.colorSpace === THREE37.SRGBColorSpace ? "srgb" : "linear";
+ const colorSpace = entry.texture.colorSpace === THREE38.SRGBColorSpace ? "srgb" : "linear";
const recipe = entry.texture.userData["kilnProcedural"];
const primaryUsage = recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");
entry.texture.userData["kilnTexture"] = {
@@ -22399,10 +22914,10 @@ function computeTangentBasis(geometry) {
}
}
const out = new Float32Array(vertexCount * 4);
- const n = new THREE37.Vector3;
- const t = new THREE37.Vector3;
- const tmp = new THREE37.Vector3;
- const tmp2 = new THREE37.Vector3;
+ const n = new THREE38.Vector3;
+ const t = new THREE38.Vector3;
+ const tmp = new THREE38.Vector3;
+ const tmp2 = new THREE38.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]);
@@ -22422,7 +22937,7 @@ function computeTangentBasis(geometry) {
out[v * 4 + 2] = tmp.z;
out[v * 4 + 3] = w;
}
- geometry.setAttribute("tangent", new THREE37.BufferAttribute(out, 4));
+ geometry.setAttribute("tangent", new THREE38.BufferAttribute(out, 4));
}
function ensureNormalMapTangents(root, warnings) {
let count = 0;
@@ -22533,7 +23048,7 @@ var init_exporter_node = __esm(() => {
});
// src/views/character.ts
-import * as THREE38 from "three";
+import * as THREE39 from "three";
function rounded(value) {
const result = Math.round(value * 1e9) / 1e9;
return Object.is(result, -0) ? 0 : result;
@@ -22575,9 +23090,9 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {
const invalidPaths = new Set(invalidFindingNodePaths);
const joints = evidence.map((joint) => {
const relative = rootInverse.clone().multiply(joint.node.matrixWorld);
- const position = new THREE38.Vector3().setFromMatrixPosition(relative);
- const forward = new THREE38.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
- const bend = new THREE38.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const position = new THREE39.Vector3().setFromMatrixPosition(relative);
+ const forward = new THREE39.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const bend = new THREE39.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
const chainId = chainIdFor(joint.descriptor, descriptorByRole);
return {
role: joint.descriptor.role,
@@ -24034,7 +24549,7 @@ var init_raster = __esm(() => {
});
// src/views/camera.ts
-import { Vector3 as Vector330, Matrix4 as Matrix412, Euler as Euler4, Group as Group3 } from "three";
+import { Vector3 as Vector331, Matrix4 as Matrix413, Euler as Euler4, Group as Group3 } from "three";
function strict(value, keys, label) {
for (const key of Object.keys(value))
if (!keys.includes(key)) {
@@ -24128,14 +24643,14 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {
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 Vector330(0, 0, -1) : new Vector330(0, 1, 0);
+ const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector331(0, 0, -1) : new Vector331(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 extent = 0.000001;
for (let i = 0;i < 8; i++) {
- const p = new Vector330((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);
+ const p = new Vector331((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);
extent = Math.max(extent, Math.abs(p.dot(x)), Math.abs(p.dot(y)));
}
const depthMin = bounds.min.map((v, i) => Math.min(v, sceneBounds.min[i]));
@@ -24216,7 +24731,7 @@ function resolveAssetCamera(root, shot = {}) {
if (relative !== "world") {
const node = relative === "part" ? selected.node : rootNode;
dir.transformDirection(node.matrixWorld);
- up = tuple5(new Vector330(0, 1, 0).transformDirection(node.matrixWorld));
+ up = tuple5(new Vector331(0, 1, 0).transformDirection(node.matrixWorld));
}
camera = cameraFromBounds(bounds, tuple5(dir), request.padding ?? 1.2, up, measureBounds(root));
} else if (request.type === "explicit") {
@@ -24251,7 +24766,7 @@ function resolveAssetCamera(root, shot = {}) {
throw new Error("padding requires bounds framing");
if (request.framing === "bounds" && request.halfHeight !== undefined)
throw new Error("bounds framing derives halfHeight");
- let matrix = new Matrix412;
+ let matrix = new Matrix413;
if (relative === "asset" || relative === "part")
matrix = (relative === "asset" ? rootNode : selected.node).matrixWorld;
if (request.frame) {
@@ -24263,7 +24778,7 @@ function resolveAssetCamera(root, shot = {}) {
const position = vec(triple(request.position, "position")).applyMatrix4(matrix);
const target = request.target ? vec(triple(request.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);
const up = vec(triple(request.up ?? [0, 1, 0], "up")).transformDirection(matrix);
- const offset = vec(triple(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector330().setFromMatrixPosition(matrix));
+ const offset = vec(triple(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector331().setFromMatrixPosition(matrix));
const radius = vec(bounds.max).sub(vec(bounds.min)).length();
camera = {
version: "kiln.camera.v1",
@@ -24367,11 +24882,11 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)
}
return result;
};
- const key = new Vector330(1.5, 2, 1).normalize();
+ const key = new Vector331(1.5, 2, 1).normalize();
const srgb = (n) => n <= 0.0031308 ? n * 12.92 : 1.055 * n ** (1 / 2.4) - 0.055;
const ordered = compositingOrder(collectTriangles(root).tris, (px, py, pz) => camera.projection === "perspective" ? Math.hypot(px - position.x, py - position.y, pz - position.z) : (position.x - px) * z.x + (position.y - py) * z.y + (position.z - pz) * z.z);
for (const tri of ordered) {
- const world = [0, 1, 2].map((i) => new Vector330(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));
+ const world = [0, 1, 2].map((i) => new Vector331(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;
@@ -24381,7 +24896,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)
const color = tri.color.map((c) => Math.round(srgb(c * light) * 255));
let polygon = world.map((p) => {
const d = p.clone().sub(position);
- return new Vector330(d.dot(x), d.dot(y), -d.dot(z));
+ return new Vector331(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++) {
@@ -24414,7 +24929,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)
}
return out;
}
-var vec = (a) => new Vector330(...a), tuple5 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;
+var vec = (a) => new Vector331(...a), tuple5 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;
var init_camera = __esm(() => {
init_raster();
init_background();
@@ -24503,13 +25018,13 @@ var init_architecture3 = __esm(() => {
// src/views/glb.ts
import {
- Primitive
+ Primitive as Primitive2
} from "@gltf-transform/core";
import {
BufferAttribute as BufferAttribute8,
BufferGeometry as BufferGeometry15,
Group as Group4,
- Matrix4 as Matrix413,
+ Matrix4 as Matrix414,
Mesh as Mesh12,
MeshStandardMaterial as MeshStandardMaterial5,
NoColorSpace as NoColorSpace4,
@@ -24519,7 +25034,7 @@ import {
QuaternionKeyframeTrack as QuaternionKeyframeTrack2,
VectorKeyframeTrack as VectorKeyframeTrack2,
Quaternion as Quaternion17,
- Vector3 as Vector331,
+ Vector3 as Vector332,
InterpolateDiscrete as InterpolateDiscrete2,
InterpolateLinear as InterpolateLinear2
} from "three";
@@ -24547,7 +25062,7 @@ var init_glb = __esm(() => {
});
// src/material-library.ts
-import { z as z3 } from "zod";
+import { z as z4 } from "zod";
function assertMaterialJson(value, allowBytes = false, depth = 0) {
if (depth > 30)
throw new Error("Material JSON exceeds nesting limit");
@@ -24685,23 +25200,23 @@ var init_material_library = __esm(() => {
emissive: "emissive",
occlusion: "occlusion"
};
- materialLibraryIdSchema = z3.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
- materialLibraryHashSchema = z3.string().regex(/^sha256:[a-f0-9]{64}$/);
- text3 = z3.string().min(1).max(1000);
- url = z3.string().max(2000).url().refine((value) => /^https?:\/\//.test(value), "Provenance URL must be HTTP(S)");
- materialSourceSchema = z3.object({
+ materialLibraryIdSchema = z4.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+ materialLibraryHashSchema = z4.string().regex(/^sha256:[a-f0-9]{64}$/);
+ text3 = z4.string().min(1).max(1000);
+ url = z4.string().max(2000).url().refine((value) => /^https?:\/\//.test(value), "Provenance URL must be HTTP(S)");
+ materialSourceSchema = z4.object({
id: materialLibraryIdSchema,
- kind: z3.enum(["external", "procedural"]),
+ kind: z4.enum(["external", "procedural"]),
provider: text3,
creator: text3,
assetId: text3.optional(),
assetUrl: url.optional(),
- accessedAt: z3.string().datetime().optional(),
- license: z3.object({ spdx: text3, url, attribution: z3.string().max(4000) }).strict(),
- originalFiles: z3.array(z3.object({
- name: z3.string().min(1).max(200),
+ accessedAt: z4.string().datetime().optional(),
+ license: z4.object({ spdx: text3, url, attribution: z4.string().max(4000) }).strict(),
+ originalFiles: z4.array(z4.object({
+ name: z4.string().min(1).max(200),
sha256: materialLibraryHashSchema,
- bytes: z3.number().int().positive().max(1024 * 1024 * 1024)
+ bytes: z4.number().int().positive().max(1024 * 1024 * 1024)
}).strict()).max(20)
}).strict().superRefine((source, context) => {
if (source.kind === "external" && (!source.assetUrl || !source.originalFiles.length))
@@ -24712,22 +25227,22 @@ var init_material_library = __esm(() => {
if (new Set(source.originalFiles.map((file) => file.name)).size !== source.originalFiles.length)
context.addIssue({ code: "custom", message: "Duplicate original filename" });
});
- materialTransformSchema = z3.object({
+ materialTransformSchema = z4.object({
operation: text3,
tool: text3,
version: text3,
- parameters: z3.record(z3.string().max(100), z3.union([z3.string().max(2000), z3.number().finite(), z3.boolean()])).optional()
+ parameters: z4.record(z4.string().max(100), z4.union([z4.string().max(2000), z4.number().finite(), z4.boolean()])).optional()
}).strict();
- color2 = z3.number().int().min(0).max(16777215);
- count2 = z3.number().int().min(1).max(256);
+ color2 = z4.number().int().min(0).max(16777215);
+ count2 = z4.number().int().min(1).max(256);
layerCommon = {
- blend: z3.enum(["normal", "multiply", "screen", "overlay"]).default("normal"),
- opacity: z3.number().min(0).max(1).default(1)
+ blend: z4.enum(["normal", "multiply", "screen", "overlay"]).default("normal"),
+ opacity: z4.number().min(0).max(1).default(1)
};
- materialProceduralSpecSchema = z3.object({
- schemaVersion: z3.literal(2),
- size: z3.number().int().min(4).max(1024).default(256),
- usage: z3.enum([
+ materialProceduralSpecSchema = z4.object({
+ schemaVersion: z4.literal(2),
+ size: z4.number().int().min(4).max(1024).default(256),
+ usage: z4.enum([
"albedo",
"normal",
"roughness",
@@ -24736,90 +25251,90 @@ var init_material_library = __esm(() => {
"emissive",
"occlusion"
]).default("albedo"),
- name: z3.string().min(1).max(80).optional(),
- layers: z3.array(z3.discriminatedUnion("op", [
- z3.object({ op: z3.literal("solid"), color: color2, ...layerCommon }).strict(),
- z3.object({
- op: z3.literal("checker"),
+ name: z4.string().min(1).max(80).optional(),
+ layers: z4.array(z4.discriminatedUnion("op", [
+ z4.object({ op: z4.literal("solid"), color: color2, ...layerCommon }).strict(),
+ z4.object({
+ op: z4.literal("checker"),
colorA: color2,
colorB: color2,
squares: count2.default(8),
...layerCommon
}).strict(),
- z3.object({
- op: z3.literal("stripes"),
+ z4.object({
+ op: z4.literal("stripes"),
colorA: color2,
colorB: color2,
count: count2.default(8),
- angleDeg: z3.number().min(-36000).max(36000).default(0),
+ angleDeg: z4.number().min(-36000).max(36000).default(0),
...layerCommon
}).strict(),
- z3.object({
- op: z3.literal("gradient"),
+ z4.object({
+ op: z4.literal("gradient"),
from: color2,
to: color2,
- angleDeg: z3.number().min(-36000).max(36000).default(0),
+ angleDeg: z4.number().min(-36000).max(36000).default(0),
...layerCommon
}).strict(),
- z3.object({
- op: z3.literal("bricks"),
+ z4.object({
+ op: z4.literal("bricks"),
brick: color2,
mortar: color2,
rows: count2.default(8),
cols: count2.default(4),
- mortarWidth: z3.number().min(0).max(1).default(0.06),
- stagger: z3.number().min(0).max(1).default(0.5),
+ mortarWidth: z4.number().min(0).max(1).default(0.06),
+ stagger: z4.number().min(0).max(1).default(0.5),
...layerCommon
}).strict(),
- z3.object({
- op: z3.literal("noise"),
+ z4.object({
+ op: z4.literal("noise"),
colorA: color2,
colorB: color2,
scale: count2.default(8),
- octaves: z3.number().int().min(1).max(6).default(3),
- seed: z3.number().int().min(-2147483648).max(2147483647).default(0),
+ octaves: z4.number().int().min(1).max(6).default(3),
+ seed: z4.number().int().min(-2147483648).max(2147483647).default(0),
...layerCommon
}).strict()
])).min(1).max(8)
}).strict();
- materialNormalDerivationSchema = z3.object({
- kind: z3.literal("normal-from-height"),
- strength: z3.number().finite().positive().max(64)
+ materialNormalDerivationSchema = z4.object({
+ kind: z4.literal("normal-from-height"),
+ strength: z4.number().finite().positive().max(64)
}).strict();
- proceduralSchema = z3.object({
- compiler: z3.literal("kiln.procedural-texture.v2"),
+ proceduralSchema = z4.object({
+ compiler: z4.literal("kiln.procedural-texture.v2"),
spec: materialProceduralSpecSchema,
derive: materialNormalDerivationSchema.optional(),
recipeHash: materialLibraryHashSchema,
pixelHash: materialLibraryHashSchema,
- encoder: z3.object({ name: z3.literal("sharp"), version: text3 }).strict()
+ encoder: z4.object({ name: z4.literal("sharp"), version: text3 }).strict()
}).strict();
- parametersSchema = z3.object({
- baseColor: z3.number().int().min(0).max(16777215).optional(),
- roughness: z3.number().min(0).max(1).default(1),
- metalness: z3.number().min(0).max(1).default(0),
- emissive: z3.number().int().min(0).max(16777215).optional(),
- emissiveIntensity: z3.number().min(0).max(64).default(1),
- alphaMode: z3.enum(["opaque", "mask", "blend"]).default("opaque"),
- alphaCutoff: z3.number().min(0).max(1).default(0.5),
- doubleSided: z3.boolean().default(false)
+ parametersSchema = z4.object({
+ baseColor: z4.number().int().min(0).max(16777215).optional(),
+ roughness: z4.number().min(0).max(1).default(1),
+ metalness: z4.number().min(0).max(1).default(0),
+ emissive: z4.number().int().min(0).max(16777215).optional(),
+ emissiveIntensity: z4.number().min(0).max(64).default(1),
+ alphaMode: z4.enum(["opaque", "mask", "blend"]).default("opaque"),
+ alphaCutoff: z4.number().min(0).max(1).default(0.5),
+ doubleSided: z4.boolean().default(false)
}).strict();
- materialManifestSchema = z3.object({
- schemaVersion: z3.literal(1),
+ materialManifestSchema = z4.object({
+ schemaVersion: z4.literal(1),
materialId: materialLibraryIdSchema,
revisionId: materialLibraryHashSchema,
- name: z3.string().min(1).max(200),
- tags: z3.array(z3.string().min(1).max(80)).max(30),
- tileable: z3.boolean(),
- physicalSizeMeters: z3.object({
- width: z3.number().finite().positive().max(1e5),
- height: z3.number().finite().positive().max(1e5)
+ name: z4.string().min(1).max(200),
+ tags: z4.array(z4.string().min(1).max(80)).max(30),
+ tileable: z4.boolean(),
+ physicalSizeMeters: z4.object({
+ width: z4.number().finite().positive().max(1e5),
+ height: z4.number().finite().positive().max(1e5)
}).strict().optional(),
parameters: parametersSchema,
- sources: z3.array(materialSourceSchema).min(1).max(20),
- maps: z3.array(z3.object({
- slot: z3.enum(MATERIAL_LIBRARY_SLOTS),
- file: z3.enum([
+ sources: z4.array(materialSourceSchema).min(1).max(20),
+ maps: z4.array(z4.object({
+ slot: z4.enum(MATERIAL_LIBRARY_SLOTS),
+ file: z4.enum([
"baseColor.png",
"normal.png",
"metallicRoughness.png",
@@ -24827,45 +25342,45 @@ var init_material_library = __esm(() => {
"occlusion.png"
]),
sha256: materialLibraryHashSchema,
- bytes: z3.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapBytes),
- width: z3.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
- height: z3.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
- usage: z3.enum(["albedo", "normal", "metallicRoughness", "emissive", "occlusion"]),
- colorSpace: z3.enum(["srgb", "linear"]),
- normalConvention: z3.literal("opengl").optional(),
- channelPacking: z3.literal("r-occlusion-g-roughness-b-metallic").optional(),
+ bytes: z4.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapBytes),
+ width: z4.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
+ height: z4.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
+ usage: z4.enum(["albedo", "normal", "metallicRoughness", "emissive", "occlusion"]),
+ colorSpace: z4.enum(["srgb", "linear"]),
+ normalConvention: z4.literal("opengl").optional(),
+ channelPacking: z4.literal("r-occlusion-g-roughness-b-metallic").optional(),
sourceId: materialLibraryIdSchema,
- originalFile: z3.string().min(1).max(200).optional(),
- transforms: z3.array(materialTransformSchema).max(30),
+ originalFile: z4.string().min(1).max(200).optional(),
+ transforms: z4.array(materialTransformSchema).max(30),
procedural: proceduralSchema.optional()
}).strict()).min(1).max(5)
}).strict();
- proceduralMaterialDraftSchema = z3.object({
+ proceduralMaterialDraftSchema = z4.object({
materialId: materialLibraryIdSchema,
- name: z3.string().min(1).max(200),
- tags: z3.array(z3.string().min(1).max(80)).max(30).optional(),
- tileable: z3.boolean(),
- physicalSizeMeters: z3.object({
- width: z3.number().finite().positive().max(1e5),
- height: z3.number().finite().positive().max(1e5)
+ name: z4.string().min(1).max(200),
+ tags: z4.array(z4.string().min(1).max(80)).max(30).optional(),
+ tileable: z4.boolean(),
+ physicalSizeMeters: z4.object({
+ width: z4.number().finite().positive().max(1e5),
+ height: z4.number().finite().positive().max(1e5)
}).strict().optional(),
parameters: parametersSchema.partial().optional(),
- sources: z3.array(materialSourceSchema).min(1).max(20),
- maps: z3.array(z3.object({
- slot: z3.enum(MATERIAL_LIBRARY_SLOTS),
+ sources: z4.array(materialSourceSchema).min(1).max(20),
+ maps: z4.array(z4.object({
+ slot: z4.enum(MATERIAL_LIBRARY_SLOTS),
sourceId: materialLibraryIdSchema,
- transforms: z3.array(materialTransformSchema).max(30),
- normalConvention: z3.literal("opengl").optional(),
- channelPacking: z3.literal("r-occlusion-g-roughness-b-metallic").optional(),
+ transforms: z4.array(materialTransformSchema).max(30),
+ normalConvention: z4.literal("opengl").optional(),
+ channelPacking: z4.literal("r-occlusion-g-roughness-b-metallic").optional(),
procedural: materialProceduralSpecSchema,
derive: materialNormalDerivationSchema.optional()
}).strict()).min(1).max(5)
}).strict();
- materialLibraryPayloadSchema = z3.object({
- schemaVersion: z3.literal(1),
- records: z3.array(z3.object({
+ materialLibraryPayloadSchema = z4.object({
+ schemaVersion: z4.literal(1),
+ records: z4.array(z4.object({
manifest: materialManifestSchema,
- files: z3.record(z3.string().regex(/^(baseColor|normal|metallicRoughness|emissive|occlusion)\.png$/), z3.string().max(Math.ceil(MATERIAL_LIBRARY_LIMITS.maxMapBytes / 3) * 4))
+ files: z4.record(z4.string().regex(/^(baseColor|normal|metallicRoughness|emissive|occlusion)\.png$/), z4.string().max(Math.ceil(MATERIAL_LIBRARY_LIMITS.maxMapBytes / 3) * 4))
}).strict()).max(MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)
}).strict();
});
@@ -25023,19 +25538,6 @@ var init_material_library_node = __esm(() => {
encoder = { name: "sharp", version: sharp.versions.sharp };
});
-// src/rebuild-options.ts
-import { z as z4 } from "zod";
-var rebuildOptionsSchema;
-var init_rebuild_options = __esm(() => {
- rebuildOptionsSchema = z4.object({
- indexPolicy: z4.enum(["indexed", "asBuilt"]).optional(),
- gltfExporter: z4.enum(["legacy", "three"]),
- geometryPolicy: z4.enum(["warn", "strict"]),
- optimize: z4.enum(["off", "auto", "palette", "full"]),
- instance: z4.enum(["off", "auto", "on"])
- });
-});
-
// src/evaluator/protocol.ts
function evaluatorOutcomeMessage(code) {
return EVALUATOR_OUTCOME_MESSAGES[code];
@@ -25231,7 +25733,7 @@ var init_renderer_id = __esm(() => {
});
// src/views/scene-raster.ts
-import * as THREE39 from "three";
+import * as THREE40 from "three";
var DEG2;
var init_scene_raster = __esm(() => {
init_evaluator();
@@ -25242,18 +25744,18 @@ var init_scene_raster = __esm(() => {
});
// src/views/vehicle.ts
-import * as THREE40 from "three";
+import * as THREE41 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 THREE40.Box3;
+ const bounds = new THREE41.Box3;
let found = false;
root.traverse((node) => {
if (!hasRole2(node, "chassis"))
return;
node.traverse((part) => {
- if (!(part instanceof THREE40.Mesh) || !(part.geometry instanceof THREE40.BufferGeometry))
+ if (!(part instanceof THREE41.Mesh) || !(part.geometry instanceof THREE41.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const box = part.geometry.boundingBox;
@@ -25263,7 +25765,7 @@ function chassisBounds(root, inverse) {
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 THREE40.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE41.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -25331,33 +25833,33 @@ function tagDiagnostic(node, role) {
stampSemanticMetadataV1(node, { roles: [role] });
}
function rod(name, start, end, radius, color, role) {
- const from = new THREE40.Vector3(...start);
- const to = new THREE40.Vector3(...end);
+ const from = new THREE41.Vector3(...start);
+ const to = new THREE41.Vector3(...end);
const direction = to.clone().sub(from);
const length = direction.length();
- const geometry = length > 0.000000001 ? new THREE40.CylinderGeometry(radius, radius, length, 8) : new THREE40.SphereGeometry(radius, 8, 6);
- const result = new THREE40.Mesh(geometry, new THREE40.MeshBasicMaterial({ color }));
+ const geometry = length > 0.000000001 ? new THREE41.CylinderGeometry(radius, radius, length, 8) : new THREE41.SphereGeometry(radius, 8, 6);
+ const result = new THREE41.Mesh(geometry, new THREE41.MeshBasicMaterial({ color }));
result.name = name;
result.position.copy(from).add(to).multiplyScalar(0.5);
if (length > 0.000000001) {
- result.quaternion.setFromUnitVectors(new THREE40.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
+ result.quaternion.setFromUnitVectors(new THREE41.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
}
tagDiagnostic(result, role);
return result;
}
function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {
- const overlay = new THREE40.Group;
+ const overlay = new THREE41.Group;
overlay.name = "VehicleDiagnosticOverlay";
const chassisSpan = descriptor.chassisBox ? Math.max(descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0], descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1], descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2]) : 1;
const thickness = Math.max(0.01, chassisSpan * 0.008);
- const arrow = new THREE40.Group;
+ const arrow = new THREE41.Group;
arrow.name = "Diagnostic_Forward_+X";
tagDiagnostic(arrow, "diagnostic.vehicle.forward");
arrow.add(rod("Diagnostic_Forward_Shaft", descriptor.forwardArrow.start, [descriptor.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));
- const arrowHead = new THREE40.Mesh(new THREE40.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE40.MeshBasicMaterial({ color: 16724804 }));
+ const arrowHead = new THREE41.Mesh(new THREE41.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE41.MeshBasicMaterial({ color: 16724804 }));
arrowHead.name = "Diagnostic_Forward_Head";
arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);
- arrowHead.quaternion.setFromUnitVectors(new THREE40.Vector3(0, 1, 0), new THREE40.Vector3(1, 0, 0));
+ arrowHead.quaternion.setFromUnitVectors(new THREE41.Vector3(0, 1, 0), new THREE41.Vector3(1, 0, 0));
tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");
arrow.add(arrowHead);
overlay.add(arrow);
@@ -25365,18 +25867,18 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));
}
for (const wheel of descriptor.wheels) {
- const ring = new THREE40.Mesh(new THREE40.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE40.MeshBasicMaterial({ color: 16763955 }));
+ const ring = new THREE41.Mesh(new THREE41.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE41.MeshBasicMaterial({ color: 16763955 }));
ring.name = `Diagnostic_Wheel_${wheel.id}`;
ring.position.set(...wheel.center);
- const axle = new THREE40.Vector3(...wheel.axle);
+ const axle = new THREE41.Vector3(...wheel.axle);
if (axle.lengthSq() > 0.000000000001) {
- ring.quaternion.setFromUnitVectors(new THREE40.Vector3(0, 0, 1), axle.normalize());
+ ring.quaternion.setFromUnitVectors(new THREE41.Vector3(0, 0, 1), axle.normalize());
}
tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);
overlay.add(ring);
}
if (descriptor.chassisBox) {
- const chassis = new THREE40.Group;
+ const chassis = new THREE41.Group;
chassis.name = "Diagnostic_ChassisBox";
tagDiagnostic(chassis, "diagnostic.vehicle.chassis");
const { min, max } = descriptor.chassisBox;
@@ -25410,7 +25912,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(chassis);
}
if (descriptor.supportPlaneY !== undefined) {
- const plane = new THREE40.Group;
+ const plane = new THREE41.Group;
plane.name = "Diagnostic_SupportPlane";
tagDiagnostic(plane, "diagnostic.vehicle.support-plane");
const halfX = Math.max(1, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;
@@ -25739,7 +26241,7 @@ var init_views = __esm(() => {
});
// src/views/character-capture.ts
-import * as THREE41 from "three";
+import * as THREE42 from "three";
function drawLine2(rgb, width, height, from, to, color) {
let x0 = Math.round(from[0]);
let y0 = Math.round(from[1]);
@@ -25776,22 +26278,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {
}
function projector(root, cameraId, size) {
root.updateMatrixWorld(true);
- const bounds = new THREE41.Box3().setFromObject(root);
+ const bounds = new THREE42.Box3().setFromObject(root);
if (bounds.isEmpty())
- bounds.set(new THREE41.Vector3(-0.5, 0, -0.5), new THREE41.Vector3(0.5, 1, 0.5));
- const center = bounds.getCenter(new THREE41.Vector3);
- const camera = cameraId === "front" ? new THREE41.Vector3(1, 0, 0) : new THREE41.Vector3(0, 0, 1);
- const upHint = new THREE41.Vector3(0, 1, 0);
- const xAxis = new THREE41.Vector3().crossVectors(upHint, camera).normalize();
- const yAxis = new THREE41.Vector3().crossVectors(camera, xAxis).normalize();
+ bounds.set(new THREE42.Vector3(-0.5, 0, -0.5), new THREE42.Vector3(0.5, 1, 0.5));
+ const center = bounds.getCenter(new THREE42.Vector3);
+ const camera = cameraId === "front" ? new THREE42.Vector3(1, 0, 0) : new THREE42.Vector3(0, 0, 1);
+ const upHint = new THREE42.Vector3(0, 1, 0);
+ const xAxis = new THREE42.Vector3().crossVectors(upHint, camera).normalize();
+ const yAxis = new THREE42.Vector3().crossVectors(camera, xAxis).normalize();
let extent = 0.000001;
for (let corner = 0;corner < 8; corner++) {
- const point = new THREE41.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);
+ const point = new THREE42.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);
extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));
}
const scale = size * 0.45 / extent;
return (assetPoint) => {
- const world = new THREE41.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
+ const world = new THREE42.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];
};
}
@@ -25917,19 +26419,10 @@ var init_character_capture = __esm(() => {
});
// src/render.ts
-import * as THREE42 from "three";
-import { Document } from "@gltf-transform/core";
+import * as THREE43 from "three";
+import { Document, Logger } from "@gltf-transform/core";
import { KHRMaterialsEmissiveStrength } from "@gltf-transform/extensions";
-import {
- dedup,
- instance,
- palette,
- flatten,
- join,
- weld,
- prune,
- mergeDocuments
-} from "@gltf-transform/functions";
+import { dedup, instance, palette, weld, prune, mergeDocuments } from "@gltf-transform/functions";
function hiddenTriangles(root, lowerLevels) {
let hidden = 0;
const visit = (node) => {
@@ -26090,7 +26583,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras) {
} else if (stdMat.transparent) {
mat.setAlphaMode("BLEND");
}
- if (stdMat.side === THREE42.DoubleSide) {
+ if (stdMat.side === THREE43.DoubleSide) {
mat.setDoubleSided(true);
}
if (stdMat.map) {
@@ -26157,7 +26650,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras) {
} else if (common.transparent || (common.opacity ?? 1) < 1) {
mat.setAlphaMode("BLEND");
}
- if (threeMat.side === THREE42.DoubleSide)
+ if (threeMat.side === THREE43.DoubleSide)
mat.setDoubleSided(true);
if (common.map && !mat.getBaseColorTexture()) {
const texture = bridgeTexture(doc, common.map, textureCache);
@@ -26292,7 +26785,7 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache,
const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;
let gtMesh = meshCache.get(cacheKey);
if (!gtMesh) {
- const geometry = new THREE42.PlaneGeometry(1, 1);
+ const geometry = new THREE43.PlaneGeometry(1, 1);
if (centerX !== 0.5 || centerY !== 0.5) {
geometry.translate(0.5 - centerX, 0.5 - centerY, 0);
}
@@ -26316,9 +26809,9 @@ function animationInterpolation(track) {
if (isCubicSplineTrack(track))
return "CUBICSPLINE";
const mode = track.getInterpolation();
- if (mode === THREE42.InterpolateDiscrete)
+ if (mode === THREE43.InterpolateDiscrete)
return "STEP";
- if (mode === THREE42.InterpolateLinear)
+ if (mode === THREE43.InterpolateLinear)
return "LINEAR";
throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);
}
@@ -26482,27 +26975,41 @@ async function applyGpuInstancing(doc, mode, role) {
const after = collectGlbMetrics(doc);
return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };
}
-async function consolidateMaterials(doc, mode) {
+async function consolidateMaterials(doc, mode, keep = []) {
+ doc.setLogger(new Logger(Logger.Verbosity.WARN));
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 || hasNodeLevelsOfDetail(doc) || hasPreservedNodeState(doc)) ? "palette" : mode;
const steps = root.listMaterials().some((material) => Object.keys(material.getExtras()).length > 0) ? [] : [palette({ min: PALETTE_MIN })];
- if (effective === "full") {
- steps.push(flatten(), join({ keepNamed: true }));
- }
+ let merge;
+ if (mode === "full")
+ steps.push(rigidMerge({ keep }, (summary) => {
+ merge = summary;
+ }));
steps.push(weld(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));
await doc.transform(...steps);
const after = collectGlbMetrics(doc);
return {
- mode: effective,
+ mode,
materialsBefore: before.uniqueMaterials,
materialsAfter: after.uniqueMaterials,
drawsBefore: before.drawCalls,
- drawsAfter: after.drawCalls
+ drawsAfter: after.drawCalls,
+ ...merge ? { rigidMerge: merge } : {}
};
}
+function optimizeWarnings(summary) {
+ const merge = summary.rigidMerge;
+ if (!merge)
+ return [];
+ const warnings = [];
+ if (merge.skipped)
+ warnings.push(`Rigid merge skipped: ${merge.skipped}; geometry left separate.`);
+ if (merge.rejected.length)
+ warnings.push(`Rigid merge retained ${merge.rejected.length} rejected buckets; first: ${merge.rejected[0].error}`);
+ if (merge.unmatchedKeep.length)
+ warnings.push(`Rigid merge did not find ${merge.unmatchedKeep.length} requested boundary names.`);
+ return warnings;
+}
async function renderSceneToGLB(root, opts = {}) {
assertNoLegacyRuntimePolicy(opts);
const requirements = resolveRequirementsContext(opts.requirements);
@@ -26598,6 +27105,7 @@ async function renderSceneToGLB(root, opts = {}) {
if (effectiveOptimize !== "off") {
try {
optimize = await consolidateMaterials(doc, effectiveOptimize);
+ warnings.push(...optimizeWarnings(optimize));
} catch (err) {
warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);
}
@@ -26701,6 +27209,7 @@ async function renderGLBInProcess(code, opts = {}) {
gltfExporter: resolveGltfExporter(opts.gltfExporter),
geometryPolicy: opts.geometryPolicy ?? "warn",
optimize: resolveOptimize(opts.optimize),
+ ...resolveOptimize(opts.optimize) === "full" ? { optimizationPipeline: FULL_OPTIMIZATION_PIPELINE } : {},
instance: resolveInstance(opts.instance)
};
let materialLibraryDependencies;
@@ -26816,8 +27325,8 @@ function collectMeshStats(root) {
if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {
return;
}
- const center = new THREE42.Vector3;
- const size = new THREE42.Vector3;
+ const center = new THREE43.Vector3;
+ const size = new THREE43.Vector3;
box.getCenter(center);
box.getSize(size);
out.push({
@@ -26832,7 +27341,7 @@ function collectMeshStats(root) {
return out;
}
function minimalGapVector(a, b) {
- const v = new THREE42.Vector3;
+ const v = new THREE43.Vector3;
for (const axis of ["x", "y", "z"]) {
if (a.min[axis] > b.max[axis])
v[axis] = b.max[axis] - a.min[axis];
@@ -26850,10 +27359,10 @@ function inspectSceneStructure(root, opts = {}) {
return warnings;
const cat = opts.category?.toLowerCase();
if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {
- const all = new THREE42.Box3;
+ const all = new THREE43.Box3;
for (const m of meshes)
all.union(m.box);
- const size = new THREE42.Vector3;
+ const size = new THREE43.Vector3;
all.getSize(size);
if (cat === "aircraft") {
if (size.y > size.x * 1.2) {
@@ -26946,6 +27455,8 @@ var init_render = __esm(() => {
init_material_recipe_runtime();
init_material_resources();
init_texture_resolver();
+ init_rebuild_options();
+ init_rigid_merge();
init_validation();
init_kit();
init_texture_bake();
diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjs
index e7eb79e0..3ee07988 100644
--- a/dist/mcp-engine.mjs
+++ b/dist/mcp-engine.mjs
@@ -4133,6 +4133,10 @@ var init_material_library_node = __esm(() => {
});
// src/asset-export.ts
+var exports_asset_export = {};
+__export(exports_asset_export, {
+ exportAssetGlb: () => exportAssetGlb
+});
async function sha2562(bytes) {
const digest = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));
return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
@@ -4251,8 +4255,8 @@ function assetLinks(collection, manifest) {
function assetMime(name) {
return name.endsWith(".glb") ? "model/gltf-binary" : name.endsWith(".png") ? "image/png" : name.endsWith(".zip") ? "application/zip" : name.endsWith(".json") ? "application/json" : "text/javascript";
}
-async function runtimeAssetLinks(collection, record) {
- const output = await exportAssetGlb(record, { profile: "runtime" });
+async function runtimeAssetLinks(collection, record, derived) {
+ const output = derived ?? await exportAssetGlb(record, { profile: "runtime" });
if (output.profile !== "runtime")
throw new Error("Expected runtime export");
return [
@@ -6674,7 +6678,7 @@ var init_architecture = __esm(() => {
scope: { kind: "category", category: "architecture" },
ruleClass: "exact",
owner: KILN_ENGINE_QA_OWNER,
- promotion: conformancePromotionAuthorization("architecture-qa-v1", "src/qa/architecture.test.ts", "c3a3bdc764c62238cede39813995fcaa428131d0aa3774bcd86cfc8b60f36671"),
+ promotion: conformancePromotionAuthorization("architecture-qa-v1", "src/qa/architecture.test.ts", "ce42ab6baef737d109f272413d902ea0903bd66c4da13ea723a52aff2f9e6c66", KILN_ENGINE_QA_OWNER, "2026-10-03T05:45:42.000Z", "enforce", "cpu-raster:0.10.0"),
defaultMode: "enforce",
evaluate: (context) => evaluateArchitectureQa(context).filter((finding) => finding.disposition === "block")
};
@@ -15282,13 +15286,14 @@ var init_requirements_report = __esm(() => {
// src/rebuild-options.ts
import { z as z6 } from "zod";
-var rebuildOptionsSchema;
+var FULL_OPTIMIZATION_PIPELINE = "rigid-v1", rebuildOptionsSchema;
var init_rebuild_options = __esm(() => {
rebuildOptionsSchema = z6.object({
indexPolicy: z6.enum(["indexed", "asBuilt"]).optional(),
gltfExporter: z6.enum(["legacy", "three"]),
geometryPolicy: z6.enum(["warn", "strict"]),
optimize: z6.enum(["off", "auto", "palette", "full"]),
+ optimizationPipeline: z6.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
instance: z6.enum(["off", "auto", "on"])
});
});
@@ -22061,6 +22066,507 @@ var init_material_metrics = __esm(() => {
});
});
+// src/rigid-merge.ts
+import {
+ ComponentTypeToTypedArray,
+ Primitive,
+ PropertyType as PropertyType3
+} from "@gltf-transform/core";
+import { createTransform, dequantizePrimitive, joinPrimitives } from "@gltf-transform/functions";
+import * as THREE37 from "three";
+function isSingular(matrix) {
+ const e = matrix.elements;
+ const scale = Math.hypot(e[0], e[1], e[2]) * Math.hypot(e[4], e[5], e[6]) * Math.hypot(e[8], e[9], e[10]);
+ const det = matrix.determinant();
+ return !Number.isFinite(det) || Math.abs(det) <= 0.000000001 * scale;
+}
+function findRigidBoundaries(doc, keep) {
+ const root = doc.getRoot();
+ const found = new Map;
+ const add = (node, reason) => {
+ const reasons = found.get(node) ?? [];
+ if (!reasons.includes(reason))
+ reasons.push(reason);
+ found.set(node, reasons);
+ };
+ for (const animation of root.listAnimations())
+ for (const channel of animation.listChannels()) {
+ const target = channel.getTargetNode();
+ if (target)
+ add(target, "animated");
+ }
+ for (const skin of root.listSkins())
+ for (const joint of skin.listJoints())
+ add(joint, "skin-joint");
+ const targets = new Set;
+ for (const node of root.listNodes()) {
+ const semantic = node.getExtras()[KILN_SEMANTIC_EXTRAS_KEY];
+ if (Array.isArray(semantic?.relationships)) {
+ for (const relationship of semantic.relationships)
+ if (relationship?.targetType === "node" && typeof relationship.target === "string")
+ targets.add(relationship.target);
+ }
+ }
+ for (const node of root.listNodes()) {
+ const name = node.getName();
+ const sceneParents = node.listParents().filter((parent) => parent.propertyType === PropertyType3.SCENE).length;
+ if (sceneParents > 1)
+ add(node, "shared-scene");
+ if (JOINT_PIVOT.test(name))
+ add(node, "joint-pivot");
+ if (hasKeys(node.getExtras()))
+ add(node, "extras");
+ if (targets.has(name))
+ add(node, "relationship-target");
+ if (node.getExtension("KHR_node_visibility"))
+ add(node, "visibility");
+ const lod = node.getExtension(MSFT_LOD);
+ if (lod) {
+ add(node, "lod");
+ for (const level of lod.listLevels())
+ if (level.propertyType === PropertyType3.NODE)
+ add(level, "lod");
+ }
+ if (keep.has(name))
+ add(node, "kept");
+ }
+ return found;
+}
+function nodeLock(node, mesh, world, expandShared) {
+ if (node.getSkin())
+ return "skinned";
+ if (node.getExtension("EXT_mesh_gpu_instancing"))
+ return "instanced";
+ if (hasKeys(mesh.getExtras()))
+ return "mesh-extras";
+ if (!expandShared && nodeUsers(mesh) > 1)
+ return "shared-mesh";
+ if (isSingular(world))
+ return "singular-matrix";
+ return;
+}
+function primLock(prim, mergeTransparent) {
+ if (prim.listTargets().length > 0)
+ return "morph-targets";
+ if (RESTART_MODES.has(prim.getMode()))
+ return "primitive-mode";
+ if (prim.listExtensions().length > 0)
+ return "primitive-extensions";
+ if (hasKeys(prim.getExtras()))
+ return "primitive-extras";
+ if (!prim.getAttribute("POSITION"))
+ return "no-position";
+ const material = prim.getMaterial();
+ if (material?.getExtension("KHR_materials_volume"))
+ return "volume";
+ if (!mergeTransparent && material && (material.getAlphaMode() === "BLEND" || material.getExtension("KHR_materials_transmission") || material.getExtension("KHR_materials_diffuse_transmission")))
+ return "transparent";
+ return;
+}
+function bucketKey(prim, materials, handedness) {
+ const layout = prim.listSemantics().sort().map((semantic) => {
+ const a = prim.getAttribute(semantic);
+ return `${semantic}:${a.getElementSize()}:${a.getComponentType()}:${a.getNormalized()}`;
+ }).join("+");
+ const hand = handedness !== null && prim.getAttribute("TANGENT") ? `|${handedness}` : "";
+ return `${materials.get(prim.getMaterial()) ?? -1}|${prim.getMode()}|${!!prim.getIndices()}|${layout}${hand}`;
+}
+function reverseWinding(prim) {
+ const indices = prim.getIndices()?.getArray();
+ const swap = (array, size, i) => {
+ for (let k = 0;k < size; k++) {
+ const [j, l] = [(i + 1) * size + k, (i + 2) * size + k];
+ [array[j], array[l]] = [array[l], array[j]];
+ }
+ };
+ if (indices) {
+ for (let i = 0;i + 2 < indices.length; i += 3)
+ swap(indices, 1, i);
+ return;
+ }
+ for (const semantic of prim.listSemantics()) {
+ const attribute = prim.getAttribute(semantic);
+ for (let i = 0;i + 2 < attribute.getCount(); i += 3)
+ swap(attribute.getArray(), attribute.getElementSize(), i);
+ }
+}
+function bake(prim, matrix) {
+ const linear = new THREE37.Matrix3().setFromMatrix4(matrix);
+ const normalMatrix = new THREE37.Matrix3().getNormalMatrix(matrix);
+ const mirrored = matrix.determinant() < 0;
+ const v = new THREE37.Vector3;
+ const each = (semantic, apply) => {
+ const attribute = prim.getAttribute(semantic);
+ const element = [];
+ for (let i = 0;i < (attribute?.getCount() ?? 0); i++) {
+ apply(attribute.getElement(i, element));
+ attribute.setElement(i, element);
+ }
+ };
+ each("POSITION", (e) => v.fromArray(e).applyMatrix4(matrix).toArray(e));
+ each("NORMAL", (e) => v.fromArray(e).applyMatrix3(normalMatrix).normalize().toArray(e));
+ each("TANGENT", (e) => {
+ v.fromArray(e).applyMatrix3(linear).normalize().toArray(e);
+ if (mirrored)
+ e[3] = -e[3];
+ });
+ if (mirrored && prim.getMode() === Primitive.Mode.TRIANGLES)
+ reverseWinding(prim);
+}
+function destinationOf(entries) {
+ let chosen = entries[0].node;
+ let best = Infinity;
+ let bestScale = Infinity;
+ for (const { node } of entries) {
+ const linear = new THREE37.Matrix3().setFromMatrix4(worldOf(node));
+ const norm = Math.hypot(...linear.elements);
+ const inverseNorm = Math.hypot(...linear.clone().invert().elements);
+ const condition = norm * inverseNorm;
+ const scale = Math.max(norm, inverseNorm);
+ if (condition < best * (1 - 0.000000000001) || Math.abs(condition - best) <= best * 0.000000000001 && scale < bestScale) {
+ chosen = node;
+ best = condition;
+ bestScale = scale;
+ }
+ }
+ return chosen;
+}
+function checkPositionPrecision(input, output, sourceWorld, destinationWorld, reversed) {
+ const expected = new THREE37.Vector3;
+ const actual = new THREE37.Vector3;
+ const bounds = new THREE37.Box3;
+ const element = [];
+ let error = 0;
+ let magnitude = 0;
+ for (let i = 0;i < input.getCount(); i++) {
+ const out = reversed ? i % 3 === 1 ? i + 1 : i % 3 === 2 ? i - 1 : i : i;
+ expected.fromArray(input.getElement(i, element)).applyMatrix4(sourceWorld);
+ actual.fromArray(output.getElement(out, element)).applyMatrix4(destinationWorld);
+ bounds.expandByPoint(expected);
+ error = Math.max(error, expected.distanceTo(actual));
+ magnitude = Math.max(magnitude, expected.length());
+ }
+ const tolerance = Math.max(bounds.getSize(expected).length() * 0.000001, magnitude * Number.EPSILON * 32, Number.EPSILON);
+ if (error > tolerance)
+ throw new Error("rigid merge: destination frame loses position precision");
+}
+function splitVertices(prim, created) {
+ if (prim.getAttribute("POSITION").getCount() <= MAX_VERTICES)
+ return [prim];
+ const width = prim.getMode() === Primitive.Mode.POINTS ? 1 : prim.getMode() === Primitive.Mode.LINES ? 2 : 3;
+ const sourceIndices = prim.getIndices()?.getArray();
+ const count = sourceIndices?.length ?? prim.getAttribute("POSITION").getCount();
+ if (count % width !== 0)
+ throw new Error("rigid merge: incomplete primitive element");
+ const chunks = [];
+ let remap = new Map;
+ let indices = [];
+ const flush = () => {
+ if (!indices.length)
+ return;
+ const chunk = prim.clone();
+ created.push(chunk);
+ const vertices = [...remap.keys()];
+ for (const semantic of prim.listSemantics()) {
+ const source = prim.getAttribute(semantic);
+ const size = source.getElementSize();
+ const ArrayType = ComponentTypeToTypedArray[source.getComponentType()];
+ if (!ArrayType)
+ throw new Error(`rigid merge: unsupported component type for ${semantic}`);
+ const data = new ArrayType(vertices.length * size);
+ const sourceData = source.getArray();
+ for (const [out, input] of vertices.entries())
+ data.set(sourceData.subarray(input * size, (input + 1) * size), out * size);
+ const attribute = source.clone().setArray(data);
+ created.push(attribute);
+ chunk.setAttribute(semantic, attribute);
+ }
+ if (prim.getIndices()) {
+ const accessor = prim.getIndices().clone().setArray(new Uint16Array(indices));
+ created.push(accessor);
+ chunk.setIndices(accessor);
+ }
+ chunks.push(chunk);
+ remap = new Map;
+ indices = [];
+ };
+ for (let offset = 0;offset < count; offset += width) {
+ const element = Array.from({ length: width }, (_, i) => sourceIndices?.[offset + i] ?? offset + i);
+ const extra = new Set(element.filter((index) => !remap.has(index))).size;
+ if (remap.size + extra > MAX_VERTICES)
+ flush();
+ for (const index of element) {
+ if (!remap.has(index))
+ remap.set(index, remap.size);
+ indices.push(remap.get(index));
+ }
+ }
+ flush();
+ for (const property of [prim, ...accessorsOf(prim)])
+ property.dispose();
+ return chunks;
+}
+function prepare(entries, dst, created) {
+ const destinationWorld = worldOf(dst);
+ const inverse = destinationWorld.clone().invert();
+ const copies = entries.map(({ node, prim }) => {
+ const copy = prim.clone();
+ created.push(copy);
+ for (const semantic of copy.listSemantics()) {
+ const attribute = copy.getAttribute(semantic).clone();
+ created.push(attribute);
+ copy.setAttribute(semantic, attribute);
+ }
+ const indices = copy.getIndices()?.clone();
+ if (indices) {
+ created.push(indices);
+ copy.setIndices(indices);
+ }
+ dequantizePrimitive(copy, { pattern: BAKED });
+ if (node !== dst) {
+ const sourceWorld = worldOf(node);
+ const matrix = inverse.clone().multiply(sourceWorld);
+ bake(copy, matrix);
+ const reversed = !copy.getIndices() && copy.getMode() === Primitive.Mode.TRIANGLES && matrix.determinant() < 0;
+ checkPositionPrecision(prim.getAttribute("POSITION"), copy.getAttribute("POSITION"), sourceWorld, destinationWorld, reversed);
+ }
+ return copy;
+ });
+ const merged = joinPrimitives(copies);
+ created.push(merged, ...accessorsOf(merged));
+ for (const semantic of ["POSITION", "NORMAL", "TANGENT"]) {
+ const array = merged.getAttribute(semantic)?.getArray();
+ if (array && !array.every(Number.isFinite))
+ throw new Error(`rigid merge: non-finite ${semantic} in the joined primitive`);
+ }
+ const elements = (p) => p.getIndices()?.getCount() ?? p.getAttribute("POSITION").getCount();
+ const expected = copies.reduce((sum, copy) => sum + elements(copy), 0);
+ if (elements(merged) !== expected)
+ throw new Error(`rigid merge: joined ${elements(merged)} of ${expected} elements`);
+ for (const copy of copies)
+ for (const property of [copy, ...accessorsOf(copy)])
+ property.dispose();
+ return splitVertices(merged, created);
+}
+function removableBytes(entries) {
+ const uses = new Map;
+ for (const { node, prim } of entries) {
+ const nodes = uses.get(prim) ?? new Set;
+ nodes.add(node);
+ uses.set(prim, nodes);
+ }
+ const removed = new Set;
+ for (const [prim, nodes] of uses) {
+ const retained = prim.listParents().some((parent) => {
+ if (parent.propertyType === PropertyType3.ROOT)
+ return false;
+ if (parent.propertyType !== PropertyType3.MESH)
+ return true;
+ return parent.listParents().some((user) => user.propertyType !== PropertyType3.ROOT && (user.propertyType !== PropertyType3.NODE || !nodes.has(user)));
+ });
+ if (!retained)
+ removed.add(prim);
+ }
+ const accessors = new Set([...removed].flatMap(accessorsOf));
+ let bytes = 0;
+ for (const accessor of accessors)
+ if (accessor.listParents().every((parent) => parent.propertyType === PropertyType3.ROOT || removed.has(parent)))
+ bytes += accessor.getArray()?.byteLength ?? 0;
+ return bytes;
+}
+function sceneNodes2(doc) {
+ const seen = new Set;
+ const visit = (node) => {
+ if (seen.has(node))
+ return;
+ seen.add(node);
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const scene of doc.getRoot().listScenes())
+ for (const child of scene.listChildren())
+ visit(child);
+ return seen;
+}
+function mergeRigidGroups(doc, options = {}) {
+ const root = doc.getRoot();
+ const keep = new Set(options.keep ?? []);
+ const nodes = sceneNodes2(doc);
+ const names = new Set([...nodes].map((node) => node.getName()));
+ const summary = {
+ primitivesBefore: countPrimitives(nodes),
+ primitivesAfter: 0,
+ groups: 0,
+ merges: 0,
+ boundaries: [],
+ locked: [],
+ rejected: [],
+ unmatchedKeep: [...keep].filter((name) => !names.has(name))
+ };
+ if (root.listAnimations().some((a) => a.listChannels().some((c) => !c.getTargetNode()))) {
+ summary.skipped = "unbounded-animation";
+ summary.primitivesAfter = summary.primitivesBefore;
+ return summary;
+ }
+ const boundaries = findRigidBoundaries(doc, keep);
+ const materials = new Map(root.listMaterials().map((m, i) => [m, i]));
+ const groups = [];
+ const locks = new Map;
+ const lock = (node, reason, primitives) => {
+ const key = `${node.getName()}|${reason}`;
+ const known = locks.get(key);
+ if (known)
+ known.primitives += primitives;
+ else {
+ const entry = { node: node.getName(), reason, primitives };
+ locks.set(key, entry);
+ summary.locked.push(entry);
+ }
+ };
+ const seen = new Set;
+ const visit = (node, parentGroup) => {
+ if (seen.has(node))
+ return;
+ seen.add(node);
+ const reasons = boundaries.get(node);
+ let group = parentGroup;
+ if (reasons) {
+ summary.boundaries.push({ node: node.getName(), reasons });
+ group = new Map;
+ groups.push(group);
+ }
+ const mesh = node.getMesh();
+ if (mesh) {
+ const world = worldOf(node);
+ const nodeReason = reasons ? "boundary" : nodeLock(node, mesh, world, options.expandSharedMeshes !== false);
+ const handedness = options.mergeMirroredTangents ? null : Math.sign(world.determinant());
+ if (nodeReason)
+ lock(node, nodeReason, mesh.listPrimitives().length);
+ else
+ for (const prim of mesh.listPrimitives()) {
+ const primReason = primLock(prim, options.mergeTransparent === true);
+ if (primReason)
+ lock(node, primReason, 1);
+ else {
+ const key = bucketKey(prim, materials, handedness);
+ const list = group.get(key);
+ if (list)
+ list.push({ node, prim });
+ else
+ group.set(key, [{ node, prim }]);
+ }
+ }
+ }
+ for (const child of node.listChildren())
+ visit(child, group);
+ };
+ for (const scene of root.listScenes()) {
+ const group = new Map;
+ groups.push(group);
+ for (const child of scene.listChildren())
+ visit(child, group);
+ }
+ summary.groups = groups.length;
+ const plans = [];
+ for (const group of groups)
+ for (const bucket of group.values()) {
+ let entries = bucket;
+ while (entries.length >= 2) {
+ const created = [];
+ const track = (event) => created.push(event.target);
+ doc.getGraph().addEventListener("node:create", track);
+ try {
+ const destination = destinationOf(entries);
+ const merged = prepare(entries, destination, created);
+ const savedDraws = entries.length - merged.length;
+ const shared = entries.filter((entry) => removableBytes([entry]) < primitiveBytes([entry.prim]));
+ const addedBytes = Math.max(0, primitiveBytes(merged) - removableBytes(entries));
+ if (savedDraws > 0 && addedBytes <= savedDraws * MAX_BYTES_PER_SAVED_DRAW) {
+ plans.push({ entries, destination, merged });
+ break;
+ }
+ for (const property of created)
+ property.dispose();
+ if (!shared.length || savedDraws <= 0)
+ break;
+ const costly = shared.reduce((best, entry) => primitiveBytes(entry.node.getMesh().listPrimitives()) > primitiveBytes(best.node.getMesh().listPrimitives()) ? entry : best);
+ const mesh = costly.node.getMesh();
+ for (const entry of entries.filter((entry) => entry.node.getMesh() === mesh))
+ lock(entry.node, "shared-byte-budget", 1);
+ entries = entries.filter((entry) => entry.node.getMesh() !== mesh);
+ } catch (error) {
+ for (const property of created)
+ property.dispose();
+ summary.rejected.push({
+ node: entries[0].node.getName(),
+ primitives: entries.length,
+ error: error instanceof Error ? error.message : String(error)
+ });
+ break;
+ } finally {
+ doc.getGraph().removeEventListener("node:create", track);
+ }
+ }
+ }
+ const owned = new Map;
+ const ownMesh = (node) => {
+ let mesh = owned.get(node);
+ if (mesh)
+ return mesh;
+ mesh = node.getMesh();
+ if (nodeUsers(mesh) > 1) {
+ mesh = mesh.clone();
+ node.setMesh(mesh);
+ }
+ owned.set(node, mesh);
+ return mesh;
+ };
+ const removed = new Set;
+ for (const { entries, destination, merged } of plans) {
+ for (const { node, prim } of entries) {
+ ownMesh(node).removePrimitive(prim);
+ removed.add(prim);
+ }
+ for (const primitive of merged)
+ ownMesh(destination).addPrimitive(primitive);
+ }
+ for (const [node, mesh] of owned)
+ if (mesh.listPrimitives().length === 0) {
+ node.setMesh(null);
+ if (nodeUsers(mesh) === 0)
+ mesh.dispose();
+ }
+ for (const prim of removed) {
+ if (prim.listParents().some((parent) => parent.propertyType === PropertyType3.MESH))
+ continue;
+ const accessors = accessorsOf(prim);
+ prim.dispose();
+ for (const accessor of accessors)
+ if (accessor.listParents().every((parent) => parent.propertyType === PropertyType3.ROOT))
+ accessor.dispose();
+ }
+ summary.merges = plans.length;
+ summary.primitivesAfter = countPrimitives(nodes);
+ return summary;
+}
+function rigidMerge(options = {}, onSummary) {
+ return createTransform("kilnRigidMerge", (doc) => {
+ const summary = mergeRigidGroups(doc, options);
+ onSummary?.(summary);
+ });
+}
+var JOINT_PIVOT, RESTART_MODES, BAKED, MAX_VERTICES = 65534, MAX_BYTES_PER_SAVED_DRAW = 4096, hasKeys = (value) => Object.keys(value).length > 0, worldOf = (node) => new THREE37.Matrix4().fromArray(node.getWorldMatrix()), nodeUsers = (mesh) => mesh.listParents().filter((parent) => parent.propertyType === PropertyType3.NODE).length, accessorsOf = (prim) => {
+ const indices = prim.getIndices();
+ return indices ? [...prim.listAttributes(), indices] : prim.listAttributes();
+}, primitiveBytes = (primitives) => [...new Set(primitives.flatMap(accessorsOf))].reduce((sum, a) => sum + (a.getArray()?.byteLength ?? 0), 0), countPrimitives = (nodes) => [...nodes].reduce((sum, node) => sum + (node.getMesh()?.listPrimitives().length ?? 0), 0);
+var init_rigid_merge = __esm(() => {
+ init_semantic();
+ init_gltf_io();
+ JOINT_PIVOT = /^joint[_-]/i;
+ RESTART_MODES = new Set([2, 3, 5, 6]);
+ BAKED = /^(POSITION|NORMAL|TANGENT)$/;
+});
+
// src/geometry-catalog.ts
var REMOVED_AUTHORING_HELPERS, geometryPrimitives;
var init_geometry_catalog = __esm(() => {
@@ -24343,7 +24849,7 @@ var init_kit = __esm(() => {
// src/texture-bake.ts
import { createHash as createHash11 } from "node:crypto";
-import * as THREE37 from "three";
+import * as THREE38 from "three";
function readPixels(texture) {
const image = texture.image;
if (!image)
@@ -24435,7 +24941,7 @@ async function bakeSceneTextures(root, warnings) {
mime: "image/png",
bytes
};
- const colorSpace = entry.texture.colorSpace === THREE37.SRGBColorSpace ? "srgb" : "linear";
+ const colorSpace = entry.texture.colorSpace === THREE38.SRGBColorSpace ? "srgb" : "linear";
const recipe = entry.texture.userData["kilnProcedural"];
const primaryUsage = recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");
entry.texture.userData["kilnTexture"] = {
@@ -24516,10 +25022,10 @@ function computeTangentBasis(geometry) {
}
}
const out = new Float32Array(vertexCount * 4);
- const n = new THREE37.Vector3;
- const t = new THREE37.Vector3;
- const tmp = new THREE37.Vector3;
- const tmp2 = new THREE37.Vector3;
+ const n = new THREE38.Vector3;
+ const t = new THREE38.Vector3;
+ const tmp = new THREE38.Vector3;
+ const tmp2 = new THREE38.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]);
@@ -24539,7 +25045,7 @@ function computeTangentBasis(geometry) {
out[v * 4 + 2] = tmp.z;
out[v * 4 + 3] = w;
}
- geometry.setAttribute("tangent", new THREE37.BufferAttribute(out, 4));
+ geometry.setAttribute("tangent", new THREE38.BufferAttribute(out, 4));
}
function ensureNormalMapTangents(root, warnings) {
let count = 0;
@@ -24650,7 +25156,7 @@ var init_exporter_node = __esm(() => {
});
// src/views/character.ts
-import * as THREE38 from "three";
+import * as THREE39 from "three";
function rounded(value) {
const result = Math.round(value * 1e9) / 1e9;
return Object.is(result, -0) ? 0 : result;
@@ -24692,9 +25198,9 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {
const invalidPaths = new Set(invalidFindingNodePaths);
const joints = evidence.map((joint) => {
const relative = rootInverse.clone().multiply(joint.node.matrixWorld);
- const position = new THREE38.Vector3().setFromMatrixPosition(relative);
- const forward = new THREE38.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
- const bend = new THREE38.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const position = new THREE39.Vector3().setFromMatrixPosition(relative);
+ const forward = new THREE39.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const bend = new THREE39.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
const chainId = chainIdFor(joint.descriptor, descriptorByRole);
return {
role: joint.descriptor.role,
@@ -26356,7 +26862,7 @@ var init_raster = __esm(() => {
});
// src/views/camera.ts
-import { Vector3 as Vector330, Matrix4 as Matrix412, Euler as Euler4, Group as Group3 } from "three";
+import { Vector3 as Vector331, Matrix4 as Matrix413, Euler as Euler4, Group as Group3 } from "three";
function strict(value, keys, label) {
for (const key of Object.keys(value))
if (!keys.includes(key)) {
@@ -26450,14 +26956,14 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {
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 Vector330(0, 0, -1) : new Vector330(0, 1, 0);
+ const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector331(0, 0, -1) : new Vector331(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 extent = 0.000001;
for (let i = 0;i < 8; i++) {
- const p = new Vector330((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);
+ const p = new Vector331((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);
extent = Math.max(extent, Math.abs(p.dot(x)), Math.abs(p.dot(y)));
}
const depthMin = bounds.min.map((v, i) => Math.min(v, sceneBounds.min[i]));
@@ -26538,7 +27044,7 @@ function resolveAssetCamera(root, shot = {}) {
if (relative !== "world") {
const node = relative === "part" ? selected.node : rootNode;
dir.transformDirection(node.matrixWorld);
- up = tuple5(new Vector330(0, 1, 0).transformDirection(node.matrixWorld));
+ up = tuple5(new Vector331(0, 1, 0).transformDirection(node.matrixWorld));
}
camera = cameraFromBounds(bounds, tuple5(dir), request.padding ?? 1.2, up, measureBounds(root));
} else if (request.type === "explicit") {
@@ -26573,7 +27079,7 @@ function resolveAssetCamera(root, shot = {}) {
throw new Error("padding requires bounds framing");
if (request.framing === "bounds" && request.halfHeight !== undefined)
throw new Error("bounds framing derives halfHeight");
- let matrix = new Matrix412;
+ let matrix = new Matrix413;
if (relative === "asset" || relative === "part")
matrix = (relative === "asset" ? rootNode : selected.node).matrixWorld;
if (request.frame) {
@@ -26585,7 +27091,7 @@ function resolveAssetCamera(root, shot = {}) {
const position = vec(triple(request.position, "position")).applyMatrix4(matrix);
const target = request.target ? vec(triple(request.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);
const up = vec(triple(request.up ?? [0, 1, 0], "up")).transformDirection(matrix);
- const offset = vec(triple(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector330().setFromMatrixPosition(matrix));
+ const offset = vec(triple(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector331().setFromMatrixPosition(matrix));
const radius = vec(bounds.max).sub(vec(bounds.min)).length();
camera = {
version: "kiln.camera.v1",
@@ -26713,11 +27219,11 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)
}
return result;
};
- const key = new Vector330(1.5, 2, 1).normalize();
+ const key = new Vector331(1.5, 2, 1).normalize();
const srgb = (n) => n <= 0.0031308 ? n * 12.92 : 1.055 * n ** (1 / 2.4) - 0.055;
const ordered = compositingOrder(collectTriangles(root).tris, (px, py, pz) => camera.projection === "perspective" ? Math.hypot(px - position.x, py - position.y, pz - position.z) : (position.x - px) * z.x + (position.y - py) * z.y + (position.z - pz) * z.z);
for (const tri of ordered) {
- const world = [0, 1, 2].map((i) => new Vector330(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));
+ const world = [0, 1, 2].map((i) => new Vector331(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;
@@ -26727,7 +27233,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)
const color = tri.color.map((c) => Math.round(srgb(c * light) * 255));
let polygon = world.map((p) => {
const d = p.clone().sub(position);
- return new Vector330(d.dot(x), d.dot(y), -d.dot(z));
+ return new Vector331(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++) {
@@ -26760,7 +27266,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)
}
return out;
}
-var vec = (a) => new Vector330(...a), tuple5 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;
+var vec = (a) => new Vector331(...a), tuple5 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;
var init_camera = __esm(() => {
init_raster();
init_background();
@@ -27509,13 +28015,13 @@ var init_architecture3 = __esm(() => {
// src/views/glb.ts
import {
- Primitive
+ Primitive as Primitive2
} from "@gltf-transform/core";
import {
BufferAttribute as BufferAttribute8,
BufferGeometry as BufferGeometry15,
Group as Group4,
- Matrix4 as Matrix413,
+ Matrix4 as Matrix414,
Mesh as Mesh12,
MeshStandardMaterial as MeshStandardMaterial5,
NoColorSpace as NoColorSpace4,
@@ -27525,7 +28031,7 @@ import {
QuaternionKeyframeTrack as QuaternionKeyframeTrack2,
VectorKeyframeTrack as VectorKeyframeTrack2,
Quaternion as Quaternion17,
- Vector3 as Vector331,
+ Vector3 as Vector332,
InterpolateDiscrete as InterpolateDiscrete2,
InterpolateLinear as InterpolateLinear2
} from "three";
@@ -27590,16 +28096,16 @@ 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:
+ case Primitive2.Mode.TRIANGLES:
return Uint32Array.from(source);
- case Primitive.Mode.TRIANGLE_STRIP: {
+ case Primitive2.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: {
+ case Primitive2.Mode.TRIANGLE_FAN: {
const triangles = [];
for (let index = 1;index + 1 < source.length; index++) {
triangles.push(source[index], source[index + 1], source[0]);
@@ -27677,7 +28183,7 @@ function noteMaterialTextures(material, reasons) {
}
}
function instanceMatrices(node) {
- const world = new Matrix413().fromArray(node.getWorldMatrix());
+ const world = new Matrix414().fromArray(node.getWorldMatrix());
const extension = node.getExtension("EXT_mesh_gpu_instancing");
if (!extension)
return { matrices: [world], count: 1 };
@@ -27700,7 +28206,7 @@ function instanceMatrices(node) {
translations?.getElement(index, translation);
rotations?.getElement(index, rotation);
scales?.getElement(index, scale);
- const local = new Matrix413().compose(new Vector331(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion17(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector331(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));
+ const local = new Matrix414().compose(new Vector332(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion17(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector332(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));
matrices.push(world.clone().multiply(local));
}
return { matrices, count };
@@ -27788,7 +28294,7 @@ async function loadGlbGeometryFlatScene(bytes) {
function localInstanceMatrices(node) {
const extension = node.getExtension("EXT_mesh_gpu_instancing");
if (!extension)
- return [new Matrix413];
+ return [new Matrix414];
const attributes = extension.listAttributes();
if (attributes.length === 0) {
throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", "Invalid empty instancing data.");
@@ -27807,7 +28313,7 @@ function localInstanceMatrices(node) {
translations?.getElement(index, translation);
rotations?.getElement(index, rotation);
scales?.getElement(index, scale);
- return new Matrix413().compose(new Vector331(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion17(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector331(...scales ? scale.slice(0, 3) : [1, 1, 1]));
+ return new Matrix414().compose(new Vector332(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion17(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector332(...scales ? scale.slice(0, 3) : [1, 1, 1]));
});
}
async function loadGlbReviewScene(bytes) {
@@ -28263,7 +28769,7 @@ var init_renderer_id = __esm(() => {
});
// src/views/scene-raster.ts
-import * as THREE39 from "three";
+import * as THREE40 from "three";
var DEG2;
var init_scene_raster = __esm(() => {
init_evaluator();
@@ -28274,18 +28780,18 @@ var init_scene_raster = __esm(() => {
});
// src/views/vehicle.ts
-import * as THREE40 from "three";
+import * as THREE41 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 THREE40.Box3;
+ const bounds = new THREE41.Box3;
let found = false;
root.traverse((node) => {
if (!hasRole2(node, "chassis"))
return;
node.traverse((part) => {
- if (!(part instanceof THREE40.Mesh) || !(part.geometry instanceof THREE40.BufferGeometry))
+ if (!(part instanceof THREE41.Mesh) || !(part.geometry instanceof THREE41.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const box = part.geometry.boundingBox;
@@ -28295,7 +28801,7 @@ function chassisBounds(root, inverse) {
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 THREE40.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE41.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -28363,33 +28869,33 @@ function tagDiagnostic(node, role) {
stampSemanticMetadataV1(node, { roles: [role] });
}
function rod(name, start, end, radius, color, role) {
- const from = new THREE40.Vector3(...start);
- const to = new THREE40.Vector3(...end);
+ const from = new THREE41.Vector3(...start);
+ const to = new THREE41.Vector3(...end);
const direction = to.clone().sub(from);
const length = direction.length();
- const geometry = length > 0.000000001 ? new THREE40.CylinderGeometry(radius, radius, length, 8) : new THREE40.SphereGeometry(radius, 8, 6);
- const result = new THREE40.Mesh(geometry, new THREE40.MeshBasicMaterial({ color }));
+ const geometry = length > 0.000000001 ? new THREE41.CylinderGeometry(radius, radius, length, 8) : new THREE41.SphereGeometry(radius, 8, 6);
+ const result = new THREE41.Mesh(geometry, new THREE41.MeshBasicMaterial({ color }));
result.name = name;
result.position.copy(from).add(to).multiplyScalar(0.5);
if (length > 0.000000001) {
- result.quaternion.setFromUnitVectors(new THREE40.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
+ result.quaternion.setFromUnitVectors(new THREE41.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
}
tagDiagnostic(result, role);
return result;
}
function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {
- const overlay = new THREE40.Group;
+ const overlay = new THREE41.Group;
overlay.name = "VehicleDiagnosticOverlay";
const chassisSpan = descriptor.chassisBox ? Math.max(descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0], descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1], descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2]) : 1;
const thickness = Math.max(0.01, chassisSpan * 0.008);
- const arrow = new THREE40.Group;
+ const arrow = new THREE41.Group;
arrow.name = "Diagnostic_Forward_+X";
tagDiagnostic(arrow, "diagnostic.vehicle.forward");
arrow.add(rod("Diagnostic_Forward_Shaft", descriptor.forwardArrow.start, [descriptor.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));
- const arrowHead = new THREE40.Mesh(new THREE40.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE40.MeshBasicMaterial({ color: 16724804 }));
+ const arrowHead = new THREE41.Mesh(new THREE41.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE41.MeshBasicMaterial({ color: 16724804 }));
arrowHead.name = "Diagnostic_Forward_Head";
arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);
- arrowHead.quaternion.setFromUnitVectors(new THREE40.Vector3(0, 1, 0), new THREE40.Vector3(1, 0, 0));
+ arrowHead.quaternion.setFromUnitVectors(new THREE41.Vector3(0, 1, 0), new THREE41.Vector3(1, 0, 0));
tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");
arrow.add(arrowHead);
overlay.add(arrow);
@@ -28397,18 +28903,18 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));
}
for (const wheel of descriptor.wheels) {
- const ring = new THREE40.Mesh(new THREE40.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE40.MeshBasicMaterial({ color: 16763955 }));
+ const ring = new THREE41.Mesh(new THREE41.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE41.MeshBasicMaterial({ color: 16763955 }));
ring.name = `Diagnostic_Wheel_${wheel.id}`;
ring.position.set(...wheel.center);
- const axle = new THREE40.Vector3(...wheel.axle);
+ const axle = new THREE41.Vector3(...wheel.axle);
if (axle.lengthSq() > 0.000000000001) {
- ring.quaternion.setFromUnitVectors(new THREE40.Vector3(0, 0, 1), axle.normalize());
+ ring.quaternion.setFromUnitVectors(new THREE41.Vector3(0, 0, 1), axle.normalize());
}
tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);
overlay.add(ring);
}
if (descriptor.chassisBox) {
- const chassis = new THREE40.Group;
+ const chassis = new THREE41.Group;
chassis.name = "Diagnostic_ChassisBox";
tagDiagnostic(chassis, "diagnostic.vehicle.chassis");
const { min, max } = descriptor.chassisBox;
@@ -28442,7 +28948,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(chassis);
}
if (descriptor.supportPlaneY !== undefined) {
- const plane = new THREE40.Group;
+ const plane = new THREE41.Group;
plane.name = "Diagnostic_SupportPlane";
tagDiagnostic(plane, "diagnostic.vehicle.support-plane");
const halfX = Math.max(1, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;
@@ -29040,7 +29546,7 @@ var init_views = __esm(() => {
});
// src/views/character-capture.ts
-import * as THREE41 from "three";
+import * as THREE42 from "three";
function drawLine2(rgb, width, height, from, to, color) {
let x0 = Math.round(from[0]);
let y0 = Math.round(from[1]);
@@ -29077,22 +29583,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {
}
function projector(root, cameraId, size) {
root.updateMatrixWorld(true);
- const bounds = new THREE41.Box3().setFromObject(root);
+ const bounds = new THREE42.Box3().setFromObject(root);
if (bounds.isEmpty())
- bounds.set(new THREE41.Vector3(-0.5, 0, -0.5), new THREE41.Vector3(0.5, 1, 0.5));
- const center = bounds.getCenter(new THREE41.Vector3);
- const camera = cameraId === "front" ? new THREE41.Vector3(1, 0, 0) : new THREE41.Vector3(0, 0, 1);
- const upHint = new THREE41.Vector3(0, 1, 0);
- const xAxis = new THREE41.Vector3().crossVectors(upHint, camera).normalize();
- const yAxis = new THREE41.Vector3().crossVectors(camera, xAxis).normalize();
+ bounds.set(new THREE42.Vector3(-0.5, 0, -0.5), new THREE42.Vector3(0.5, 1, 0.5));
+ const center = bounds.getCenter(new THREE42.Vector3);
+ const camera = cameraId === "front" ? new THREE42.Vector3(1, 0, 0) : new THREE42.Vector3(0, 0, 1);
+ const upHint = new THREE42.Vector3(0, 1, 0);
+ const xAxis = new THREE42.Vector3().crossVectors(upHint, camera).normalize();
+ const yAxis = new THREE42.Vector3().crossVectors(camera, xAxis).normalize();
let extent = 0.000001;
for (let corner = 0;corner < 8; corner++) {
- const point = new THREE41.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);
+ const point = new THREE42.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);
extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));
}
const scale = size * 0.45 / extent;
return (assetPoint) => {
- const world = new THREE41.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
+ const world = new THREE42.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];
};
}
@@ -29218,19 +29724,10 @@ var init_character_capture = __esm(() => {
});
// src/render.ts
-import * as THREE42 from "three";
-import { Document } from "@gltf-transform/core";
+import * as THREE43 from "three";
+import { Document, Logger } from "@gltf-transform/core";
import { KHRMaterialsEmissiveStrength } from "@gltf-transform/extensions";
-import {
- dedup,
- instance,
- palette,
- flatten,
- join as join9,
- weld,
- prune,
- mergeDocuments
-} from "@gltf-transform/functions";
+import { dedup, instance, palette, weld, prune, mergeDocuments } from "@gltf-transform/functions";
function hiddenTriangles(root, lowerLevels) {
let hidden = 0;
const visit = (node) => {
@@ -29391,7 +29888,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras) {
} else if (stdMat.transparent) {
mat.setAlphaMode("BLEND");
}
- if (stdMat.side === THREE42.DoubleSide) {
+ if (stdMat.side === THREE43.DoubleSide) {
mat.setDoubleSided(true);
}
if (stdMat.map) {
@@ -29458,7 +29955,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras) {
} else if (common.transparent || (common.opacity ?? 1) < 1) {
mat.setAlphaMode("BLEND");
}
- if (threeMat.side === THREE42.DoubleSide)
+ if (threeMat.side === THREE43.DoubleSide)
mat.setDoubleSided(true);
if (common.map && !mat.getBaseColorTexture()) {
const texture = bridgeTexture(doc, common.map, textureCache);
@@ -29593,7 +30090,7 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache,
const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;
let gtMesh = meshCache.get(cacheKey);
if (!gtMesh) {
- const geometry = new THREE42.PlaneGeometry(1, 1);
+ const geometry = new THREE43.PlaneGeometry(1, 1);
if (centerX !== 0.5 || centerY !== 0.5) {
geometry.translate(0.5 - centerX, 0.5 - centerY, 0);
}
@@ -29617,9 +30114,9 @@ function animationInterpolation(track) {
if (isCubicSplineTrack(track))
return "CUBICSPLINE";
const mode = track.getInterpolation();
- if (mode === THREE42.InterpolateDiscrete)
+ if (mode === THREE43.InterpolateDiscrete)
return "STEP";
- if (mode === THREE42.InterpolateLinear)
+ if (mode === THREE43.InterpolateLinear)
return "LINEAR";
throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);
}
@@ -29783,27 +30280,41 @@ async function applyGpuInstancing(doc, mode, role) {
const after = collectGlbMetrics(doc);
return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };
}
-async function consolidateMaterials(doc, mode) {
+async function consolidateMaterials(doc, mode, keep = []) {
+ doc.setLogger(new Logger(Logger.Verbosity.WARN));
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 || hasNodeLevelsOfDetail(doc) || hasPreservedNodeState(doc)) ? "palette" : mode;
const steps = root.listMaterials().some((material) => Object.keys(material.getExtras()).length > 0) ? [] : [palette({ min: PALETTE_MIN })];
- if (effective === "full") {
- steps.push(flatten(), join9({ keepNamed: true }));
- }
+ let merge;
+ if (mode === "full")
+ steps.push(rigidMerge({ keep }, (summary) => {
+ merge = summary;
+ }));
steps.push(weld(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));
await doc.transform(...steps);
const after = collectGlbMetrics(doc);
return {
- mode: effective,
+ mode,
materialsBefore: before.uniqueMaterials,
materialsAfter: after.uniqueMaterials,
drawsBefore: before.drawCalls,
- drawsAfter: after.drawCalls
+ drawsAfter: after.drawCalls,
+ ...merge ? { rigidMerge: merge } : {}
};
}
+function optimizeWarnings(summary) {
+ const merge = summary.rigidMerge;
+ if (!merge)
+ return [];
+ const warnings = [];
+ if (merge.skipped)
+ warnings.push(`Rigid merge skipped: ${merge.skipped}; geometry left separate.`);
+ if (merge.rejected.length)
+ warnings.push(`Rigid merge retained ${merge.rejected.length} rejected buckets; first: ${merge.rejected[0].error}`);
+ if (merge.unmatchedKeep.length)
+ warnings.push(`Rigid merge did not find ${merge.unmatchedKeep.length} requested boundary names.`);
+ return warnings;
+}
async function renderSceneToGLB(root, opts = {}) {
assertNoLegacyRuntimePolicy(opts);
const requirements = resolveRequirementsContext(opts.requirements);
@@ -29899,6 +30410,7 @@ async function renderSceneToGLB(root, opts = {}) {
if (effectiveOptimize !== "off") {
try {
optimize = await consolidateMaterials(doc, effectiveOptimize);
+ warnings.push(...optimizeWarnings(optimize));
} catch (err) {
warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);
}
@@ -30002,6 +30514,7 @@ async function renderGLBInProcess(code, opts = {}) {
gltfExporter: resolveGltfExporter(opts.gltfExporter),
geometryPolicy: opts.geometryPolicy ?? "warn",
optimize: resolveOptimize(opts.optimize),
+ ...resolveOptimize(opts.optimize) === "full" ? { optimizationPipeline: FULL_OPTIMIZATION_PIPELINE } : {},
instance: resolveInstance(opts.instance)
};
let materialLibraryDependencies;
@@ -30127,8 +30640,8 @@ function collectMeshStats(root) {
if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {
return;
}
- const center = new THREE42.Vector3;
- const size = new THREE42.Vector3;
+ const center = new THREE43.Vector3;
+ const size = new THREE43.Vector3;
box.getCenter(center);
box.getSize(size);
out.push({
@@ -30143,7 +30656,7 @@ function collectMeshStats(root) {
return out;
}
function minimalGapVector(a, b) {
- const v = new THREE42.Vector3;
+ const v = new THREE43.Vector3;
for (const axis of ["x", "y", "z"]) {
if (a.min[axis] > b.max[axis])
v[axis] = b.max[axis] - a.min[axis];
@@ -30161,10 +30674,10 @@ function inspectSceneStructure(root, opts = {}) {
return warnings;
const cat = opts.category?.toLowerCase();
if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {
- const all = new THREE42.Box3;
+ const all = new THREE43.Box3;
for (const m of meshes)
all.union(m.box);
- const size = new THREE42.Vector3;
+ const size = new THREE43.Vector3;
all.getSize(size);
if (cat === "aircraft") {
if (size.y > size.x * 1.2) {
@@ -30257,6 +30770,8 @@ var init_render = __esm(() => {
init_material_recipe_runtime();
init_material_resources();
init_texture_resolver();
+ init_rebuild_options();
+ init_rigid_merge();
init_validation();
init_kit();
init_texture_bake();
@@ -31300,12 +31815,12 @@ var exports_part_placement = {};
__export(exports_part_placement, {
createPartPlacementReader: () => createPartPlacementReader
});
-import * as THREE43 from "three";
+import * as THREE44 from "three";
function createPartPlacementReader(root) {
const bounds = createPartBoundsReader(root);
- const position = new THREE43.Vector3;
- const quaternion = new THREE43.Quaternion;
- const scale = new THREE43.Vector3;
+ const position = new THREE44.Vector3;
+ const quaternion = new THREE44.Quaternion;
+ const scale = new THREE44.Vector3;
return (node) => {
node.matrixWorld.decompose(position, quaternion, scale);
const box = bounds(node);
@@ -31456,13 +31971,13 @@ var init_inspect = __esm(() => {
});
// src/views/measurement.ts
-import { Box3 as Box322, Vector3 as Vector336 } from "three";
+import { Box3 as Box323, Vector3 as Vector337 } from "three";
function describeSubjectFrame(root, subject) {
const selected = selectCameraSubject(root, subject);
selected.node.updateWorldMatrix(true, true);
const matrix = selected.node.matrixWorld;
- const bounds = new Box322().setFromObject(selected.node);
- const local = new Box322;
+ const bounds = new Box323().setFromObject(selected.node);
+ const local = new Box323;
const invertible = matrix.determinant() !== 0;
const inverse = matrix.clone().invert();
selected.node.traverse((node) => {
@@ -31473,10 +31988,10 @@ function describeSubjectFrame(root, subject) {
if (!attr)
return;
for (let i = 0;i < attr.count; i++)
- local.expandByPoint(new Vector336().fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse));
+ local.expandByPoint(new Vector337().fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse));
});
const box = (b) => b.isEmpty() ? null : { min: b.min.toArray(), max: b.max.toArray() };
- const axis = (i) => new Vector336().setFromMatrixColumn(matrix, i).normalize().toArray();
+ const axis = (i) => new Vector337().setFromMatrixColumn(matrix, i).normalize().toArray();
return {
path: selected.path,
name: selected.name,
@@ -31486,7 +32001,7 @@ function describeSubjectFrame(root, subject) {
invertible,
worldMatrix: matrix.toArray(),
axes: { frame: "world", x: axis(0), y: axis(1), z: axis(2) },
- origin: new Vector336().setFromMatrixPosition(matrix).toArray()
+ origin: new Vector337().setFromMatrixPosition(matrix).toArray()
};
}
function measureAttachment(root, input) {
@@ -31499,7 +32014,7 @@ function measureAttachment(root, input) {
return {
path: selected.path,
local: [...local],
- world: new Vector336(...local).applyMatrix4(selected.node.matrixWorld).toArray()
+ world: new Vector337(...local).applyMatrix4(selected.node.matrixWorld).toArray()
};
};
const from = endpoint(input.from), to = endpoint(input.to);
@@ -31509,7 +32024,7 @@ function measureAttachment(root, input) {
method: "straight-line anchor distance",
from,
to,
- distance: new Vector336(...from.world).distanceTo(new Vector336(...to.world))
+ distance: new Vector337(...from.world).distanceTo(new Vector337(...to.world))
};
}
var init_measurement = __esm(() => {
@@ -31518,10 +32033,10 @@ var init_measurement = __esm(() => {
// src/revision-comparison.ts
import {
- PropertyType as PropertyType3
+ PropertyType as PropertyType4
} from "@gltf-transform/core";
import { ALL_EXTENSIONS as ALL_EXTENSIONS2 } from "@gltf-transform/extensions";
-import { Box3 as Box323, Matrix4 as Matrix414, Vector3 as Vector337 } from "three";
+import { Box3 as Box324, Matrix4 as Matrix415, Vector3 as Vector338 } from "three";
async function accessorFingerprint(accessor) {
const array = accessor?.getArray();
if (!accessor || !array)
@@ -31534,13 +32049,13 @@ async function accessorFingerprint(accessor) {
];
}
function lowerLevels(node) {
- return (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType3.NODE);
+ return (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType4.NODE);
}
function bounds(box) {
return box.isEmpty() ? null : {
min: box.min.toArray(),
max: box.max.toArray(),
- size: box.getSize(new Vector337).toArray()
+ size: box.getSize(new Vector338).toArray()
};
}
async function digest8(bytes) {
@@ -31574,7 +32089,7 @@ async function snapshot3(bytes) {
if (depth > 128)
throw new Error("Revision comparison hierarchy exceeds 128 levels.");
const names = new Set;
- const combined = new Box323;
+ const combined = new Box324;
const placed = siblings.flatMap((node) => [
{ node, drawn: true },
...lowerLevels(node).map((level) => ({ node: level, drawn: false }))
@@ -31591,8 +32106,8 @@ async function snapshot3(bytes) {
if (node.listExtensions().some((extension) => extension.extensionName !== MSFT_LOD && extension.extensionName !== "KHR_node_visibility") || mesh?.listExtensions().length)
throw new Error("Revision comparison does not support node/mesh extensions (including instancing).");
const primitives = mesh?.listPrimitives() ?? [];
- const own = new Box323;
- const matrix = parentWorld.clone().multiply(new Matrix414().fromArray(node.getMatrix()));
+ const own = new Box324;
+ const matrix = parentWorld.clone().multiply(new Matrix415().fromArray(node.getMatrix()));
if (matrix.elements.some((value) => !Number.isFinite(value)))
throw new Error("Revision comparison requires finite transforms.");
for (const primitive of primitives) {
@@ -31604,7 +32119,7 @@ async function snapshot3(bytes) {
const indices = primitive.getIndices();
const count = indices?.getCount() ?? position.getCount();
vertices += count;
- if (vertices > MAX_VERTICES)
+ if (vertices > MAX_VERTICES2)
throw new Error("Revision comparison exceeds 2,000,000 placed vertices.");
const element = [0, 0, 0];
for (let index = 0;index < count; index++) {
@@ -31612,7 +32127,7 @@ async function snapshot3(bytes) {
if (!Number.isInteger(vertex) || vertex < 0 || vertex >= position.getCount())
throw new Error("Revision comparison found an invalid vertex index.");
position.getElement(vertex, element);
- const point = new Vector337(...element).applyMatrix4(matrix);
+ const point = new Vector338(...element).applyMatrix4(matrix);
if (point.toArray().some((value) => !Number.isFinite(value)))
throw new Error("Revision comparison requires finite positions.");
own.expandByPoint(point);
@@ -31631,7 +32146,7 @@ async function snapshot3(bytes) {
if (scenes[0].listExtensions().length)
throw new Error("Revision comparison does not support scene extensions.");
const scenePath = `/${encodeURIComponent(scenes[0].getName() || "Scene")}[0]`;
- const box = visit(scenes[0].listChildren(), "", 0, new Matrix414);
+ const box = visit(scenes[0].listChildren(), "", 0, new Matrix415);
const nodePaths = new Map([...parts].map(([path, part]) => [part.node, path]));
const animation = new Map;
const clipNames = new Set;
@@ -31791,7 +32306,7 @@ async function compareRevisionGlbs(before, after, page = {}) {
nextOffset: offset + limit < changes.length ? offset + limit : null
};
}
-var MAX_GLB_BYTES, MAX_NODES = 1e4, MAX_VERTICES = 2000000, ACCESSOR_IGNORED, MATERIAL_IGNORED;
+var MAX_GLB_BYTES, MAX_NODES = 1e4, MAX_VERTICES2 = 2000000, ACCESSOR_IGNORED, MATERIAL_IGNORED;
var init_revision_comparison = __esm(() => {
init_gltf_io();
init_metrics();
@@ -31802,20 +32317,20 @@ var init_revision_comparison = __esm(() => {
// src/views/surface-distance.ts
import {
- Box3 as Box324,
- Matrix4 as Matrix415,
+ Box3 as Box325,
+ Matrix4 as Matrix416,
Ray,
Triangle as Triangle2,
- Vector3 as Vector338
+ Vector3 as Vector339
} from "three";
function hierarchy(triangles) {
- const box = new Box324;
+ const box = new Box325;
for (const triangle of triangles)
box.union(triangle.box);
const count = triangles.length;
if (count <= 4)
return { box, count, triangles };
- const size = box.getSize(new Vector338);
+ const size = box.getSize(new Vector339);
const axis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";
const center = (triangle) => triangle.box.min[axis] / 2 + triangle.box.max[axis] / 2;
triangles.sort((a, b) => center(a) - center(b));
@@ -31834,7 +32349,7 @@ function boxDistanceSquared(a, b) {
}
function collect(node, paths) {
const triangles = [];
- const bounds = new Box324;
+ const bounds = new Box325;
node.updateWorldMatrix(true, true);
node.traverseVisible((child) => {
const mesh = child;
@@ -31858,7 +32373,7 @@ function collect(node, paths) {
for (let instance = 0;instance < instances; instance++) {
const matrix = mesh.matrixWorld.clone();
if (instanced.isInstancedMesh) {
- const local = new Matrix415;
+ const local = new Matrix416;
instanced.getMatrixAt(instance, local);
matrix.multiply(local);
}
@@ -31867,13 +32382,13 @@ function collect(node, paths) {
const id = index ? index.getX(i + offset) : i + offset;
if (!Number.isSafeInteger(id) || id < 0 || id >= position.count)
throw new Error("Surface distance encountered an invalid triangle index.");
- const point = new Vector338().fromBufferAttribute(position, id).applyMatrix4(matrix);
+ const point = new Vector339().fromBufferAttribute(position, id).applyMatrix4(matrix);
if (![point.x, point.y, point.z].every(Number.isFinite))
throw new Error("Surface distance encountered a non-finite world position.");
return point;
};
const triangle = new Triangle2(vertex(0), vertex(1), vertex(2));
- const box = new Box324().setFromPoints([triangle.a, triangle.b, triangle.c]);
+ const box = new Box325().setFromPoints([triangle.a, triangle.b, triangle.c]);
bounds.union(box);
triangles.push({
triangle,
@@ -31926,10 +32441,10 @@ function trianglePair(a, b) {
const av = [a.a, a.b, a.c], bv = [b.a, b.b, b.c];
if (b.getArea() > 0)
for (const p of av)
- record(p, b.closestPointToPoint(p, new Vector338));
+ record(p, b.closestPointToPoint(p, new Vector339));
if (a.getArea() > 0)
for (const q of bv)
- record(a.closestPointToPoint(q, new Vector338), q);
+ record(a.closestPointToPoint(q, new Vector339), q);
for (let i = 0;i < 3; i++) {
const p = av[i], q = av[(i + 1) % 3];
for (let j = 0;j < 3; j++)
@@ -31942,9 +32457,9 @@ function trianglePair(a, b) {
const length = delta.length();
if (length === 0)
continue;
- const hit = new Ray(origin, delta.divideScalar(length)).intersectTriangle(target.a, target.b, target.c, false, new Vector338);
+ const hit = new Ray(origin, delta.divideScalar(length)).intersectTriangle(target.a, target.b, target.c, false, new Vector339);
if (hit && origin.distanceTo(hit) <= length) {
- const onFace = target.closestPointToPoint(hit, new Vector338);
+ const onFace = target.closestPointToPoint(hit, new Vector339);
if (vertices === av)
record(hit, onFace);
else
@@ -32103,6 +32618,221 @@ var init_surface_distance = __esm(() => {
init_camera();
});
+// src/draw-diagnostics.ts
+var exports_draw_diagnostics = {};
+__export(exports_draw_diagnostics, {
+ inspectDrawDiagnostics: () => inspectDrawDiagnostics
+});
+import { Primitive as Primitive3 } from "@gltf-transform/core";
+import { cloneDocument } from "@gltf-transform/functions";
+import * as THREE45 from "three";
+function withinLimits(doc) {
+ const root = doc.getRoot();
+ if (root.listNodes().length > MAX_NODES2 || root.listAccessors().length > 4096 || root.listMaterials().length > 2048 || root.listTextures().length > 256 || root.listScenes().length > 32 || doc.getGraph().listEdges().length > 32768)
+ return false;
+ let bytes = root.listAccessors().reduce((n, a) => n + (a.getArray()?.byteLength ?? 0), 0) + root.listTextures().reduce((n, t) => n + (t.getImage()?.byteLength ?? 0), 0);
+ let uses = 0;
+ let vertices = 0;
+ const walk = (node, depth) => {
+ if (depth > 128)
+ return false;
+ for (const p of node.getMesh()?.listPrimitives() ?? []) {
+ uses++;
+ vertices += p.getAttribute("POSITION")?.getCount() ?? 0;
+ bytes += p.listAttributes().reduce((n, a) => n + (a.getArray()?.byteLength ?? 0), 0) + (p.getIndices()?.getArray()?.byteLength ?? 0);
+ }
+ return uses <= MAX_USES && vertices <= MAX_VERTICES3 && bytes <= MAX_BYTES && node.listChildren().every((n) => walk(n, depth + 1));
+ };
+ return bytes <= MAX_BYTES && root.listScenes().every((s) => s.listChildren().every((n) => walk(n, 0)));
+}
+function collect2(doc, keep) {
+ const root = doc.getRoot();
+ const boundaries = findRigidBoundaries(doc, new Set(keep));
+ const nodeIds = new Map(root.listNodes().map((n, i) => [n, i]));
+ const anchors = new Map;
+ const uses = [];
+ for (const [sceneIndex, scene] of root.listScenes().entries()) {
+ const id = `scene:${sceneIndex}`;
+ const initial = { id, name: nameOf(scene.getName() || "Scene"), draws: 0, afterRigidMerge: 0 };
+ anchors.set(id, initial);
+ const walk = (node, anchor) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const part = { id: `${id}/node:${nodeIds.get(node)}`, name: nameOf(node.getName()) };
+ if (boundaries.has(node)) {
+ anchor = { ...part, draws: 0, afterRigidMerge: 0 };
+ anchors.set(part.id, anchor);
+ }
+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
+ anchor.draws++;
+ uses.push({ node, primitive, part });
+ }
+ for (const child of node.listChildren())
+ walk(child, anchor);
+ };
+ for (const child of scene.listChildren())
+ walk(child, initial);
+ }
+ return { anchors, uses };
+}
+function overlaps(a, b) {
+ if (Math.abs(a.normal.dot(b.normal)) < 1 - 0.00000001 || !a.bounds.intersectsBox(b.bounds))
+ return false;
+ const tolerance = Math.max(a.bounds.getSize(new THREE45.Vector3).length(), b.bounds.getSize(new THREE45.Vector3).length(), 0.000000000001) * 0.000001;
+ if (b.points.some((p) => Math.abs(a.normal.dot(p.clone().sub(a.points[0]))) > tolerance))
+ return false;
+ const normal = a.normal.toArray().map(Math.abs);
+ const drop = normal.indexOf(Math.max(...normal));
+ const project = (p) => p.toArray().filter((_, i) => i !== drop);
+ const clip = a.points.map(project);
+ if (cross22(clip[0], clip[1], clip[2]) < 0)
+ clip.reverse();
+ let polygon = b.points.map(project);
+ for (let i = 0;i < 3 && polygon.length; i++) {
+ const x = clip[i], y = clip[(i + 1) % 3];
+ const output = [];
+ for (let j = 0;j < polygon.length; j++) {
+ const p = polygon[j], q = polygon[(j + 1) % polygon.length];
+ const dp = cross22(x, y, p), dq = cross22(x, y, q);
+ if (dp >= 0)
+ output.push(p);
+ if (dp >= 0 !== dq >= 0) {
+ const t = dp / (dp - dq);
+ output.push([p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])]);
+ }
+ }
+ polygon = output;
+ }
+ let area = 0;
+ for (let i = 0;i < polygon.length; i++) {
+ const p = polygon[i], q = polygon[(i + 1) % polygon.length];
+ area += p[0] * q[1] - p[1] * q[0];
+ }
+ return Math.abs(area) / 2 > tolerance * tolerance;
+}
+function observe(uses) {
+ const mirrored = new Map;
+ const samples = [];
+ let eligibleTriangles = 0;
+ let unexaminedPrimitiveUses = 0;
+ for (const { node, primitive, part } of uses) {
+ if (node.getSkin() || node.getExtension("EXT_mesh_gpu_instancing") || primitive.listTargets().length) {
+ unexaminedPrimitiveUses++;
+ continue;
+ }
+ const matrix = new THREE45.Matrix4().fromArray(node.getWorldMatrix());
+ if (primitive.getAttribute("TANGENT") && matrix.determinant() < 0)
+ mirrored.set(part.id, part);
+ const position = primitive.getAttribute("POSITION");
+ if (!position || primitive.getMode() !== Primitive3.Mode.TRIANGLES) {
+ unexaminedPrimitiveUses++;
+ continue;
+ }
+ const indices = primitive.getIndices();
+ const count = Math.floor((indices?.getCount() ?? position.getCount()) / 3);
+ eligibleTriangles += count;
+ const amount = Math.min(count, 8, MAX_SAMPLES - samples.length);
+ for (let i = 0;i < amount; i++) {
+ const start = Math.floor(i * count / amount) * 3;
+ const points = [0, 1, 2].map((j) => new THREE45.Vector3().fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, [])).applyMatrix4(matrix));
+ const normal = points[1].clone().sub(points[0]).cross(points[2].clone().sub(points[0]));
+ if (!Number.isFinite(normal.lengthSq()) || normal.lengthSq() === 0)
+ continue;
+ samples.push({
+ points,
+ normal: normal.normalize(),
+ bounds: new THREE45.Box3().setFromPoints(points),
+ part
+ });
+ }
+ }
+ const pairs = new Map;
+ for (let i = 0;i < samples.length; i++)
+ for (let j = i + 1;j < samples.length; j++) {
+ const a = samples[i], b = samples[j];
+ if (a.part.id === b.part.id || a.part.id.split("/")[0] !== b.part.id.split("/")[0])
+ continue;
+ const key = [a.part.id, b.part.id].sort().join("|");
+ if (!pairs.has(key) && overlaps(a, b))
+ pairs.set(key, { parts: [a.part, b.part] });
+ }
+ return {
+ mirroredTangents: {
+ count: mirrored.size,
+ omitted: Math.max(0, mirrored.size - MAX_FINDINGS),
+ parts: [...mirrored.values()].slice(0, MAX_FINDINGS),
+ evidence: "Visible static nodes with tangent attributes and negative world determinant; not proof of a shading defect. Skinned, morphed and GPU-instanced uses are not assessed."
+ },
+ coplanarParts: {
+ sampledTriangles: samples.length,
+ eligibleTriangles,
+ unexaminedPrimitiveUses,
+ candidatePairs: pairs.size,
+ omitted: Math.max(0, pairs.size - MAX_FINDINGS),
+ candidates: [...pairs.values()].slice(0, MAX_FINDINGS),
+ evidence: "Sampled overlapping coplanar triangles in separate static nodes; not proof of visible z-fighting. At most 8 triangles per primitive and 256 total; unexamined faces may contain other candidates."
+ }
+ };
+}
+function analyzeDrawDiagnostics(doc, options = {}) {
+ try {
+ if (!withinLimits(doc))
+ return skipped("input-limit");
+ const keep = options.keep ?? [];
+ const before = collect2(doc, keep);
+ const copy = cloneDocument(doc);
+ const merge = mergeRigidGroups(copy, { keep });
+ const after = collect2(copy, keep);
+ const all = [...before.anchors.values()].map((anchor) => ({
+ ...anchor,
+ afterRigidMerge: after.anchors.get(anchor.id)?.draws ?? 0
+ }));
+ const currentDraws = before.uses.length;
+ return {
+ version: "kiln.draw-diagnostics.v1",
+ status: "assessed",
+ scope: SCOPE,
+ currentDraws,
+ mergeEstimate: {
+ method: METHOD,
+ draws: after.uses.length,
+ saved: currentDraws - after.uses.length,
+ rejectedBuckets: merge.rejected.length,
+ ...merge.skipped ? { skipped: merge.skipped } : {}
+ },
+ anchors: {
+ total: all.length,
+ omitted: Math.max(0, all.length - MAX_ANCHORS),
+ items: all.slice(0, MAX_ANCHORS)
+ },
+ observations: observe(before.uses)
+ };
+ } catch {
+ return skipped("analysis-failed");
+ }
+}
+async function inspectDrawDiagnostics(bytes, options = {}) {
+ if (bytes.byteLength > MAX_BYTES)
+ return skipped("input-limit");
+ try {
+ return analyzeDrawDiagnostics(await createGltfIO().readBinary(bytes), options);
+ } catch {
+ return skipped("unreadable-glb");
+ }
+}
+var MAX_NODES2 = 2048, MAX_USES = 256, MAX_VERTICES3 = 262144, MAX_BYTES, MAX_ANCHORS = 16, MAX_SAMPLES = 256, MAX_FINDINGS = 4, SCOPE = "Static single-pass primitive draws across document scenes, respecting node visibility. Excludes culling, alternate LOD selections, shadow, reflection and depth passes, and renderer-specific extra passes; GPU instances count once per primitive. IDs use scene/node indices; names are bounded labels.", METHOD = "Current rigid-merge policy on a bounded clone with existing materials: includes layouts, boundaries, locks, shared-byte budget and vertex splits. Excludes palette consolidation and instancing; not a full-mode or GPU performance prediction.", nameOf = (name) => name.length <= 80 ? name : `${name.slice(0, 79)}…`, skipped = (reason) => ({
+ version: "kiln.draw-diagnostics.v1",
+ status: "skipped",
+ scope: SCOPE,
+ reason
+}), cross22 = (a, b, p) => (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]);
+var init_draw_diagnostics = __esm(() => {
+ init_gltf_io();
+ init_metrics();
+ init_rigid_merge();
+ MAX_BYTES = 32 * 1024 * 1024;
+});
+
// src/widget-transfer.ts
import { deflateSync as deflateSync2, inflateSync as inflateSync2 } from "three/addons/libs/fflate.module.js";
function base64(bytes) {
@@ -32592,8 +33322,8 @@ function fingerprintSourceDir(dir) {
// render-service/src/build-identity.mjs
var RENDER_SERVICE_PROTOCOL = "kiln.render-service.v2";
var RENDER_SERVICE_DEPENDENCIES = Object.freeze({
- three: "0.186.0",
- webgpu: "0.6.1",
+ three: "0.186.1",
+ webgpu: "0.6.2",
pngjs: "7.0.0"
});
var REQUIRED_RENDER_CAPABILITIES = Object.freeze([
@@ -34103,7 +34833,7 @@ init_render();
// src/program-store-node.ts
import { link as link3, lstat as lstat4, mkdir as mkdir4, readFile as readFile4, readdir as readdir4, stat, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
import { randomUUID as randomUUID4 } from "node:crypto";
-import { join as join10 } from "node:path";
+import { join as join9 } from "node:path";
// src/program-store.ts
var MAX_PROGRAM_BYTES = 1024 * 1024;
@@ -34205,7 +34935,7 @@ class FileProgramStore {
if (!entry.isFile() || !/^[a-f0-9]{64}\.js$/.test(entry.name))
continue;
try {
- bytes += (await stat(join10(this.directory, entry.name))).size;
+ bytes += (await stat(join9(this.directory, entry.name))).size;
entries++;
} catch (error) {
if (error.code !== "ENOENT")
@@ -34223,7 +34953,7 @@ class FileProgramStore {
const canonical = ref.startsWith("p_") ? await this.readHandle(ref) : ref;
if (canonical === undefined)
throw this.notFound(ref);
- const path = join10(this.directory, `${canonical.slice(7)}.js`);
+ const path = join9(this.directory, `${canonical.slice(7)}.js`);
let code;
try {
if ((await stat(path)).size > MAX_PROGRAM_BYTES)
@@ -34242,7 +34972,7 @@ class FileProgramStore {
return programNotFound(ref, "This program store has no such reference; it was issued by another store (KILN_PROGRAM_STORE selects which) or its store was removed.");
}
async readHandle(handle) {
- const path = join10(this.directory, "refs", `${handle}.ref`);
+ const path = join9(this.directory, "refs", `${handle}.ref`);
try {
const info = await lstat4(path);
if (!info.isFile() || info.size !== 71)
@@ -34261,7 +34991,7 @@ class FileProgramStore {
await this.get(ref);
if (ref.startsWith("p_"))
return ref;
- const directory = join10(this.directory, "refs");
+ const directory = join9(this.directory, "refs");
await mkdir4(directory, { recursive: true });
for (const handle of shortProgramRefCandidates(ref)) {
const owner = await this.readHandle(handle);
@@ -34269,11 +34999,11 @@ class FileProgramStore {
return handle;
if (owner !== undefined)
continue;
- const temporary = join10(directory, `.write-${randomUUID4()}`);
+ const temporary = join9(directory, `.write-${randomUUID4()}`);
await writeFile4(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });
try {
try {
- await link3(temporary, join10(directory, `${handle}.ref`));
+ await link3(temporary, join9(directory, `${handle}.ref`));
return handle;
} catch (error) {
if (error.code !== "EEXIST")
@@ -34290,8 +35020,8 @@ class FileProgramStore {
async put(code) {
const ref = await programReference(code);
await mkdir4(this.directory, { recursive: true });
- const target = join10(this.directory, `${ref.slice(7)}.js`);
- const temporary = join10(this.directory, `.write-${randomUUID4()}`);
+ const target = join9(this.directory, `${ref.slice(7)}.js`);
+ const temporary = join9(this.directory, `.write-${randomUUID4()}`);
await writeFile4(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });
try {
try {
@@ -34522,7 +35252,7 @@ import {
utimes,
writeFile as writeFile5
} from "node:fs/promises";
-import { join as join11, resolve as resolve5 } from "node:path";
+import { join as join10, resolve as resolve5 } from "node:path";
var keyPattern = /^sha256:[a-f0-9]{64}$/;
var filePattern2 = /^[a-f0-9]{64}\.json$/;
var digest5 = (text) => createHash15("sha256").update(text).digest("hex");
@@ -34539,7 +35269,7 @@ class FileBuildCache {
path(key) {
if (!keyPattern.test(key))
throw new Error("Invalid build cache key.");
- return join11(this.directory, `${key.slice(7)}.json`);
+ return join10(this.directory, `${key.slice(7)}.json`);
}
async get(key) {
const path = this.path(key);
@@ -34567,7 +35297,7 @@ class FileBuildCache {
if (Buffer.byteLength(bytes) > Math.min(this.maxBytes, 96 * 1024 * 1024))
return;
await mkdir5(this.directory, { recursive: true });
- const temporary = join11(this.directory, `.write-${randomUUID5()}`);
+ const temporary = join10(this.directory, `.write-${randomUUID5()}`);
await writeFile5(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });
try {
await rename4(temporary, path);
@@ -34581,7 +35311,7 @@ class FileBuildCache {
for (const name of await readdir5(this.directory)) {
if (!filePattern2.test(name))
continue;
- const path = join11(this.directory, name);
+ const path = join10(this.directory, name);
try {
const item = await stat2(path);
entries.push({ path, size: item.size, used: item.mtimeMs });
@@ -34602,7 +35332,7 @@ class FileBuildCache {
import { createHash as createHash16 } from "node:crypto";
import { lstat as lstat5, readFile as readFile6, readdir as readdir6, realpath as realpath4, stat as stat3 } from "node:fs/promises";
import { createRequire as createRequire2 } from "node:module";
-import { dirname as dirname5, join as join12, relative as relative5 } from "node:path";
+import { dirname as dirname5, join as join11, relative as relative5 } from "node:path";
var digest6 = (bytes) => createHash16("sha256").update(bytes).digest("hex");
var compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
async function installedRuntimeIdentity(root, limits = {}) {
@@ -34611,7 +35341,7 @@ async function installedRuntimeIdentity(root, limits = {}) {
const absentPackages = [];
const maxBytes = limits.maxBytes ?? 512 * 1024 * 1024;
const maxFiles = limits.maxFiles ?? 40000;
- const manifest = async (directory) => JSON.parse(await readFile6(join12(directory, "package.json"), "utf8"));
+ const manifest = async (directory) => JSON.parse(await readFile6(join11(directory, "package.json"), "utf8"));
let readers = 0;
const waiting = [];
const read = async (path) => {
@@ -34637,17 +35367,17 @@ async function installedRuntimeIdentity(root, limits = {}) {
const pkg = await manifest(root);
if (pkg.name !== "@kiln/engine")
throw new Error("Not a Kiln installation.");
- const build = JSON.parse(await readFile6(join12(root, "dist", "build.json"), "utf8"));
+ const build = JSON.parse(await readFile6(join11(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:${digest6(await read(join12(root, "dist", worker.file)))}`;
+ const workerHash = `sha256:${digest6(await read(join11(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(join12(parent, "package.json"));
+ const require2 = createRequire2(join11(parent, "package.json"));
let found;
try {
found = require2.resolve(`${name}/package.json`);
@@ -34656,7 +35386,7 @@ async function installedRuntimeIdentity(root, limits = {}) {
found = require2.resolve(name);
} catch {
for (const modules of require2.resolve.paths(name) ?? []) {
- const candidate = join12(modules, name);
+ const candidate = join11(modules, name);
try {
await lstat5(candidate);
} catch (error) {
@@ -34688,7 +35418,7 @@ async function installedRuntimeIdentity(root, limits = {}) {
return (await Promise.all(entries.map(async (entry) => {
if (entry.name === "node_modules" || entry.name === ".git")
return [];
- const path = join12(directory, entry.name);
+ const path = join11(directory, entry.name);
if (entry.isSymbolicLink())
throw new Error("Dependency contains an untracked internal symlink.");
if (entry.isDirectory())
@@ -34766,19 +35496,19 @@ async function installedRuntimeIdentity(root, limits = {}) {
// src/local-runtime.ts
import { readFile as readFile7, stat as stat4 } from "node:fs/promises";
-import { dirname as dirname6, isAbsolute, join as join15, resolve as resolve7 } from "node:path";
+import { dirname as dirname6, isAbsolute, join as join14, resolve as resolve7 } from "node:path";
import { fileURLToPath as fileURLToPath5 } from "node:url";
import { Console } from "node:console";
init_material_resources();
// src/workspace-node.ts
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
-import { join as join14 } from "node:path";
+import { join as join13 } from "node:path";
// src/projects-node.ts
import { createHash as createHash17, randomUUID as randomUUID6 } from "node:crypto";
import { link as link4, lstat as lstat6, mkdir as mkdir6, open, readdir as readdir7, realpath as realpath5, unlink as unlink4 } from "node:fs/promises";
-import { join as join13, relative as relative6, resolve as resolve6, sep as sep4 } from "node:path";
+import { join as join12, relative as relative6, resolve as resolve6, sep as sep4 } from "node:path";
init_projects();
var missing2 = (error) => error.code === "ENOENT";
var exists = (error) => error.code === "EEXIST";
@@ -34802,7 +35532,7 @@ class FileProjectStore {
if (!workspace.trim())
throw new Error("A workspace directory is required");
this.workspace = resolve6(workspace);
- this.directory = join13(this.workspace, ".kiln", "projects");
+ this.directory = join12(this.workspace, ".kiln", "projects");
}
async path(projectId, create = false) {
if (projectId !== undefined)
@@ -34812,7 +35542,7 @@ class FileProjectStore {
const canonical = await realpath5(this.workspace);
let path = this.workspace;
for (const part of [".kiln", "projects", ...projectId ? [projectId, "revisions"] : []]) {
- path = join13(path, part);
+ path = join12(path, part);
if (create)
await mkdir6(path).catch((error) => {
if (!exists(error))
@@ -34844,7 +35574,7 @@ class FileProjectStore {
return latest;
}
async load(projectId, directory, sequence) {
- const path = join13(directory, filename(sequence));
+ const path = join12(directory, filename(sequence));
const info = await lstat6(path);
if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_PROJECT_BYTES)
throw new Error("Invalid or oversized project revision file");
@@ -34927,7 +35657,7 @@ class FileProjectStore {
for (const revision of new Set(record.reviews.map((review) => review.projectRevisionId)))
await this.read(record.projectId, revision);
const directory = await this.path(record.projectId, true);
- const temporary = join13(directory, `.write-${randomUUID6()}`);
+ const temporary = join12(directory, `.write-${randomUUID6()}`);
const handle = await open(temporary, "wx", 384);
try {
try {
@@ -34937,7 +35667,7 @@ class FileProjectStore {
await handle.close();
}
try {
- await link4(temporary, join13(directory, filename(sequenceOf(record.revisionId))));
+ await link4(temporary, join12(directory, filename(sequenceOf(record.revisionId))));
} catch (error) {
if (!exists(error))
throw error;
@@ -35022,7 +35752,7 @@ class FileWorkspace {
this.root = root;
this.defaultProjectId = defaultProjectId;
this.projects = new FileProjectStore(root);
- this.materials = new FileMaterialLibrary(join14(root, ".kiln", "materials"));
+ this.materials = new FileMaterialLibrary(join13(root, ".kiln", "materials"));
}
current() {
return this.active.getStore();
@@ -35297,7 +36027,7 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst
}
const cacheBytes = integer2(env, "KILN_BUILD_CACHE_MB", 128, 0, 1024) * 1024 * 1024;
const store = context.programStore;
- const directory = resolve7(env.KILN_BUILD_CACHE_DIR ?? join15(store instanceof FileProgramStore ? dirname6(store.directory) : ".kiln", "cache", "builds"));
+ const directory = resolve7(env.KILN_BUILD_CACHE_DIR ?? join14(store instanceof FileProgramStore ? dirname6(store.directory) : ".kiln", "cache", "builds"));
context.buildCache = new FileBuildCache(directory, cacheBytes);
context.evaluatorCacheIdentity = `${identity.identity}:${JSON.stringify({
execution: context.localExecution,
@@ -40730,7 +41460,7 @@ init_render();
init_requirements_context();
init_evaluator();
init_material_resources();
-import * as THREE44 from "three";
+import * as THREE46 from "three";
// src/edit-buffer.ts
class KilnDraftBuffer {
@@ -41048,7 +41778,7 @@ async function renderDerivativeCell(input, context) {
return;
const prepare = (material) => {
const copy = material.clone();
- copy.side = THREE44.DoubleSide;
+ copy.side = THREE46.DoubleSide;
return copy;
};
mesh.material = Array.isArray(mesh.material) ? mesh.material.map(prepare) : prepare(mesh.material);
@@ -41298,8 +42028,8 @@ function collectSceneMetrics(root) {
let meshes = 0;
const materialSet = new Set;
let lowestPart;
- const box = new THREE44.Box3;
- const point = new THREE44.Vector3;
+ const box = new THREE46.Box3;
+ const point = new THREE46.Vector3;
root.updateWorldMatrix(true, true);
root.traverseVisible((node) => {
const n = node;
@@ -41315,7 +42045,7 @@ function collectSceneMetrics(root) {
const mesh = node;
const position = mesh.geometry.getAttribute("position");
const index = mesh.geometry.index;
- const mb = new THREE44.Box3;
+ const mb = new THREE46.Box3;
if (position) {
for (let i = 0;i < (index?.count ?? position.count); i++) {
point.fromBufferAttribute(position, index ? index.getX(i) : i);
@@ -41330,7 +42060,7 @@ function collectSceneMetrics(root) {
});
let bbox;
if (!box.isEmpty()) {
- const size = new THREE44.Vector3;
+ const size = new THREE46.Vector3;
box.getSize(size);
bbox = {
min: [box.min.x, box.min.y, box.min.z],
@@ -41794,6 +42524,7 @@ async function runInspect(input, context) {
if (input.measure && input.measure.mode !== "surface")
measurement = measureAttachment(root, input.measure);
const measurements = {
+ drawDiagnostics: await (await Promise.resolve().then(() => (init_draw_diagnostics(), exports_draw_diagnostics))).inspectDrawDiagnostics(evaluated.glb),
...input.listParts ? { partListing: await listPartPage(root, input.listParts) } : {},
...measurement ? { measurement } : {},
...surfaceMeasurements ? { surfaceMeasurements } : {},
@@ -42486,10 +43217,17 @@ function createKilnAssetDefs(context) {
inputSchema: profileExportInput,
run: async (raw) => {
const input = profileExportInput.parse(raw);
+ const record = await readSavedRevision(library(), input.collection, input.assetId, input.revisionId);
+ await Promise.resolve().then(() => init_draw_diagnostics());
if (input.profile === "runtime") {
- const record = await readSavedRevision(library(), input.collection, input.assetId, input.revisionId);
+ const output = await (await Promise.resolve().then(() => (init_asset_export(), exports_asset_export))).exportAssetGlb(record, {
+ profile: "runtime"
+ });
+ if (output.profile !== "runtime")
+ throw new Error("Expected runtime export");
return {
ok: true,
+ drawDiagnostics: await inspectDrawDiagnostics(output.glb),
profile: input.profile,
collection: input.collection,
asset: {
@@ -42497,10 +43235,13 @@ function createKilnAssetDefs(context) {
revisionId: input.revisionId,
name: record.manifest.name
},
- resources: await (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).runtimeAssetLinks(input.collection, record)
+ resources: await (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).runtimeAssetLinks(input.collection, record, output)
};
}
- return links(input.collection, (await readSavedRevision(library(), input.collection, input.assetId, input.revisionId)).manifest);
+ return {
+ ...await links(input.collection, record.manifest),
+ drawDiagnostics: await inspectDrawDiagnostics(record.files["asset.glb"])
+ };
}
},
{
diff --git a/docs/backlog.md b/docs/backlog.md
new file mode 100644
index 00000000..03cd722d
--- /dev/null
+++ b/docs/backlog.md
@@ -0,0 +1,262 @@
+# Kiln current backlog
+
+**Release direction, 3 October:** Matt confirmed the farmer hand fixes and could not
+reproduce the water jump locally. He authorized final performance review, commits,
+main integration and Cloudflare deployment. The focused performance investigation is
+settled for release with its original failures and limits preserved. See the
+[release disposition](reviews/2026-10-03-release-disposition.md). Bridge stills are refreshed; physical-device
+promotion, Troy construction and npm publication remain deferred.
+
+Updated 3 October 2026. This is the maintained queue for the
+[alignment plan](plans/2026-10-02-core-scenes-site-alignment.md). It separates work
+still needed from historical requests already implemented and suggestions awaiting a
+decision. Code and CHANGELOG.md establish shipped behavior; dated reports retain
+their original evidence and limits. No queued item below is an acceptance claim.
+
+Matt's current direction is stabilization of existing core/scenes/assets, with full
+adversarial review of behavior, implementation and cycle intent, bounded known issues,
+and reproducible final-artifact evidence. Report failures, skips, unverified areas,
+risks and blockers explicitly. Troy brainstorming is not a specification, backlog or
+task; construction/refinement awaits direct Matt discussion, and the Troy pack stays
+off the public site. Commit, main integration and site deployment are now authorized; npm publication is not.
+
+## Completed optimization baseline
+
+PR #131 (`b1ac6ee`) landed the large runtime optimization pass in all three scenes.
+Farm's hero/shadow work, Golden Gate's bridge/shadow/reflection work and Foundry's
+planting/MSAA work are implemented. Foundry's 160/160 recorded parity checks passed;
+no Foundry regression caused by that pass has been established. PR #132 (`ac8456c`)
+then fixed engine ORM UV/transform handling, without changing scenes.
+
+Asset GLBs were not rewritten. Farm's optimized runtime is live; production Golden
+Gate g9 and Foundry ff3-review2 still serve their previous sealed runtimes. Local
+`g9-code5` and `ff3-review2-code5` delivery pins are now active in the candidate;
+their publication and remaining qualification are delivery work, not another
+optimization implementation pass.
+
+## Local candidate progress, 3 October
+
+Work is on `codex/core-scenes-alignment`, based on `ac8456c`; a fresh fetch still
+shows zero commits ahead/behind `origin/main`. Changes below are local and
+uncommitted. They have not changed the production website or saved asset revisions.
+The code5 site (`26ecd2b2…`) now has fresh changed-surface qualification. The prior
+code3 site (`a4d1e2d0…`) and UI3 timing retain their original scopes. The bounded
+[adversarial review](reviews/2026-10-03-stabilization-adversarial-review.md) records
+implementation findings and remaining limits. Final skill-only artifact `978664da…`
+passes fresh static/delivery/HTTP checks and strict continuity: all 2,721 product
+files, 200 HTML files and 243 scene files are exact to `26ecd2b2…`; current guidance
+archives are separately verified. After documentation freezes, the final offline
+package byte audit is separately recorded at
+`tmp/alignment-20261003/package-stabilization-final/receipt.json`; the qualification
+ledger records its result. This prose does not pre-claim the audit outcome.
+Matt selected focused timing checks, expanding only for a failure requiring
+investigation; owner farmer/water review follows the development goals.
+All 18 intended focused runs / 20.5 measured minutes are collection-valid, with raw
+D41 17 pass / one fail and two failed post-run quiet gates. A separate unchanged
+two-minute flyover pair passes D41, before/internal/after quiet checks and cleanup;
+it does not erase the original failures. Intended measurements are complete and
+functional implementation is complete within tested scope, but strict desktop
+performance acceptance remains open. No further benchmark expansion is presently justified.
+
+| Items | Implemented locally and checked | Still required |
+| --- | --- | --- |
+| CORE-1 | Shared ORM images isolated per packing pair; serialized, order and other-slot tests; independent adversarial review | Full root/coverage and installed-package gates pass; awaiting release review |
+| CORE-2/3/4 | Rigid merging wired into full; LOD, named pivots, placements and shared-scene boundaries; byte budget, 16-bit splits, precision and failure cleanup; `rigid-v1` rebuild policy | Full root/coverage and installed-package gates pass; release review remains |
+| CORE-5 | Bounded per-anchor draw diagnostics and sampled geometry observations in inspection/export; compact render unchanged | Fresh/managed Codex and Claude setup/upgrade qualification passes; paid dogfood remains separate |
+| ASSET-1 | Consolidated 292 revision/resource rows across all existing families; all 113 scene GLB consumers and 109 auxiliary inputs represented; final code5 reconciliation repeats 882 checks with zero mismatches | 56 Foundry original source/export records are not linked by selected models-only inputs; fresh appearance, functional pivot/clip/scale and owner acceptance remain separate. Bridge previews explicitly apply to the full tier |
+| ASSET-2 | Fresh 224/224 current-source corpus at 58b1 passes: 86 examples, 113 scene GLBs and 25 saved Troy regressions; every result and optimized hash matches the prior run | Structural/deterministic/Khronos scope only; 20 compressed terrain inputs remain decoded derivatives. GPU/material/importer/owner acceptance stays separate |
+| UPGRADE-1 | Compatible geometry, image, MCP/provider and tooling updates; Vite 8.3.2 synchronized; Node 22.23.3/npm 12.2.0 pins and isolated hub tools aligned | Full root/coverage and installed-package gates pass; renderer scene parity remains UPGRADE-2 |
+| UPGRADE-2 | Three 0.186.1/types 0.186.0/WebGPU 0.6.2 coherent; renderer 78 tests, NVIDIA smoke/conformance, core/package and fresh 58b1 corpus pass. Prior bounded scene matrices, motion3 both-backend controls and code5 public/site qualification retain exact scopes; all intended focused measurements are collected | Strict desktop performance acceptance stays open: original 18 runs retain one D41 miss and two failed post-run quiet gates despite a passing flyover repeat. Prior UI3/shared pilot failures, missing latest runtime owner receipt and GG strict flags remain |
+| TOOL-1/2/3, KIT-1 | Exact packs restored and hash-verified; portable browser resolution/profile cleanup; script tests in normal gate; exact-input gate 22 pass with zero skips; WebP serving and actual browser lifecycle checks pass | New release qualification and authorization remain separate |
+| KIT-3, FARM-1 | Morph-weight shadow observation, tested explicit live/invalidation contract, economy trailer exemption; direct images pass 160/160, all six settled X-02 fields match 32/32, and same-phase paired audit finds no introduced failure in 32/32 | Four absolute pilot-image failures are shared with the original; performance and owner acceptance remain separate |
+| KIT-2 | Shared panel bounds/scroll/stacking and nested touch handling; 72/72 DOM contracts. Code5 passes all six NVIDIA public-control scenarios / 34 checks, nine lifecycle/viewer/failure areas and fresh accessibility; skill-only final site has exact product continuity | Physical-device and owner acceptance stay separate |
+| KIT-5 | All 18 intended focused runs / 20.5 measured minutes collected validly; raw 17 D41 pass / one fail. Farm minimal pair passes at 25.0/33.4 ms maxima. Extra unchanged flyover pair passes D41 at 50.0/16.7 ms, all quiet gates and cleanup | Overall focused audit remains FAIL: original candidate flyover 50.1 ms and post-run CPU maxima 16.473% / 16.159% remain. Repeat preflight CPU 12.694% failed before browser and is preserved. No further benchmark expansion presently justified; full 108-run preparation remains deferred/unrun |
+| FARM-2 | Busy-port handling verified; original Farm's 42 files verified; direct 160/160 and settled X-02 32/32 pass; paired 32/32 has no introduced failures; existing r34 B-07 pooling/optimization/ordered collider counts pass for both builds, with 41 cached-shadow textures | Four pilot-image failures are shared, not absolute parity. B-07 retains its r34 visible-source provenance note; no new collider soup/motion oracle. D-64/D-68 adopts the comparison baseline but no hash-bound latest scene-runtime owner acceptance receipt is established, so releaseQualified remains false |
+| FARM-3 | Four valid allocation observations complete; current late GC remains about 36 ms with stable endpoint counts/joints. Separate focused 135-second minimal hero-view pair has original/candidate maxima 25.0/33.4 ms, both raw D41 pass | Post-run CPU maximum 16.159%, sampled 6.326 s after the block, fails strict quiet qualification. Source allocation/retainer ownership stays unresolved; no speculative repair, hitch-fixed, leak-freedom or performance-acceptance claim |
+| GG-1 | Opt-in depth and sky/reflection/bias adaptations; NVIDIA prototype-reference comparison passes 78/78 on each backend; final public/startup/missing-clip probes pass; local `g9-code5` delivery prepared | Authentic original→final retains 17 WebGPU and 11 WebGL2 strict flags; owner review and publication remain separate |
+| GG-2 | Dynamic reflection exclusions and persistent hidden fog banks; 17 focused tests; both-backend 78-view comparisons retain camera/bridge counts and pass against the reconstructed depth reference; local `g9-code5` delivery prepared | Moving-workload timing remains GG-4/PERF-1; owner review and publication remain separate |
+| GG-3 | Verified per-world layout and deterministic 12,706-byte startup projection; code5 public runtime is 1,708,928 raw / 512,680 gzip, within fixed ceilings; both-backend initialization checks pass | Quiet timing remains PERF-1; no tablet tier promotion |
+| GG-4 | Contact-shadow prewarming has focused tests and first-use native proof. Original focused candidate flyover misses D41 at 50.1 ms near 57 s; the nearby 41.3 ms render-call wall interval is not measured CPU. One unchanged extra A/B pair completes at 50.0/16.7 ms maxima with D41, quiet and cleanup passing | The candidate miss did not recur; no actionable cause or new runtime repair is justified. The repeat does not erase the first miss or failed quiet gate. Broader preparation stays deferred; owner review follows development goals |
+| FF-1 | Prior comparison passes 120 default image cases and 56 static X-02 rows. Code5 keeps asset bytes/acceptance; motion3 first-key/follow and code5 controls/lifecycle pass both backends. Selected focused runs have raw D41 passes | Strict desktop performance acceptance remains open because the shared block fails post-run quiet qualification; owner acceptance and historical interior-pose limits stay separate |
+| FARM-4 | Per-render empty-hand correction, borrowed mirrored arm, 150 ms blending and registered warming preserve saved GLBs. Motion3 both-backend entry/start-stop/reentry and code5 public controls pass; bounded adversarial review finds no new concrete blocker | Owner confirmed the hand/animation appearance on the local candidate on 3 October; physical mobile remains a separate scope |
+| GG-5 | Phase/foam-origin fixes and reduced wakes are implemented; bounded shader/render checks pass. Owner could not reproduce the jump in the local candidate on 3 October | Closed for this release on scoped local evidence; reopen with an exact path/device if it recurs. No universal water or physical-device claim |
+| FARM-5 | Desired camera separated from collision projection; motion3 both-backend orbit/pinch and obstacle regressions pass. Code5 public-02 additionally passes real incremental touch orbit/pinch and first W on actual NVIDIA WebGPU/WebGL2 | Physical-device and owner acceptance remain separate. Public-01 behavior passed but its warning-classifier failure stays recorded; public-02 uses the maintained exact classifier |
+| KIT-6 | Pre-#131 joystick cleanup defect fixed with movement ownership; unchanged DOM fixture passes 8/8. Motion3 Farm/Foundry and code5 public Farm first-key/touch checks pass both backends; current fresh/managed guidance copies and final skill-only site continuity pass | The separately recorded final package audit, open strict desktop performance acceptance and deferred physical-device evidence remain separate |
+| SITE-1 | Portable static-only deployment preflight; artifact hashes rechecked before upload; all three upload manifests summarize 486 files with zero problems; actual dry run correctly refuses the dirty checkout | Clean reviewed source/artifact and authorized upload after remaining release work |
+| SITE-2 | Local g9-code5 and ff3-review2-code5 archives reproduce exactly, stage through the normal path and match runtime/page/catalog references; original model/data bytes, saved revisions and checksums are unchanged. Final skill-only artifact continuity passes | Clean authorized R2/Pages delivery/public verification; old objects remain unchanged |
+| SITE-3 | Final skill-only artifact 978664da…: 2,728 files / 199,998,384 bytes; fresh static/delivery/HTTP pass. Strict continuity preserves 2,721 product files, all 200 HTML and 243 scene files from 26ecd2b2…, retaining its 564-test, 70-Astro-file, six-control/34-check, nine-flow, 396-width/44-tour evidence within original scopes. Current skill archives match maintained guidance | Final package audit is separately recorded after documentation freezes; strict desktop performance acceptance stays open and owner/device/release boundaries remain |
+
+The latest portable gate records 713 passes, 18 historical skips and zero failures
+across 123 files; typecheck/lint pass. Core coverage remains 3,187 passes, three
+platform skips, 95.11% functions and 92.32% lines. All six runtime bundles retain
+58b1 identity and installed-package smoke scope. The fresh source corpus at that
+identity passes all 224 inputs with stable before/after source and unchanged assets;
+all per-input outputs equal the prior dd25 run. See
+`tmp/full-optimizer-corpus/current58b1-20261003/qualified.json` and its independent
+`verification.json`. This is source execution, with dist execution covered separately.
+
+Code5 site qualification and final revision/runtime/reference reconciliation are
+complete within the scopes above. Current fresh/managed Codex and Claude copies
+pass after KIT-6 guidance; the final skill-only site rebuild and exact product
+continuity proof pass; the final offline package byte audit is separately recorded
+after these documents freeze. The bounded adversarial
+review reports no new concrete blocker and preserves the authorship/test limits.
+No release or owner approval is implied. The four bounded Farm allocation observations
+are complete, as are the intended focused measurements and bounded flyover repeat.
+The overall focused audit remains failed; strict desktop performance acceptance is
+open, with no further benchmark expansion presently justified. Earlier code3/UI3 receipts and
+the deferred, unrun 108-run preparation stay historical. No all-tier, repeated-run
+or desktop-speedup claim follows from the selected checks.
+
+The prior `f0e49fbc…` site's accessibility receipt freshly checks four widths on the two
+changed documentation routes and reuses 392 widths and all 44 tours from artifact
+`42a41439…` only after exact HTML/dependency identity and unchanged Chrome, axe and
+verifier are proved. That preserved prior receipt combined 60 freshly checked
+routes with 138 byte-identical preliminary routes; its original proof remains
+bound to those checks. That prior receipt and proof are under
+`site/.cache/alignment-release-docs/`; this chain does not qualify activated
+scene/viewer interactions or UI2. Its strict continuation proof rejects reuse for
+UI2 because emitted shared CSS also differs outside the two approved rules; all
+198 routes / 396 widths, 44 tours and 2,138 stops now pass freshly on `a4d1e2d0…`,
+with zero problems and no reused routes. The exact receipt is
+`site/.cache/alignment-site-qualified/accessibility/combined.json`.
+The authenticated Cloudflare list at 10:35 UTC still identifies production
+deployment `33c716c7…` / `b1ac6ee`. A fresh Node-fetch check at 10:50 UTC verifies
+its public build metadata and manifest `5ecbbe76…`, with old `g9` / `ff3-review2`
+pins. The earlier Python-client 403 attempt remains preserved separately.
+No upload or commit has occurred; the successful public recheck is
+`tmp/alignment-20261003/production-recheck-20261003T103132Z/node-public-receipt.json`.
+
+The complete scene-script gate passes **108 tests / 615 assertions / 0 failures**
+across 22 files (`/tmp/kiln-scenes-timing-evidence-scripts-host-final.log`). It covers
+bounded cleanup, measured-interval visibility/focus and actual GPU device-to-canvas
+binding as well as complete readable quiet telemetry. Unknown GPU load or locker
+state cannot qualify as idle. The kit generator reads `scenes/toolchain.json`.
+The quiet-host blocker is resolved without changing thresholds. The balanced
+block completes 7 of 18 cells / 42 of 108 one-minute runs against the exact original
+and UI3 candidate binaries; before, internal and after quiet checks pass. D41 is
+37 pass / 5 fail. All 12 Farm and 18 Foundry runs pass raw D41; the six static
+Foundry fab runs have absent exterior pose fields under the expected schema,
+so these receipts do not claim independently measured interior camera coordinates.
+
+All six Golden Gate flyover runs peak at about 25 s into sampling (about 30 s of
+scene time after warmup), in both builds: A 50.0/66.6/58.4 ms and B 58.2/50.1/49.9 ms.
+Four fail D41; candidate drive pair2 separately fails at 58.3 ms, about 4.408 s
+into sampling. Flyover busy×clock rises +3.45%, +0.05% and +2.91% across the three
+pairs; higher clocks alone do not explain it, but coarse global GPU polling does
+not establish a code cause. No desktop margin or tablet adoption threshold is applied.
+
+Seven economy and four orbit cells were unrun in that historical UI3 campaign.
+The current motion3 campaign prepares all 18 cells / 108 runs and is unstarted;
+the code5 functional/site checks do not qualify its performance. Raw historical
+results remain in
+`scenes/evidence/perf/hub-alignment-2026-10-03/candidate-ui3-balanced/`, with independent
+calculations in `tmp/alignment-20261003/balanced-performance-review/review.json`.
+All five D41 failures and the separate drive event remain recorded. Four bounded
+135-second Farm allocation observations are prepared under
+`scenes/.tmp/alignment-farm/allocation-plan/`, with execution pending. No allocation
+cause, timing pass, deployment or release approval is claimed.
+
+## Work items and required completion evidence
+
+The order is core correctness and compatible upgrades, focused scene follow-ups,
+then qualified site delivery. The rows include regression checks and release chores;
+they are **not a count of unimplemented defects or mandates to rework every asset**.
+The local-progress table above records which implementation and checks already pass. Existing
+accepted evidence remains useful. Recheck the surfaces changed by the next release.
+
+| ID | Work | Required completion evidence |
+| --- | --- | --- |
+| CORE-1 | Fix pre-existing shared-image ORM overwrite | Tests for distinct AO maps, other-slot consumers, order independence and serialized GLB; preserve material/UV/sampler behavior |
+| CORE-2 | Complete deferred engine full-export optimizer | Named pivots, placements, animation targets and all LOD levels survive; caller inventory and public contract settled; separate from landed scene runtime merging |
+| CORE-3 | Correct D2/D3 and bake-frame policy | Actual added bytes per saved draw, conditioned transforms, 65,534-vertex split and end-to-end determinism tests |
+| CORE-4 | Version rebuild behavior and expose diagnostics | Old saved revisions have an explicit replay/migration policy; merge/rejection summary reaches callers |
+| CORE-5 | D23 outputs and maintained skill guidance | Qualified draw estimates and geometry observations; compact output budgets; fresh setup and managed upgrade preserve user customizations |
+| UPGRADE-1 | Compatible dependency and maintainer-tool updates | Peer-compatible exact pins, synchronized locks/toolchain/CI and applicable offline gates |
+| UPGRADE-2 | Renderer-family update | Coordinated Three.js/types/WebGPU dependencies, build identity, GPU smoke and both-backend scene parity |
+| ASSET-1 | Reconcile existing inventories and acceptance | Match final scene consumers, source/material/asset revisions, acceptance states, pack/archive/mirror pins and served download hashes; keep new runtime delivery labels separate from asset revisions. Preserve originals and exclude Troy from the public catalog/artifact |
+| ASSET-2 | Core regression corpus | All 86 examples, exact released scene assets and pinned Troy revisions; engine LOD-aware IO, world-space geometry and semantic assertions |
+| TOOL-1 | Clean-hub exact inputs and browser launch | Public hash-pinned inputs restored; Linux/Windows executable selection; scene builds independent of missing author workspaces |
+| TOOL-2 | Scene test and release coverage | Script tests in normal gate; correct Foundry budget fixture; exact-input gate cannot pass via fixture skips; Golden Gate count baseline |
+| TOOL-3 | Browser process/profile lifecycle | Owned-port handling and cleanup on normal close and launch failure |
+| KIT-1 | WebP static serving (GG-004) | GET, HEAD and range MIME tests with existing access controls preserved |
+| KIT-2 | Consolidate existing HUD/touch workarounds (GG-007, FF-002) | Narrow/short screens, panel scrolling/stacking/focus and nested controls retain behavior; no claim of broken current scene controls |
+| KIT-3 | Shadow motion contract (D26) | Explicit treatment of morphs, shader motion and custom instance attributes; auto detection or documented live-caster behavior tested |
+| KIT-4 | Collision/interaction regression verification | Preserve already-tested doors/joints/proxies when changing optimization; no current broken interaction established |
+| KIT-5 | Shared parity and GPU timing tools (D18, D16) | Thin-line budget and repeat-capture noise; units/provenance for GPU clock and busy-times-clock |
+| FARM-1 | Trailer shadow and baseline work (D8) | Economy trailer exemption with appearance, draw and shadow parity |
+| FARM-2 | Paired pilot audit (D20) | Busy-port fix; new and last-accepted same-phase captures on both backends; texture/count provenance |
+| FARM-3 | Late hero-view hitch (D22) | Desktop GC mechanism reproduced; measure allocations/retainers before a targeted fix and repeated quiet-host validation; retain tractor/joint behavior |
+| GG-1 | Reversed depth (D15) | Opt-in renderer feature, sky/reflection/polygon-offset adjustments, WebGPU/WebGL2 and unsupported fallback evidence |
+| GG-2 | Reflection exclusions (D5/D6) | Traffic, player car and fog banks excluded as adopted; vegetation cards preserved and fog banks stay hidden |
+| GG-3 | Runtime layout delivery (D27) | Verified layout data; missing/corrupt/cancelled-load tests; bundle budget and initialization parity |
+| GG-4 | Shared flyover transition and separate drive hitch (D22) | Startup-context native pipeline proof passes; qualify repeated exact-candidate quiet timing; retain the separate drive event and five historical D41 failures. No tablet tier change |
+| FF-1 | Verify and release the optimized Foundry runtime | Preserve #131's planting work and unchanged interior; reuse existing tests against restored exact inputs; 62 metadata/pin records already agree |
+| FARM-4 | Farmer pose, gesture and transitions | Implemented cadence/relaxed-hand/blend/warming pass focused and both-backend public motion checks; carry them into rebuilt deliveries and affected lifecycle checks. Broader pose/seat and owner review retain their explicit bounds |
+| FARM-5 | Mobile third-person camera | Farm and shared Foundry motion3 checks pass both backends; complete rebuilt delivery checks. Preserve drag distance, pinch in/out and obstruction recovery; physical devices remain a separate boundary |
+| GG-5 | Owner-observed wakes and high-angle water snapping | Reproduce pier wake size/distinctness and water texture/orientation clipping/snapping during high-angle orbit; qualify the targeted visual behavior without wholesale asset rebaking |
+| KIT-6 | Touch-to-keyboard movement handoff | Preserve the newer input when the joystick hides or releases; actual React lifecycle and first-key browser regressions, including cancel/clear ownership |
+| PERF-1 | Focused investigation settled for release | Retain original 50.1 ms miss and post-run quiet failures; targeted unchanged repeat passes. No reproducible actionable regression established, no additional benchmark or speculative patch required. Strict all-run acceptance and 108-minute campaign remain unclaimed |
+| SITE-1 | Portable deploy preflight | Preserve clean-tree/commit/packs/file-limit checks; verify artifact hashes immediately before upload; refusal and dry-run tests |
+| SITE-2 | Prepare affected local scene deliveries | Qualified exact runtimes and producer hashes; synchronized scene-packs, scene-input archives, mirror/upload manifests and applicable catalog scenePack references; unchanged saved asset revisions and old objects |
+| SITE-3 | Final local launch-mode qualification | Full existing assets/scenes, accessibility/touch/keyboard/failure flows and exact served downloads on the final artifact; explicit identity proof for reused evidence; Troy absent. Cloudflare upload/deployment requires a separate authorization |
+| RELEASE-1 | Installed-package and workspace qualification | Full applicable gates, runtime rebuild, package/skills contents and fresh setup/managed-upgrade checks |
+
+CORE-1 can be a small isolated fix. CORE-2 through CORE-4 change full-mode behavior
+and need the planned 0.11 release/migration treatment. A scene runtime optimization
+does not by itself justify replacing standalone asset revisions. Paid harness dogfood
+needs its own concrete authorized run scope; offline qualification stays provider-free.
+
+## Stabilization readiness exit
+
+The final review must connect each adopted change to intended behavior and exact
+source/build/input evidence, reconcile final existing-scene and asset delivery pins,
+and retain a bounded known-issue inventory with impact and disposition. Report local
+failures/skips/unverified areas and external owner/device/release boundaries separately.
+Prior green matrices or site/package checkpoints do not qualify changed bytes without
+an explicit continuity proof. Complete required local gates before reporting readiness;
+no blanket acceptance, release action or Troy task follows from this report.
+
+## Implemented or superseded requests
+
+- PR #132 shipped UV/transform guards and other recorded fixes. It did **not** fix
+ CORE-1's shared-image overwrite.
+- PR #131 landed the completed scene runtime optimization work. It did not
+ implement every adopted follow-up or reseal all production runtimes.
+- The maintained compose-scene skill includes #131's optimization lessons; the
+ published website archive matched main at the 3 October audit. Four narrow
+ reference clarifications are now local, pending release. The v0.10.0 tag predates
+ #131, and Troy's current workspace has no optional compose skill installed.
+- FARM-001 through FARM-007, GG-001/FF-001 and GG-009/GG-010 are recorded as done.
+- FF-003's callback-cancellation identity handling is present in the shared kit and
+ tests; it is no longer an open implementation request. Full failure-flow acceptance
+ remains part of each new scene release.
+- Requested placement output, extras/visibility, cubic easing, index policy,
+ hide-node captures, intentional open shells and LOD support shipped. Sweep analysis
+ has bounded local coverage, not a general distant-intersection guarantee.
+- Foundry's earlier deferred-startup repair and Golden Gate's earlier rejected bridge
+ variant are superseded by their accepted revisions; do not reopen them from old logs.
+
+## Held, optional or awaiting evidence
+
+| Item | Disposition |
+| --- | --- |
+| Troy scene ideas | Brainstorming only, not an adopted specification, backlog or task. Construction is deferred for direct discussion with Matt; foundation exit does not start it automatically |
+| Troy pack/refinement/publication | Keep off the public site. No refinement or publication task is adopted; existing revisions may remain local regression inputs without changing this boundary |
+| AI SDK/provider/OpenRouter/OpenAI major upgrades | Blocked by current Strands peer compatibility; compatible-family updates are locally qualified |
+| Site TypeScript 7 | Keep TypeScript 6 while Astro's checker/compiler-API consumers require it |
+| Xclipse tier classification (GG-008) | Needs actual device strings and performance evidence |
+| FARM-008 instancing/warm-up advice | Measure applicability per scene; not a proven global defect or automatic rewrite |
+| Shared meshopt loader (GG-002) | Optional consolidation; Golden Gate has a working local path |
+| Terrain derivative encoder (GG-005) | Regeneration tooling is distinct from the usable sealed terrain; decide when new tiles are needed |
+| Static scene export (GG-006) | New delivery contract requiring a separate decision |
+| Foundry S3 cross-pass and roof/seam design | Pre-existing asset/design questions, not #131 regressions; D-75 retains campus structures. Change only after an explicit design disposition |
+| Next vegetation cycle (D33) | Adopted later performance exploration: per-tree culling before LOD, with visual/GPU-work gates. Keep separate from shipping the completed pass |
+| R8 shadow targets, reflection cadence, output-pass depth and extra merge layouts | Optional measured follow-ups; not silently prerequisites |
+| MCP render file destination | Unadopted; existing CLI file output and MCP media/receipts remain supported |
+| SEP-2640 resources and large present metadata | Retain the roadmap's recorded defer decisions |
+| Ten-pack production, broader importers, public v1 package | Later milestones with their own acceptance |
+
+Update this ledger when evidence or an owner decision changes a disposition. Link the
+test/report/revision that closes an item. Historical reports should gain a current
+pointer where needed, not be rewritten to claim new acceptance.
diff --git a/docs/google.md b/docs/google.md
index 1f529bd1..d20a0ae2 100644
--- a/docs/google.md
+++ b/docs/google.md
@@ -20,7 +20,7 @@ cd ../my-assets
node agy.mjs --model gemini-3.8-flash-high
```
-Use the supported Bun 1.4.2 and Node 22.23.2 toolchain. A built package avoids the
+Use the supported Bun 1.4.2 and Node 22.23.3 toolchain. A built package avoids the
Bun/build steps: run `npm exec --offline -- kiln-init ../my-assets --harness agy`
from its installation directory instead. Check [release compatibility](install.md#release-compatibility)
before following saved-asset examples with an older package.
diff --git a/docs/migration.md b/docs/migration.md
index 4b958225..1db153e9 100644
--- a/docs/migration.md
+++ b/docs/migration.md
@@ -4,6 +4,28 @@ Existing inline-code transport and the legacy capture format remain supported. T
Discovery and authoring-helper changes below require explicit migration; retired
names have no callable compatibility aliases.
+## Unreleased changes planned for 0.11
+
+These changes describe the local alignment candidate, not the downloadable 0.10.0
+release. Use the documentation and package from the same release when upgrading.
+
+- **Full optimization.** `optimize: 'full'` replaces flatten/join with rigid-group
+ merging. The rigid-merge pass keeps every node's name, parent and transform, but an
+ ordinary named mesh can become empty or hold its group's merged geometry. The
+ separate GPU-instancing pass can remove named instance nodes. Use `instance: 'off'`
+ with `optimize: 'off'` or `'palette'` if your integration requires geometry on each
+ named part. Animation, joint,
+ semantic, composition-placement and LOD boundaries remain protected. See the
+ [full-mode contract](runtime.md#bake-defaults).
+- **Saved rebuilds.** New full-mode builds record `optimizationPipeline: 'rigid-v1'`.
+ Rebuilding an older unversioned full-mode revision with the new pipeline is refused.
+ Keep its original pinned engine for an exact rebuild, or explicitly author and
+ save a new child revision with the new engine. Reading or exporting its original
+ saved GLB remains supported; existing revisions are not rewritten.
+- **Tool outputs.** Inspection and export add bounded draw diagnostics and advisory
+ geometry observations. Tool input schemas and compact render results are unchanged;
+ older packages do not provide these new observations.
+
## Changes in 0.10.0
The [changelog](../CHANGELOG.md) names every break; these are the ones an existing
diff --git a/docs/plans/2026-10-02-core-scenes-site-alignment.md b/docs/plans/2026-10-02-core-scenes-site-alignment.md
new file mode 100644
index 00000000..d9eb4c51
--- /dev/null
+++ b/docs/plans/2026-10-02-core-scenes-site-alignment.md
@@ -0,0 +1,1299 @@
+# Kiln core, scene and asset stabilization
+
+**Release direction, 3 October:** Matt confirmed the farmer hand fixes look good,
+could not reproduce the water jump in the local candidate, and authorized settling
+the performance findings followed by commit, main integration and site deployment.
+The [release disposition](../reviews/2026-10-03-release-disposition.md) records the bounded performance decision.
+Troy, physical-device promotion and npm publication remain deferred. Earlier open
+water and authorization statements below describe superseded checkpoints.
+
+**Reopened 3 October after owner feedback:** Matt still observes repeated wave-position
+jumps while orbiting Golden Gate. GG-5 is open; earlier boundary checks are bounded
+evidence, not proof that this report is resolved. The current investigation and exact
+preview/build distinction are in [the water follow-up](../reviews/2026-10-03-water-orbit-follow-up.md).
+The 108-minute campaign is not a requirement for this release checkpoint; use focused
+failure-driven validation and preserve historical failed results. Prepare commit/push
+and Cloudflare deployment, but do not execute those release actions yet. Troy follows
+stabilization and a separate requirements discussion.
+
+This is the current alignment plan, recorded on 2 October 2026 after the hub audit
+and updated by Matt's 3 October clarification. The goal is to stabilize the existing
+core, scenes and assets, adversarially review behavior, implementation correctness
+and the cycle's intent, and qualify reproducible final local artifacts. Troy ideas
+were brainstorming, not an adopted specification, backlog or task. Troy construction
+is deferred for direct discussion with Matt; keep the Troy pack off the public site.
+No commit, upload, deployment or package publication is authorized. Current code,
+AGENTS.md and CHANGELOG.md remain the behavior and release authorities.
+
+Updated 3 October with the maintained [backlog](../backlog.md). Read the backlog for
+item status and this plan for acceptance criteria and sequencing.
+
+The implementation is now on local branch `codex/core-scenes-alignment`, based on
+`ac8456c` and still uncommitted. The backlog's local-progress table is authoritative
+for candidate status; the starting-point evidence below describes the earlier audit.
+No production deployment, public package publication or saved-asset rebake has occurred.
+
+Core implementation and separate runtime/package gates pass. A fresh 224/224
+source corpus run now binds current identity `58b1b178…`, with every per-input result
+and optimized hash equal to the prior dd25 checkpoint; 20 terrain files remain
+explicitly decoded derivatives. The motion3 portable gate passes 713 tests with
+18 historical skips, and Farm/Foundry controls pass both backends. Bounded
+[adversarial review](../reviews/2026-10-03-stabilization-adversarial-review.md) finds
+no new concrete implementation blocker within its stated surfaces and test limits.
+
+The code5 local site `26ecd2b2…` now has fresh qualification: 564 tests with two
+historical skips, 70 Astro files without diagnostics, static checks, six NVIDIA
+control scenarios / 34 checks, nine flows, 396 accessibility widths and 44 keyboard
+tours pass. HTTP checks cover 116 downloads, 520 files, 89 pages and three checksum
+endpoints; revision reconciliation covers 292 records / 882 checks without mismatch.
+Actual public Farm orbit/pinch/first-key behavior passes on both backends in public-02;
+public-01's warning-classification failure is preserved. Current fresh/managed skill
+copies pass. The final skill-only artifact `978664da…` passes fresh static/delivery/
+HTTP checks and exact continuity: 2,721 product files, all 200 HTML and 243 scene
+files are unchanged from `26ecd2b2…`. Current skill archives match maintained
+guidance. Original browser measurements retain their identity and scope. After
+documentation freezes, the final offline package byte audit is separately recorded
+at `tmp/alignment-20261003/package-stabilization-final/receipt.json`; the qualification
+ledger records its result, with no outcome claimed in advance.
+
+Matt selected focused checks, expanding only if a failure needs investigation.
+All 18 intended focused runs / 20.5 measured minutes are collection-valid, with raw
+D41 17 pass / one fail. The original candidate Golden Gate balanced flyover's
+50.1 ms interval at 56.9993 s stays failed. Both post-run quiet gates fail, with CPU
+maxima of 16.473% and 16.159%, sampled 18.125 s and 6.326 s after their respective
+blocks. Farm's 135-second minimal hero-view pair has original/candidate maxima of
+25.0/33.4 ms, both raw D41 pass. The overall focused audit remains **FAIL**.
+One additional unchanged flyover A/B pair completes two measured minutes at
+50.0/16.7 ms maxima, with both D41 and all quiet/cleanup checks passing. Its early
+12.694% CPU preflight failure stopped before browser launch and is retained.
+The candidate's later 50.1 ms miss did not recur; no actionable cause or new runtime
+fix is justified. The repeat does not erase failures or establish full qualification.
+All intended measurements and functional implementation are complete within their
+tested scopes; strict desktop performance acceptance remains open. No further
+benchmark expansion is presently justified. The 18-cell / 108-run preparation is preserved,
+deferred and unrun; it is no longer the active requirement. The older
+UI3 balanced block retains 37 D41 passes and five failures across 42 runs; it does
+not qualify the changed candidate. Golden Gate startup native pipeline preparation
+has functional proof; the separate drive event remains. Farm's late pause overlaps
+major GC. Four serialized 135-second allocation observations are complete: neither
+current observation has a natural interval above 40 ms, while original observations
+reach 50.0 and 41.7 ms. Current GC still takes about 36 ms; source allocation/retainer
+ownership remains unresolved and no speculative repair is justified. Owner farmer/
+water appearance review follows development goals. Device/importer limits and
+original failures/skips remain explicit; no release or Troy work is authorized.
+
+## What already landed
+
+The large scene optimization pass **is done in source**: PR #131 (`b1ac6ee`,
+2 October) integrated the scene-kit features, all three scene adaptations, count
+baselines, parity tools and compose-scene guidance. PR #132 (`ac8456c`) subsequently
+fixed ORM UV/transform handling; it did not change the scenes. Fresh fetch on this
+hub confirms main and origin/main both point to `ac8456c`.
+
+| Scene | Landed optimization and recorded evidence | Remaining delivery |
+| --- | --- | --- |
+| Farm | Hero merges inside anchors, cached shadows and stand-ins; shadow-tier fixture draws 8,161 to 3,025; 86/86 parity cases | Optimized Farm is already deployed from b1ac6ee |
+| Golden Gate | Bridge merges, once-per-frame shadows, shadow/reflection stand-ins; fixture draws down 64–72%; recorded parity has known tower thin-line failures across several views/tiers (the original 488/489 tally was corrected) | Optimized source is landed; production still uses sealed g9 pending reseal |
+| Foundry Floor | Shared planting material graph, multisample discard, 60-row count baseline and count gate; draws down 6.3–6.6%, pipeline totals 303–305 to 138–140; 160/160 parity cases | Optimized source is landed; production still uses sealed ff3-review2 pending reseal |
+
+These figures are the cycle's recorded evidence, not new browser runs on this hub.
+Foundry's fab and planting-off captures were byte-identical before/after: its
+already-efficient interior was retained. No Foundry regression from #131 has been
+established. This plan does not call for redoing the completed optimization pass.
+
+The pass changed browser runtime code, **not asset GLBs, source assets, materials or
+sealed pack files**. The general engine full optimizer (`e72b610`) was deliberately
+excluded from #131 and is now implemented in the local candidate. Distinguish the
+completed implementation from its remaining qualification:
+
+- Golden Gate depth/reflection and Farm's economy trailer exemption are implemented.
+ GG/FF static checks and Farm's direct/paired/count/pooling/collider checks are
+ complete within their named build and baseline scopes.
+- The engine optimizer and adopted test tooling pass their local gates. Bounded
+ hitch traces have explicit dispositions below; they do not imply a newly caused
+ scene regression or justify an unmeasured repair.
+- Local Golden Gate/Foundry code5 delivery seals are prepared. Integrated controls,
+ lifecycle and fresh accessibility gates pass within their exact-artifact scopes;
+ quiet performance and owner/release review remain before any authorized publication.
+ A verification checklist is not a list of newly discovered defects.
+
+## Direction and boundaries
+
+- Troy construction and refinement are deferred for direct discussion with Matt.
+ The earlier sea/shore/plain/wall/city ideas and battle composition are brainstorming
+ and reference material, not specifications, acceptance criteria or queued tasks.
+ Completing this foundation does not authorize starting them.
+- Keep the Troy pack, assets and scene off the public site. Existing local Troy
+ revisions may remain fixed regression inputs; that does not authorize publishing,
+ refining or constructing them.
+- Review adopted changes adversarially against intended behavior and cycle decisions,
+ not only aggregate test counts. Keep a bounded inventory of demonstrated issues,
+ explicit failures/skips/unverified areas, risks and blockers; distinguish source
+ defects from verifier mistakes and external owner/device/release decisions.
+- Preserve standalone asset revisions, their sources, material pins and review history.
+ Runtime merges, shadow proxies, collision setup, terrain and controllers belong to
+ scenes. A runtime improvement does not automatically require rebaking an asset.
+- Existing Farm, Golden Gate and Foundry are the proving environments. Each needs an
+ exact accepted baseline and a candidate. Historical draw counts or unit tests alone
+ do not establish current appearance, interaction, loading or performance.
+- Review every upgrade family, but move versions in compatible groups with measured
+ acceptance. A version being newer is not sufficient evidence to replace a working pin.
+
+## Verified starting point
+
+| Surface | State verified in this audit |
+| --- | --- |
+| Engine repository | main at ac8456c, identical to origin/main after fetch; no open PRs |
+| Source release | 0.10.0, with later changes under Unreleased; npm publication remains a separate milestone |
+| Raw optimization branch | draw-optimization at 4a1d238; scene work already squash-landed, engine commit e72b610 not integrated |
+| Existing local changes | Scene pin-path portability fix and test, contributor/handoff updates; preserved, uncommitted |
+| Core validation | 3,137 pass, 3 skip; functions 95.06%, lines 92.25%; toolchain, skills, typecheck and lint pass; render-service 78 pass |
+| Scene validation | Toolchain, pins, typecheck, lint and portable tests pass; separate script tests 58 pass, 1 fixture skip |
+| Runtime | All six dist source identities and bundle hashes match |
+| Site validation | Frozen dependency install restored; 455 pass, 2 fixture skips; Astro checks 70 files with no diagnostics |
+| Production website | Public build-info and authenticated Cloudflare deployment list agree: b1ac6ee, clean, packs enabled; deployment 33c716c7-16e5-46c6-93bf-f2260f0082be |
+| Production scene inputs | Farm r36-local-review with source-built runtime; Golden Gate g9 and Foundry ff3-review2 with sealed runtimes |
+| Cloudflare access | Wrangler 4.147.0 ran through an exact-version temporary npm invocation; existing OAuth accesses the kilnstudio Pages project and kiln-assets R2 bucket |
+
+The production build predates ac8456c. Its artifact manifest counts 2,727 files,
+excluding the two final receipts. No upload, deployment, DNS change or package
+publication was performed in the starting audit. At that point GPU driver detection
+succeeded, while engine GPU rendering and browser performance still needed fresh
+qualification. Completed renderer checks and the remaining performance scope are
+recorded in the current progress and integrated evidence sections.
+
+## Core work
+
+### E1 Preserve shared textures during ORM packing
+
+Confirmed on current main: two materials sharing metallic-roughness but using different
+occlusion maps both end up reading the last map. A base-color consumer of the same
+image can also be changed. The UV/transform guard added in #132 does not isolate the
+mutation in src/kit.ts.
+
+Git history dates this shared-image mutation to 8 August (`022b30f`); it is not
+a regression from the October scene pass or #132.
+
+Write failing tests first for distinct occlusion maps, reversed material order,
+already-packed occlusion and other-slot consumers. Copy per distinct packing
+combination or report a deliberate skip. Preserve unaffected channels, alpha where
+another consumer needs it, UVs, transforms and sampler behavior. Validate both
+applyKitContract and serialized packKitGlb results. This is the first isolated fix.
+
+### E2 Qualify and integrate the replacement full optimizer
+
+Today's full mode can delete an unanimated named pivot without reducing draws. The
+replacement has useful existing tests, but is not ready to land unchanged. Port only
+the engine work; do not merge all raw branch commits. The ignored wiring patch no
+longer applies cleanly after #132 and needs a reviewed port.
+
+This is the separate GLB-export optimizer, not the scene-kit runtime merge that
+already landed and was exercised in #131. The old flatten/join path dates to June
+(`b459adc`). Conditions below qualify the unlanded replacement; they are not
+failures introduced into the shipped scenes. Current Uint32 indices are valid;
+D3 is an adopted output/size policy, not a repair for corrupt geometry.
+
+Required conditions from the adversarial review, now supported by targeted probes:
+
+1. D2 must measure additional baked bytes per actual saved draw. The scratch predicate
+ undercounts a reproduced case. A conservative per-mesh cap is an alternative policy,
+ not an equivalent implementation of the owner's 4 KB per saved draw decision.
+2. Protect MSFT_lod referenced levels, including levels still attached to a scene, as
+ boundaries. Current proposed code protects only the extension owner.
+3. Return merge and rejection diagnostics through OptimizeSummary and render warnings.
+4. Choose a deterministic, well-conditioned bake frame; do not blindly choose the
+ first contributor. Test scale extremes, mirrored transforms, normals and tangents.
+5. Implement and exercise D3's split at 65,534 vertices, including boundary cases and
+ subsequent weld behavior; the scratch option is not currently wired.
+6. Record the optimization pipeline version and define behavior for older full-mode
+ rebuilds. A saved mode name alone cannot promise the old bytes after changing its meaning.
+
+Also cover partial meshes, shared meshes across boundaries, UV/COLOR layouts,
+texture transforms, quantized geometry, animation targets, transparent ordering,
+determinism through the whole pipeline and failure behavior. Verify off, auto and
+palette behavior remain stable unless a separately recorded fix intentionally changes it.
+
+Caller inventory and contract are now settled in the local candidate. Main CLI/MCP
+evaluation pins `off`; library calls and review derivatives retain documented mode
+and environment behavior. The local Studio production services use off/palette;
+its explicit full-mode quality fixture asserts semantic nodes/metadata, which are
+protected boundaries. Composition wrappers are protected. The rigid-merge pass retains every node's
+name, parent and transform, while an ordinary non-boundary mesh can become empty
+or hold its group's merged geometry; consumers requiring geometry on each named
+part use off/palette with `instance: 'off'`, because the separate GPU-instancing pass
+can remove named instance nodes. No model-facing input knob was added. This is a planned
+breaking full-mode contract, not an assertion that every named mesh retains geometry.
+
+All 258 off/auto/palette comparisons across the 86 examples match the previous
+`ac8456c` worker bytes under the same Bun/runtime dependencies. That isolates the
+source-level optimizer change; it is not an old-versus-new dependency comparison.
+The provisional Node-versus-Bun comparison differed in last-bit colour factors and
+was replaced by the same-runtime comparison, not treated as an optimizer regression.
+Receipt: `tmp/engine-claim-audit-20261002/off-mode-compat.json`.
+
+Target the behavior-changing work at the planned 0.11 release with migration notes,
+a Breaking changelog entry, one final runtime rebuild and fresh installed-package
+qualification. A decision to ship E1 separately can keep its release scope small.
+
+### E3 Useful outputs and authoring guidance
+
+D23 is output-only: per-anchor draw information and qualified estimates, mirrored
+tangent and coplanar-part observations, plus export/inspection summaries. Keep compact
+render results and tool input schemas within their existing contracts. Estimates must
+count eligible material/layout buckets and locked/split draws, state the passes covered,
+and avoid claiming that material count alone equals draw count.
+
+Apply demonstrated lessons to maintained authoring/QA skills, then qualify fresh setup
+and managed upgrade without overwriting user customizations. Compose-scene guidance
+already landed; its missing dogfood remains work. Run Agy/OpenCode live qualification
+only as an explicitly authorized paid step with a concrete scope; historical approval
+in a dated record is not a new run started by this plan.
+
+Skill freshness checked 3 October: compose-scene was expanded on 1 October in
+#125 and updated again on 2 October in #131 (three entrypoint lines and 87 lines
+of runtime guidance). The composition API reference agrees with current exports
+and defaults. At audit time, all three files in the published website skill archive
+matched main, and the archive matched its discovery digest. The v0.10.0 tag predates
+the #131 additions. A current package dry run includes all three maintained files.
+
+This alignment pass clarifies prototype versus adopted results, renderer support
+versus available host API, shadow observation, and custom-material transforms in
+extra passes. Compose guidance now names the optional scene-kit reversed-depth
+API, its default-off contract, effective unsupported-WebGL fallback and camera
+flags for custom frustum tests. These edits are local and unpublished. The existing Troy workspace has only author/refine/QA installed;
+compose-scene is optional, not a stale installed copy there. When scene authoring
+resumes, qualify a workspace with that optional skill and the chosen harness.
+Authoring/QA references now also describe the rigid-boundary contract and bounded
+draw diagnostics. Compose guidance reflects movable morph-weight observation while
+keeping shader/custom-attribute motion explicit. All three skill validators and
+`check:skills` pass. Existing installed copies remain untouched. Fresh Codex and Claude workspaces now
+pass byte-for-byte skill copying, current-state checks and managed upgrade; unrelated
+files and local customizations survive, and an upstream/local conflict refuses
+atomically. The receipt is `tmp/engine-claim-audit-20261002/workspace-independent-result.json`,
+against final rebuilt runtime identity `58b1b178…`. Paid live dogfood remains separate.
+
+## Existing asset alignment
+
+Extend the existing manifests into a cross-consumer revision matrix; do not recreate
+their inventories or rebake assets without cause. For each consumer record source/material revisions,
+GLB hash, converter/profile, axes/units, pivots/clips, LODs, licenses, preview provenance,
+scene release and site download pins. Identify missing original author sources separately
+from the available sealed binaries; restoring a scene runtime must not require those sources.
+For each final existing-scene delivery, reconcile its compiled runtime/producer identity,
+`site/src/data/scene-packs.json`, the archive pins in `scene-inputs.json`, mirror/upload
+manifests, applicable pack catalog references (including Foundry `scenePack`), and the
+actual served hashes. Asset/model/data digests and accepted source/material revisions
+must remain unchanged unless a separately justified revision is recorded. A new delivery
+label or runtime chunk must not promote asset acceptance or imply a rebake. Recheck the
+site catalog, route inventory and downloads exclude Troy in the final artifact.
+
+The audit checked current tracked catalogs against mirror/upload manifests without
+finding hash/size mismatches for Farm, bridge, vehicles or Foundry. All six shared
+road-vehicle revisions and GLB hashes agree between Vehicles and Foundry. This is
+record consistency, not a fresh binary, visual or public-download qualification.
+
+The 3 October consolidated local matrix is now recorded in
+`tmp/alignment-20261003/asset-revision-matrix.json`, with a compact companion summary.
+It joins 292 revision/resource rows across Farm, bridge/terrain, Road Vehicles,
+Foundry, Troy, gallery and material families. All 113 scene GLB consumer entries and
+109 sealed auxiliary inputs are represented; 788 fresh local byte/hash checks and
+94 catalog-to-manifest comparisons have zero mismatches. All six shared vehicle
+revisions and delivered GLB hashes agree across Vehicles, Golden Gate and Foundry.
+Fresh Foundry GLB headers show zero images in all 62 models and 43 models with LOD
+links. These are byte and declaration checks, not a new appearance or motion review.
+
+The matrix preserves provenance gaps: six shared Foundry road assets resolve to
+verified vehicle editable archives, while the other 56 original authored sources
+and export settings are not linked/restored by the selected models-only records.
+This does not restrict access to the complete sealed binaries. Axes/units and
+pivot/clip declarations retain their recorded scope; functional pivots, world scale
+and animation timing have not been freshly measured. The bridge page explicitly
+identifies its preview and reference images as full-tier views; web/far download
+rows make no exact-image claim, so sharing that family poster is not an alignment
+defect. Historical gallery pictures retain their separate provenance, material
+dependency inventories do not prove visible bindings, and no owner acceptance is
+promoted by the matrix. The 17 current Troy picks and eight older corpus revisions
+remain separate; original terrain survey inputs have not been restored.
+
+| Asset surface | Existing inventory and acceptance boundary |
+| --- | --- |
+| Farm | 23 assets, 10 material records and 30 maps. Exact current asset revisions are owner-accepted; historical whole-pack/performance/publication flags remain false and need reconciliation with dated release evidence, not automatic promotion |
+| Golden Gate bridge/terrain | Three saved bridge tiers (full/web/far), editable/source/archive lineage and sealed terrain derivatives. Standalone bridge acceptance is separate from scene and terrain/performance acceptance |
+| Road Vehicles | Six r4 child revisions, currently 0/6 owner-accepted in the catalog. Earlier accepted r2 parents do not transfer acceptance to lamp/LOD child revisions |
+| Foundry Floor | 62 models: 31 interior, 12 campus, six shared road vehicles, eight plants and five freight. Catalog records 43 LOD models, 55 review candidates and seven accepted assets; models-only download, no textures |
+| Historical gallery | 86 source examples / 80 public archive assets; unvetted historical showcases, not golden outputs. Normal bun run assets rebuilt the current 80 canonical/runtime pairs and recorded their identities; historical images retain separate provenance |
+| Maintained materials | 48 production maps across 16 families, five teaching texture resources and five procedural presets; distinguish these shipped resources from immutable workspace material records |
+| Troy | 16 standalone candidates plus one reference composition and seven material pins; owner-unreviewed, off the public site and deferred for direct Matt discussion. Exact revisions are local regression inputs only |
+
+Use current catalog acceptance rather than a broad statement that every pack is
+approved. A pending owner appearance review is also not proof of an asset defect.
+Preserve historical editable-archive engine pins where deliberate. Foundry has no
+texture consumers in its current catalog, so E1 does not establish any need to rebake it.
+The sealed inputs have now been restored and verified. The local full-optimizer
+corpus checks 224 inputs: all 86 examples, 113 released scene GLBs and 25 pinned Troy
+revisions. All pass world-geometry aggregate, hierarchy/animation/LOD, material-binding,
+deterministic-byte and Khronos-error checks with a stable runtime source/dependency
+identity. Twenty meshopt-compressed Golden Gate terrain files use recorded decoded
+in-memory derivatives, because core IO has no injected decoder; this does not claim
+direct compressed-input optimization support. Original files remain untouched.
+See `scripts/qualify-full-optimizer.mjs` and the local receipt
+`tmp/full-optimizer-corpus/qualified.json`. This gate does not establish appearance.
+
+The site's normal asset build deletes/rebuilds generated gallery output from current
+sources and guards engine identity; its old ignored local cache is not an identified
+production defect. Follow that existing build contract for the next release.
+
+Exercise representative assets from every family through E1/E2. Reuse the 86-example
+corpus and pack fixtures, but do not mistake the existing integration-corpus script for
+full-mode coverage: it renders off and its generic NodeIO does not register Kiln's LOD
+extension. Use the engine's IO and world-space geometry/semantic-boundary assertions,
+not node-for-node equality where a merge intentionally changes topology.
+
+Keep accepted originals immutable. Only demonstrated asset defects produce new asset
+revisions; refresh preview, inventory, archive and site pins together when that happens.
+Recheck material pixels, named interactions, intermediate poses and destination behavior.
+Blender/Unity support stays limited to the tested importer profiles; the extension
+compatibility table is not proof that every consumer implements a feature.
+
+Foundry's pre-existing S3 cross-pass and seam/roof appearance questions need an explicit
+asset/design disposition, then collision/drive verification if changed. D-75 retained
+the campus structures during the optimization cycle; those questions do not authorize
+redesign or block delivery of the already-qualified optimization by themselves.
+They are not engine defects or regressions introduced by #131.
+Troy's existing off-mode revisions are a useful pinned-material regression set, but the
+full-mode replacement alone does not justify migrating them.
+
+### Foundry release scope
+
+Keep the existing interior optimization and the landed campus planting work. All
+62 source/catalog revision and available hash pins agree, including the 24 interior
+LOD replacements. Reuse the existing loading, transport, rig, freight-coupling,
+clearance and LOD tests. Correct the integration test's historical staged/ff2 path
+so restored exact released inputs exercise it rather than produce a fixture skip.
+
+For the new runtime seal, verify the changed paths on both backends while preserving
+simulation inputs, AMR/arm lot ownership, humanoid maintenance visits, deferred
+interior entry/exit, cutaway, walking/driving and articulated freight. These features
+already exist. Old reports about eager interior startup, static transport, missing
+visits or old vehicle lamps are superseded by later implementation and intake.
+
+The S3 through-road remains a separate design choice: the current scene deliberately
+uses driveable stubs and non-driven outer legs. D13 retained the structures. Portal
+versus raised link requires a design decision; roof/link/seam observations do not
+mandate repair. No new Foundry optimization project is justified by this audit.
+
+## Shared scene tooling and correctness
+
+| Work | Completion evidence |
+| --- | --- |
+| Exact inputs on a clean hub | Restore hash-pinned public scene archives using site/scripts/scene-inputs.mjs; rebuild runtimes through scenes/scripts/build-scene.ts without old Windows author paths |
+| Portable browser launch | Shared executable discovery/configuration for Linux and Windows; preserve owned-port behavior; clean temporary profiles on close and launch failure |
+| D19 test coverage | scripts/tests participates in normal scene tests; correct Foundry budget fixture selection; separate exact-input integration gate ensures fixture skips cannot count as qualification; commit Golden Gate count baseline |
+| GG-004 WebP serving | GET, HEAD and range responses use image/webp; existing server access/path checks remain intact |
+| GG-007 shared help/credits | Correct panel sizing, scrolling, stacking, keyboard/focus behavior and narrow/short HUD layouts; retire scene workarounds only after parity |
+| FF-002 nested touch controls | Nested joystick/buttons receive touches without click-through beneath panels; verify all three scene HUDs |
+| D26 shadow motion | Settle automatic detection versus explicit live-caster contract; cover morphs, shader-position motion and custom instance attributes without matrix changes |
+| D26 collision and naming | Assert that optimization preserves collision/interaction results and excludes proxies/hidden duplicates; preserve collision-before-optimization ordering where required |
+| D18 parity | Shared comparer enforces the adopted thin-line budget with repeat-capture noise; individual tools already have a budget and should consume one implementation |
+| D16 timing | Report GPU clock and busy times clock with units, provenance and paired decisions; do not infer equal GPU work from equal frame rate |
+
+The specific GateLeaf versus /leaf/i collider allegation is not reproduced by current
+source: Farm restricts that regex to faceted-tree and selects doors separately. Keep
+the general regression obligation without labeling the current gate broken. The shadow
+cache now observes morph weights and tests the explicit live/invalidation contract
+for motion it cannot observe; it does not promise automatic shader inspection.
+
+GG-007 and FF-002 had scene-local workarounds. Shared bounds/scroll/stacking and
+nested-touch changes pass 72 DOM contracts and all six final public scene/backend
+control scenarios. Integration reproduced and fixed the narrower Foundry campus
+More/Controls overlap; live panel stacking, touch, scrolling and visible focus now
+pass on both backends. The CSS-only repair is separate from geometry optimization.
+FF-003's exact callback-cancellation
+identity handling is already implemented and must not be listed as a new repair.
+
+## Scene changes and performance
+
+| Scene | Work before its next qualified release |
+| --- | --- |
+| Farm | D8 exemption and D20 tooling are implemented; 160 direct, 32 paired, 32 settled-count and pooling/collider checks pass within explicit baseline scope. Four absolute pilot-image failures are shared. Four allocation observations are complete: neither current observation has a natural interval above 40 ms in those two observations, but about 36 ms late GC and unresolved allocation/retainer ownership remain. Balanced walk/tractor and the minimal hero-view pair are collected with raw D41 passes, but both blocks fail strict post-run quiet qualification. No speculative repair or hitch-fixed claim. |
+| Golden Gate | D15 opt-in depth and sky/reflection/bias adaptations, plus D5/D6 exclusions and persistent fog-bank hiding, are implemented and checked on both NVIDIA backends. Reconstructed depth-reference matrices pass 78/78 each; authentic original→final strict flags remain recorded. Missing-clip fallback, final public startup and both-backend controls pass; local `g9-code5` delivery is qualified within the site continuity scope. Owner review follows development goals; publication remains separate. |
+| Golden Gate delivery | D27 verified layout and bounded bootstrap are implemented. Code5 public code is 1,708,928 raw / 512,680 gzip bytes, within unchanged ceilings. First-use native evidence proves contact pipeline variants prepared before ready and reused at the 580 m jump. The focused pairs and unchanged flyover repeat are collected. The repeat passes, but the original candidate flyover D41 miss and block quiet failure remain; preserve the separate historical drive event and defer the larger campaign. Tablet stays minimal. |
+| Foundry Floor | The recorded default matrix passes 120 image comparisons and 56 static X-02 checks; four actual NVIDIA startup probes pass. Local `ff3-review2-code5` retains unchanged model/data hashes and acceptance states. Both-backend controls/lifecycle and first-key ownership checks pass. Focused balanced campus/fab landing/drive runs have raw D41 passes, but strict block quiet qualification fails; owner/release acceptance remains separate. |
+| Farm owner observations | Empty-hand correction, arm borrowing/blending and warming are implemented and have bounded compiled/public evidence. Owner farmer appearance review follows the development goals; sampled checks do not establish every clipping or seated pose. |
+| Golden Gate owner observations | Targeted phase/foam continuity and shorter, softer wakes are implemented with frozen comparisons and public integration checks. Owner water appearance review follows the development goals; physical-device acceptance remains separate. |
+| Shared performance | All 18 intended focused runs are validly collected, raw 17 D41 pass / one fail, with two failed post-run quiet gates. A separate unchanged flyover repeat passes D41/quiet/cleanup but does not erase failures. Overall audit remains FAIL; no further benchmark expansion is justified. Motion3's 108-run preparation is preserved, deferred and unrun. Prior UI3 balanced evidence retains 37 D41 pass/five fail; busy×clock remains a proxy, not code causality or desktop acceptance. |
+
+The tablet remains minimal. Retain Farm variant A and trailer/farmer joint boundaries,
+the live shadow-map sizes already selected, existing tractor kinematics, and the decision
+against hero instancing across placements. The watermill stall came from a rejected
+packed-woodland variant; it is not a demonstrated production defect.
+
+Farm preparation on 3 October preserves the original `draw-after` binary through
+`scenes/packages/farm/dist/original-draw-after/test`: all 42 Farm files / 8,824,115
+bytes match the preserved timing-kit manifest. Its `index-oAhThwe1.js` and the
+candidate use the same r36 asset-pack hash. D-64/D-68 establishes this historical
+comparison baseline; no hash-bound latest scene-runtime acceptance receipt has
+been established. The maintained paired runner can still compare all 32 named/play
+cases against r34, reporting `releaseQualified: false` without that receipt. This
+boundary concerns scene-runtime acceptance, not individual asset-owner review.
+The separate #131 source reconstruction uses current dependencies and is labeled
+diagnostic; it does not replace the preserved binary.
+
+The Farm's direct parity tool now returns a failure status for failed, errored,
+missing or duplicate requested cells, and X-02 records its resolved headed/headless
+launch mode. The focused 32-test tool slice and scene lint pass; no threshold or
+committed count baseline was changed. Final direct images now pass all 160 cases
+(20 views × four tiers × two backends), with 144/144 luminance tiles passing per
+case and at most 18 pixels above the >32-channel repeat-adjusted threshold against
+the unchanged 100-pixel budget. Draws, triangles and pipelines match exactly. This
+does not mean identical images: 60 cases contain nonzero after differences, 48 have
+repeat noise, and 37 trigger the retained-difference heuristic; all satisfy the
+existing gate. Settled X-02 passes all 32 cases and exactly matches all six baseline
+fields: draws, triangles, pipelines, programs, geometries and textures. All report
+41 textures with cached shadows and three agreeing count samples; 39 textures names
+the historical prewarm condition, which this run did not measure.
+
+The source-hashed local receipts and full scope are preserved in
+`scenes/.tmp/alignment-farm/final-counts-and-images-summary.json` and its Markdown
+companion. These direct/X-02 results do not establish B-07 texture pooling,
+optimization or collider equality on their own. Same-phase paired run 02 has now
+completed all 32 cases with no introduced pilot-image failure and clean shutdown.
+Both builds pass absolute pilot parity in 28 cases; `play-house` and
+`play-house-door` fail on both backends in both builds. Those four shared failures
+remain explicit. Run 01 aborted before capture and provides no qualification.
+
+Independent retained-statistics auditing passes the existing r34 B-07 checks in
+all 32 cases for both builds: textures pool from 98 to 29 with 92 shared assignments,
+cached-shadow renderer textures are 41, and ordered collider counts/shapes match
+the frozen r34 fixture (13 colliders, 95,382 static and 14,468 dynamic triangles,
+nine doors, ten door pivots). All six X-02 fields also match exactly in the paired
+captures. Pilot renderer textures vary by view: 39 in 22 cases, 35 in four and 29
+in six, identical across first/repeat samples. Those are observations, not an
+equality requirement against cached-shadow textures. The audit first selected the
+older r33 collider fixture in error; that rejected output is retained, and selecting
+the existing r34 fixture by declared release resolves the mismatch without changing
+any baseline. The historical r34 script already records the farmhouse-only +264
+static triangles.
+
+See `scenes/.tmp/alignment-farm/final-qualification-summary.json` and its Markdown
+companion for the completed, hash-bound rollup. B-07 retains its r34 visible-source
+provenance note: the current rule records 2,195 meshes without requiring equality
+to r33's 2,194. This postprocessing does not re-derive that source delta or compare
+collision soup bytes, and does not replace functional collision/motion tests. The
+missing hash-bound latest scene-runtime owner acceptance receipt keeps
+`releaseQualified: false`; public site interactions and performance are separate
+evidence.
+
+The four historical hero hitches were confirmed at approximately 96.0–97.7 seconds
+into sampling, after a five-second warmup, lasting 66.5–99.6 ms. Fresh serialized
+original/candidate traces on actual NVIDIA WebGPU now reproduce a late 41.7/50.0 ms
+frame at about 106 seconds. Both overlap V8 memory-reducer major GC: 41.739/44.791 ms
+wall time and 35.349/38.918 ms renderer-main-thread CPU. The larger 242/267 ms frames
+occur during trace startup and are instrumentation artifacts. All 58 sampled joint
+transforms, sim state, draws, pipelines and programs remain constant at minimal.
+Both heaps show startup garbage and allocation/collection cycles, then shrink from
+about 275 MB capacity to about 85 MB; post-collection used heap stays in a similar
+65–73 MB range. No obvious new retention path was found in the relevant source diff.
+
+FARM-3's captured desktop mechanism is therefore identified; the allocation/retainer
+cause and any worthwhile narrow repair are not yet measured. Defer that repair
+until they are, preserving GC, scene features, tractor behavior and hitch limits.
+These instrumented values are smaller than the historical tablet spikes but do not
+prove improvement, the same tablet cause or performance acceptance. Local hashed
+receipts and the analysis are under `scenes/.tmp/alignment-farm/`, summarized in
+`trace-findings.md`. Source-built Farm runtime changes require a fresh site build
+and integrated checks, while the unchanged r36 input archive/catalog hashes stay
+pinned.
+
+R8 shadow color targets, reflection cadence changes, output-pass depth removal and
+additional merge layouts are optional follow-ups, not automatic prerequisites. Xclipse
+classification needs actual device strings/performance before promotion. Shared meshopt
+loading is a possible consolidation of Golden Gate's working local loader; static scene
+export is a new contract, and terrain derivative regeneration is distinct from verifying
+the existing delivered tiles. Give these explicit dispositions rather than silently
+turning every historical suggestion into a mandatory rewrite.
+
+The next vegetation cycle (D33) is later exploration, separate from releasing the
+completed pass: per-tree culled woodland packing before LOD, subject to the adopted
+smoothness/GPU-work criteria and visual acceptance. Foundry already has per-tree
+frustum culling and three vegetation LOD levels; D33 does not call for building
+those again. Its older eager-interior-load defect is
+fixed; the next release checks that the existing deferred-loading behavior remains
+intact rather than reopening the original implementation.
+
+## Upgrade policy
+
+Audit direct and optional dependencies, resolved lockfiles and maintainer tooling together.
+Three.js, its types, scene dependencies and renderer build identities must move together;
+renderer changes require GPU smoke and both-backend scene parity before adoption.
+Do not blindly unify the site's TypeScript 6 compiler API consumers with the root/scenes
+TypeScript 7 CLI toolchain. Restore installations with frozen locks before diagnosing
+version incompatibilities; the audit's initial site failures disappeared after doing so.
+
+The AI SDK/provider/OpenRouter/Strands group is one peer-compatibility decision. Inspect
+current upstream constraints before advancing a major; preserve provider prompt-cache
+and usage fields through the existing adapter tests. Node/Bun/npm maintainer pins remain
+separate from consumer engine requirements. Candidate versions and their gate outcomes
+must be recorded before the upgrade commit, not left as unversioned latest commands.
+
+Registry audit on 2 October identified the following candidates. These are proposals,
+not installed upgrades or qualification results; recheck metadata when executing.
+
+Execution update, 3 October: compatible non-renderer candidates below are now
+installed locally with synchronized locks. Registry/peer and lock-diff receipts are
+under `tmp/upgrade1-audit-20261003/`; focused geometry/image (138), provider/MCP (79)
+and site (503, plus two fixture skips) tests pass. Node 22.23.3/npm 12.2.0 are installed
+in an isolated hub prefix, with the old prefix retained; Bun remains 1.4.2. Active
+metadata/workflows/guidance agree. UPGRADE-2 is installed too: Three.js 0.186.1,
+types 0.186.0 and WebGPU 0.6.2 across engine, site, scenes and render service. The
+renderer identity includes the new exact pins; immutable old asset packs retain
+their original producer versions. All six Node bundles are rebuilt. Render-service
+78 tests, real NVIDIA Dawn/Vulkan smoke, display and material conformance pass.
+The integrated core coverage and installed-package gates pass. Both-backend scene
+and final site browser gates also pass within the explicitly recorded binary and
+continuity scopes. Quiet timing and owner/release acceptance remain separate;
+these receipts do not qualify a production deployment.
+
+| Family | Current to candidate | Qualification |
+| --- | --- | --- |
+| glTF Transform packages / manifold | 4.5.0 to 4.5.1 / 3.5.3 to 3.5.4 | Core geometry, IO, kit and regression corpus |
+| MCP client/server | 2.2.0 to 2.3.0 | Protocol handshakes, lazy loading, registry/manifest and installed MCP; ext-apps 2.0.3 remains current |
+| Strands / AI SDK / provider | 1.18.0 to 1.19.0 / 6.0.282 to 6.0.300 / 3.0.16 to 3.0.18 | Compatible peer group, adapter/cache/usage tests; retain existing major families |
+| Bedrock SDK / Google GenAI | 3.1131.0 to 3.1146.0 / 2.22.0 to 2.27.0 | Offline provider adapter contracts |
+| Three.js / native webgpu runtime | 0.186.0 to 0.186.1 / 0.6.1 to 0.6.2 | Coordinate renderer consumers and identities; Three.js types remain 0.186.0 unless a compatible update is published |
+| Canvas / root sharp | 1.0.9 to 1.0.10 / 0.35.4 to 0.35.5 | CPU raster/PNG/cache checks; site already uses sharp 0.35.5 |
+| Biome / Vite / Zod / site parse5 | 2.5.13 to 2.5.15 / 8.3.0 to 8.3.2 / 4.6.4 to 4.6.5 / 8.0.0 to 8.0.1 | Applicable lint/build/schema/HTML checks and scene/site bundle budgets |
+| Maintainer Node / npm / Bun | 22.23.2 to 22.23.3 / 12.0.2 to 12.2.0 / retain 1.4.2 | Pin files, CI, isolated hub runtime and workspace launchers; keep consumer engines separate |
+
+[Strands 1.19.0 metadata](https://registry.npmjs.org/@strands-agents%2fsdk/1.19.0)
+still requires provider 3, OpenAI 6 and the older Anthropic peer family. AI SDK 7,
+provider 4, OpenRouter 3, OpenAI 7 and the newest Anthropic family cannot be assumed
+compatible. OpenRouter 2.10 and OpenAI 6.49 are compatible-family candidates to assess
+with their exact patch releases. [Astro checker 0.9.10 metadata](https://registry.npmjs.org/@astrojs%2fcheck/0.9.10)
+supports TypeScript 5/6, so the site's 6.0.3 pin is intentional. Inspect actual bundle
+graphs before overriding older transitive Three.js copies; a lockfile entry alone
+does not prove duplicated shipped code.
+
+## Cloudflare delivery
+
+Keep the existing hosting architecture: Cloudflare Pages direct upload to project
+kilnstudio, production branch production, domain kilnstudio.tools; public versioned
+assets on kiln-assets through assets.kilnstudio.tools. GitHub main is the source branch;
+the Website workflow validates and deploys nothing. No hosting-provider migration is needed.
+
+The hub already has valid OAuth and Pages write scope; project and R2 bucket reads succeed.
+Initial OAuth verification used Wrangler 4.147.0 under Node 22.23.2 through an
+exact-version npm invocation; current maintainer pins are Node 22.23.3/npm 12.2.0. Do not
+refresh unrelated OAuth scopes just to satisfy a warning when required operations work.
+If required access expires, use browser OAuth; never copy token contents into docs or logs.
+
+The deployment work now has these local results and remaining boundaries:
+
+1. The portable Node entrypoint and PowerShell compatibility wrapper retain clean-tree,
+ exact-commit, packs-enabled and file-limit checks with an exact Wrangler pin.
+ Refusal tests pass; the real dry run correctly refuses the dirty candidate checkout.
+2. The preflight verifies the artifact manifest and every file immediately before
+ upload. The read-only upload summary now validates all three manifests, including
+ scene archives: 484 files, zero problems. No upload has run.
+3. The prior code3 launch artifact passes site, static, asset, HTTP, all six hardware
+ control scenarios, all nine lifecycle/viewer/failure areas and fresh accessibility.
+ New changed scene runtimes require affected-surface requalification on their exact
+ final artifact; prior results carry forward only with explicit dependency identity. Default
+ Website CI uses packs=0 and has no browser acceptance; it is not the full deployment gate.
+4. Local Golden Gate `g9-code3` and Foundry `ff3-review2-code3` archive/runtime pins are
+ restored and staged through the normal build path, with the Foundry gallery's pack
+ reference aligned. New delivery metadata and dependency notices preserve all model/data
+ bytes, SHA256SUMS and saved source revisions. Old public objects remain unchanged.
+5. Integrated viewer/scene controls, touch, failure/retry, entry/exit/teardown and
+ loading checks pass and are bound to the final artifact by exact product-byte
+ continuity. Preserve those receipts and requalify affected flows if product bytes
+ change; static accessibility and hashes alone do not replace interaction or timing evidence.
+6. After the reviewed release is authorized for production, upload required new R2
+ objects and verify public hashes, deploy those exact Pages bytes, then check public
+ build-info, artifact/scene hashes, asset downloads and real scene flows. Record the
+ deployment ID and rollback target. Authentication alone is not a deployment.
+
+Current latest production is b1ac6ee and must not be relabeled as current source ac8456c.
+The former PowerShell-only operational gap on Linux is closed by the tested Node
+wrapper. Local seals and technical checks do not claim a clean production artifact,
+owner acceptance or deployment; no upload or commit has occurred.
+
+## Implementation sequence and exit
+
+1. Reconcile current docs and request ledgers; establish exact baselines, portable tools,
+ source/material/asset lineage and Cloudflare preflight. Preserve the existing local changes.
+2. Land E1, then compatible dependency updates in small tested groups. Re-establish
+ renderer and bundle baselines after upgrades that change them.
+3. Resolve E2 policy questions and complete the optimizer, rebuild compatibility,
+ output/skill work and installed-package qualification. Run core regression assets here.
+4. Complete shared correctness and adopted scene follow-ups; diagnose measured stalls.
+ Keep the next vegetation experiment separate from shipping the completed pass;
+ qualify it using the agreed look/performance gates if pursued in this cycle.
+5. Rebaseline only accepted changes, prepare immutable local delivery candidates and
+ validate the exact final site with aligned scene, asset, archive and download pins.
+ Retain the reviewed Cloudflare preflight/rollback procedure; perform no release action.
+6. Report stabilization readiness and the remaining explicit boundaries to Matt. Any
+ Troy discussion is a later direct conversation, not an automatic next implementation
+ phase, asset task or publication step.
+
+Readiness requires evidence per changed surface and a bounded final review:
+
+- Review behavior, implementation and cycle intent adversarially; close adopted local
+ requirements with reproducible commands, exact source/build/dependency/input hashes
+ and applicable focused, full offline, installed-package/workspace and browser gates.
+ Treat aggregate counts as summaries, not proof of unexercised behavior.
+- Qualify the exact final scene/site artifacts, changed controls/lifecycle paths and
+ required quiet-host comparisons. Preserve baseline failures and prove any reuse by
+ byte/dependency identity; do not turn missing or skipped evidence into a pass.
+- Reconcile existing scene/asset/source/material/acceptance/download records across
+ catalogs, sealed packs, archives, mirrors and served bytes. Preserve old immutable
+ objects and keep Troy absent from public routes, assets and downloads.
+- Deliver a known-issue inventory with reproduction/evidence, affected builds, impact,
+ confidence and disposition, including explicit failures, skips, unverified areas,
+ risks and blockers. Missing physical-device, owner visual, importer or paid-dogfood
+ evidence stays separate from local implementation and qualification requirements.
+- State the release boundary: no commit, push, upload, deployment or publication is
+ authorized. Optional ideas need a decision; Troy brainstorming supplies no tasks.
+ These reports establish local readiness, not owner acceptance or release approval.
+
+## Evidence and records
+
+- [Cycle close and adversarial conditions](2026-10-02-cycle-close.md)
+- [Engine handoff](../reviews/2026-10-02-draw-optimization-engine-handoff.md)
+- [Draw optimization review](../reviews/2026-10-02-draw-optimization.md)
+- [Scene decisions](../../scenes/DECISIONS.md) and [kit requests](../../scenes/KIT-REQUESTS.md)
+- [Cloudflare deployment contract](../../site/DEPLOYMENT.md)
+- [Importer qualification limits](../engine-handoff.md)
+- [Troy handoff](../../packs/troy/HANDOFF.md)
+
+The local hub index is ~/X/START-HERE.md. Preserved raw evidence is in the separate
+kiln-draw-optimization worktree's ignored tmp/drawcalls and scenes/evidence folders;
+reproduction scripts from this audit are under this checkout's ignored
+tmp/engine-claim-audit-20261002. Historical records retain their dates and acceptance limits.
+
+## Integrated candidate validation, 3 October
+
+The original timing kit was subsequently found outside `X`, at
+`~/kiln-hub/draw-base-vs-draw-after/`. All **505 files / 74,132,012 bytes** match
+its manifest (SHA-256 `ecd9a3cce2001b9ae6e08375e7384eec4e751b0c363198220281baa83696ab5d`).
+Its original optimized Farm, Golden Gate and Foundry pack hashes match the current
+candidate. The manifest names source commit `75751ec` and the build records say
+working tree; these are preserved original binaries, not a claim of a clean #131
+build. They allow actual old-binary comparisons, while reconstructed #131 builds
+using current dependencies isolate source changes. Neither provenance alone
+confers owner appearance acceptance.
+
+The final root coverage run passes **3,187 tests / 3 platform skips / 0 failures**.
+The maintained gate reports **95.11% functions / 92.32% lines**, above the unchanged
+94.00% / 92.10% thresholds. Typecheck and lint pass. The first full run found the
+architecture conformance fixture hash still pinned to its old full-to-palette
+assertion. The title/mode expectation now reflects rigid full mode; all architecture
+QA assertions remain. Its conformance receipt was refreshed with the actual CPU
+renderer identity and date, then the 70 focused checks and full coverage passed.
+No acceptance threshold or rule behavior was weakened.
+
+The final scope review removed the unused importer-profile experiment and its
+12 tests from the candidate; neither the rigid optimizer nor D23 calls it.
+Its source remains in the raw worktree and local audit evidence. Importer profiles
+were not an adopted integration requirement and are not newly qualified here.
+The final coverage run above followed that removal; earlier 3,199-pass logs
+describe the larger provisional scope.
+
+All six Node bundles carry `sha256:58b1b1784701b3b04bac6e7a429ea5dd9d1aeac646e5189bbb21f251e9f1a295`.
+The final local package smoke passes installation without development dependencies,
+Node CLI/MCP, CSG/UV WASM, CPU PNG, source-store persistence, capture reuse and
+textured subprocess export. Fresh Codex/Claude workspace copying and managed
+upgrade/conflict preservation also pass against this identity. These are local
+checks of an unreleased candidate; package publication remains deferred.
+
+The upgraded-dependency corpus passes **199 example/released-asset inputs plus 25
+Troy revisions**, with deterministic bytes and preserved structure. Its two receipts
+are `tmp/full-optimizer-corpus/renderer-upgrade-qualified.json` and
+`renderer-upgrade-troy-qualified.json`. They record identity `dd25c75c…`, before the
+architecture receipt-only refresh above; optimizer and geometry code are unchanged.
+The subsequent unused-profile removal also changes the source identity without
+changing the optimizer, geometry code or any reachable runtime behavior.
+Twenty compressed terrain inputs remain explicitly decoded in-memory derivatives,
+not a claim of native compressed-input support.
+
+Renderer checks pass: 78 offline tests, real NVIDIA Dawn/Vulkan smoke, calibrated
+display output and material-channel conformance. The separate headed browser probe
+confirms NVIDIA WebGPU and WebGL2, with owned profile removal; headless Chrome 150
+uses SwiftShader here. No performance comparison or scene pixel acceptance is
+inferred from that capability probe. The exact released-input gate passes 22 tests
+with zero skips. The normal site gallery pipeline rebuilt 80 historical assets
+(1,472,955 triangles, 34.8 MB GLB) without changing accepted Commons revisions.
+
+Foundry Floor's authentic preserved optimized binary→`alignment-final` comparison
+passes **120/120 default cases**: 80 WebGPU views across all four tiers and 40
+WebGL2 views at minimal/high, each at 1280×720 with the unchanged 100-pixel
+thin-line budget. All 80 WebGPU captures are pixel-identical. WebGL2 has 36 exact
+matches; the other four fab views differ in only one to seven pixels by one
+channel level. Every recorded before/after backend matches, with no browser
+messages. This fresh default regression matrix is distinct from the earlier
+**160-case optimization qualification**: it does not repeat the 40
+`plantingShared=false` isolation cases or relabel their historical evidence.
+
+Foundry X-02 passes all **56 judged static rows**, exactly matching the committed
+optimized reference in draws, triangles, bound pipelines, pipeline cache,
+programs, geometries and textures. All 60 fixtures are present and stable, GPU
+encoder and JS draw counts agree, and raw records identify the final chunks with
+unmixed 1920×1080/shared-page WebGPU conditions. Four drive rows remain
+informational under the existing rule; minimal drive differs by 136 fewer
+triangles. There are no errors or messages. A separate four-start probe confirms
+actual NVIDIA WebGPU Turing and WebGL2 ANGLE GTX 1660 Ti for both exact builds,
+their expected entry chunks, one ready event each, no fallback and owned-profile
+cleanup. The parity runner did not retain repeat-backend or per-row adapter
+identity; this bounded startup evidence does not invent those missing fields.
+Receipts are summarized in `scenes/.tmp/alignment-ff/evidence-summary.md`.
+
+The local Foundry delivery pin is now `ff3-review2-code1`. Changes to its asset
+archive are limited to delivery metadata: `assets/SHA256SUMS` and all model/data
+hashes remain unchanged, as do the source catalog's 55 review-candidate and seven
+accepted asset states. The local launch candidate containing this pin passes
+517 site tests with two historical skips, plus initial dependency-closure/bundle
+budget and served runtime/asset-hash checks. The integrated FF3 site interaction
+flow remains pending. These local checks do not publish the delivery or confer
+owner appearance acceptance.
+
+Golden Gate's static comparisons now cover both NVIDIA backends at 1280×720:
+78 views per matrix across two tiers, three presets and thirteen cameras. The
+same-dependency #131 source control retains 17 strict WebGPU flags and 11 WebGL2
+flags; all 78 luminance checks pass on each backend. Rebuilding the preserved D15
+prototype source under current dependencies gives **78/78 strict passes on each
+backend**, with no pixels over the 32-channel threshold. This is a reconstructed
+reference, not a relabeled historical executable or owner appearance acceptance.
+
+Direct comparisons of the authentic preserved optimized binary to the final
+`alignment-final` build cover the Three 0.186.0→0.186.1 and final KIT-2 CSS changes.
+They retain exactly the same 17 WebGPU and 11 WebGL2 strict flags as the source
+controls, with no additional flagged cases and all luminance gates passing.
+The WebGPU list matches the 17 historical D15 cases. Two WebGL2 flags,
+High/Day `drive-nb-0` and `far-low`, are outside that historical WebGPU list;
+they pass against the reconstructed depth reference and remain separately named.
+All gates keep the default 100-pixel budget beyond repeat noise; flags are not
+converted to passes. Camera and bridge draw/proxy states agree in all matrices.
+GG-2 combines this visual/content evidence with regression-tested dynamic-layer
+exclusion and persistent fog hiding; these matrices do not measure a new per-pass
+reflection draw saving. Evidence is in `scenes/.tmp/alignment-gg/parity-{webgpu,webgl2}/`,
+`parity-d15-{webgpu,webgl2}/` and `parity-original-{webgpu,webgl2}/`.
+
+The final Golden Gate public build is **1,706,652 raw / 511,859 gzip bytes**, below
+the fixed 1,796,415 / 530,691 ceilings. Its producer receipts verify chunk hashes
+and actual current dependencies; the immutable g9 asset pack remains unchanged.
+Final startup probes confirm verified layout loading, one ready event, the public
+surface without test hooks, and supported reversed depth on NVIDIA WebGPU/WebGL2.
+An injected missing `EXT_clip_control` yields the expected warning, standard depth
+and standard offset signs; two fallback views pass against the #131 standard-depth
+control. Six supplemental final-build views also pass. Receipts and their bounded
+scope are recorded in `scenes/.tmp/alignment-gg/evidence-summary.md`. Flyover traces
+and quiet-host performance remain separate from these static checks.
+
+A serialized diagnostic flight trace on each Golden Gate build observed the
+natural postcard-to-tower transition at 17.2 ms in the original and 15.3 ms in the
+final build. The historical large transition hitch did not reproduce in this
+bounded run. Both builds show slower cold postcard starts and new pipelines;
+repeated starts peak at 12.5 / 11.5 ms. Separate final-build mid-path pauses are
+predominantly off-CPU: representative render callbacks take 95.22 / 6.06 ms and
+110.39 / 9.30 ms of wall / thread CPU time. This does not attribute the remaining
+wall time to a scene algorithm, GC or a specific external cause. CPU profiling
+and per-frame observation make these diagnostic receipts, not quiet performance
+acceptance. No speculative precompile or transition repair was added. The receipt
+is `scenes/.tmp/alignment-gg/flight-diagnostic-comparison.json`; remaining workload
+measurements and tablet-tier decisions stay separate.
+
+The preserved intermediate launch-mode site build passed 513 site tests (two historical
+fixture skips), checks 70 Astro files without diagnostics and emits 198 pages.
+All 458 public mirror pins verify. Its local HTTP review passes 116 mapped
+downloads, 520 linked site files, 89 mapped pages, three checksum endpoints and
+all three scenes' served runtime/pack hashes. Artifact inventory SHA-256 is
+`836c4a5c030a16bf3cbedd5f593f57f7ade3dc11d082c3e020ad35ed6a88ae32`.
+That build retained the existing Golden Gate g9 and Foundry ff3-review2 seals;
+its receipts remain bound to that earlier artifact in
+`site/.cache/alignment-preliminary/`.
+
+The final local launch artifact is
+`f0e49fbc557acaecef1eff8044459f4b4bc57996d4e2b1f88f88bb00783fb60a`:
+**2,728 inventoried files / 199,968,715 bytes**, with 198 Astro pages and 200 static
+HTML documents. It carries local `g9-code1` and `ff3-review2-code1` delivery pins;
+the original asset/source revisions, model/data bytes and SHA256SUMS remain unchanged.
+All **517 site tests pass / two historical skips**, all 70 Astro files check clean,
+and static, asset and local HTTP verification pass: 116 mapped downloads, 520 linked
+files, 89 mapped pages and three checksum endpoints. All three served scene hashes
+and copy/fallback checks pass. Final migration/runtime wording and the three updated
+skill references are included; fresh-workspace and skill-package checks pass. The
+final private-data scan has zero findings. The all-manifest upload summary contains
+484 files and zero problems.
+
+Final static accessibility covers **396 route/width checks / 44 keyboard tours /
+zero problems**. The final build freshly checks four widths on `/docs/migration/`
+and `/docs/runtime/`; 196 unchanged routes reuse 392 widths and all 44 tours from
+artifact `42a41439670a415fa2f3cd204fbd4af61f5ca68576e5369b5431f9d15f739b6e`.
+Every final artifact was rehashed, and reused HTML, shared JS/CSS/fonts and loaded
+display resources are byte-identical, with unchanged browser, axe and verifier.
+The final receipt is `site/.cache/alignment-release-docs/accessibility/combined.json`;
+its proof is `proof/a11y-reuse-proposal.json` under the same directory. The preserved
+prior receipt under `site/.cache/alignment-before-migration/` retains its own proof:
+60 routes freshly ran 120 widths and eight tours, while 138 routes reused 276 widths
+and 36 tours from the preliminary artifact. This chain is static load/axe/overflow/Tab
+evidence; integrated scene/viewer controls, touch and failure flows remain pending, as does
+quiet performance qualification. The deployment dry run correctly refuses the dirty
+tree. No upload or commit has occurred, and production retains its old delivery IDs.
+
+Logs remain local under `/tmp/kiln-alignment-*`; package/skill/corpus receipts name
+the actual build identity. Integrated scene/viewer flows, quiet-host timing and
+clean production release acceptance remain in progress; local delivery seals and
+the final launch-site artifact are prepared.
+
+The maintained timing tools now read the Node pin from `scenes/toolchain.json`
+when generating a kit and require a complete readable GPU sample window for hub,
+tablet and PC quiet checks. Missing, nonfinite or outside-0–100-percent samples
+cannot be treated as idle; existing load thresholds are unchanged. Focused
+test-first regressions pass **19 tests / 164 assertions** across
+`timing-kit.test.ts`, `timing-ab.test.ts` and `gpu-work.test.ts`. The subsequent
+complete `bun test scripts/tests` gate in `scenes/` passes **93 tests / 540
+assertions / 0 failures** across 20 files, recorded in
+`/tmp/kiln-scenes-final-scripts-complete.log`. The earlier
+`/tmp/kiln-scenes-final-script-gate.log` retains its 89-test / 521-assertion result.
+The current runner was rebundled; immutable historical kits were not edited.
+These checks qualify tool behavior, not the remaining device-performance cells.
+
+## UI2 rebuild checkpoint, 3 October
+
+This is a later candidate than the `alignment-final` / code1 / `f0e49fbc…`
+receipts above. Those full matrices remain tied to their original binaries. The
+five UI2 builds preserve all original asset packs and 296 current module source
+files from the prebuild snapshot. Eight fresh image sanity cells pass the unchanged
+D18 thresholds; GG actual NVIDIA WebGPU/WebGL2/missing-clip startup probes pass.
+Farm public code independently reproduces exactly at `6b537900…` with the same
+producer/module inventory; only the two recorded UI source files differ from its
+prior source receipt. The portable scene gate passes 678 tests / 18 historical
+skips; the exact released-input gate passes 22 / 0 skips.
+
+New local archives `g9-code2` and `ff3-review2-code2` reproduce byte for byte and
+preserve all saved revisions and sealed payloads. The separate code2 matrix retains
+292 records / 882 checks, plus all 222 active sealed dist files. GG code measures
+1,706,950 raw / 511,965 gzip bytes; Foundry's verified initial closure measures
+1,532,188 / 448,714. Both retain their unchanged ceilings.
+
+Site artifact `28f84720ad3eb8a1a0c04010772f253c36bd65873d819c90c294916fa033557f`
+has 2,728 inventoried files / 199,993,239 bytes. Its 538 site tests / two historical
+skips, static/assets checks, 116 downloads, 520 linked files, 89 mapped HTML pages,
+three checksum endpoints and all three served runtime seals pass. Its upload set
+has 484 files and zero problems; nothing was uploaded. This artifact contains the
+44 px topbar and Explore layout reservation, awaiting final width checks.
+
+The new public control gate passes Golden Gate WebGPU, including panel focus,
+touch steering, exit and disposal. Foundry's narrow campus toolbar reproduces a
+separate issue: reopening More leaves Credits behind the open help panel. The
+failed run and hit-test/screenshot evidence are preserved under
+`site/.cache/alignment-ui2/flows/`; a focused shared stacking fix and new exact
+runtime qualification are required. Do not label UI2 fully qualified.
+
+A strict accessibility continuation proof refuses reuse because emitted shared
+CSS differs outside its two approved normalization rules. After the final HUD
+fix, run all 198 routes / 396 widths and 44 keyboard tours fresh. Quiet-host
+performance also remains unmeasured: 18 cells / 108 minutes are prepared, but the
+candidate kit must follow the final runtime hashes. Owner/device/clean-release
+boundaries and deferred Troy remain unchanged.
+
+## UI3 menu fix checkpoint, 3 October
+
+The Foundry menu defect is fixed with one shared CSS stacking rule. All 72 HUD
+browser contracts pass, including four campus touch/hit-test cases; UI3 public
+Foundry panels now pass touch scrolling, simultaneous help/credits, Escape and
+visible focus restoration. Golden Gate WebGPU controls also pass. All 14 compiled
+JS chunks across five builds become byte-identical to UI2 after removing only the
+exact 207-byte CSS addition and mapping generated sibling chunk filenames. Farm's
+independent public rebuild is also exact and requires only that CSS removal to
+match UI2. No geometry, simulation, asset or input behavior changed in this slice.
+
+Current local delivery pins are `g9-code3` and `ff3-review2-code3`. Their archives
+reproduce exactly; the distinct code3 matrix preserves all 292 records / 882 checks
+and 222 active sealed files. The launch artifact is
+`d2659dfbb7adfcb8f132b7470aa8026b21784944aa0dcc3b5ab5254878a567c0`
+(2,728 inventoried files / 199,993,860 bytes). Its 539 site tests, static/assets,
+HTTP downloads/links/checksums and all three served runtime checks pass.
+
+The live control run stopped at an over-specific freight observation: neither
+semi bucket is visible within 15 seconds of a portrait Arrival view. A read-only
+four-view probe confirms actual camera transitions, ordinary traffic and delivery
+vans; distant Campus/One pair views cull traffic by design. This is not evidence
+that freight simulation is broken. Establish a useful public camera/visibility
+setup, then finish all six scenarios and the other final browser gates. Strict
+accessibility proof requires all 198 routes / 396 widths and 44 tours fresh. The
+18-cell quiet timing kit now targets UI3; actual measurements and final package/
+requirement audits remain. No upload, commit or release approval has occurred.
+
+## UI4 public controls checkpoint, 3 October
+
+The final launch artifact is
+`70ccf7d40c845c3d8d2dcd243db9d512b216b0a8f6f077069c0401db5d8688ff`:
+2,728 inventoried files / 199,993,860 bytes. It retains the same compiled code3
+scene bytes and asset inputs. The site suite passes 542 tests, with two historical
+skips, zero failures and 7,560 assertions across 75 files. The preceding UI4
+artifact `627a7f56…` passes the width gate with zero issues and all 12 hidden
+Explore reservation checks. The final rebuild differs only in its source-files
+receipt; that byte binding is recorded separately from the browser observations.
+
+All six public control scenarios now pass on actual hardware WebGPU and WebGL2
+for Golden Gate, Foundry and Farm. They include panel stacking, touch, scrolling
+and visible focus restoration; Golden Gate driving; Foundry interior walking and
+return, driving, and freight pause/public-camera scan/resume; and actual Farm
+joystick movement. The exact-artifact receipt is
+`site/.cache/alignment-ui4-final/live-controls/controls.json`, with execution log
+`/tmp/kiln-site-ui4-final-live-controls.log`.
+
+The earlier freight failures tested unsuitable visibility and camera-height
+assumptions. The corrected verifier clears the existing campus floor constraint
+through public camera gestures, finds visible freight and observes motion after
+Resume. No production traffic defect or runtime fix was established; the failed
+receipts remain diagnostic records, and this check does not claim individual
+trailer-joint alignment or owner appearance acceptance.
+
+Eight remaining lifecycle/viewer/failure jobs are running. Fresh accessibility
+still requires 198 routes / 396 widths and 44 keyboard tours; the 18-cell quiet
+timing campaign remains unmeasured. Final documentation, package-byte and evidence
+binding follow those results. Historical image matrices keep their original
+binary scope. Production remains unchanged; no upload, commit or release approval
+has occurred.
+
+## Final lifecycle checkpoint, 3 October
+
+The current artifact is
+`a4d1e2d0023d9ec17f8063f53b04568e4aecd2a5958c9413d696e254e7f30b19`
+(2,728 files / 199,993,860 bytes). All nine flow areas pass: eight new executions
+on `70ccf7d4…` plus the prior `627a7f56…` width gate. All six public control
+scenarios / 34 checks pass on actual hardware WebGPU and WebGL2. The receipt at
+`site/.cache/alignment-site-qualified/lifecycle-continuity.json` rehashes every
+file and proves all 2,727 product files unchanged, preserving the original browser
+receipt identities. Only `source-files.json` differs after synchronizing the
+fullscreen verifier; no production code changed. The 12 hidden Explore checks
+carry forward through that same proof. Eleven copy/fallback checks pass freshly
+on the final artifact; the site suite remains 542 passes, two historical skips,
+zero failures and 7,560 assertions across 75 files.
+
+Fresh accessibility passes all 198 routes / 396 widths, 44 keyboard tours and
+2,138 stops, with zero problems and no reused routes. The exact final-artifact
+receipt is `site/.cache/alignment-site-qualified/accessibility/combined.json`.
+All local site browser gates pass. The 18-cell / 108-minute quiet timing campaign
+and final documentation/package/evidence binding remain pending. Historical image
+and browser evidence retains its original scope.
+
+The authenticated Cloudflare deployment list checked at approximately 10:35 UTC
+still identifies production `33c716c7-16e5-46c6-93bf-f2260f0082be` / `b1ac6ee`.
+A subsequent Node-fetch check at 10:50 UTC freshly verifies public build metadata
+and manifest `5ecbbe7673348989a85ef2beb2613e5f27f92c9449cec67690f0791288ab7d15`,
+still with old `g9` / `ff3-review2` pins. Its receipt is
+`tmp/alignment-20261003/production-recheck-20261003T103132Z/node-public-receipt.json`.
+The earlier Python-client 403 attempt remains preserved as a separate attempt.
+No upload, commit or deployment has occurred.
+
+## Quiet preflight checkpoint, 3 October
+
+Implemented changes and the local site browser gates pass within their recorded
+scopes. The prepared 18-cell / 108-minute timing campaign has not started. Its
+first balanced-block quiet preflight at 10:53 UTC failed: CPU mean 10.76%, CPU
+max 18.68%, GPU max 34%; the screen was unlocked. The unchanged hub limits are
+mean CPU below 5%, max CPU below 12% and max GPU at most 3%. The receipt is
+`scenes/.tmp/alignment-perf/quiet-candidate-ui3-balanced-before.json`.
+
+Owned browsers and servers were closed, but desktop compositor and ChatGPT
+activity remained. The next step requires an idle host, potentially with Codex
+minimized by the user; no user process was stopped. This failed environmental
+precondition is not a scene regression or an authorization/access failure.
+Preserve the receipt and retry with a new filename when the host is quiet. Timing
+and final evidence review remain open; no performance acceptance is inferred from
+the completed implementation, package or browser gates.
+
+The final current-prose reconciliation also corrects the site README's qualification
+pointer and deployment runbook's code3 object examples. Rebuilding retains artifact
+`a4d1e2d0023d9ec17f8063f53b04568e4aecd2a5958c9413d696e254e7f30b19`;
+the build receipt records the new build time and source diff without changing the
+inventoried product bytes. The current package-byte receipt is recorded separately
+at `tmp/alignment-20261003/package-final-prose/receipt.json`: it compares shipped
+members with the frozen source and binds the six runtime bundles to their already
+qualified `58b1b178…` identity. This bounded packing check does not rebuild runtime,
+repeat installed-package smoke, or confer timing/release acceptance.
+
+
+## Balanced timing checkpoint, 3 October
+
+The idle-host blocker is resolved without relaxing quiet limits. Before, internal
+and after checks pass. The balanced block completes **7 of 18 cells / 42 of 108
+one-minute runs** on the exact preserved optimized `draw-after` and UI3 candidate
+binaries. Collection is complete and valid; performance is not an overall pass.
+D41 records **37 pass / 5 fail**. All 12 Farm and 18 Foundry balanced runs pass
+raw D41. The six static Foundry fab runs have absent exterior pose fields under
+the expected schema; readiness is enforced, but interior camera coordinates were
+not independently retained. This is a scope limit, not a hidden failed pose check.
+
+All six Golden Gate flyover runs have their longest frame about 25 s into sampling,
+near 30 s of scene time after the five-second warmup. Both builds share the peak:
+A 50.0/66.6/58.4 ms; B 58.2/50.1/49.9 ms. Four exceed D41. Candidate drive pair2
+has a separate 58.3 ms event about 4.408 s into sampling. These five failures stay
+failed; the earlier instrumented traces retain their different workload/startup
+scope. Exact tracing must distinguish the shared transition from the separate
+drive event before assigning cause or changing behavior.
+
+Independent arithmetic over all 462 readable GPU polls reproduces the recorded
+same-sample busy×clock summaries. Flyover rises +3.45%, +0.05% and +2.91% across
+the three pairs. Mean busy rises about 1.18/0.09/1.27 points while mean clocks
+change +13.64/−2.73/0 MHz; higher clocks alone do not explain the observed signal.
+This is a small global activity-proxy increase, not proof of code causality, energy
+or per-frame GPU time. Frame p50/p95 remain 8.3/8.4 ms at the locked display rate.
+Coarse polling, thermal/clock history and compositor activity limit attribution.
+No desktop acceptance margin or tablet D-65 adoption threshold is applied. The
+historical +2–4 busy-point observation used different cells and draw-base→draw-after;
+this block does not directly repeat that comparison.
+
+Seven economy cells and four orbit cells remain. The owner has now reported Farm
+arms clipping/snapping over milliseconds, with an empty-hand walking grip and
+wrist twist despite no pitchfork; and Golden Gate pier wakes that look too large/
+distinct, plus water texture/orientation clipping or snapping at high orbit angles.
+These are owner observations, not yet independent reproductions or assigned causes.
+Hold the remaining timing blocks until the targeted diagnoses and fixes settle,
+then measure the exact resulting candidate. Begin with pose/attachment/transition
+and camera/water behavior; do not wholesale-rebake assets or assume an asset defect.
+Prior UI3 timing keeps its original candidate scope. Raw results are preserved under
+`scenes/evidence/perf/hub-alignment-2026-10-03/candidate-ui3-balanced/`; independent
+42-run calculations and scope are in
+`tmp/alignment-20261003/balanced-performance-review/review.json`. Earlier failed
+quiet attempts are retained. Existing core, site and package qualifications remain
+valid within their recorded checkpoint scopes; the previous package tar does not
+bind these newly edited status docs. A new package binding is pending. No upload,
+deployment, blanket timing pass or release approval is claimed.
+
+
+## Targeted motion and touch checkpoint, 3 October
+
+The owner clarified that the gripping/clipping farmer was seen in a local preview;
+its exact build is unknown. The observation was not dismissed as an old build.
+The reported mobile behavior also had a reproduced cause: collision-shortened camera
+position fed back into the intended orbit distance.
+
+Farm now applies its empty-hand pose after every rendered mixer update, borrows a
+mirrored saved relaxed lower arm without changing GLB bytes, blends Idle/Walk over
+150 ms, and warms the explicitly registered hidden pose and shadow variants. CPU
+regressions cover zero/substep frames, interrupted blends, overview/seat restoration
+and original buffers; the measured shoulder release jump falls 13.13→1.05 degrees
+and the hip step 24.91→2.54 degrees in the exact r36 sequence. Actual public
+entry/start-stop/reentry checks pass on WebGPU and WebGL2 with 345/506 rendered
+frames retaining correct hand state and restoring overview. Pipeline counts remain
+54→54 / 21→21 and program counts 40→40. The WebGPU API observer records no new
+first-use pipeline events; its empty event list is not evidence about WebGL2 calls.
+Receipts are `scenes/.tmp/alignment-motion/farmer-controls-motion2-{webgpu,webgl2}/receipt.json`.
+These checks do not prove every clipping pose or confer owner appearance acceptance.
+
+FARM-5 separates intended camera pose from collision projection. Actual emulated
+mobile touch passes on both backends: orbit retains 4.697 m and pinch changes
+9.86→1.943 m, with the actor stationary. Receipts are
+`scenes/.tmp/alignment-motion/farmer-touch-motion2-{webgpu,webgl2}/receipt.json`;
+physical-device qualification remains separate. The later Foundry first-key failure
+was diagnosed as a shared joystick cleanup defect, repaired and qualified in motion3
+as recorded below; it was not a pause-order verifier issue.
+
+Golden Gate phase/foam origin fixes and shorter, softer wakes are implemented.
+Actual shader graph tests and frozen origin-boundary comparisons cover all three
+tiers on both backends; the previously recorded crossing and appearance evidence
+keeps its scope. Contact-shadow side prewarming is now integrated before readiness,
+with abort/failure disposal and retained cache ownership covered by 39 focused tests.
+The production integration check now passes: both native side variants settle before
+first ready, remain cached, and actual contact draws at the natural 580 m jump reuse
+them with no new pipeline or shader module. The exact receipt is
+`scenes/.tmp/alignment-gg/balanced-contact-first-use-motion2-01/summary.json`.
+This startup/first-use proof is not a D41 performance pass.
+Earlier unsuccessful single-variant and strict index-identity probes remain preserved.
+Normal Uint16→Uint32 promotion retains the same six indices. None of these diagnostic
+probes converts the five preserved balanced D41 failures into passes.
+
+The full portable scene gate passes 711 tests, with 18 historical skips and zero
+failures across 123 files in 49.82 s (`/tmp/kiln-scenes-motion2-test.log`); typecheck
+and lint pass after all three slices. Current builds and receipts are under
+`scenes/.tmp/alignment-motion/` and `scenes/.tmp/alignment-gg/`; the root qualification
+index records 206 checks at this checkpoint. Prior code3 site `a4d1e2d0…`, its browser
+evidence, UI3 timing and package receipts remain exact historical checkpoints.
+The changed source still needs affected scene/site rebuilds, controls/lifecycle
+requalification, final-candidate quiet timing and fresh document/skill/package
+bindings. Production is unchanged; owner/device/release boundaries and deferred
+Troy construction remain explicit.
+
+
+KIT-6 repairs the reproduced pre-#131 joystick cleanup defect: the first KeyW
+reached the focused root, then joystick unmount erased that newer keyboard movement.
+Movement ownership now preserves the newer input. The unchanged DOM regression
+passes 8/8; compiled Foundry motion3 passes both backends, including first-key walking
+(about 0.956/0.965 m), orbit/wheel/pinch, interior hand-back and campus return.
+Farm motion3 public controls and touch also pass both backends, and GG's native
+prewarm handles remain reused. The combined scene gate passes 713 tests with 18
+historical skips and zero failures (4,382,983 assertions, 49.84 s); typecheck/lint
+and fresh/managed skill copies pass. These are functional and packaging checks,
+not quiet performance or release acceptance.
+
+At that test-build checkpoint, motion2 and prepared code4 archives remained preserved
+and code4 was not activated. Motion3/code5 site pins were then in progress and not
+yet qualified; the subsequent site and final-source checkpoint below supersedes
+that pending status. The isolated motion3 timing preparation verifies 18 cells /
+108 planned one-minute runs, but no timing has started. No production or saved
+asset revision changed.
+
+
+## Code5 site and final-source checkpoint, 3 October
+
+The fresh corpus run in `tmp/full-optimizer-corpus/current58b1-20261003/` executes
+current source with stable initial/final `58b1b178…` identity: 86 examples, 113 released
+scene GLBs and 25 saved Troy regression inputs, 224/224 complete with zero failures.
+All input bytes remain unchanged; every prepared hash, optimized artifact hash and
+per-input result equals the earlier dd25 run. The 20 decoded terrain derivatives
+retain explicit provenance. Frozen dist hashes still match their build receipt,
+with execution qualified separately by installed-package smoke. This closes the
+prior current-identity corpus gap without relabeling historical receipts or claiming
+appearance, native compressed-input, importer or owner acceptance.
+
+The bounded [stabilization adversarial review](../reviews/2026-10-03-stabilization-adversarial-review.md)
+records source hashes, ownership/cadence/transition/input checks and their limits.
+No new concrete blocker was found in those reviewed surfaces. Motion3 has 713 portable
+passes / 18 historical skips and clean typecheck/lint. Current fresh and managed
+Codex/Claude copies qualify the KIT-6 ownership guidance; final package binding
+will follow the status-document update.
+
+Golden Gate `g9-code5` and Foundry `ff3-review2-code5` archives reproduce exactly.
+Their public payloads are respectively 1,708,928 raw / 512,680 gzip bytes and
+1,710,132 raw / 519,928 gzip bytes, within unchanged ceilings. Saved asset revisions,
+model/data payloads and checksums stay unchanged. Code5 site artifact
+`26ecd2b29e15191edce22a0df48da108b0d91851a37f9b062f8c97347fc21efb`
+contains 2,728 inventoried files / 199,998,092 bytes. It passes 564 site tests with two
+historical skips, 70 Astro files without diagnostics and static validation. Fresh
+browser checks pass six NVIDIA public-control scenarios / 34 checks, nine
+lifecycle/viewer/failure areas, 396 accessibility widths and 44 keyboard tours with
+zero issues. HTTP verification passes 116 downloads, 520 linked files, 89 pages and
+three checksum endpoints. Final revision reconciliation repeats 882 checks across
+292 records with zero mismatches; asset appearance and owner acceptance stay separate.
+
+The direct public Farm probe passes orbit, pinch out/in, post-pinch orbit and first
+keyboard movement after touch on NVIDIA WebGPU and WebGL2:
+`site/.cache/alignment-motion3/farm-touch-public-02/receipt.json`. Public-01 retained
+passing behavior but failed its warning classifier; that failed receipt is preserved.
+These are actual public-runtime desktop-emulated touch checks, not physical devices.
+The site source/input binding is
+`site/.cache/alignment-motion3/final-delivery-binding.json`; the launch flows and
+HTTP checks are alongside it. A skill-only site rebuild and exact continuity proof
+are being completed separately; do not inherit the code5 browser gates onto changed
+bytes without that proof.
+
+The current motion3 18-cell / 108-run quiet campaign and four serialized 135-second
+Farm allocation observations remain unstarted. The latter are bounded diagnostics,
+not timing or retainer acceptance. Historical UI3 timing retains all five D41 failures;
+Golden Gate's original strict-image flags and separate drive event retain their
+owner/diagnostic dispositions. Final package/status binding, exact-candidate timing
+and authorized clean delivery remain separate. No public release action occurred.
+
+## Focused qualification decision, 3 October
+
+Matt selected **“Focused checks, expand only if a failure needs investigation”**
+and placed owner farmer/water review **after the development goals**. This replaces
+the motion3 18-cell / 108-run preparation as the active timing requirement. That
+larger preparation remains preserved, deferred and unrun; prior dated checkpoints
+describe their state at the time and are not rewritten.
+
+The selected block is one original/candidate A/B pair for each case below:
+
+| Scene | Cases | Duration per build |
+| --- | --- | --- |
+| Farm | Balanced walk; balanced tractor | 60 seconds each |
+| Golden Gate | Balanced flyover; balanced drive; high orbit | 60 seconds each |
+| Foundry Floor | Balanced campus; balanced fab landing; balanced drive | 60 seconds each |
+| Farm | Minimal hero view | 135 seconds |
+
+This is 16 one-minute measurements plus two 135-second measurements: **20.5 minutes
+measured, plus loading**. Quiet-host checks, actual hardware identity, foreground
+validity and D41 limits remain unchanged. Preserve every failed or incomplete case;
+expand only where a failure needs investigation. One pair does not establish repeat
+stability, all-tier performance, a desktop speedup, tablet promotion or release acceptance.
+
+The bounded FARM-3 allocation diagnosis is complete in
+`scenes/.tmp/alignment-farm/allocation-plan/four-run-comparison.json` and `.md`.
+All four 135-second observations are valid. Original lean/sampled runs contain
+natural 50.0/41.7 ms intervals; neither current observation contains a natural
+interval above 40 ms. Current late major GC still takes about 36 ms. Both sampled runs
+retain their separate 66.7 ms profiler-stop interval as instrumentation evidence.
+The common embedder-heap cycle and minified allocation stacks do not establish
+source allocation/retainer ownership. No new regression, speculative repair,
+hitch-fixed, long-term leak-freedom or D41-pass claim follows. The selected minimal
+hero-view pair is separate unprofiled timing evidence.
+
+Final skill-only site artifact
+`978664da398a2f67ea8e1ed210db6609a997095ffeff9d8961a7e044e2884d8d`
+contains 2,728 inventoried files / 199,998,384 bytes. Fresh static, delivery and HTTP
+checks pass. Strict continuity against `26ecd2b2…` proves 2,721 unchanged product
+files, including all 200 HTML and 243 scene files, with identical local download
+mapping. Original browser measurements keep their artifact identities and scopes.
+The five regenerated skill archives match every maintained member: four tar streams
+are byte-identical with only Node/Bun gzip encoding differences; compose changes
+only `references/runtime-scenes.md` plus its size/checksum metadata. The failed
+strict attempts remain preserved alongside
+`site/.cache/alignment-kit6-site/product-continuity.json`. Current guidance and
+fresh/managed workspace copies are verified separately. These new status edits
+still require final package binding; no upload, deployment, tag or publication is authorized.
+
+## First focused block checkpoint, 3 October
+
+All **16 of 16 runs are collection-valid** for the eight selected 60-second A/B
+cases. Every run has a p95 frame interval of **8.4 ms**. Raw D41 records **15 pass /
+one fail**: candidate Golden Gate balanced flyover has a **50.1 ms** interval at
+**56.9993 s**, while its original comparison has **50.0 ms** near **25.0293 s**.
+These rounded values do not waive the raw verdict.
+
+Strict quiet qualification **fails**. The post-run CPU maximum is **16.473%**, with
+that sample **18.125 s after the block ended**. Collection validity and the sample's
+later timing do not convert the failed strict quiet gate into a pass; retain its
+original failed receipt. No overall performance acceptance follows.
+
+Bounded triage finds a nearby candidate render call spanning **41.3 ms wall time**.
+This is not measured CPU time and does not identify a CPU, driver, upload or pipeline
+cause. The event is later than the known first-use contact-shadow event; no new
+runtime repair is justified by this observation alone.
+
+The only added measurement planned is **one unchanged original/candidate balanced
+flyover pair**, two measured minutes, to investigate this failure. The originally
+selected **135-second Farm minimal hero-view pair** remains. Keep the same quiet,
+actual-hardware, foreground and D41 limits. The full 108-minute preparation stays
+preserved, deferred and unrun. There is no all-tier, repeated-run stability or desktop
+speedup claim. Owner farmer/water review follows the development goals. Final
+status/package binding and release authorization remain separate; no public action occurred.
+
+## Final collected focused timing checkpoint, 3 October
+
+The original focused scope is fully collected: **18/18 collection-valid runs,
+20.5 measured minutes**, with **17 raw D41 passes and one failure**. Candidate
+Golden Gate balanced flyover's **50.1 ms** interval at **56.9993 s** remains failed.
+The Farm minimal hero-view pair completes **135 seconds per build**, with maxima
+of **25.0 ms original / 33.4 ms candidate**, both raw D41 pass.
+
+Both strict post-run quiet failures remain: the first block records **16.473% CPU**
+maximum **18.125 s after the block ended**; the Farm block records **16.159% CPU**
+maximum **6.326 s afterward**. These later samples do not excuse the failed gates.
+The overall focused audit remains **FAIL**, encompassing those two quiet failures
+and the original candidate flyover D41 miss.
+
+The one bounded, unchanged flyover repeat is also complete: an additional **two
+measured minutes**, original/candidate maxima **50.0/16.7 ms**, both D41 pass,
+before/internal/after quiet checks pass, and owned cleanup passes. An earlier
+repeat preflight with **12.694% CPU** stopped before browser launch; its failed
+receipt is preserved. The candidate's near-57-second miss did not recur. The
+earlier nearby **41.3 ms render-call wall interval** was not measured CPU time;
+there is no actionable cause or justified new runtime repair. A passing repeat
+does not erase failed evidence or establish full qualification.
+
+All intended focused measurement work and functional implementation are complete
+within their stated scopes. **Strict desktop performance acceptance remains open**;
+no further benchmark expansion is presently justified. The broader 108-minute
+preparation remains preserved, deferred and unrun. Physical-device acceptance is
+deferred; owner farmer/water appearance review follows the development goals.
+No all-tier, repeat-stability, desktop-speedup, full-goal-completion or release
+acceptance is claimed. Source and runtime are unchanged by this status update.
+
+After these documents are frozen, the final offline package byte audit is separately
+recorded at `tmp/alignment-20261003/package-stabilization-final/receipt.json`; the
+qualification ledger records its result. This checkpoint does not pre-claim that
+audit's outcome. No commit, public upload, deployment, tag or publication occurred.
diff --git a/docs/plans/2026-10-02-cycle-close.md b/docs/plans/2026-10-02-cycle-close.md
index e1b5d64b..bf50c913 100644
--- a/docs/plans/2026-10-02-cycle-close.md
+++ b/docs/plans/2026-10-02-cycle-close.md
@@ -1,5 +1,10 @@
# Cycle close before the trip: plan of record (2 October 2026)
+**Later hub direction:** the owner has deferred the full Troy scene until core, existing
+assets/scenes, upgrades and Cloudflare delivery are aligned. The current work queue is
+[Kiln alignment before Troy](2026-10-02-core-scenes-site-alignment.md). This document
+retains the cycle-close scope, decisions and verification as their dated record.
+
Written 14:05 -04:00, revised 14:40 after the owner's direction ("finish what can be committed, pushed, merged and deployed before the trip; clear-cut engine defects confirmed by the adversarial review go in; tricky or undetermined work waits for the hub and is documented") and after the engine module review.
Owners: **F** = the engine session (orchestration, merges, releases, hub sync), **O1** = Opus agent landing the scenes work (PR 1), **O2** = Opus agent fixing the clear-cut engine defects (PR 3), **Owner** = Matt, who continues on the hub (his Linux laptop) after the trip.
@@ -72,3 +77,64 @@ Plus missing tests (D2/D3 cases, in-scene LOD levels, partial-mesh and cross-gro
## 8. Decisions
- A (the split), B (no 0.11.0 now; clear-cut fixes land without a bump) and C (one site deploy after the merges, on the owner's word): taken by the owner's direction of 2 October, 14:00 to 14:20.
- Q1 to Q3: open, for the hub.
+
+## 9. Hub readiness verification (2 October 2026)
+
+The hub fetched and pulled `origin/main`: both the checkout and remote are at
+`ac8456c` (#132), with a clean starting tree. PRs #129 through #132 are merged;
+there are no open PRs. CI and Website passed on that commit. The package remains
+0.10.0 with the three engine fixes under `Unreleased`; the rigid-merge and
+extension-compatibility modules are still only on the raw `draw-optimization`
+branch at `4a1d238`. Its worktree, wiring patches and ignored evidence are intact.
+The private evidence repository is also current with its remote at `3cdd416`.
+
+Readiness changes, left uncommitted for review:
+
+- Fix `scenes/scripts/check-pins.ts` to read this integrated checkout's engine,
+ site, renderer and toolchain instead of the old Windows worktrees. The relocated
+ filesystem test failed on the old path and passes with the fix; it also verifies
+ detection of a changed engine pin.
+- Refresh contributor validation/version guidance, scene checks, the Troy setup
+ commands and the hub's `~/X/START-HERE.md`. Preserve the earlier dated plans and
+ evidence; the original landing goal's deferred items remain deferred.
+- Upgrade the live Troy workspace's runtime metadata through managed setup. The
+ initial refresh needed no managed file rewrites. After the owner approved the
+ host's full OS upgrade for ChatGPT, install isolated Node 22.23.2/npm 12.0.2
+ under `~/.local/share/kiln-toolchain/` rather than downgrade system packages,
+ then repin `kiln.mjs` and `.mcp.json` through another managed upgrade. Existing
+ local relocation/skill edits were preserved. Setup reports `current`; CLI
+ Discovery resolves `~/X/kiln`. Restart a previously open harness/MCP session.
+
+Local checks used Bun 1.4.2, Node 22.23.2 and npm 12.0.2:
+
+| Check | Result |
+| --- | --- |
+| Root and scene frozen installs | No dependency or lockfile changes |
+| All six runtime bundles | Source identities and bundle hashes match |
+| Root toolchain, skills, typecheck and lint | Pass |
+| Root `test:coverage` | 3,137 pass, 3 skip, 0 fail; functions 95.06%, lines 92.25%; ratchet passes |
+| Render-service tests | 78 pass, 0 fail; no GPU required |
+| Scene toolchain, pins, typecheck and lint | Pass |
+| Scene portable tests | 525 pass, 30 fixture skips, 0 fail |
+| Scene script tests (run separately) | 58 pass, 1 fixture skip, 0 fail |
+
+After the owner's approved host OS upgrade, the full root coverage gate was
+rerun: the same 3,137 passes, three skips and coverage percentages, with no
+failures. Root toolchain, skills, typecheck and lint, all 78 render-service tests,
+45 focused runtime/capture/material tests and the 11 scene-check tests also
+passed. Scene toolchain/pins and the repinned Troy setup/Discovery checks remained
+current. The official ChatGPT Linux preview was installed and its visible
+XWayland launch verified; host installation, update and reboot notes are in
+`~/X/START-HERE.md`. No reboot or GPU qualification was performed.
+
+The raw branch's author-reported scene acceptance figures are still historical
+evidence. These portable checks do not establish browser parity, GPU readiness,
+quiet-host timing, pack acceptance or live dogfood. Those remain in section 7.
+
+One queued engine defect was independently reproduced on current `main`:
+materials A and B share a metallic-roughness texture but have distinct occlusion
+maps, with red values 40 and 220. After `applyKitContract`, both occlusion slots
+read 220 and the summary reports two successful packs with no skip. The UV and
+transform guard in #132 does not prevent mutation of the shared image. Add a
+focused failing test in `src/__tests__/kit.test.ts`, then preserve each material's
+occlusion through a per-occlusion image copy or an explicitly reported skip.
diff --git a/docs/plans/2026-10-02-draw-optimization-landing.md b/docs/plans/2026-10-02-draw-optimization-landing.md
index 87423766..ad5df297 100644
--- a/docs/plans/2026-10-02-draw-optimization-landing.md
+++ b/docs/plans/2026-10-02-draw-optimization-landing.md
@@ -1,7 +1,14 @@
-# Draw optimization landing (PR 1): plan of record
+# Draw optimization landing (PR 1): historical plan
-Status: waiting for the owner to pass the goal statement at the end of this file. Nothing below is implemented
-until then. Written 2026-10-02 at 13:17 -04:00.
+Current disposition (3 October): PR #131 landed the 24 existing non-engine commits,
+records and compose-scene corrections as `b1ac6ee`. The larger goal statement below
+was split; its new follow-up work was explicitly deferred, as the progress log and
+scenes/DECISIONS.md D-65 through D-76 record. The engine modules did not land.
+Use the [current alignment plan](2026-10-02-core-scenes-site-alignment.md) and
+[backlog](../backlog.md) for remaining work. Do not redo the completed scene pass.
+
+Status at writing: waiting for the owner to pass the goal statement at the end of
+this file. Written 2026-10-02 at 13:17 -04:00. The original proposal follows.
## Purpose
@@ -260,7 +267,7 @@ Keep `draw-base`, `draw-after`, `flicker-revz2`, the evidence and the reports.
- 14:02: PR #130 (docs and site only, no shared file) merged as `a396612` at 13:53, so the landing branch was rebased
onto it before the push and its gates were rerun.
-## Goal statement
+## Original goal statement before the landing split
<!-- goal:start -->
Land the draw-optimization scene work as PR 1 by following docs/plans/2026-10-02-draw-optimization-landing.md (owner answers of 2 October to sweep decisions D1-D34). Work on a new branch, draw-optimization-landing, cut from origin/main in the worktree C:/Users/Mattm/X/kiln-draw-optimization, with every draw-optimization commit except e72b610 cherry-picked (the engine modules are for the engine agent's PR 2). Never edit, stash, switch or clean C:/Users/Mattm/X/kiln-oss or C:/Users/Mattm/X/kiln-v1-readiness. Never edit a file PR #129 changes. Never touch site/, deploy, upload assets or post upstream. Artifacts stay private. The only live spend is the D31 dogfood runs.
diff --git a/docs/plans/2026-10-03-release-preparation.md b/docs/plans/2026-10-03-release-preparation.md
new file mode 100644
index 00000000..4ddef847
--- /dev/null
+++ b/docs/plans/2026-10-03-release-preparation.md
@@ -0,0 +1,82 @@
+# Repository and site release preparation — 3 October 2026
+
+Execute the stabilization release. Matt has now authorized commit, main integration
+and Cloudflare deployment after performance review and final organization. Troy requirements, assets and scene work follow
+this checkpoint and a direct discussion; its pack remains off the public site.
+
+## Current blockers and preserved evidence
+
+Matt confirmed the farmer hand fixes and could not reproduce the water jump locally.
+The [release disposition](../reviews/2026-10-03-release-disposition.md) closes those
+release holds and records the bounded performance decision; historical evidence
+remains in the [investigation](../reviews/2026-10-03-water-orbit-follow-up.md).
+The original focused timing audit remains failed (one 50.1 ms interval and two
+post-run quiet failures); the targeted repeat passes. That is a known acceptance
+limit, not grounds for a speculative runtime patch or automatic 108-minute rerun.
+Physical mobile and owner visual acceptance remain distinct from desktop emulation.
+
+Core, shared input/camera, farmer and existing site functional receipts retain their
+exact source/artifact scopes. No current source change was made merely to suppress
+a failed result. The previous package and report are preserved before reopening.
+Current documentation changes require a new package/document binding; a clean release
+commit also requires fresh site build provenance before deployment.
+
+## Efficient validation
+
+1. No further water repair or timing run is required for the present candidate. If
+ the issue recurs, reproduce it and add a failing regression for its actual cause.
+2. Run the nearest tests, scene typecheck/lint and the required portable scene gate
+ after a source repair. Use rendered before/after orbit evidence on both backends,
+ including transient frames and animation if implicated by the reproduction.
+3. For a water-only change, budget three original/candidate 60-second pairs:
+ balanced orbit, high orbit and flyover — six measured minutes plus loading and
+ unchanged quiet checks. Expand only when a failure needs attribution. Do not
+ remeasure unchanged Farm or Foundry merely because they share the repository.
+4. Rebuild only changed delivery surfaces; verify exact scene seals, site references,
+ affected public controls and downloaded bytes. Retain the existing core runtime
+ qualification when those bundles are byte-identical.
+
+The 108-minute plan is archived as optional broader coverage, not the current release
+gate. Omitted tiers and repetitions remain unmeasured. No hitch threshold is relaxed,
+and a passing repeat does not replace earlier failures.
+
+## Housekeeping and commit structure
+
+The read-only inventory initially contains 267 pending files with no `.env`,
+`node_modules`, `.tmp` or `.cache` entries in the proposed tracked/untracked set.
+`git diff --check` passes. Ignored diagnostic captures remain local evidence; preserve
+them and old artifacts, rather than running broad cleanup or deleting unknown files.
+New documentation added by this checkpoint is additional to that initial inventory.
+
+Prepare these coherent review groups, preserving the existing working tree:
+
+- Core ORM/full-exporter fixes, their regression coverage and rebuilt Node bundles.
+- Compatible dependency/toolchain updates and lockfiles; coordinate scene/site pins.
+- Shared scene input/camera and Farm/Golden Gate runtime fixes with their tests.
+- Site verification/deployment tooling, exact scene delivery catalogs and asset pins.
+- Maintained guidance, roadmap/backlog and release/migration records aligned to the
+ final implementation. Troy document edits clarify deferral, not construction.
+
+A file inventory is not a blanket correctness review of every diff. Review staged
+groups before committing, check for unintended generated payloads, and keep code,
+its required tests and its build outputs together. Do not blindly stage all files.
+
+## Concrete release sequence
+
+Owner commit/push/deploy authorization is recorded in the release disposition.
+Fetch and inspect remote changes; preserve local work and integrate only if needed. Commit the reviewed groups,
+run applicable checks on the resulting tree, then push the agreed branch/PR path.
+
+The website uses direct upload to Cloudflare Pages project `kilnstudio`, production
+branch `production`; GitHub Actions does not deploy it automatically. Follow
+[`site/DEPLOYMENT.md`](../../site/DEPLOYMENT.md): build from the clean intended commit,
+verify the full artifact inventory and exact scene/runtime/asset pins, validate the
+R2 upload sets without mutation, upload only approved immutable assets, verify their
+public hashes, and run the portable deployment dry run before the actual upload.
+The dirty-checkout refusal is expected until the release commit exists; do not bypass it.
+
+Current public rollback reference: deployment `33c716c7-16e5-46c6-93bf-f2260f0082be`,
+commit `b1ac6ee`, artifact `5ecbbe76…`, Golden Gate `g9` / Foundry `ff3-review2`.
+Preserve existing versioned assets. After an authorized deployment, verify the public
+build-info, scene runtime hashes and actual scene entry/control flows against the new
+artifact. npm publication remains a separate deferred action.
diff --git a/docs/reviews/2026-10-02-draw-optimization-engine-handoff.md b/docs/reviews/2026-10-02-draw-optimization-engine-handoff.md
index cf555881..9dac7210 100644
--- a/docs/reviews/2026-10-02-draw-optimization-engine-handoff.md
+++ b/docs/reviews/2026-10-02-draw-optimization-engine-handoff.md
@@ -1,5 +1,14 @@
# Draw optimization: handoff to the engine and 0.10.0 work
+Current disposition (3 October): #129, #131 and #132 are merged. The scene runtime
+optimization landed; the separate engine modules and full-mode replacement did not.
+#132 fixed UV/transform handling, while the pre-existing shared-image ORM overwrite
+remains reproduced on main. The old wiring patch no longer applies cleanly after
+#132. The [current alignment plan](../plans/2026-10-02-core-scenes-site-alignment.md)
+records six implementation conditions and release scope; the [backlog](../backlog.md)
+separates pending work from completed scene work. Patch applicability and readiness
+claims below describe the original commit, not current main.
+
This record is for the agent that owns the engine and the 0.10.0 release (branch `v1-readiness`,
PR #129). It lists what the draw-optimization cycle changed or found that touches the engine,
its skills, assets or projects. That covers what is ready to apply, what is only proposed, and
diff --git a/docs/reviews/2026-10-02-draw-optimization.md b/docs/reviews/2026-10-02-draw-optimization.md
index 5db2e9fc..27d0b5f6 100644
--- a/docs/reviews/2026-10-02-draw-optimization.md
+++ b/docs/reviews/2026-10-02-draw-optimization.md
@@ -1,5 +1,13 @@
# Draw optimization across the three scenes
+Current disposition (3 October): the non-engine optimization work below landed in
+PR #131 (`b1ac6ee`). Optimized Farm is deployed; Golden Gate and Foundry await the
+planned reseal of their optimized runtimes. The separate engine modules remain
+unlanded. The [current plan](../plans/2026-10-02-core-scenes-site-alignment.md) and
+[backlog](../backlog.md) distinguish completed work from adopted follow-ups. All
+before/after counts, timing and local-only statements below describe the recorded
+cycle, not a new run or the current delivery state.
+
The draw-optimization cycle ran on branch `draw-optimization` in the worktree
`C:/Users/Mattm/X/kiln-draw-optimization`, following
`docs/plans/2026-10-01-draw-optimization-cycle.md`. Owner decisions OD-1 to OD-18
diff --git a/docs/reviews/2026-10-03-bridge-preview-refresh.md b/docs/reviews/2026-10-03-bridge-preview-refresh.md
new file mode 100644
index 00000000..7ab8b6a9
--- /dev/null
+++ b/docs/reviews/2026-10-03-bridge-preview-refresh.md
@@ -0,0 +1,38 @@
+# Golden Gate still-image refresh — 3 October 2026
+
+The owner's request covers the still images on the homepage, scene listing and
+Golden Gate scene page. Those three surfaces share the same two image records:
+the wide daytime view and the closer driving view. Both have been retaken from the
+prepared `g9-code5` runtime; the previous images came from `g9` and `g5` respectively.
+
+The maintained `site/scripts/capture-scene-poster.mjs` workflow captures the actual
+scene canvas at 1440×925, using its normal view controls and hiding the HUD. A local
+launch wrapper selects headed Chrome, X11 and Vulkan; captured adapter telemetry
+confirms NVIDIA WebGPU. The initial default headless attempt was stopped without
+using an image. Neither replacement is composited or retouched. Both were visually
+inspected before recording them in the media catalog.
+
+The runtime SHA-256 is
+`1a01a81a912157936f05a2060f1df377c418607a83567753e4db2b0257bdb556`.
+The new PNG pins are:
+
+| View | Bytes | SHA-256 |
+| --- | ---: | --- |
+| Day | 886155 | `3b75ae261e59a034165ec705d20931484b03600d39fae51c42fc02db22ba42e5` |
+| Drive | 728452 | `487793596f730d5424c1b25016fbc27408d6d2ab707c57343acbbc6a52b1bc56` |
+
+The new immutable media paths live under `media/scenes/golden-gate/g9-code5/`.
+The media pipeline derives six widths in both AVIF and WebP, plus each full-size
+WebP fallback. Historical image pins remain available for rollback. Scene runtime,
+GLBs and camera behavior are unchanged by this refresh. Social cards use separate
+asset or Farm imagery and do not depend on these two bridge scene captures.
+
+Local capture, build and validation evidence is retained in
+`site/.cache/water-reopened-posters/`, alongside the preceding site artifact.
+The refreshed local preview uses port 4412. These images are prepared locally;
+production has not been deployed.
+
+This image refresh does not close the [water orbit report](2026-10-03-water-orbit-follow-up.md).
+If another water repair changes the final runtime, retake these two images again
+before release and bind their provenance to that runtime. The 108-minute timing
+matrix is not required for a still-image update.
diff --git a/docs/reviews/2026-10-03-release-disposition.md b/docs/reviews/2026-10-03-release-disposition.md
new file mode 100644
index 00000000..76315fcf
--- /dev/null
+++ b/docs/reviews/2026-10-03-release-disposition.md
@@ -0,0 +1,70 @@
+# Stabilization release disposition — 3 October 2026
+
+Matt confirmed that the farmer hand fixes look good, reported that he could not
+reproduce the water jump in the local candidate, and authorized settling performance,
+reviewing/organizing the changes, then proceeding with main and the Cloudflare site.
+This supersedes the earlier hold for owner review and release authorization. It does
+not authorize npm publication or Troy construction.
+
+## Scene acceptance
+
+The reviewed local candidate is `g9-code5` with Golden Gate runtime SHA-256
+`1a01a81a912157936f05a2060f1df377c418607a83567753e4db2b0257bdb556`.
+Its latest still-image site artifact is `79c52c97…`; all 243 scene files are identical
+to the previously functionally qualified candidate. Farm uses runtime SHA-256
+`f167f46cdf22b72ea860ca183cee901cfc6cc86c089ab39f01ea01556aebe4ef`.
+
+Close FARM-4's owner appearance check and GG-5's release hold on that scoped local
+evidence. No second speculative water fix was made. Reopen the report if a particular
+camera path or device reproduces it. Physical-phone/tablet qualification remains
+deferred; desktop touch checks do not stand in for hardware qualification. Existing
+Foundry and vehicle asset acceptance statuses are unchanged.
+
+## Performance decision
+
+The focused campaign collected eight original/candidate 60-second pairs and one
+135-second Farm pair: 18 observations, 20.5 measured minutes. All were collection-valid;
+17 met the unchanged D41 limits. The candidate Golden Gate balanced flyover recorded
+one 50.1 ms interval near 57 seconds. The original maximum was 50.0 ms. Both builds'
+p95 was 8.4 ms on the measured 120 Hz desktop.
+
+The original blocks also failed post-run idle checks: CPU maxima 16.473% and 16.159%,
+measured after the blocks. These readings do not establish the cause of the late frame.
+The nearby 41.3 ms renderer-call duration is wall time, not measured CPU execution.
+The event is distinct from the earlier reproduced first-use shadow compilation fix.
+
+An unchanged targeted flyover pair added two measured minutes. Original/candidate
+maxima were 50.0/16.7 ms; both D41 and before/internal/after quiet checks passed.
+The separate 135-second Farm pair had 25.0/33.4 ms maxima and 8.4 ms p95 on both sides.
+Earlier allocation probes retain roughly 36 ms late GC and unresolved allocator
+ownership; no leak or late-hitch cure is claimed.
+
+**Release judgment:** proceed with these documented limitations. There is no
+reproduced remaining performance regression with an actionable cause that justifies
+another code change or broader campaign. Do not repeat measurements until something
+changes or the hitch recurs. This is a bounded release decision, not a passing
+all-run performance audit: original failures remain failures, thresholds are unchanged,
+and all-tier/repeated/device qualification remains unclaimed. The 108-minute matrix
+stays deferred. Reopen investigation for recurring >50 ms desktop frames, sustained
+frame-time regression, or repeatable late pauses, with the exact build/path/device.
+
+The preserved raw evidence and independent audits live under
+`scenes/.tmp/alignment-perf-focused/`; causal review is under
+`tmp/alignment-20261003/focused-flyover-triage/`. Earlier results are not overwritten.
+
+## Release execution
+
+Review the source, tests, generated runtime and pinned delivery changes in coherent
+commit groups. Refresh remote state; run local offline core/scene/site gates. Main
+requires eight CI checks and strict up-to-date integration; use a pull request and
+wait for all applicable checks without bypassing branch protection.
+
+After merge, build from clean main, validate exact artifact and scene hashes, and
+verify/upload only the four new immutable R2 objects (two scene input archives and
+two bridge capture PNGs). Existing paths must not be overwritten with different
+bytes. Run the deployment dry run, deploy Pages, and verify production build-info,
+assets and all three scene entry/exit flows. Retain the previous production deployment
+`33c716c7-16e5-46c6-93bf-f2260f0082be` as the rollback reference.
+
+This document records the decision and procedure, not completion of those release
+actions. Execution receipts are retained under `tmp/release-20261003/`.
diff --git a/docs/reviews/2026-10-03-stabilization-adversarial-review.md b/docs/reviews/2026-10-03-stabilization-adversarial-review.md
new file mode 100644
index 00000000..4fa9d5ce
--- /dev/null
+++ b/docs/reviews/2026-10-03-stabilization-adversarial-review.md
@@ -0,0 +1,169 @@
+# Kiln stabilization and adversarial review — 3 October 2026
+
+**Release direction, 3 October:** Matt confirmed the farmer hand fixes look good,
+could not reproduce the water jump in the local candidate, and authorized settling
+the performance findings followed by commit, main integration and site deployment.
+The [release disposition](2026-10-03-release-disposition.md) records the bounded performance decision.
+Troy, physical-device promotion and npm publication remain deferred. Earlier open
+water and authorization statements below describe superseded checkpoints.
+
+**Superseding owner feedback:** Golden Gate water is reopened after repeated wave-position
+jumps reported during orbit. The implementation-complete wording below describes the
+earlier checkpoint; it is not current water acceptance. See the [water follow-up](2026-10-03-water-orbit-follow-up.md)
+and [release preparation](../plans/2026-10-03-release-preparation.md).
+
+This is the current review checkpoint, not release acceptance. The maintained queue
+is [the backlog](../backlog.md); exact receipts and scopes are indexed in
+`tmp/alignment-20261003/qualification.json`. The adopted focused measurements and
+bounded follow-up are collected. Strict desktop performance acceptance remains open;
+implementation and functional verification are complete within the scopes below.
+
+## Repository and scope
+
+A fresh fetch found `codex/core-scenes-alignment` at `ac8456c`, zero commits ahead
+or behind `origin/main`, with the accumulated alignment changes uncommitted.
+PR #131 already landed the scene optimization pass; #132 subsequently fixed ORM
+UV/transform handling. The new issues below do not establish that the optimization
+pass broke every scene. Saved asset GLBs have been preserved.
+
+The current task is to stabilize the engine and existing scenes/assets, challenge
+implementation and evidence, and leave a reviewable result for Matt. Troy ideas
+are not an adopted specification or backlog. Its pack remains off the public site;
+construction, refinement and requirements await direct discussion. No commit,
+push, tag, npm publication, upload or deployment is authorized by this checkpoint.
+
+## Verified implementation and actual behavior
+
+| Surface | Finding and repair | Evidence and limits |
+| --- | --- | --- |
+| Core ORM | Materials sharing one metallic-roughness image could overwrite each other's occlusion. Packing now isolates each pair while preserving other consumers. | Serialized GLB, order, slot and sampling regressions; final engine coverage and installed-package checks. This was separate from #132's UV fix. |
+| Core full exporter | Full-mode rigid merging now respects named pivots, animation, placement and LOD boundaries, conditioned transforms, actual added bytes per saved draw, splitting and rollback. Replay policy is explicitly versioned. | Maintained adversarial tests cover the six adopted conditions; planned 0.11 behavior/migration remains unreleased. |
+| Core diagnostics/upgrades | Bounded draw/geometry observations and compatible dependency/toolchain updates are implemented. | Final engine identity `58b1b178…`; 3,187 tests pass, three platform skips, zero failures, 95.11% function / 92.32% line coverage. Renderer and installed CLI/MCP/WASM checks have separate exact receipts. |
+| Farmer hand and animation | Mixer-only frames missed the empty-hand correction; the original rigid right hand remained a grip; stopping actions caused abrupt transitions. Correction now runs every rendered frame, a scene-only relaxed arm borrows existing geometry, Idle/Walk blends, and hidden pose/shadow variants warm before use. | Exact r36 CPU sequences and both-backend rendered play/start-stop/reentry pass. Saved assets are unchanged. Sampled clearance and restoration are bounded evidence, not every pose or owner appearance acceptance. |
+| Farmer mobile camera | Collision-shortened camera distance fed back into desired orbit distance. A single sideways drag reproduced 4.70 m → 1.46 m. Desired camera pose is now independent of collision projection. | Native-control regressions and actual compiled touch checks on WebGPU/WebGL2 preserve orbit radius and pinch in both directions. Physical-phone behavior remains unverified. |
+| Shared input / Foundry | Hiding the joystick erased the newer first keyboard movement. Movement ownership now makes release/cancel/unmount affect only its own contribution. This code predates #131, from #125. | Three real DOM failures observed before repair, all eight cases pass afterward. Foundry's compiled first key moves the actor; desktop orbit/wheel, touch orbit/pinch and camera hand-back pass on both backends. |
+| Golden Gate water | Incorrect floating-origin phase sign and unrelated foam offsets caused surface discontinuity. Pier wakes were too strong and long. | Actual shader-graph tests and both-backend boundary comparisons across three tiers support the phase/foam fix. Wakes are shorter and softer. Appearance/device acceptance is distinct. |
+| Golden Gate first use | The natural flyover transition first created two contact-shadow pipelines, producing a reproduced hitch. Both sides now warm before ready and retain their cache owners. | Actual native pipeline handles settle before readiness and are reused at the natural 580 m camera jump on motion3. This is functional first-use proof, not a timing pass. |
+| Foundry assets/runtime | The optimized exterior and existing interior remain intact; shared follow/input repairs apply to its controls. | Prior bounded image/count comparisons, fresh both-backend public controls and lifecycle flows pass. No optimization-caused Foundry regression was established. |
+
+The fresh final-source corpus passes **224/224**: 86 examples, 113 scene GLBs and
+25 saved Troy revisions used only as regression inputs. All optimized hashes and
+per-input result data equal the earlier checkpoint. Twenty compressed terrain inputs
+are explicitly decoded derivatives. This executes current source matching `58b1`;
+dist execution is covered by separate installed-package checks. The historical
+`dd25` corpus was not relabeled as a fresh final-build run.
+
+Independent review examined Farm ownership/restoration and warming; root separately
+reviewed FollowRig/native-input behavior. Input ownership also received a separate
+review. No new concrete implementation blocker was found within those scopes.
+The source hashes, authorship disclosures and gaps are in
+`tmp/alignment-20261003/adversarial-motion3/`.
+
+## Revision and site alignment
+
+The final local site is `978664da398a2f67ea8e1ed210db6609a997095ffeff9d8961a7e044e2884d8d`:
+2,728 inventoried files, 199,998,384 bytes. Golden Gate `g9-code5` and Foundry
+`ff3-review2-code5` archives reproduce exactly, retain all original model/data bytes,
+and remain within their runtime ceilings. Farm uses the current source bundle.
+
+Fresh reconciliation covers 292 revision/resource records and 882 checks, with zero
+mismatches; all 113 scene GLB consumers are represented. Only delivery labels changed.
+The final artifact audit checks all members, 222 sealed scene payload files and 86
+current gallery viewer revision/model/download references. Served HTTP checks bind
+all three scenes to actual runtime chunks, frames, shell attributes and pack bases;
+116 downloads, 520 linked site files, 89 mapped pages and three checksum endpoints
+pass. No stale code1–4 page references or Troy delivery was found.
+
+Adversarial review found a verifier gap: a self-consistent stale frame/runtime could
+pass without agreeing with the catalog or page references. The added binding checks
+reject that case. They also verified the old code3 candidate was internally aligned;
+this was a verification gap, not evidence of an old pin mismatch.
+
+The code5 site passes 564 tests with two historical skips, all 70 Astro files without
+diagnostics, static validation, six hardware public-control scenarios / 34 checks,
+and nine fresh lifecycle/layout/touch/viewer areas. Accessibility passes 396 page-width
+checks and 44 keyboard tours with zero problems. The direct public Farm diagnostic
+passes drag orbit, both pinch directions, post-pinch orbit and the first keyboard
+movement after touch on actual NVIDIA WebGPU and WebGL2. Its first run remains
+recorded as a warning-classification failure; the second uses the maintained exact
+warning classifier and passes. These browser observations were collected on `26ecd2b29…`.
+The final skills-only refresh proves all 2,721 product files, including 200 HTML pages
+and 243 scene files, byte-identical to that tested artifact. Fresh final static,
+delivery and HTTP checks pass. Four skill archives only changed compression; their
+decompressed tar streams are identical. Compose changes only the intended input-ownership
+guidance. Every current archive member matches maintained source, and fresh/managed
+workspace copy checks pass. The earlier browser results have not been relabeled as reruns.
+
+Production remains the separately recorded Cloudflare deployment `33c716c7…`,
+commit `b1ac6ee`, using old Golden Gate/Foundry seals. The portable deployment
+preflight is implemented and tested, including refusal of a dirty checkout.
+No local qualification changes production or authorizes publication.
+
+## Bounded remaining issues and evidence limits
+
+| Item | Current disposition |
+| --- | --- |
+| Final performance checks | All 18 adopted observations are collected: eight old/new 60-second pairs and one 135-second Farm pair, totaling 20.5 measured minutes. Collection is valid, but the overall independent audit fails: 17 raw D41 passes, one candidate flyover 50.1 ms failure, and failed post-run idle checks for both blocks. One targeted additional flyover pair (two measured minutes) passes every encoded timing and quiet check. It does not erase the original failures. The full 18-cell / 108-minute campaign is preserved, deferred and unrun. Thresholds are unchanged; strict desktop performance acceptance is still open. |
+| Farm late hitch | Four valid 135-second observations are complete. Original lean/sample runs retain natural 50.0/41.7 ms intervals near 106 seconds; current lean/sample runs have no natural interval above 40 ms, but retain roughly 36 ms late major GC. Both sampled runs have a separately excluded profiler-stop hitch. Sampled JS allocation estimates differ by about 0.81%; the shared embedder-memory cycle and exact allocator/retainer ownership remain unresolved. These single instrumented observations do not prove a fix or leak. No speculative runtime change is justified by this result. |
+| Golden Gate timing events | The historical 58.3 ms drive event remains distinct from the shared flyover pipeline cause. The focused drive pair is 25.0 ms maximum on both sides. The new flyover miss occurs near 57 seconds, later than the old first-use event; it does not recur in the targeted pair. No additional actionable runtime cause is demonstrated. Historical failures remain visible. |
+| Device and appearance | Desktop touch emulation does not qualify physical mobile hardware. Samsung/Mali evidence for this candidate is absent; Xclipse is unverified. Golden Gate original strict-image flags and owner appearance decisions remain open. |
+| Asset acceptance/source scope | Farm's 23 selected assets retain their recorded acceptance; a latest hash-bound scene-runtime owner acceptance is absent. Foundry retains seven accepted and 55 candidate assets. Road-vehicle owner acceptance is not inferred. Original editable-source linkage and metadata-only pivot/scale facts retain the matrix's explicit limits. |
+| Historical failures/skips | Four Farm pilot-image differences shared with the original, Golden Gate strict flags, timing failures and platform/fixture skips remain visible. They are not converted into passes by a successful test count. |
+| Held upgrades/work | Incompatible provider-family majors, site TypeScript 7, physical-device promotion, optional redesigns and separately authorized paid dogfood remain held. Troy work remains deferred. |
+| Final bindings | Skills/site byte continuity and fresh workspace copies pass. The offline package byte audit is recorded separately at `tmp/alignment-20261003/package-stabilization-final/receipt.json` after these docs are frozen; the qualification ledger records its result. Matt will review corrected appearances after the development goals are complete. No owner decision is inferred from these technical checks. |
+
+
+## Focused timing disposition
+
+All samples use the unchanged collector, exact original optimized and current motion3
+builds, a visible NVIDIA WebGPU renderer, 1920×1080 at DPR 1, and measured nominal
+120 Hz. Each side has one observation; these are not reliable speedup estimates.
+Every sample has a p95 of 8.4 ms. The existing limit is no interval above 50 ms and
+none above 100 ms; the 50.1 ms failure is not rounded into a pass.
+
+| Case | Original maximum, ms | Candidate maximum, ms | Raw D41 |
+| --- | ---: | ---: | --- |
+| Farm balanced walk, 60 s | 25.1 | 16.8 | Both pass |
+| Farm balanced tractor drive, 60 s | 16.8 | 33.2 | Both pass |
+| Golden Gate balanced flyover, 60 s | 50.0 | 50.1 | Candidate fails |
+| Golden Gate balanced drive, 60 s | 25.0 | 25.0 | Both pass |
+| Golden Gate high orbit, 60 s | 25.0 | 25.1 | Both pass |
+| Foundry balanced campus, 60 s | 16.7 | 25.0 | Both pass |
+| Foundry balanced fab landing, 60 s | 25.0 | 25.1 | Both pass |
+| Foundry balanced drive, 60 s | 16.8 | 25.0 | Both pass |
+| Farm minimal hero, 135 s | 25.0 | 33.4 | Both pass |
+| Targeted flyover follow-up, 60 s | 50.0 | 16.7 | Both pass |
+
+The first block's before/internal idle checks passed, but its post-run CPU maximum
+was 16.473%, above the strict 12% limit. The spike was sampled 18.125 seconds after
+the block ended, outside all scene measurements. The Farm pair also passed its
+before/internal checks but failed post-run idle at 16.159%, sampled 6.326 seconds
+after the block ended. Neither failure is silently excused or replaced. Their timing
+limits causal conclusions about the scene samples; it does not make the protocol pass.
+
+The candidate flyover's sole 50.1 ms interval ends at 56.999 seconds. A nearby
+render-call wall-duration sample is 41.3 ms; this does not distinguish actual thread
+CPU work, driver/GPU waiting, GC or descheduling. The frame and render arrays are not
+a calibrated timestamp join. This is later than the known first-use boundary near
+25 seconds in the measured window. Zero recorded long tasks and final pipeline counts
+do not establish the cause or rule out transient work.
+
+The unchanged follow-up preserves both exact builds and lasts only two measured
+minutes. Its first idle attempt failed before any browser launched; that receipt is
+retained. A fresh gate after a 20-second settling period passed, as did its internal
+and post-run gates. The candidate's maximum is 16.7 ms and the 57-second event does
+not recur. All owned browsers, profiles and server ports were independently confirmed
+closed. No speculative code repair, repeated testing until success, or broader tier
+campaign follows from this result.
+
+The bounded investigation is complete with mixed evidence. The strict overall audit
+remains failed, and performance promotion stays open. It is reasonable to review the
+implemented functional repairs with this limitation visible; it is not accurate to
+label the candidate fully performance-qualified. Any further timing work should target
+a reproduced failure or a specific acceptance decision. The original full campaign
+remains deferred, and physical-mobile and owner appearance evidence are separate.
+
+The exit gate is reproducible evidence for the in-scope repairs on identified final
+artifacts, with known failures, risks, skips, unverified areas and justified deferrals
+reported explicitly. It is not a promise of zero possible bugs, and it does not
+start Troy automatically. Matt reviews the resulting checkpoint before that discussion.
diff --git a/docs/reviews/2026-10-03-water-orbit-follow-up.md b/docs/reviews/2026-10-03-water-orbit-follow-up.md
new file mode 100644
index 00000000..a7c4a628
--- /dev/null
+++ b/docs/reviews/2026-10-03-water-orbit-follow-up.md
@@ -0,0 +1,101 @@
+# Golden Gate water orbit follow-up — 3 October 2026
+
+**Release direction, 3 October:** Matt confirmed the farmer hand fixes look good,
+could not reproduce the water jump in the local candidate, and authorized settling
+the performance findings followed by commit, main integration and site deployment.
+The [release disposition](2026-10-03-release-disposition.md) records the bounded performance decision.
+Troy, physical-device promotion and npm publication remain deferred. Earlier open
+water and authorization statements below describe superseded checkpoints.
+
+**Open.** Matt still sees waves jump to different positions repeatedly during orbit.
+The earlier phase/foam correction and boundary captures do not establish that his
+observation is resolved. No new product-code change was made during this investigation:
+a residual cause must be demonstrated before another repair is justified.
+
+## Build identity comes first
+
+A fresh read of `https://kilnstudio.tools/build-info.json` at 17:34 UTC confirms
+production commit `b1ac6ee`, Golden Gate `g9`, artifact `5ecbbe76…`. It does **not**
+include the prepared water repairs. The local candidate uses `g9-code5`, artifact
+`978664da…`, with `index-DhpWxFro.js` SHA-256
+`1a01a81a912157936f05a2060f1df377c418607a83567753e4db2b0257bdb556`.
+The exact current preview is `http://127.0.0.1:4412/scenes/golden-gate/`; its server
+verifies each requested file against the candidate inventory. This URL is local to
+the development machine. The served runtime was independently fetched and hash-checked.
+
+A question asking whether the observation is local or on the live site is pending.
+Do not infer the answer. If it is production, first reproduce on this identified
+candidate. If it is the candidate, record the view/altitude, backend and the repeated
+jump before changing code. A working-tree fix is not evidence that the live site changed.
+
+## Competing explanations and evidence
+
+| Explanation | Investigation and current interpretation |
+| --- | --- |
+| Camera-relative wave phase | The old shader used the wrong sign for the origin correction. The existing repair makes `k·(p−origin) + k·origin − omega·time` independent of the shading origin. Actual TSL tests and earlier before/after captures support that repair. The renewed report remains open until its build and condition are matched. |
+| Mesh recentring or level changes | Sixteen additional 2 mm camera crossings cover negative and positive shading-origin and clipmap thresholds. Same-pose controls are pixel-identical; largest whole-image mean maximum-channel difference is below 0.05/255. Edge pixels can differ, so this is not absolute image identity or proof for every route. |
+| Flow or texture-offset reset | Three.js Water2 blends two offset flow phases to hide resets. Our shader also blends staggered phases and uses repeated texture offsets. Code review found no new definite reset defect. Frozen-time probes deliberately exclude animation; they cannot rule out a time-dependent fault. |
+| Reflection movement mistaken for surface movement | Full-colour and normal-debug probes separate view-dependent lighting/reflections from the wave normal. The high-tier full-colour orbit has a largest center-pixel step of 6/255, with a broad lighting change around the sun direction. This does not qualify every pixel or camera path. |
+| A transient first frame | A new probe stops automatic frame advancement and renders one frame per changed camera pose, rather than waiting twelve frames for each settled capture. It does not reproduce a large fixed-point normal jump on the tested far orbit. |
+| Backend, depth or adaptive quality | Current high-tier WebGL2 and balanced WebGPU fixed-point orbit probes each vary at most 1/255 between sampled positions. The installed Three.js depth conversion explicitly handles reversed depth. The governor changes live density knobs, not structural water tiers during an orbit. Physical-device behavior and the exact owner's rendering path are not established. |
+
+## Expanded local probes
+
+All five orbit sequences contain 121 poses, including the repeated 360-degree
+endpoint, and use a frozen scene time of 12 seconds. An odd 801×601 viewport keeps
+the center pixel on the projected water-plane target. The tested renderer is actual
+NVIDIA hardware; these are visual diagnostics, not performance measurements.
+
+| Build / probe | Camera radius / height | Largest center RGB-channel step |
+| --- | --- | ---: |
+| Earlier UI3, balanced normal, WebGPU | 1,200 m / 500 m | 6/255 |
+| Current motion3, balanced normal, WebGPU | 1,200 m / 500 m | 1/255 |
+| Current motion3, high full colour, WebGPU | 1,200 m / 500 m | 6/255 |
+| Current motion3, high normal, WebGL2 | 1,200 m / 500 m | 1/255 |
+| Current motion3, high normal, WebGPU, near displaced surface | 80 m / 30 m | 7/255 |
+
+The near probe looks at a plane target while the actual surface is displaced, so it
+does not track an identical material point through every angle. Its numbers are
+observations, not an invented acceptance threshold. UI3 is a retained earlier
+candidate, not a claimed byte-identical copy of the live `g9` build. All diagnostic
+pages, browsers and temporary servers reported successful cleanup. The separately
+owned local review server remains available for matching the reported issue.
+
+Receipts and image sequences are under `scenes/.tmp/water-reopen-20261003/`.
+`tmp/alignment-20261003/water-reopened/` records current/live identities, the file
+inventory and the preserved prior qualification checkpoint. Earlier failed or
+limited evidence is not overwritten with a pass.
+
+## Open-source comparisons
+
+- [Three.js Water](https://github.com/mrdoob/three.js/blob/dev/examples/jsm/objects/Water.js)
+ samples its normal pattern from world position and treats reflection projection
+ separately. That is the appropriate coordinate distinction to test here.
+- [Three.js Water2](https://github.com/mrdoob/three.js/blob/dev/examples/jsm/objects/Water2.js)
+ uses two flow phases and a crossfade to avoid visible resets. Its shader and update
+ code are a useful reference for testing a suspected temporal discontinuity.
+- [Nugget8/Three.js-Ocean-Scene](https://github.com/Nugget8/Three.js-Ocean-Scene)
+ documents a camera-centered ocean with scrolling normal maps, illustrating why
+ moving geometry and texture anchoring must be considered separately.
+- [Mohido/Ocean](https://github.com/Mohido/Ocean) implements the GPU Gems water model
+ and offers a normal-map viewer, a useful precedent for separating surface-normal
+ debugging from final lighting.
+
+These are diagnostic references, not adopted dependencies or evidence that replacing
+our water implementation will fix this report. No external shader code was copied.
+
+## Next repair and validation boundary
+
+Match the owner's runtime first. If the jump persists on `g9-code5`, capture that
+path with motion running and frozen, then isolate normals, foam, reflection and mesh
+selection. Record the first failing frame and relevant origin/time/quality state.
+Add a focused regression that fails on the demonstrated cause, make the smallest
+repair, and validate the real orbit on both backends before resealing the scene/site.
+Do not close GG-5 on the basis of the bounded probes above.
+
+The 108-minute matrix is not required for this checkpoint. After a water-only repair,
+paired 60-second balanced orbit, high orbit and flyover cases total six measured
+minutes, plus loading/quiet checks. Existing D41 limits remain unchanged. Repeat a
+long Farm sample only if shared frame or Farm code changes, or a late pause recurs.
+The historical aggregate timing audit stays failed; its result is not rewritten by
+reducing future scope. See [release preparation](../plans/2026-10-03-release-preparation.md).
diff --git a/docs/runtime.md b/docs/runtime.md
index 6cc0fd17..3334da63 100644
--- a/docs/runtime.md
+++ b/docs/runtime.md
@@ -133,15 +133,36 @@ Advanced geometry callbacks also have operation-specific input limits. Those che
### Bake defaults
+The rigid-group `full` contract and `rigid-v1` rebuild policy below describe the
+unreleased alignment candidate planned for 0.11. They are not implemented by the
+downloadable 0.10.0 package; see the [migration notes](migration.md#unreleased-changes-planned-for-011).
+
`KILN_BAKE_OPTIMIZE` and `KILN_BAKE_INSTANCE` choose the bake passes for a render that does not pass `optimize` or `instance`; a value the call passes always wins.
| Environment variable | Supported values |
| --- | --- |
-| `KILN_BAKE_OPTIMIZE` | `off` (default), `auto`, `palette` or `full`; any other value means `off`. `palette` merges flat-colour materials into one palette material and texture, `auto` does so only for an asset with at least four distinct materials, and `full` also flattens and joins meshes to cut draw calls, falling back to `palette` for an asset that is animated, skinned or LOD-chained or has nodes that carry extras or visibility |
+| `KILN_BAKE_OPTIMIZE` | `off` (default), `auto`, `palette` or `full`; any other value means `off`. `palette` merges flat-colour materials into one palette material and texture; `auto` does so only for an asset with at least four distinct materials. `full` also merges compatible primitives within rigid groups, preserving animation, joint, semantic, visibility and LOD boundaries |
| `KILN_BAKE_INSTANCE` | `auto` (default), `off` or `on`; any other value means `auto`. `on` batches a mesh shared by five or more nodes with `EXT_mesh_gpu_instancing` and `auto` does so only for `role: 'fill'` assets; neither batches an animated or skinned asset, or one with `Joint_` pivots, LOD chains, or nodes that carry extras or visibility |
The MCP and CLI tools pin `optimize: 'off'` for every render, inspection and save, so `KILN_BAKE_OPTIMIZE` does not change a tool's GLB; they leave `instance` to the host, so `KILN_BAKE_INSTANCE` does. Library calls that omit `optimize` take the variable: `renderGLB` in process, `renderSceneToGLB` (including the review copies some tool views are rendered from), `renderCodeViewGrid` and `rasterizeComposedScene`. The library's own subprocess mode does not pass either variable to its worker. `node kiln.mjs asset ASSET_ID REVISION --rebuild --out rebuilt.glb` replays the `optimize` and `instance` the saved manifest recorded, whatever the variables say. Both variables are part of the local build-cache key.
+Full mode's rigid-merge pass retains every node name, parent and transform. Geometry on a protected
+boundary stays there; other named mesh nodes can become empty or hold their group's
+merged geometry. Consumers that require geometry attached to each ordinary named
+part should use `optimize: 'off'` or `'palette'` with `instance: 'off'`: the separate
+GPU-instancing pass runs first and can remove named instance nodes. A host can
+disable that pass with `KILN_BAKE_INSTANCE=off`. Composition placement wrappers are protected
+automatically. Transparent, skinned, morphing and other incompatible primitives stay
+separate. Shared geometry is copied only within 4 KiB per saved draw, and merged
+buckets split at 65,534 vertices. The optimization summary reports locks and rejected
+buckets; these are geometry results, not GPU performance or appearance acceptance.
+
+New full-mode builds record `optimizationPipeline: 'rigid-v1'`. An older saved
+revision with unversioned `full` options cannot use the new algorithm as an exact
+rebuild: use its original pinned engine, or explicitly author and save a new child
+revision. Reading and exporting the original saved GLB still work. Other saved modes
+retain their replay behavior.
+
## What a build identity covers
Two hashes identify a local Kiln and they answer different questions. The **build
diff --git a/package.json b/package.json
index b5896091..a54fadde 100644
--- a/package.json
+++ b/package.json
@@ -127,24 +127,24 @@
"dogfood:tier2": "node scripts/tier2-dogfood.mjs"
},
"dependencies": {
- "@gltf-transform/core": "4.5.0",
- "@gltf-transform/extensions": "4.5.0",
- "@gltf-transform/functions": "4.5.0",
- "@modelcontextprotocol/client": "^2.2.0",
+ "@gltf-transform/core": "4.5.1",
+ "@gltf-transform/extensions": "4.5.1",
+ "@gltf-transform/functions": "4.5.1",
+ "@modelcontextprotocol/client": "^2.3.0",
"@modelcontextprotocol/ext-apps": "2.0.3",
- "@modelcontextprotocol/server": "^2.2.0",
+ "@modelcontextprotocol/server": "^2.3.0",
"@types/three": "^0.186.0",
"acorn": "^8.18.0",
"acorn-walk": "^8.3.5",
"gltf-validator": "2.0.0-dev.3.10",
- "manifold-3d": "^3.5.3",
+ "manifold-3d": "^3.5.4",
"minisearch": "7.2.0",
"pngjs": "7.0.0",
- "sharp": "^0.35.4",
- "three": "0.186.0",
+ "sharp": "^0.35.5",
+ "three": "0.186.1",
"three-subdivide": "1.1.5",
"xatlasjs": "^0.2.0",
- "zod": "^4.6.4"
+ "zod": "^4.6.5"
},
"peerDependencies": {
"@ai-sdk/provider": "^3.0.0",
@@ -152,7 +152,7 @@
"@openrouter/ai-sdk-provider": "^2.10.0"
},
"overrides": {
- "sharp": "^0.35.4"
+ "sharp": "^0.35.5"
},
"peerDependenciesMeta": {
"@ai-sdk/provider": {
@@ -166,20 +166,20 @@
}
},
"devDependencies": {
- "@ai-sdk/provider": "^3.0.16",
+ "@ai-sdk/provider": "^3.0.18",
"@anthropic-ai/sdk": "0.109.1",
- "@aws-sdk/client-bedrock-runtime": "^3.1131.0",
- "@biomejs/biome": "^2.5.13",
- "@google/genai": "^2.22.0",
+ "@aws-sdk/client-bedrock-runtime": "^3.1146.0",
+ "@biomejs/biome": "^2.5.15",
+ "@google/genai": "^2.27.0",
"@openrouter/ai-sdk-provider": "^2.10.0",
- "@strands-agents/sdk": "1.18.0",
+ "@strands-agents/sdk": "1.19.0",
"@types/bun": "^1.4.2",
- "ai": "^6.0.282",
+ "ai": "^6.0.300",
"openai": "^6.49.0",
"typescript": "^7.0.2"
},
"optionalDependencies": {
- "@napi-rs/canvas": "1.0.9",
- "webgpu": "0.6.1"
+ "@napi-rs/canvas": "1.0.10",
+ "webgpu": "0.6.2"
}
}
diff --git a/packs/troy/HANDOFF.md b/packs/troy/HANDOFF.md
index 6bb4907f..e847e247 100644
--- a/packs/troy/HANDOFF.md
+++ b/packs/troy/HANDOFF.md
@@ -5,13 +5,22 @@ owner's laptop. State: **in progress, unreviewed by the owner**; the engine work
merged, the pack is local to this folder, R2 and the private evidence repository, and nothing is
on the site.
+## Current direction after the hub audit
+
+The owner has deferred Troy scene construction until the core, existing assets/scenes,
+upgrades and Cloudflare delivery are aligned. Follow
+`docs/plans/2026-10-02-core-scenes-site-alignment.md` in the engine repository first.
+The eventual scene is full scale, inspired by the film Troy: sea and shoreline, sand
+rising toward the wall, and the city behind the wall. The saved battle composition is
+reference only; its layout and small scene budget do not define the new scene.
+
## Where everything is
| What | Where |
| --- | --- |
| The pick records (source, manifest), materials, project, inventory | this folder (`README.md` has the table) |
| Every saved revision's GLB and preview, the material maps | public R2 bucket `kiln-assets`: `https://assets.kilnstudio.tools/troy/assets/<assetId>/<revisionId>/asset.glb` and `preview.png`; `troy/materials/<id>/<revision>/`; `r2-manifest.json` here lists each object's sha256 |
-| The live Kiln workspace of the pack (project `troy`, pinned materials, every revision, retained programs) | the private repository `matthew-kissinger/kiln-dogfood-v1-readiness-2026-10`, cloned to `C:\Users\Mattm\X\kiln-dogfood\v1-readiness-2026-10` on the owner's PC and to `~/X/kiln-dogfood/v1-readiness-2026-10` on the hub (Linux, user `matthewk`; its engine checkout is `~/X/kiln`): `review/troy-refine/ws`; the same workspace without its build cache as `troy/workspace/troy-refine-ws-2026-10-02.zip` on R2 (sha256 `69b4fb6b35a3a08db2ac0b67b501271cdbceefb64749fe0aef9a2165ac4f75d0`) |
+| The live Kiln workspace of the pack (project `troy`, pinned materials and every saved revision; transient program handles are not retained) | the private repository `matthew-kissinger/kiln-dogfood-v1-readiness-2026-10`, cloned to `C:\Users\Mattm\X\kiln-dogfood\v1-readiness-2026-10` on the owner's PC and to `~/X/kiln-dogfood/v1-readiness-2026-10` on the hub (Linux, user `matthewk`; its engine checkout is `~/X/kiln`): `review/troy-refine/ws`; the same workspace without its build cache as `troy/workspace/troy-refine-ws-2026-10-02.zip` on R2 (sha256 `69b4fb6b35a3a08db2ac0b67b501271cdbceefb64749fe0aef9a2165ac4f75d0`) |
| The material-pass sources, render sheets and the scene recomposer | `review/troy-refine/{sources,out,scene}` in the private repository |
| Picks, alternates and what changed per asset | `picks.md` in the private repository; `findings.md` has one row per session |
| The report | `docs/reviews/2026-10-01-v1-readiness-live-sessions.md` (section 7 candidates, section 9 the owner's decisions, section 11 the follow-ups and the material pass) |
@@ -20,22 +29,34 @@ on the site.
## Resume authoring
+Use this procedure when the alignment work is complete and Troy authoring resumes.
+The hub workspace currently targets Claude, has no configured default project and no
+retained program handles. Saved sources and revisions are complete: restore the exact
+pick before editing, name project `troy` explicitly and set up the chosen harness rather
+than assuming that opening the folder in Codex registers its tools.
+
1. Clone the private repository to the path above. Its `README.md` says what is excluded and how
to make it again (runtime clones, harness homes, caches).
2. Make a runtime beside it: clone this repository, `bun install --frozen-lockfile`,
`node scripts/build-runtime.mjs all`; the evidence tools expect `runtime-<label>/` under the
evidence root (`runtime-0.10.0-fix3` was a clone of `3fc369c`; any later commit of `main` serves).
+ On the Linux hub, the existing `/home/matthewk/X/kiln` checkout is already the live
+ workspace's runtime; a second clone is needed only for tools that require their own
+ frozen runtime.
3. Open `review/troy-refine/ws` as a Kiln workspace: its `kiln.mjs` and `.mcp.json` name the
- runtime; run `node kiln.mjs init --check` and, after moving the runtime, `--upgrade`
- (`skills/kiln-setup-workspace`). Or generate a fresh workspace with `kiln-init` and import the
- revisions from the workspace zip with `kiln_import`.
+ runtime. From that runtime, run `node scripts/create-workspace.mjs /absolute/workspace --check`,
+ then `--upgrade` if required (`skills/kiln-setup-workspace`); restart the harness/MCP
+ session afterward. An installed package uses `kiln-init /absolute/workspace --check`
+ and `--upgrade`. These are setup commands, not flags on `node kiln.mjs init`.
+ Or generate a fresh workspace with `kiln-init` and import the revisions from the
+ workspace zip with `kiln_import`.
4. Refine through `skills/kiln-refine-asset`: `inventory.json` has each pick's `assetId` and
`revisionId`; a call that names `projectId: "troy"` (revision 2) implies the material pins, and a
pin the call names replaces the project's for the same `resourceId`.
5. Keep the pack standalone-first (AGENTS.md): scene terrain, controllers and optimization
derivatives belong to the scene package, never to these assets.
-## What the owner wants next (2 October, his direction)
+## Troy work after foundation alignment
- Revise several assets first; he has a list and will say which. Feed demonstrated authoring
defects back into the maintained skills at the relevant boundary.
@@ -64,3 +85,8 @@ on the site.
- Every revision was saved through the 0.10.0 CLI with project `troy`; the engine follow-ups of
2 October (strict-mode generated code, implied project pins, the `resourceId` alias) landed
after the pass, so the saved sources predate them and still run under them.
+- The hub audit verified the selected source/manifest pairs and GLB/source/preview hashes.
+ Project inventory entries still need exact asset links; `inventory.json` is the pick list.
+ Project convention says +Z forward while saved manifests declare +X. Reconcile metadata
+ and bind meaningful requirements before integration: saved structural QA and unassessed
+ visual QA do not establish passage clearance, wall joins, grips or destination behavior.
diff --git a/packs/troy/README.md b/packs/troy/README.md
index efa37622..ed82ca1a 100644
--- a/packs/troy/README.md
+++ b/packs/troy/README.md
@@ -51,7 +51,7 @@ masonry is `MATERIAL_IMAGE_COUNT_BUDGET` (the `web.portable.v1/standard` four-im
| Greek soldier | `greek-soldier` | `r_647e60b4…` | 2,000 | 24 | 3 | 6 | accepted/warn | c38, from the Trojan soldier |
| Hector | `hector` | `r_44e1d798…` | 2,224 | 25 | 3 | 6 | accepted/warn | c39 |
| Achilles | `achilles` | `r_a108d7a3…` | 2,424 | 27 | 3 | 6 | accepted/warn | c40 |
-| Trojan Horse | `wooden-horse` | `r_7ee4d961…` | 2,060 | 16 | 3 | 6 | accepted/warn | w36; `open_hatch` clip |
+| Trojan Horse | `wooden-horse` | `r_7ee4d961…` | 2,060 | 16 | 3 | 6 | accepted/warn | w36; `hatch_open` clip |
| Battle before the gate | `battle-scene-reference` | `r_4573e90a…` (`r_150bbef8…`) | 208,178 | 130 | 28 | 16 | accepted/warn | s50's composition recomposed from the revisions above: a reference for the real scene, not the scene itself |
The sessions named in the origin column (w19, c37, ...) are the live sessions of the report; the
diff --git a/render-service/package-lock.json b/render-service/package-lock.json
index 9b1665a7..00924231 100644
--- a/render-service/package-lock.json
+++ b/render-service/package-lock.json
@@ -9,8 +9,8 @@
"version": "0.1.0",
"dependencies": {
"pngjs": "^7.0.0",
- "three": "0.186.0",
- "webgpu": "0.6.1"
+ "three": "0.186.1",
+ "webgpu": "0.6.2"
}
},
"node_modules/@webgpu/types": {
@@ -52,15 +52,15 @@
}
},
"node_modules/three": {
- "version": "0.186.0",
- "resolved": "https://registry.npmjs.org/three/-/three-0.186.0.tgz",
- "integrity": "sha512-cr/fIM2ddMSVbYVgkfD4jLJv7Fh/8ZTjvo+7gQeSVGUZHxpx9FDwoL5iC7hUz/LiRA8wMbqfnb90xKfm1/HHkQ==",
+ "version": "0.186.1",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz",
+ "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==",
"license": "MIT"
},
"node_modules/webgpu": {
- "version": "0.6.1",
- "resolved": "https://registry.npmjs.org/webgpu/-/webgpu-0.6.1.tgz",
- "integrity": "sha512-T+B65/j2jhyFjbWHsVZ4TJw0nk0RVT27lG+nL3V5IIYMsvuVYKYOUli/yJhMpwvXAwqVPZehakWvTjxk+mK8LQ==",
+ "version": "0.6.2",
+ "resolved": "https://registry.npmjs.org/webgpu/-/webgpu-0.6.2.tgz",
+ "integrity": "sha512-3L4GfmqJLvYUIEWJngEQY+2HQiUlAFkg8+P8NDDj3Xx5hHHIFO/r8JW+ynfqBj7kHN4mbnwO74uB+lrRtLhp4Q==",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
diff --git a/render-service/package.json b/render-service/package.json
index 937cad57..3b274fb8 100644
--- a/render-service/package.json
+++ b/render-service/package.json
@@ -1,22 +1,22 @@
-{
- "name": "kiln-render-service",
- "private": true,
- "version": "0.1.0",
- "type": "module",
- "description": "GLB in, PBR PNG views out. Dawn/WebGPU + three.js, headless. No Kiln engine coupling.",
- "scripts": {
- "start": "node --import ./src/register-hooks.mjs src/server.mjs",
+{
+ "name": "kiln-render-service",
+ "private": true,
+ "version": "0.1.0",
+ "type": "module",
+ "description": "GLB in, PBR PNG views out. Dawn/WebGPU + three.js, headless. No Kiln engine coupling.",
+ "scripts": {
+ "start": "node --import ./src/register-hooks.mjs src/server.mjs",
"test": "node --test test/bind-policy.test.mjs test/beauty-camera.test.mjs test/display-output.test.mjs test/readback.test.mjs test/cache-identity.test.mjs test/asset-camera.test.mjs test/contract.test.mjs test/framing.test.mjs test/material-fixture.test.mjs test/presentation-presets.test.mjs test/gallery-presentation.test.mjs test/display-transform.test.mjs test/instance.test.mjs test/hardening.test.mjs test/node-visibility.test.mjs",
- "smoke": "node --import ./src/register-hooks.mjs test/smoke.mjs",
- "conformance:display": "node --import ./src/register-hooks.mjs test/display-output-conformance.mjs",
- "conformance:material": "node --import ./src/register-hooks.mjs test/material-conformance.mjs"
- },
- "dependencies": {
- "pngjs": "^7.0.0",
- "three": "0.186.0",
- "webgpu": "0.6.1"
- },
- "allowScripts": {
- }
-}
+ "smoke": "node --import ./src/register-hooks.mjs test/smoke.mjs",
+ "conformance:display": "node --import ./src/register-hooks.mjs test/display-output-conformance.mjs",
+ "conformance:material": "node --import ./src/register-hooks.mjs test/material-conformance.mjs"
+ },
+ "dependencies": {
+ "pngjs": "^7.0.0",
+ "three": "0.186.1",
+ "webgpu": "0.6.2"
+ },
+ "allowScripts": {
+ }
+}
diff --git a/render-service/src/build-identity.mjs b/render-service/src/build-identity.mjs
index 228d2719..735019f1 100644
--- a/render-service/src/build-identity.mjs
+++ b/render-service/src/build-identity.mjs
@@ -6,8 +6,8 @@ import { fingerprintSourceDir } from './instance.mjs';
export const RENDER_SERVICE_PROTOCOL = 'kiln.render-service.v2';
export const RENDER_SERVICE_DEPENDENCIES = Object.freeze({
- three: '0.186.0',
- webgpu: '0.6.1',
+ three: '0.186.1',
+ webgpu: '0.6.2',
pngjs: '7.0.0',
});
export const REQUIRED_RENDER_CAPABILITIES = Object.freeze([
diff --git a/render-service/test/instance.test.mjs b/render-service/test/instance.test.mjs
index 675ef213..74b3484e 100644
--- a/render-service/test/instance.test.mjs
+++ b/render-service/test/instance.test.mjs
@@ -101,7 +101,7 @@ test('compatibility binds source and all expected dependency versions without lo
);
assert.throws(
() => resolvedRendererDependencies(anchor),
- /webgpu version conflict.*0.6.1.*0.4.0/,
+ /webgpu version conflict.*0.6.2.*0.4.0/,
);
} finally {
rmSync(dir, { recursive: true, force: true });
diff --git a/scenes/KIT-REQUESTS.md b/scenes/KIT-REQUESTS.md
index b8e73d4a..bce4c7cc 100644
--- a/scenes/KIT-REQUESTS.md
+++ b/scenes/KIT-REQUESTS.md
@@ -1,5 +1,7 @@
# Compatible kit requests after M1
+Current disposition (3 October): use the [alignment plan](../docs/plans/2026-10-02-core-scenes-site-alignment.md) and [backlog](../docs/backlog.md). This ledger preserves original requests and measurements. FARM-001 through FARM-007, GG-001/FF-001, GG-009/GG-010 and FF-003 are implemented. GG-003 reversed depth and GG-004 WebP serving are implemented in the local alignment candidate. Shared GG-007/FF-002 bounds, scrolling and nested-touch changes are also implemented; final integration reproduced a Foundry campus More/help stacking defect, tracked by KIT-2. The original dated response cells below are historical, not the current queue. FARM-008 is advisory and must be demonstrated per scene. The large runtime optimization pass landed in #131; it is not pending work.
+
| Id | Need | Proposed API | Interim behavior | Response |
|---|---|---|---|---|
| FARM-001 | SPEC 6.4 starts CPU preparation when verified layout data arrives while renderer/model work remains pending. | Optional `loadPack(..., { onData })` notification and optional `SceneDefinition.prepareData(data, { signal, registry })`. Existing consumers keep their current task order and behavior. | Farm integration is separate from the completed compatible kit extension. | Kit implementation complete 2026-09-29. Seven new deterministic regressions in `packages/scene-kit/tests/assets/early-data.test.ts`; asset/lifecycle scope totals 40 passing tests and 427 assertions. Evidence: `evidence/m2/preparation/kit-unit.log` and `evidence/m2/preparation/kit-audit.md`. Prepared geometry belongs to the current mount registry; no page callbacks, error codes or readiness semantics changed. |
@@ -22,4 +24,4 @@
| FARM-008 | Advisory for Golden Gate and Foundry Floor (no kit change made): three 0.186.0 keeps the matrices of every instanced mesh with at most 1,024 instances in a uniform buffer declared in that mesh's own vertex shader, so each such mesh compiles its own program or pipeline (lazily, when it first comes into view: the M4 WebGL2 hitches of 100 to 243 ms) and uploads its whole buffer every frame it draws (924 KB a frame on the Farm's minimal tier). | If the other scenes show the same, a kit-level version of the Farm's two measures: (1) `installInstanceAttributes(renderer)` (`packages/farm/src/world/instance-attributes.ts`: three's documented `renderer.debug.onNodeBuilderCreated` hook reports no uniform-buffer room to instanced meshes, so three reads their matrices as an instanced attribute; identical images, M4 A/B) with static usage for batches that move rarely; (2) the SPEC 6.4 warm pass (`packages/farm/src/world/prewarm.ts`: `compileAsync` per drawable, a few chains at a time, then one unculled frame, before ready). | Farm only, in `packages/farm`. | Open (filed 2026-09-29 by the Farm builder, M4) for the coordinator to route; the Farm measurements are in `evidence/m4/hitches/README.md`. |
| FF-001 | The Foundry Floor builder may serve and connect only on ports 4700-4749 (TASK-FF1). The kit's owned-port helpers in `testing/node.ts` (`serveOwned`, `assertOwnedUrl`, `runSceneContractTests`, `runPerformance`) are fixed to 4400-4499: the same need as GG-001. | Nothing new: GG-001's optional `ports` range would serve Foundry Floor too. | `packages/foundry-floor/tests/tools/owned.ts` binds 4700-4749 with the kit's `startStaticServer` (try-bind; `EADDRINUSE` moves to the next port; no listener is probed), mirroring Golden Gate's helper. FF1 made no kit change. | Done with GG-001 (FF2 builder, 2026-09-30, TASK-FF2 item 5): `runSceneContractTests({ ..., ports: { first: 4700, last: 4749 } })`. The FF2 contract run on 4700-4749 is recorded in `packages/foundry-floor/REPORT.md` (FF2) and `packages/foundry-floor/evidence/contract/ff2/`. |
| FF-002 | Advisory (no kit change made). The kit gives `.ks-help-button` and `.ks-credits-button` their pointer events back explicitly, but `.ks-joystick` and `.ks-touch-buttons` take them only as direct children of `.ks-hud` (`.ks-hud{pointer-events:none}` with `.ks-hud>*{pointer-events:auto}`, `packages/scene-kit/src/ui/styles.tsx`). A scene that renders them inside its own full-HUD layer (the GG-007 toolbar pattern) gets a joystick that never receives a touch. Found by the Foundry Floor FF2 phone capture (390x844, touch): the walker moved 0 m under a held joystick until the scene CSS took the events back, then 1.542 m in 1.5 s. | Add `.ks-joystick,.ks-touch-buttons{pointer-events:auto}` beside the help and credits rule, so the touch controls work wherever a scene nests them. | `packages/foundry-floor/src/scene/Hud.tsx`: `.ff-hud>.ks-joystick{pointer-events:auto}`. | Open (filed 2026-09-30 by the Foundry Floor FF2 builder). |
-| FF-003 | B-04's callback-failure fixtures (`callbackFailureOptions`) accept only a cancelled `pack.json` request (`isExpectedCallbackFailureDiagnostic`, `packages/scene-kit/src/testing/node.ts`). The kit calls `onBackend` and `onTier` during renderer initialisation while `loadPack` is still fetching (the two run concurrently by design), so when a scene's pack is still loading at that moment, the fatal error cancels files listed in the pack and the suite counts those cancellations as unexpected diagnostics. Measured on the Foundry Floor campus test build (55 pack tasks: 47 models, 10,076,504 B, and 8 data files): the backend and tier fixtures failed at 18 to 32 of 55 assets loaded and cancelled pack-listed files in 3 of 3 runs each; the graphics, pack and build fixtures cancelled nothing (`packages/foundry-floor/evidence/contract/ffc1/callback-probe.json`, from `tests/tools/callback-probe.ts`). The B-04 check then fails on its diagnostics assertion, which runs after all nine cases have passed their own assertions (`evidence/contract/ffc1/browser-results.json`, both attempts). FF2's smaller pack finished first: its recorded B-04 cases cancelled nothing. | For callback fixtures, also treat `net::ERR_ABORTED` of a file listed in that mount's `pack.json` (same asset base, same request identity) as expected, as the pack URL already is. | None in the scene: a fatal error cancelling the scene's own in-flight pack requests is the kit's intended teardown. The FF-C1 contract run reports B-04 as failing on this rule only. | Open (filed 2026-09-30 by the Foundry Floor FF-C1 builder). |
+| FF-003 | B-04's callback-failure fixtures (`callbackFailureOptions`) accept only a cancelled `pack.json` request (`isExpectedCallbackFailureDiagnostic`, `packages/scene-kit/src/testing/node.ts`). The kit calls `onBackend` and `onTier` during renderer initialisation while `loadPack` is still fetching (the two run concurrently by design), so when a scene's pack is still loading at that moment, the fatal error cancels files listed in the pack and the suite counts those cancellations as unexpected diagnostics. Measured on the Foundry Floor campus test build (55 pack tasks: 47 models, 10,076,504 B, and 8 data files): the backend and tier fixtures failed at 18 to 32 of 55 assets loaded and cancelled pack-listed files in 3 of 3 runs each; the graphics, pack and build fixtures cancelled nothing (`packages/foundry-floor/evidence/contract/ffc1/callback-probe.json`, from `tests/tools/callback-probe.ts`). The B-04 check then fails on its diagnostics assertion, which runs after all nine cases have passed their own assertions (`evidence/contract/ffc1/browser-results.json`, both attempts). FF2's smaller pack finished first: its recorded B-04 cases cancelled nothing. | For callback fixtures, also treat `net::ERR_ABORTED` of a file listed in that mount's `pack.json` (same asset base, same request identity) as expected, as the pack URL already is. | None in the scene: a fatal error cancelling the scene's own in-flight pack requests is the kit's intended teardown. The FF-C1 contract run reports B-04 as failing on this rule only. | Implemented in current kit: callback fixtures recognize aborted files by the exact pack-listed request URL (testing/node.ts and node-policy tests). The original FF-C1 failure below is historical; current FF3 records report B-04 passing. Recheck failure recovery for each changed release. |
diff --git a/scenes/README.md b/scenes/README.md
index 02e4bd7f..585b4aef 100644
--- a/scenes/README.md
+++ b/scenes/README.md
@@ -5,9 +5,19 @@ here. They were integrated from the separate authored scene workspace for the v0
site rollout. Generated capture evidence and asset payloads are kept out of Git.
Historical milestone documents describe their original runs, not current release acceptance.
+The [current alignment plan](../docs/plans/2026-10-02-core-scenes-site-alignment.md)
+and [backlog](../docs/backlog.md) cover core, shared tooling, all three existing
+scenes and their assets before new Troy scene construction. Request ledgers retain
+the original reports; their current dispositions are summarized in the backlog.
+
Install with `bun install --frozen-lockfile` in this directory. Scene dependencies
-are separate from engine and site dependencies. Run `bun run typecheck`, `bun run lint`
-and `bun run test` for the portable source contracts. The runner explicitly lists
+are separate from engine and site dependencies. Run `bun run check:toolchain` and
+`bun run check:pins` first; the pin check resolves `../package.json`,
+`../render-service/package.json`, `../site/package.json` and `../site/bun.lock`
+within this integrated checkout, and compares the root and scene toolchain pins.
+Run `bun run typecheck`, `bun run lint` and `bun run test` for the portable source
+and script contracts; the normal test command now includes `scripts/tests`.
+The portable runner explicitly lists
19 author-input suites that belong to `bun run test:integration`; several other
asset-dependent cases also report their existing fixture skips. Browser and asset-integration scripts
require staged inputs; authoring scripts that regenerate packs also require their
@@ -20,7 +30,68 @@ The site builds Farm directly from this source, and serves the reviewed Golden G
and Foundry chunks without rewriting them. Use the scene kit's `sceneStandaloneConfig`
and verified asset packs when building a new standalone revision; changing source
requires requalification and new runtime pins before a site release.
+After restoring those exact inputs, `bun run test:release-inputs` exercises the
+released-asset integration cases and fails when required fixtures are absent.
Current scene inputs are Farm r36-local-review, Golden Gate g9 and Foundry ff3-review2.
-Those revision names are retained for provenance. Foundry remains an in-production
-preview, with AMRs and arms transporting containers and humanoids doing maintenance.
+Those revision names are retained for provenance. Foundry uses AMRs and arms to
+transport containers and humanoids for maintenance. Its old in-production preview
+label is historical; current source changes still require qualification and a newly
+sealed runtime before being served by the site.
+
+### Browser qualification on this Linux hub
+
+Scene-kit browser tools and the site's scene island/width/touch/Foundry-flow checks
+accept host-only configuration. The default remains headless. On the audited
+NVIDIA Linux hub, use `KILN_SCENE_HEADED=1` and
+`KILN_SCENE_CHROME_ARGS='["--ozone-platform=x11","--enable-features=Vulkan","--enable-unsafe-webgpu"]'`
+for hardware qualification. Arguments are a JSON array, not a shell command. An
+explicit helper `headless` option wins; helper arguments append after host flags.
+The 3 October capability probe found SwiftShader with headless Chrome 150 and real
+NVIDIA WebGPU/WebGL2 with this headed configuration. Record the actual adapter,
+backend and source receipt for each run; a successful API check alone is not
+hardware performance evidence. These options affect QA tools, not deployed scenes.
+
+### Farm release audit
+
+`scripts/capture-farm-paired.ts` implements D-68: capture the candidate and an
+explicit last-accepted test build against the same immutable pilot pair at the
+same phase. Supply `--label`, `--accepted-root` and `--new-root`; defaults cover
+all 16 named/play views on both backends. A new failure against the pilot counts
+as a regression only when the accepted build passes that same comparison.
+This audit supplements direct before/after parity, counts and performance checks.
+
+Release qualification also requires `--accepted-receipt`: a
+`kiln.farm-accepted-build/1` record binding the exact accepted build hash to its
+owner decision. Without that evidence the runner still produces useful diagnostic
+results but reports `releaseQualified: false`. An arbitrary label, reconstruction
+or adopted count baseline is not appearance acceptance. B-07 records its resource
+profile explicitly: 39 textures for the prewarmed path and 41 for the current
+cached-shadow path; legacy pilot allocations remain observations.
+
+For the preserved full-matrix alignment audit, `packages/farm/dist/original-draw-after/test`
+aliases the preserved optimized hub binary and `alignment-final/test` is the
+historical candidate. Later UI rebuilds retain separate identities and bounded
+evidence in the alignment plan. The original's 42 files were checked against the historical manifest.
+Use the shared hardware options above, then run from this directory:
+
+```sh
+bun scripts/capture-farm-paired.ts --label alignment-farm-paired-local-new-run --accepted-root packages/farm/dist/original-draw-after/test --new-root packages/farm/dist/alignment-final/test --release r34 --backend both
+bun scripts/farm-x02-baseline.ts measure --build alignment-final --backends webgpu,webgl2 --out .tmp/alignment-farm/local-new-run-x02-observed.json --log .tmp/alignment-farm/local-new-run-x02-observed-log.json
+bun scripts/farm-x02-baseline.ts check --summary .tmp/alignment-farm/local-new-run-x02-observed.json --backend webgpu --json .tmp/alignment-farm/local-new-run-x02-webgpu-check.json
+bun scripts/farm-x02-baseline.ts check --summary .tmp/alignment-farm/local-new-run-x02-observed.json --backend webgl2 --json .tmp/alignment-farm/local-new-run-x02-webgl2-check.json
+```
+
+Omit `--views` on the paired runner to cover all 32 cases; that runner does not
+accept `--views all`. The command deliberately supplies no acceptance receipt, so
+its result remains diagnostic even when every pair passes. Always give count
+measurement an explicit `--out`: its default is the committed baseline. A
+measurement is not authorization to re-baseline. Direct before/after image checks
+use `capture-farm-draw-parity.ts` separately; its status now fails for failed,
+errored or incomplete requested cells and reports that invocation's coverage.
+
+Full-view parity uses the shared luminance and thin-line gates. Historical stream
+crops retain their explicit luminance-only scope. `scripts/timing-ab.ts` records
+GPU clock in MHz and paired busy-times-clock samples with provenance; it is an
+activity proxy, not energy. Quiet-host/device and paired-decision requirements
+remain independent of image/count acceptance.
diff --git a/scenes/bun.lock b/scenes/bun.lock
index fa32175e..76fab781 100644
--- a/scenes/bun.lock
+++ b/scenes/bun.lock
@@ -12,17 +12,17 @@
"@vitejs/plugin-react": "6.1.1",
"axe-core": "4.13.0",
"fflate": "0.8.3",
- "npm": "12.0.2",
+ "npm": "12.2.0",
"pixelmatch": "7.2.0",
"pngjs": "7.0.0",
"puppeteer-core": "25.12.0",
"react": "19.3.0",
"react-dom": "19.3.0",
- "three": "0.186.0",
+ "three": "0.186.1",
"three-mesh-bvh": "0.9.15",
"typescript": "7.0.2",
"typescript-6": "npm:[email protected]",
- "vite": "8.3.0",
+ "vite": "8.3.2",
},
},
"packages/farm": {
@@ -36,13 +36,13 @@
"@types/three": "0.186.0",
"react": "19.3.0",
"react-dom": "19.3.0",
- "three": "0.186.0",
+ "three": "0.186.1",
},
"peerDependencies": {
"@react-three/fiber": "9.8.1",
"react": "19.3.0",
"react-dom": "19.3.0",
- "three": "0.186.0",
+ "three": "0.186.1",
},
},
"packages/foundry-floor": {
@@ -56,13 +56,13 @@
"@types/three": "0.186.0",
"react": "19.3.0",
"react-dom": "19.3.0",
- "three": "0.186.0",
+ "three": "0.186.1",
},
"peerDependencies": {
"@react-three/fiber": "9.8.1",
"react": "19.3.0",
"react-dom": "19.3.0",
- "three": "0.186.0",
+ "three": "0.186.1",
},
},
"packages/golden-gate": {
@@ -76,13 +76,13 @@
"@types/three": "0.186.0",
"react": "19.3.0",
"react-dom": "19.3.0",
- "three": "0.186.0",
+ "three": "0.186.1",
},
"peerDependencies": {
"@react-three/fiber": "9.8.1",
"react": "19.3.0",
"react-dom": "19.3.0",
- "three": "0.186.0",
+ "three": "0.186.1",
},
},
"packages/scene-kit": {
@@ -97,13 +97,13 @@
"@types/three": "0.186.0",
"react": "19.3.0",
"react-dom": "19.3.0",
- "three": "0.186.0",
+ "three": "0.186.1",
},
"peerDependencies": {
"@react-three/fiber": "9.8.1",
"react": "19.3.0",
"react-dom": "19.3.0",
- "three": "0.186.0",
+ "three": "0.186.1",
},
},
},
@@ -284,7 +284,7 @@
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug=="],
- "npm": ["[email protected]", "", { "dependencies": { "@isaacs/string-locale-compare": "^1.1.0", "@npmcli/arborist": "^10.0.2", "@npmcli/config": "^11.0.1", "@npmcli/fs": "^6.0.0", "@npmcli/git": "^8.0.0", "@npmcli/map-workspaces": "^6.0.0", "@npmcli/metavuln-calculator": "^10.0.0", "@npmcli/package-json": "^8.0.0", "@npmcli/promise-spawn": "^10.0.0", "@npmcli/redact": "^5.0.0", "@npmcli/run-script": "^11.0.0", "@sigstore/tuf": "^5.0.0", "abbrev": "^5.0.0", "archy": "~1.0.0", "bin-links": "^7.0.0", "cacache": "^21.0.1", "chalk": "^5.6.2", "ci-info": "^4.4.0", "diff": "^8.0.2", "fastest-levenshtein": "^1.0.16", "fs-minipass": "^3.0.3", "glob": "^13.0.6", "graceful-fs": "^4.2.11", "hosted-git-info": "^10.1.1", "ini": "^7.0.0", "init-package-json": "^9.0.0", "is-cidr": "^7.0.0", "json-parse-even-better-errors": "^6.0.0", "libnpmaccess": "^11.0.0", "libnpmdiff": "^9.0.2", "libnpmexec": "^11.0.2", "libnpmfund": "^8.0.2", "libnpmorg": "^9.0.0", "libnpmpack": "^10.0.2", "libnpmpublish": "^12.0.0", "libnpmsearch": "^10.0.0", "libnpmteam": "^9.0.0", "libnpmversion": "^9.0.0", "make-fetch-happen": "^16.0.1", "minimatch": "^10.2.5", "minipass": "^7.1.3", "minipass-pipeline": "^1.2.4", "ms": "^2.1.2", "node-gyp": "^13.0.0", "nopt": "^10.0.1", "npm-audit-report": "^8.0.0", "npm-install-checks": "^9.0.0", "npm-package-arg": "^14.0.0", "npm-pick-manifest": "^12.0.0", "npm-profile": "^13.0.1", "npm-registry-fetch": "^20.0.1", "npm-user-validate": "^5.0.0", "p-map": "^7.0.4", "pacote": "^22.0.0", "parse-conflict-json": "^6.0.0", "proc-log": "^7.0.0", "qrcode-terminal": "^0.12.0", "read": "^6.0.0", "semver": "^7.8.5", "spdx-expression-parse": "^4.0.0", "ssri": "^14.0.0", "supports-color": "^10.2.2", "tar": "^7.5.19", "text-table": "~0.2.0", "tiny-relative-date": "^2.0.2", "treeverse": "^3.0.0", "validate-npm-package-name": "^8.0.0", "which": "^7.0.0" }, "bin": { "npm": "bin/npm-cli.js", "npx": "bin/npx-cli.js" } }, "sha512-uIXokLlBj6FpNUTQX1PmT5pz7BlIN9QlixX+zdaSNHsd0qUXsbDLr50xzY6Sw7cJVr0uzHKDOle0swmPW/p5Qw=="],
+ "npm": ["[email protected]", "", { "dependencies": { "@isaacs/string-locale-compare": "^1.1.0", "@npmcli/arborist": "^10.0.3", "@npmcli/config": "^11.2.0", "@npmcli/fs": "^6.0.0", "@npmcli/git": "^8.0.0", "@npmcli/map-workspaces": "^6.0.0", "@npmcli/metavuln-calculator": "^10.0.0", "@npmcli/package-json": "^8.0.0", "@npmcli/promise-spawn": "^10.0.0", "@npmcli/redact": "^5.0.0", "@npmcli/run-script": "^11.0.0", "@sigstore/tuf": "^5.0.0", "abbrev": "^5.0.0", "archy": "~1.0.0", "bin-links": "^7.0.0", "cacache": "^21.0.1", "chalk": "^5.6.2", "ci-info": "^4.4.0", "diff": "^8.0.2", "fastest-levenshtein": "^1.0.16", "fs-minipass": "^3.0.3", "glob": "^13.0.6", "graceful-fs": "^4.2.11", "hosted-git-info": "^10.1.1", "ini": "^7.0.0", "init-package-json": "^9.0.0", "is-cidr": "^7.0.0", "json-parse-even-better-errors": "^6.0.0", "libnpmaccess": "^11.0.0", "libnpmdiff": "^9.0.3", "libnpmexec": "^11.0.3", "libnpmfund": "^8.0.3", "libnpmorg": "^9.0.0", "libnpmpack": "^10.0.3", "libnpmpublish": "^12.0.1", "libnpmsearch": "^10.0.0", "libnpmteam": "^9.0.0", "libnpmversion": "^9.0.0", "make-fetch-happen": "^16.0.1", "minimatch": "^10.2.5", "minipass": "^7.1.3", "minipass-pipeline": "^1.2.4", "ms": "^2.1.2", "node-gyp": "^13.0.0", "nopt": "^10.0.1", "npm-audit-report": "^8.0.0", "npm-install-checks": "^9.0.0", "npm-package-arg": "^14.0.0", "npm-pick-manifest": "^12.0.0", "npm-profile": "^13.0.1", "npm-registry-fetch": "^20.0.1", "npm-user-validate": "^5.0.0", "p-map": "^7.0.4", "pacote": "^22.0.0", "parse-conflict-json": "^6.0.0", "proc-log": "^7.0.0", "qrcode-terminal": "^0.12.0", "read": "^6.0.0", "semver": "^7.8.5", "spdx-expression-parse": "^4.0.0", "ssri": "^14.0.0", "supports-color": "^10.2.2", "tar": "^7.5.22", "text-table": "~0.2.0", "tiny-relative-date": "^2.0.2", "treeverse": "^3.0.0", "validate-npm-package-name": "^8.0.0", "which": "^7.0.0" }, "bin": { "npm": "bin/npm-cli.js", "npx": "bin/npx-cli.js" } }, "sha512-ZsJjKpTnlmSXOLLXiU1xDCzC4Wlok4IwZmh/aw2KUuXytU7q6qMv/cUT7MoeSf95Slwuw/lRXYefGzGCspHPNQ=="],
"picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
@@ -316,7 +316,7 @@
"suspend-react": ["[email protected]", "", { "peerDependencies": { "react": ">=17.0" } }, "sha512-aqldKgX9aZqpoDp3e8/BZ8Dm7x1pJl+qI3ZKxDN0i/IQTWUwBx/ManmlVJ3wowqbno6c2bmiIfs+Um6LbsjJyQ=="],
- "three": ["[email protected]", "", {}, "sha512-cr/fIM2ddMSVbYVgkfD4jLJv7Fh/8ZTjvo+7gQeSVGUZHxpx9FDwoL5iC7hUz/LiRA8wMbqfnb90xKfm1/HHkQ=="],
+ "three": ["[email protected]", "", {}, "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA=="],
"three-mesh-bvh": ["[email protected]", "", { "peerDependencies": { "three": ">= 0.159.0" } }, "sha512-9xdEDkCzFoT8VPFH9DznwFSdbaIEjMvM106Iqq7TJurrIheUKDcdW4prfJTCxryih4XS/UxWs0H3K4MLMRFyOQ=="],
@@ -330,7 +330,7 @@
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="],
- "vite": ["[email protected]", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.6", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ=="],
+ "vite": ["[email protected]", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.11", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-SQr1x6W5vVSbROg7vsyXIaxK9b0G7zsT68acdWWRmnBUsgDieLCRG+Rep9WdZgcposvv/GSnr4GUUBqB3vXq6w=="],
"webdriver-bidi-protocol": ["[email protected]", "", {}, "sha512-uuN0goWfxP22B7J/uAgBpOYNPttC+XVseYE+rSY5+rQ+YBeVz/VORw8WbmLVcqW78zNg5A4qnjNXYUWR3il2ig=="],
@@ -360,7 +360,7 @@
"npm/@npmcli/arborist": ["@npmcli/[email protected]", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@isaacs/string-locale-compare": "^1.1.0", "@npmcli/fs": "^6.0.0", "@npmcli/installed-package-contents": "^5.0.0", "@npmcli/map-workspaces": "^6.0.0", "@npmcli/metavuln-calculator": "^10.0.0", "@npmcli/name-from-folder": "^5.0.0", "@npmcli/node-gyp": "^6.0.0", "@npmcli/package-json": "^8.0.0", "@npmcli/query": "^5.0.0", "@npmcli/redact": "^5.0.0", "@npmcli/run-script": "^11.0.0", "bin-links": "^7.0.0", "cacache": "^21.0.1", "common-ancestor-path": "^2.0.0", "diff": "^8.0.2", "hosted-git-info": "^10.1.1", "json-stringify-nice": "^1.1.4", "lru-cache": "^11.2.1", "minimatch": "^10.0.3", "nopt": "^10.0.1", "npm-install-checks": "^9.0.0", "npm-package-arg": "^14.0.0", "npm-pick-manifest": "^12.0.0", "npm-registry-fetch": "^20.0.1", "pacote": "^22.0.0", "parse-conflict-json": "^6.0.0", "proc-log": "^7.0.0", "proggy": "^4.0.0", "promise-all-reject-late": "^1.0.0", "promise-call-limit": "^3.0.1", "semver": "^7.3.7", "ssri": "^14.0.0", "treeverse": "^3.0.0", "validate-npm-package-name": "^8.0.0", "walk-up-path": "^4.0.0" }, "bundled": true, "bin": { "arborist": "bin/index.js" } }, "sha512-QuGpR01YV/4RuJ+5S0W5qh4uljQygmk7b50Jkx+zLErOMMUpKhpbLu/TqQlKfsvuR3SOwXIn3ht+G4bcxrv1WA=="],
- "npm/@npmcli/config": ["@npmcli/[email protected]", "", { "dependencies": { "@npmcli/map-workspaces": "^6.0.0", "@npmcli/package-json": "^8.0.0", "ci-info": "^4.0.0", "ini": "^7.0.0", "nopt": "^10.0.1", "proc-log": "^7.0.0", "semver": "^7.3.5", "walk-up-path": "^4.0.0" }, "bundled": true }, "sha512-xw2VW5qFHnkQL7svD7JY2hOu79golhbSsVFPe+yvMp4pShY31+VHGjh9jpdO3xhYgRUyo9gjmHD6a6UxeDwYjQ=="],
+ "npm/@npmcli/config": ["@npmcli/[email protected]", "", { "dependencies": { "@npmcli/map-workspaces": "^6.0.0", "@npmcli/package-json": "^8.0.0", "ci-info": "^4.0.0", "ini": "^7.0.0", "nopt": "^10.0.1", "proc-log": "^7.0.0", "semver": "^7.3.5", "walk-up-path": "^4.0.0" }, "bundled": true }, "sha512-PZtUL2rXqThZUT5KGsbVEGdrJswgBoY56X8hXIozwoayHC/rRsaJCIz4nsBzHJvNpCjGEbufJqStaqB7Qdd4ww=="],
"npm/@npmcli/fs": ["@npmcli/[email protected]", "", { "dependencies": { "semver": "^7.3.5" }, "bundled": true }, "sha512-AheOs4swKka/XLtht6xxJDPezlQ7K2IYQ9Y8lST4JLDjnralnWuMM9AE2CdVcgQJ5omrXhsRzM7F7aYmeZBvKQ=="],
diff --git a/scenes/package.json b/scenes/package.json
index 82d459fd..19332736 100644
--- a/scenes/package.json
+++ b/scenes/package.json
@@ -13,6 +13,7 @@
"lint": "bun scripts/lint.ts",
"test": "bun scripts/test-portable.ts",
"test:integration": "bun test",
+ "test:release-inputs": "bun scripts/test-release-inputs.ts",
"test:browser": "bun scripts/run-m1.ts",
"build": "bun packages/scene-kit/demo/stage-demo.ts && bun scripts/build-demo.ts --all",
"demo:build": "bun packages/scene-kit/demo/stage-demo.ts && bun scripts/build-demo.ts --all",
@@ -35,16 +36,16 @@
"@vitejs/plugin-react": "6.1.1",
"axe-core": "4.13.0",
"fflate": "0.8.3",
- "npm": "12.0.2",
+ "npm": "12.2.0",
"pixelmatch": "7.2.0",
"pngjs": "7.0.0",
"puppeteer-core": "25.12.0",
"react": "19.3.0",
"react-dom": "19.3.0",
- "three": "0.186.0",
+ "three": "0.186.1",
"three-mesh-bvh": "0.9.15",
"typescript": "7.0.2",
"typescript-6": "npm:[email protected]",
- "vite": "8.3.0"
+ "vite": "8.3.2"
}
}
diff --git a/scenes/packages/farm/package.json b/scenes/packages/farm/package.json
index 79943f13..79ac5265 100644
--- a/scenes/packages/farm/package.json
+++ b/scenes/packages/farm/package.json
@@ -10,13 +10,13 @@
"react": "19.3.0",
"react-dom": "19.3.0",
"@react-three/fiber": "9.8.1",
- "three": "0.186.0"
+ "three": "0.186.1"
},
"devDependencies": {
"react": "19.3.0",
"react-dom": "19.3.0",
"@react-three/fiber": "9.8.1",
- "three": "0.186.0",
+ "three": "0.186.1",
"@types/three": "0.186.0"
}
}
diff --git a/scenes/packages/farm/scripts/stage-assets.ts b/scenes/packages/farm/scripts/stage-assets.ts
index c8fbf801..5b610990 100644
--- a/scenes/packages/farm/scripts/stage-assets.ts
+++ b/scenes/packages/farm/scripts/stage-assets.ts
@@ -19,11 +19,11 @@ export function stageFarm(args:readonly string[]=process.argv.slice(2)){
for(const [path,body]of selected.archives.runtime.entries)if(path.startsWith('licenses/'))files.push({from:resolve(runtimeRoot,path),to:path,sha256:sha256(body)});
for(const name of ['LICENSE-FIELD-GRASS.txt','LICENSE-VIEWER.txt','LICENSE-THREE.txt','LICENSE-BVH.txt']){const path=`scene/${name}`;files.push({from:resolve(sceneRoot,path),to:`licenses/${name}`,sha256:sha256(required(selected.archives.scene.entries,path))});}
const source={projectRevision:selected.downloads.projectRevision,downloadsSha256:selected.downloadsSha256,runtimeZipSha256:selected.archives.runtime.receipt.sha256.slice(7),sceneZipSha256:selected.archives.scene.receipt.sha256.slice(7),parentDeliveryManifestSha256:selected.downloads.parentDeliveryManifestSha256.slice(7),fullPackAccepted:selected.downloads.fullPackAccepted,archives:Object.fromEntries(Object.entries(selected.archives).map(([profile,v])=>[profile,{...v.receipt,verifiedMembers:v.verifiedMembers}])),sceneMetadata:{runtimeArchiveSha256:selected.sceneManifest.runtimeArchiveSha256,deliverySha256:selected.sceneManifest.deliverySha256},memberReceiptSelfExclusion:'delivery.json only; authenticated by enclosing archive SHA-256'};
- const result=stageFiles({id:'farm',release:options.release,three:'0.186.0',out,force:options.force,models:selected.models.map(m=>({id:m.id,to:m.path})),data,files,source,credits:[
+ const result=stageFiles({id:'farm',release:options.release,three:'0.186.1',out,force:options.force,models:selected.models.map(m=>({id:m.id,to:m.path})),data,files,source,credits:[
{name:'Shapes & Seasons Farm assets',licence:'CC0-1.0',note:'Designated CC0-1.0 by the project owner. Exact declaration and legal text: licenses/ASSET-LICENSE.txt and licenses/CC0-1.0.txt.'},
{name:'Field Grass 0.1.0',licence:'MIT',holder:'Matthew Kissinger',note:'Vendored source, commit 2a0d3a3256dc8d8f6d9de68f3dc1636a621559c5; licenses/LICENSE-FIELD-GRASS.txt.'},
{name:'Farm viewer derivative',licence:'MIT',holder:'Matthew Kissinger',note:'licenses/LICENSE-VIEWER.txt.'},
- {name:'three',licence:'MIT',note:'licenses/LICENSE-THREE.txt; runtime package pinned to 0.186.0.'},
+ {name:'three',licence:'MIT',note:'licenses/LICENSE-THREE.txt; runtime package pinned to 0.186.1.'},
{name:'three-mesh-bvh',licence:'MIT',note:'licenses/LICENSE-BVH.txt.'},
]});
const verification=verifyStaged(out);if(!verification.ok)throw new Error(verification.problems.join('\n'));
diff --git a/scenes/packages/farm/scripts/stage-review2.ts b/scenes/packages/farm/scripts/stage-review2.ts
index c9f2c7b8..16c90a3a 100644
--- a/scenes/packages/farm/scripts/stage-review2.ts
+++ b/scenes/packages/farm/scripts/stage-review2.ts
@@ -14,7 +14,7 @@ const hand = resolve(root, '../engine-work/local-v09-review/revision2-20260930/f
const handHash = '088edfec80dc0ed8da9a3883ebf74ff75d55efdb71a056ddb271b553999c3c9e';
const hash = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex');
const files = parent.files.map(file => ({ from: file.path === 'models/farmer.glb' ? hand : resolve(before, file.path), to: file.path, sha256: file.path === 'models/farmer.glb' ? handHash : file.sha256 }));
-const result = stageFiles({ id: parent.id, release: 'r35-local-review', three: '0.186.0', out, force: true,
+const result = stageFiles({ id: parent.id, release: 'r35-local-review', three: '0.186.1', out, force: true,
models: parent.models.map(model => ({ id: model.id, to: model.path })), data: parent.data, files, credits: parent.credits,
source: { parentRelease: 'r34', parentPackSha256: hash(readFileSync(resolve(before, 'pack.json'))), ownerAccepted: false,
replacements: [{ id: 'farmer', assetId: asset, parentRevision: 'r_d0e65e4d47aa4449a07ed288a78d461b', revision, sha256: handHash, exportProfile: 'runtime', canonicalSha256: '6ebf243099f0325e30c3937c41d079e95e3d98a20a92e0d6436234c926139bfd',
diff --git a/scenes/packages/farm/src/constants.ts b/scenes/packages/farm/src/constants.ts
index 4061d688..093a9668 100644
--- a/scenes/packages/farm/src/constants.ts
+++ b/scenes/packages/farm/src/constants.ts
@@ -46,7 +46,8 @@ export const FARM_DESTINATIONS = {
* again after `settleFrames` still frames), hero depth stand-ins on `standInLayer` (never 0, below the kit's 30 and 31),
* and casters under `minCasterTexels` shadow texels of the tier's map dropped inside stand-ins and from the herd batches.
* Heroes of `keepSmallCasters` keep every part through that threshold: the player's own shadow is on screen in every play
- * frame, so at economy his neck, cuffs and boot contact stay in it (review RF-1); their parts still bake into stand-ins.
+ * frame, so at economy his neck, cuffs and boot contact stay in it (review RF-1). The trailer also keeps its drawbar,
+ * hitch ring and hitch pin (D-72); these retained parts still bake into stand-ins.
*/
-export const FARM_SHADOW = { cache: true, standIns: true, minCasterTexels: 2, settleFrames: 30, standInLayer: 1, keepSmallCasters: ['farmer'] as readonly string[] };
+export const FARM_SHADOW = { cache: true, standIns: true, minCasterTexels: 2, settleFrames: 30, standInLayer: 1, keepSmallCasters: ['farmer', 'trailer'] as readonly string[] };
export const FARM_STRUCTURE = { batchingCell: 96, batchingOffset: 48, woodlandTrees: 843, woodlandCell: 64, woodlandSourceMeshes: 4, bvhLeafSize: 10, resolvePasses: 3, floorDrop: .35, porchFloorDrop: .25, routeSeconds: 30 };
diff --git a/scenes/packages/farm/src/play/farmer-rig.ts b/scenes/packages/farm/src/play/farmer-rig.ts
index f0537e54..ce13991c 100644
--- a/scenes/packages/farm/src/play/farmer-rig.ts
+++ b/scenes/packages/farm/src/play/farmer-rig.ts
@@ -1,20 +1,93 @@
-import { Quaternion, Vector3 } from 'three/webgpu';
-import type { Object3D } from 'three/webgpu';
+import { LoopRepeat, Quaternion, Vector3 } from 'three/webgpu';
+import type { Mesh, Object3D } from 'three/webgpu';
+import { registerWarmPoseVariant } from '../world/prewarm';
+import type { FarmInstance } from '../world/types';
/** Ports of the sealed `interaction-rig.mjs` poses. Authored GLBs stay byte-identical;
- * every per-step call reuses module scratch objects (SPEC 12.4 rule 2). */
+ * every pose update reuses captured or module scratch objects (SPEC 12.4 rule 2). */
const find = (root: Object3D, name: string): Object3D => {
const node = root.getObjectByName(name); if (!node) throw new Error('Missing rig joint ' + name); return node;
};
-export interface EmptyHandedPose { apply(): void }
-/** The source right forearm is authored across the body to hold a tool. */
+export interface EmptyHandedPose { apply(): void; restore(): void; dispose(): void }
+/** Scene-only relaxed right arm, borrowed from the saved left arm. The original tool
+ * grip and asymmetric forearm remain intact for seating and overview/tool poses. */
export function createEmptyHandedPose(farmer: Object3D): EmptyHandedPose {
- const left = farmer.getObjectByName('Joint_LeftShoulder'), right = farmer.getObjectByName('Joint_RightShoulder'), elbow = farmer.getObjectByName('Joint_RightElbow');
- if (!left || !right || !elbow) throw new Error('Missing farmer arm rig');
- const relaxed = new Quaternion().setFromUnitVectors(new Vector3(.15, -.035, .113).normalize(), new Vector3(.02, -1, .06).normalize());
- // A small outward shoulder angle keeps the relaxed hands outside the hips through the full
- // authored stride, including chest yaw. Preserve the clip's forward/back shoulder swing.
- return { apply() { left.rotation.x = .28; right.rotation.set(-.28, 0, -left.rotation.z); elbow.quaternion.copy(relaxed); } };
+ const left = find(farmer, 'Joint_LeftShoulder'), right = find(farmer, 'Joint_RightShoulder');
+ const leftElbow = find(farmer, 'Joint_LeftElbow'), elbow = find(farmer, 'Joint_RightElbow');
+ const source = find(farmer, 'Mesh_Consolidated_Joint_LeftElbow_0') as Mesh;
+ const original = find(farmer, 'Mesh_Consolidated_Joint_RightElbow_0') as Mesh;
+ const attachment = find(farmer, 'Joint_RightHandToolAttachment');
+ if (!source.isMesh || !original.isMesh) throw new Error('Missing farmer consolidated lower-arm geometry');
+ // This whole saved mesh is only elbow, forearm, palm, fingers and thumb. Mirroring the
+ // complete surface retains its wrist contact without guessing vertex splits or dimensions.
+ // Mesh's negative determinant selects the renderer's mirrored front-face convention.
+ const relaxed = source.clone(false); relaxed.name = 'Mesh_EmptyHandedRightArm';
+ relaxed.position.z *= -1; relaxed.scale.z *= -1;
+ relaxed.quaternion.set(-source.quaternion.x, -source.quaternion.y, source.quaternion.z, source.quaternion.w);
+ relaxed.userData = { farmEmptyHanded: { source: source.name, borrowedGeometry: true }, farmPoseVisibility: true };
+ relaxed.visible = false; elbow.add(relaxed);
+ const unregisterWarm = registerWarmPoseVariant(relaxed);
+ const leftRest = left.quaternion.clone(), rightRest = right.quaternion.clone(), elbowRest = elbow.quaternion.clone();
+ const relaxedElbow = leftElbow.quaternion.clone(); relaxedElbow.set(-relaxedElbow.x, -relaxedElbow.y, relaxedElbow.z, relaxedElbow.w);
+ const originalVisible = original.visible, attachmentVisible = attachment.visible;
+ const originalAnchor = original.userData.farmPoseVisibility; original.userData.farmPoseVisibility = true;
+ let disposed = false;
+ function restore() {
+ relaxed.visible = false; original.visible = originalVisible; attachment.visible = attachmentVisible;
+ left.quaternion.copy(leftRest); right.quaternion.copy(rightRest); elbow.quaternion.copy(elbowRest);
+ }
+ return { apply() {
+ if (disposed) return;
+ // Keep the authored forward/back swing and the measured outward hip clearance.
+ left.rotation.x = .28; right.rotation.set(-.28, 0, -left.rotation.z); elbow.quaternion.copy(relaxedElbow);
+ original.visible = false; attachment.visible = false; relaxed.visible = true;
+ }, restore, dispose() {
+ if (disposed) return; disposed = true; restore(); unregisterWarm(); relaxed.removeFromParent();
+ if (originalAnchor === undefined) delete original.userData.farmPoseVisibility; else original.userData.farmPoseVisibility = originalAnchor;
+ // The saved geometry/material belong to the loaded pack; this derivative owns neither.
+ } };
+}
+type PlayerClip = 'Idle' | 'Walk';
+/** Only the player locomotion clips blend. Explicit seat/overview restores still stop
+ * them immediately. Weights advance with the one rendered mixer update, not physics steps. */
+export function createFarmerClipBlend(player: FarmInstance, indices: Record<PlayerClip, string>) {
+ const actions = { Idle: player.mixer.clipAction(player.clips[Number(indices.Idle)]!), Walk: player.mixer.clipAction(player.clips[Number(indices.Walk)]!) };
+ const duration = .15;
+ let target: PlayerClip | null = null, walkWeight = 0, fromWeight = 0, elapsed = duration;
+ function reset() {
+ player.mixer.stopAllAction();
+ for (const action of Object.values(actions)) action.setEffectiveWeight(0);
+ target = null; walkWeight = fromWeight = 0; elapsed = duration;
+ player.action = null; player.clipIndex = '';
+ }
+ return {
+ select(name: PlayerClip, timeScale = 1) {
+ const action = actions[name];
+ if (!target) {
+ reset(); walkWeight = name === 'Walk' ? 1 : 0; fromWeight = walkWeight;
+ action.reset().setLoop(LoopRepeat, Infinity).setEffectiveWeight(1).play();
+ } else if (target !== name) {
+ // A reversed fade starts at the currently rendered weights and keeps active clip
+ // time. Reset only a retired action; never restart one still contributing a pose.
+ if (!action.isScheduled()) action.reset().setLoop(LoopRepeat, Infinity).setEffectiveWeight(name === 'Walk' ? walkWeight : 1 - walkWeight).play();
+ fromWeight = walkWeight; elapsed = 0;
+ }
+ target = name; action.timeScale = timeScale;
+ player.action = action; player.clipIndex = indices[name];
+ },
+ update(dt: number) {
+ if (!target) return;
+ elapsed = Math.min(duration, elapsed + Math.max(0, dt));
+ walkWeight = fromWeight + ((target === 'Walk' ? 1 : 0) - fromWeight) * (elapsed / duration);
+ actions.Walk.setEffectiveWeight(walkWeight); actions.Idle.setEffectiveWeight(1 - walkWeight);
+ if (elapsed === duration) {
+ const outgoing = actions[target === 'Walk' ? 'Idle' : 'Walk'];
+ if (outgoing.isScheduled()) outgoing.stop();
+ }
+ player.mixer.update(dt);
+ },
+ reset,
+ };
}
/** Rest transforms captured once at construction, restored like the pilot's restoreRig. */
export interface RigRest { restore(): void }
diff --git a/scenes/packages/farm/src/play/sim.ts b/scenes/packages/farm/src/play/sim.ts
index 1725b908..c99278ef 100644
--- a/scenes/packages/farm/src/play/sim.ts
+++ b/scenes/packages/farm/src/play/sim.ts
@@ -9,7 +9,7 @@ import type { FarmColliders } from '../world/colliders';
import type { FarmInstance } from '../world/types';
import { doorCenter, stepDoors, toggleDoor } from './doors';
import type { DoorStepContext, FarmDoor } from './doors';
-import { captureRest, createEmptyHandedPose, createSeatRig } from './farmer-rig';
+import { captureRest, createEmptyHandedPose, createFarmerClipBlend, createSeatRig } from './farmer-rig';
import { createTractorRig, driveTractor, findTractorExit, TRACTOR_EXITS, TRACTOR_PROBE } from './tractor';
import type { TractorState } from './tractor';
import { FARM_DESTINATIONS, isFarmDestination } from './destinations';
@@ -45,7 +45,7 @@ export function createFarmSim(o: { instances: readonly FarmInstance[]; colliders
if (!fork) throw new Error('Missing farmer pitchfork joint');
const clipIndex = (name: string) => { const index = player.clips.findIndex(clip => clip.name === name); if (index < 0) throw new Error('Missing farmer clip ' + name); return String(index); };
const clips = { Idle: clipIndex('Idle'), Walk: clipIndex('Walk') };
- const home = player.object.position.clone(), rest = captureRest(player.object);
+ const home = player.object.position.clone(), rest = captureRest(player.object), animation = createFarmerClipBlend(player, clips);
const emptyHands = createEmptyHandedPose(player.object), seat = createSeatRig(player.object, tractor.object), rig = createTractorRig(tractor.object);
const prompts = new Map(doors.map(door => [door, { open: doorPrompt(door.label, false), close: doorPrompt(door.label, true) }]));
const mover: MoverState = { position: player.object.position, velocityY: 0, yaw: player.object.rotation.y, speedXZ: 0, status: '' };
@@ -74,16 +74,16 @@ export function createFarmSim(o: { instances: readonly FarmInstance[]; colliders
return FARM_STRINGS.approach;
},
get canInteract() { return active && (driving || nearestTractor || !!nearestDoor); },
- start, stop, interact, exitVehicle, visit, reset, update, resetCamera,
+ start, stop, interact, exitVehicle, visit, reset, update, updateAnimation, resetCamera,
/** The last interaction input kind decides the tractor help string (SPEC 13.1). */
setTouch(value: boolean) { touch = value; },
- dispose() { disposed = true; active = false; follow.subject.current = null; },
+ dispose() { disposed = true; active = false; follow.subject.current = null; animation.reset(); emptyHands.dispose(); },
};
- function restoreRig() { player!.mixer.stopAllAction(); rest.restore(); currentClip = ''; }
+ function updateAnimation(dt: number) { if (!disposed && active && !driving) animation.update(dt); }
+ function restoreRig() { animation.reset(); emptyHands.restore(); rest.restore(); currentClip = ''; }
function clip(name: 'Idle' | 'Walk', scale = 1) {
- if (currentClip !== name) { chooseClip(player!, clips[name]); currentClip = name; }
- if (player!.action) player!.action.timeScale = scale;
+ animation.select(name, scale); currentClip = name;
}
function subject() { return driving ? tractor!.object : player!.object; }
/** Keeps the rig target on the pilot's `target()`: subject position plus 1.9 m walking or 1.6 m driving. */
@@ -187,8 +187,11 @@ export function createFarmSim(o: { instances: readonly FarmInstance[]; colliders
doorContext.status = sim.status; stepDoors(doors, step, doorContext); sim.status = doorContext.status;
if (!active) return;
if (driving) driveStep(step, input);
- else { walk(step, input, cameraForward); emptyHands.apply(); }
+ else walk(step, input, cameraForward);
});
+ // The mixer runs on every rendered frame, including frames without a fixed step.
+ // Reapply the procedural pose after it before matrices and the follow camera consume it.
+ if (active && !driving) emptyHands.apply();
if (active) { syncFollow(); nearestInteraction(); }
}
return sim;
diff --git a/scenes/packages/farm/src/play/systems.ts b/scenes/packages/farm/src/play/systems.ts
index 04979600..d515b2ec 100644
--- a/scenes/packages/farm/src/play/systems.ts
+++ b/scenes/packages/farm/src/play/systems.ts
@@ -26,7 +26,7 @@ export function useFarmPlaySystems(world: FarmWorld | null, session: FarmSession
// Walking is user-initiated motion (SPEC 13.4): it animates without ambient animation, on
// the unscaled step. A frozen test/dev clock (time scale 0) holds the current clip at its
// present time, so a clip chosen while frozen (Idle on entering play) still poses Rowan.
- if (player?.action) player.mixer.update(clock.timeScale > 0 ? Math.min(.1, dt) : 0);
+ if (player?.action) world.sim.updateAnimation(clock.timeScale > 0 ? Math.min(.1, dt) : 0);
});
useSystem('farm-sim', SystemOrder.sim, dt => {
const sim = world?.sim; if (!sim) return;
diff --git a/scenes/packages/farm/src/ui/FarmHud.tsx b/scenes/packages/farm/src/ui/FarmHud.tsx
index b2c01229..cb00b3dc 100644
--- a/scenes/packages/farm/src/ui/FarmHud.tsx
+++ b/scenes/packages/farm/src/ui/FarmHud.tsx
@@ -5,7 +5,7 @@ import { FARM_STRINGS } from './strings';
/**
* Farm-scoped layout (M3a, D-22). The HUD lays out from 360 px wide in both orientations:
- * - the toolbar is static inside a full-HUD layer, so the help panel sizes against the HUD (GG-007) and stacks above the controls;
+ * - the toolbar shares the full-HUD layer; the kit anchors the help panel to that HUD and stacks it above the controls;
* - the overview camera controls sit bottom-left and wrap, clear of the toolbar;
* - the status line rises above the overview camera controls; in touch play it sits under the toolbar, away from the
* joystick, the context button and the player (beside the toolbar in a short landscape scene); it never takes input.
diff --git a/scenes/packages/farm/src/world/optimize.ts b/scenes/packages/farm/src/world/optimize.ts
index 99e62076..34904aea 100644
--- a/scenes/packages/farm/src/world/optimize.ts
+++ b/scenes/packages/farm/src/world/optimize.ts
@@ -27,7 +27,7 @@ export interface FarmShadowBuild {mapSize:number;standIns:boolean;minCasterTexel
* material after batching, so every B-07 count is taken first, then given shadow stand-ins before freezing (stand-ins copy
* their anchor's matrix flags). Merged geometry is shared per asset, anchor path and group through one cache (the gates), and
* keeps the GLB's interleaved vertex layout, so a merged mesh shares the pipeline of unmerged meshes (review RK-1).
- * Stand-ins bake only sources the sun's shadow camera draws (farmShadowMask); farmers keep their small parts (RF-1).
+ * Stand-ins bake only sources the sun's shadow camera draws (farmShadowMask); farmers and trailers keep their small parts (RF-1, D-72).
*/
export function optimizeFarmWorld(root:Scene,instances:readonly FarmInstance[],woodland:{meshes:InstancedMesh[];derivatives:number},options:{packWoodland:boolean;heroMerge?:boolean;shadow?:FarmShadowBuild|null}){
const owners=farmInstanceOwners(instances),policy=farmBatchPolicy(),registry=new DisposeRegistry();
diff --git a/scenes/packages/farm/src/world/prewarm.ts b/scenes/packages/farm/src/world/prewarm.ts
index 3983d41a..8378bc3c 100644
--- a/scenes/packages/farm/src/world/prewarm.ts
+++ b/scenes/packages/farm/src/world/prewarm.ts
@@ -4,7 +4,7 @@ import type { Camera, Layers, Material, Object3D, Scene } from 'three/webgpu';
export interface WarmPassRenderer { compileAsync(object: Object3D, camera: Camera, targetScene?: Scene | null): Promise<unknown> }
export type WarmPhase = 'compiling' | 'drawing' | 'done';
export interface WarmPassStats {
- /** Nodes that draw (meshes, lines, points, sprites) visible below the world root when the pass started. */
+ /** Visible drawables plus explicitly registered pose variants on the main camera layers. */
renderables: number;
/** Compile chains; renderables that share a material and vertex layout share a chain. */
chains: number;
@@ -22,7 +22,7 @@ export interface WarmPass {
readonly stats: WarmPassStats;
/** Call once per frame before the render; true once the pass is complete (the caller may then declare the world built). */
step(): boolean;
- /** Restores the culling flags the pass changed and shows the world it hid; pending compiles finish without effect. */
+ /** Restores culling and registered-pose visibility, and shows the world it hid; pending compiles finish without effect. */
dispose(): void;
}
@@ -46,17 +46,30 @@ export interface WarmPassOptions {
onDraw?(): void;
}
+// Explicit Farm consumer variants only; ordinary hidden model branches stay excluded.
+const poseVariants = new WeakSet<Object3D>();
+export function registerWarmPoseVariant(object: Object3D): () => void {
+ poseVariants.add(object); return () => { poseVariants.delete(object); };
+}
+
const drawable = (object: Object3D) => { const o = object as unknown as Record<string, unknown>; return !!(o.isMesh || o.isLine || o.isPoints || o.isSprite); };
-/**
- * Every drawable node below root whose own visibility and that of its ancestors below root is true (root's own flag is
- * ignored); with `layers`, only those a camera on them draws (three tests layers per object: shadow stand-ins are not).
- */
-export function warmRenderables(root: Object3D, layers?: Layers): Object3D[] {
- const found: Object3D[] = [];
- const visit = (object: Object3D) => { if (!object.visible) return; if (drawable(object) && (!layers || object.layers.test(layers))) found.push(object); for (const child of object.children) visit(child); };
+/** Collect visible branches plus explicitly registered hidden pose roots. A registration
+ * never pierces an unrelated hidden ancestor or makes ordinary hidden children visible. */
+function warmTargets(root: Object3D, layers?: Layers) {
+ const drawables: Object3D[] = [], variants: Object3D[] = [];
+ const visit = (object: Object3D) => {
+ if (!object.visible) { if (!poseVariants.has(object)) return; variants.push(object); }
+ if (drawable(object) && (!layers || object.layers.test(layers))) drawables.push(object);
+ for (const child of object.children) visit(child);
+ };
for (const child of root.children) visit(child);
- return found;
+ return { drawables, variants };
+}
+/** Drawables below root (root visibility ignored), including registered pose variants.
+ * With layers, only nodes drawn by that camera are returned; shadow proxies remain draw-only. */
+export function warmRenderables(root: Object3D, layers?: Layers): Object3D[] {
+ return warmTargets(root, layers).drawables;
}
/**
@@ -91,23 +104,30 @@ export function warmChainKey(object: Object3D): string {
* what compileAsync does not (shadow-map pipelines, which three skips while pre-compiling) and makes every
* first-draw driver variant happen before ready. Drawables off the camera's layers (shadow stand-ins) are not compiled
* but draw unculled here too; `onDraw` runs as this frame starts (the cached shadow re-arms at the reveal).
- * 3. done: culling is restored; the next frame is the first complete frame.
+ * Registered hidden pose variants compile individually and are shown only for the warm drawing
+ * frame, including their shadow proxies. Ordinary hidden branches stay hidden.
+ * 3. done: culling and pose visibility are restored; the next frame is the first complete frame.
*/
export function startWarmPass(renderer: WarmPassRenderer, scene: Scene, camera: Camera, root: Object3D, options: WarmPassOptions): WarmPass {
- const drawables = warmRenderables(root), renderables = drawables.filter(o => o.layers.test(camera.layers)), chains = new Map<string, Object3D[]>();
+ const { drawables, variants } = warmTargets(root), renderables = drawables.filter(o => o.layers.test(camera.layers)), chains = new Map<string, Object3D[]>();
for (const object of renderables) { const key = warmChainKey(object); (chains.get(key) ?? chains.set(key, []).get(key)!).push(object); }
const concurrency = Math.max(1, Math.min(Math.floor(options.concurrency ?? WARM_CONCURRENCY), chains.size));
const stats: WarmPassStats = { renderables: renderables.length, chains: chains.size, concurrency: chains.size ? concurrency : 0, failed: 0, compileFrames: 0, revealed: options.reveal };
- let phase: WarmPhase = 'compiling', compiled = false, disposed = false, unculled: Object3D[] = [];
+ let phase: WarmPhase = 'compiling', compiled = false, disposed = false, unculled: Object3D[] = [], revealedVariants: Object3D[] = [];
+ const restoreDrawing = () => {
+ for (const object of unculled) object.frustumCulled = true;
+ for (const object of revealedVariants) object.visible = false;
+ unculled = []; revealedVariants = [];
+ };
if (options.reveal) root.visible = false;
// compileAsync collects its render items synchronously, from the object and its descendants; each drawable is its own
// unit here, so its children are hidden and its culling is off for exactly that synchronous part.
const compileOne = (object: Object3D) => {
- const children = object.children.filter(child => child.visible), culled = object.frustumCulled;
+ const children = object.children.filter(child => child.visible), culled = object.frustumCulled, visible = object.visible;
for (const child of children) child.visible = false;
- object.frustumCulled = false;
+ object.frustumCulled = false; object.visible = true;
try { return renderer.compileAsync(object, camera, scene); }
- finally { object.frustumCulled = culled; for (const child of children) child.visible = true; }
+ finally { object.frustumCulled = culled; object.visible = visible; for (const child of children) child.visible = true; }
};
// Each slot takes the next chain in first-seen order and compiles its drawables one after another.
const queue = [...chains.values()];
@@ -130,12 +150,14 @@ export function startWarmPass(renderer: WarmPassRenderer, scene: Scene, camera:
if (options.reveal) root.visible = true;
unculled = drawables.filter(object => object.frustumCulled);
for (const object of unculled) object.frustumCulled = false;
- phase = 'drawing'; options.onDraw?.();
+ revealedVariants = variants.filter(object => !object.visible);
+ for (const object of revealedVariants) object.visible = true;
+ phase = 'drawing';
+ try { options.onDraw?.(); } catch (error) { restoreDrawing(); disposed = true; throw error; }
return false;
}
if (phase === 'drawing') {
- for (const object of unculled) object.frustumCulled = true;
- unculled = []; phase = 'done';
+ restoreDrawing(); phase = 'done';
}
return true;
},
@@ -143,8 +165,7 @@ export function startWarmPass(renderer: WarmPassRenderer, scene: Scene, camera:
if (disposed) return;
disposed = true;
if (phase === 'compiling' && options.reveal) root.visible = true;
- for (const object of unculled) object.frustumCulled = true;
- unculled = [];
+ restoreDrawing();
},
};
}
diff --git a/scenes/packages/farm/src/world/shadows.ts b/scenes/packages/farm/src/world/shadows.ts
index 4bcdb0a6..2fa52aa1 100644
--- a/scenes/packages/farm/src/world/shadows.ts
+++ b/scenes/packages/farm/src/world/shadows.ts
@@ -30,13 +30,14 @@ export function createFarmSun(mapSize: number): DirectionalLight {
/**
* farm.md section 4: what a hero keeps through the anchor merge and where its stand-ins cut. The placement wrapper, the GLB
* clone root (the mixer root), every clip track target (mixer bindings were cached before optimization) and every node the
- * play code finds by name in a clone (Joint_*, DoorPivot). Crop soil and plant names belong to fixed owners, never merged;
+ * play code finds by name in a clone (Joint_*, DoorPivot), plus independently toggled
+ * empty-hand arm meshes so their shadow stand-ins inherit the same visibility. Crop soil and plant names belong to fixed owners, never merged;
* Mesh_Building_Wood is read from the pack's original scene.
*/
export function farmHeroAnchors(instance: FarmInstance): Set<Object3D> {
const root = instance.mixer.getRoot() as Object3D, keep = new Set<Object3D>([instance.object, root]);
for (const clip of instance.clips) for (const track of clip.tracks) { const node = PropertyBinding.findNode(root, PropertyBinding.parseTrackName(track.name).nodeName) as Object3D | undefined; if (node) keep.add(node); }
- root.traverse(n => { if (n.name.startsWith('Joint_') || n.name === 'DoorPivot') keep.add(n); });
+ root.traverse(n => { if (n.name.startsWith('Joint_') || n.name === 'DoorPivot' || n.userData.farmPoseVisibility === true) keep.add(n); });
return keep;
}
export interface FarmShadowWorld {
diff --git a/scenes/packages/farm/tests/unit/hand-clearance.test.ts b/scenes/packages/farm/tests/unit/hand-clearance.test.ts
index a8710df1..a1e99bb9 100644
--- a/scenes/packages/farm/tests/unit/hand-clearance.test.ts
+++ b/scenes/packages/farm/tests/unit/hand-clearance.test.ts
@@ -1,8 +1,9 @@
import { expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
-import { AnimationMixer, Box3, MeshBasicMaterial, Vector3 } from 'three/webgpu';
-import type { Mesh, Object3D } from 'three/webgpu';
+import { AnimationMixer, Box3, BoxGeometry, Group, Mesh, MeshBasicMaterial, Quaternion, Vector3 } from 'three/webgpu';
+import type { Object3D } from 'three/webgpu';
import { createEmptyHandedPose } from '../../src/play/farmer-rig';
/** Saved component ranges let us measure actual hand vertices despite rigid draw consolidation. */
@@ -33,11 +34,110 @@ for (const release of ['r34', 'r35-local-review']) test(`${release} saved farmer
mixer.setTime(sample / 120 * clip.duration); pose.apply(); root.updateMatrixWorld(true);
// Historical exports dropped component extras; the complete rigid forearm/hand and hip draws
// give a conservative separation test that also works with those exact accepted bytes.
- const hip = componentBox(root, /Consolidated_Joint_(Left|Right)Hip/), left = componentBox(root, /Consolidated_Joint_LeftElbow_0/), right = componentBox(root, /Consolidated_Joint_RightHandToolAttachment/);
+ const hip = componentBox(root, /Consolidated_Joint_(Left|Right)Hip/), left = componentBox(root, /Consolidated_Joint_LeftElbow_0/), right = componentBox(root, /Mesh_EmptyHandedRightArm/);
minimum = Math.min(minimum, hip.min.z - left.max.z, right.min.z - hip.max.z);
}
console.log('minimum hand-to-hip lateral clearance', minimum);
expect(minimum).toBeGreaterThan(.01);
- mixer.stopAllAction(); mixer.uncacheRoot(root);
+ mixer.stopAllAction(); mixer.uncacheRoot(root); pose.dispose();
root.traverse(object => { const mesh = object as Mesh; if (mesh.isMesh) { mesh.geometry.dispose(); const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]; materials.forEach(m => m.dispose()); } });
});
+
+
+test('exact r36 released farmer preserves relaxed shoulders on substep and normal rendered frames', async () => {
+ await import('three');
+ const { createFarmSim } = await import('../../src/play/sim');
+ const { buildFarmColliders } = await import('../../src/world/colliders');
+ const { FARM_WALK } = await import('../../src/constants');
+ const loader = new GLTFLoader();
+ loader.register(() => ({ name: 'fit-material', loadMaterial: async () => new MeshBasicMaterial() }));
+ const expected = { farmer: 'b6c49161d0627c26e3cc7ea07e88f58c2726fe2c8b15773afcb621d3ab21b829', tractor: '8185aea55248ec02eb49de46eb04d85c2cdd9a9f9a1d485d649d79009c3f1117' };
+ const instances: import('../../src/world/types').FarmInstance[] = [];
+ for (const id of ['farmer', 'tractor'] as const) {
+ const bytes = readFileSync(new URL(`../../../../.cache/site-inputs/farm/standalone/assets/models/${id}.glb`, import.meta.url));
+ expect(createHash('sha256').update(bytes).digest('hex')).toBe(expected[id]);
+ const gltf = await loader.parseAsync(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), '');
+ const wrapper = new Group(); wrapper.name = id === 'farmer' ? 'farmer-yard-0' : 'tractor-0'; wrapper.add(gltf.scene);
+ if (id === 'tractor') wrapper.position.set(20, 0, 20);
+ instances.push({ id: wrapper.name, asset: { id }, object: wrapper, mixer: new AnimationMixer(gltf.scene), clips: gltf.animations, action: null, clipIndex: '' });
+ }
+ const geometryHash = (mesh: Mesh) => {
+ const hash = createHash('sha256'), geometry = mesh.geometry;
+ const arrays = [...Object.values(geometry.attributes).map(attribute => 'data' in attribute ? attribute.data.array : attribute.array), ...(geometry.index ? [geometry.index.array] : [])];
+ for (const array of arrays) hash.update(new Uint8Array(array.buffer, array.byteOffset, array.byteLength));
+ return hash.digest('hex');
+ };
+ const originalBuffers = new Map<Mesh, string>();
+ for (const instance of instances) instance.object.traverse(node => { const mesh = node as Mesh; if (mesh.isMesh) originalBuffers.set(mesh, geometryHash(mesh)); });
+ const ground = new Mesh(new BoxGeometry(100, 1, 100), new MeshBasicMaterial()); ground.position.y = -.5;
+ const colliders = buildFarmColliders({ ground, bridge: null, instances }), sim = createFarmSim({ instances, colliders });
+ const input = { move: { x: 0, y: 1 }, run: false }, forward = new Vector3(0, 0, -1);
+ try {
+ sim.start(); sim.update(FARM_WALK.step, input, forward);
+ sim.updateAnimation(FARM_WALK.step); sim.update(FARM_WALK.step, input, forward);
+ expect(sim.currentClip).toBe('Walk');
+ expect(sim.player.object.getObjectByName('Joint_Pitchfork')!.visible).toBe(false);
+ const left = sim.player.object.getObjectByName('Joint_LeftShoulder')!, right = sim.player.object.getObjectByName('Joint_RightShoulder')!;
+ const originalLeft = sim.player.object.getObjectByName('Mesh_Consolidated_Joint_LeftElbow_0') as Mesh;
+ const derivedRight = sim.player.object.getObjectByName('Mesh_EmptyHandedRightArm') as Mesh;
+ expect(derivedRight).toBeDefined(); expect(derivedRight.visible).toBe(true);
+ expect(derivedRight.geometry).toBe(originalLeft.geometry);
+ expect(sim.player.object.getObjectByName('Joint_RightHandToolAttachment')!.visible).toBe(false);
+ expect(sim.player.object.getObjectByName('Mesh_Consolidated_Joint_RightElbow_0')!.visible).toBe(false);
+ expect(sim.player.object.getObjectByName('Joint_RightElbow')!.quaternion.angleTo(new Quaternion())).toBe(0);
+ // Source component ranges identify the actual relaxed wrist overlap; no guessed split.
+ const localBox = (name: string) => {
+ const range = originalLeft.userData.rowanComponents.ranges.find((r: { name: string }) => r.name === name)!;
+ const box = new Box3(), position = originalLeft.geometry.getAttribute('position'), index = originalLeft.geometry.index, point = new Vector3();
+ // The runtime export deduplicates vertices; saved triangle ranges address its index stream.
+ for (let i = range.firstTriangle * 3; i < (range.firstTriangle + range.triangleCount) * 3; i++) box.expandByPoint(point.fromBufferAttribute(position, index ? index.getX(i) : i));
+ return box;
+ };
+ const overlap = localBox('Mesh_LeftForearm').intersect(localBox('Mesh_LeftHand')).getSize(new Vector3());
+ expect(overlap.x).toBeGreaterThan(.01); expect(overlap.y).toBeGreaterThan(.01); expect(overlap.z).toBeGreaterThan(.01);
+ expect(derivedRight.scale.toArray()).toEqual([1, 1, -1]);
+ const before = sim.player.object.position.clone();
+ for (const [i, dt] of [1 / 240, 1 / 240, 1 / 121, 1 / 119, 0, 1 / 120, 1 / 60].entries()) {
+ sim.updateAnimation(dt); sim.update(dt, input, forward);
+ if (i === 0) expect(sim.player.object.position.equals(before)).toBe(true);
+ if (i === 1) expect(sim.player.object.position.equals(before)).toBe(false);
+ expect(left.rotation.x).toBeCloseTo(.28, 12);
+ expect(right.rotation.z).toBeCloseTo(-left.rotation.z, 12);
+ }
+ // Actual authored Idle→Walk right hip and Walk→Idle shoulders/chest must blend,
+ // including non-overlapping track sets; selecting a clip must not restore rest mid-frame.
+ const idle = { move: { x: 0, y: 0 }, run: false };
+ for (let i = 0; i < 30; i++) { sim.updateAnimation(1 / 120); sim.update(1 / 120, idle, forward); }
+ const hip = rootJoint('Joint_RightHip');
+ sim.updateAnimation(1 / 120); sim.update(1 / 120, input, forward);
+ const hipBefore = hip.quaternion.clone(); sim.updateAnimation(1 / 120); sim.update(1 / 120, input, forward);
+ expect(hipBefore.angleTo(hip.quaternion) * 180 / Math.PI).toBeLessThan(5);
+ for (let i = 0; i < 17; i++) { sim.updateAnimation(1 / 120); sim.update(1 / 120, input, forward); }
+ sim.updateAnimation(1 / 120);
+ const shoulderBefore = left.rotation.z, chestBefore = rootJoint('Joint_Chest').quaternion.clone();
+ sim.update(1 / 120, idle, forward);
+ expect(left.rotation.z).toBeCloseTo(shoulderBefore, 10);
+ expect(chestBefore.angleTo(rootJoint('Joint_Chest').quaternion)).toBeLessThan(1e-7);
+ function rootJoint(name: string) { return sim.player.object.getObjectByName(name)!; }
+ // Retain the actual-vertex hip-clearance contract for the current sealed revision.
+ for (let i = 0; i < 24; i++) { sim.updateAnimation(1 / 120); sim.update(1 / 120, input, forward); }
+ sim.player.action!.timeScale = 1; // Sample exactly one full authored Walk cycle below.
+ const root = sim.player.object, walk = sim.player.clips.find(clip => clip.name === 'Walk')!;
+ root.position.set(0, 0, 0); root.rotation.set(0, 0, 0);
+ let minimum = Infinity;
+ for (let sample = 0; sample <= 120; sample++) {
+ sim.player.mixer.setTime(sample / 120 * walk.duration); sim.update(0, input, forward); root.updateMatrixWorld(true);
+ const hip = componentBox(root, /Consolidated_Joint_(Left|Right)Hip/), leftHand = componentBox(root, /Consolidated_Joint_LeftElbow_0/), rightHand = componentBox(root, /Mesh_EmptyHandedRightArm/);
+ minimum = Math.min(minimum, hip.min.z - leftHand.max.z, rightHand.min.z - hip.max.z);
+ }
+ expect(minimum).toBeGreaterThan(.01);
+ } finally {
+ sim.dispose(); colliders.dispose();
+ for (const [mesh, before] of originalBuffers) expect(geometryHash(mesh)).toBe(before);
+ for (const instance of instances) {
+ instance.mixer.stopAllAction(); instance.mixer.uncacheRoot(instance.mixer.getRoot());
+ instance.object.traverse(object => { const mesh = object as Mesh; if (mesh.isMesh) { mesh.geometry.dispose(); for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) material.dispose(); } });
+ }
+ ground.geometry.dispose(); ground.material.dispose();
+ }
+});
diff --git a/scenes/packages/farm/tests/unit/optimize.test.ts b/scenes/packages/farm/tests/unit/optimize.test.ts
index 76bcc109..048b1a08 100644
--- a/scenes/packages/farm/tests/unit/optimize.test.ts
+++ b/scenes/packages/farm/tests/unit/optimize.test.ts
@@ -161,16 +161,18 @@ test('S4b: the hero merge keeps the source vertex layout (RK-1), so a merged mes
const buffers=new Set(Object.values(merged.geometry.attributes).map(a=>(a as InterleavedBufferAttribute).data));expect(buffers.size).toBe(1);
o.restore();g.dispose();
});
-test('S4: stand-ins bake exactly what the sun shadow camera draws, and every farmer part stays a caster at economy (RF-1)',()=>{
+test('S4: stand-ins keep every farmer and trailer part at economy (RF-1, D-72) while other small casters still drop',()=>{
const root=new Scene(),{farmShadowMask}=shadowsModule;
const house=hero('farmhouse',0,[['wall-a',shared.masonry,0],['pin',shared.brass,.8],['seen',shared.trim,1],['unseen',shared.trim,3]],[]);
// The player rig: a 1 cm neck alone under its joint, and a 1 cm cuff beside a boot under the ankle.
const farmer=hero('farmer',10,[['Mesh_Body',shared.hide,0],['Mesh_Neck',shared.brass,0,'Joint_Neck'],['Mesh_Cuff',shared.brass,.2,'Joint_Ankle'],['Mesh_Boot',shared.leaf,0,'Joint_Ankle']],['Joint_Neck','Joint_Ankle']);
+ const trailer=hero('trailer',20,[['Body',shared.masonry,0],['Drawbar',shared.brass,0,'Joint_Hitch'],['HitchRing',shared.iron,.2,'Joint_Hitch'],['HitchPin',shared.trim,.4,'Joint_Hitch']],['Joint_Hitch']);
const part=(o:FarmInstance,name:string)=>o.object.getObjectByName(name) as Mesh;
for(const name of['Mesh_Neck','Mesh_Cuff'])part(farmer,name).geometry=shared.pin;
+ for(const name of['Drawbar','HitchRing','HitchPin'])part(trailer,name).geometry=shared.pin;
part(house,'seen').layers.set(FARM_SHADOW.standInLayer);part(house,'unseen').layers.set(5);
- root.add(house.object,farmer.object);root.traverse(n=>{if((n as Mesh).isMesh)n.castShadow=true;});root.updateMatrixWorld(true);
- const o=optimizeFarmWorld(root,[house,farmer],{meshes:[],derivatives:0},{packWoodland:false,shadow:{mapSize:512,standIns:true,minCasterTexels:2}});
+ root.add(house.object,farmer.object,trailer.object);root.traverse(n=>{if((n as Mesh).isMesh)n.castShadow=true;});root.updateMatrixWorld(true);
+ const o=optimizeFarmWorld(root,[house,farmer,trailer],{meshes:[],derivatives:0},{packWoodland:false,shadow:{mapSize:512,standIns:true,minCasterTexels:2}});
// The sun's shadow camera sees layer 0 and the stand-in layer; a caster on another layer is never drawn, so it is left alone.
expect(farmShadowMask(true)).toBe(1|1<<FARM_SHADOW.standInLayer);expect(farmShadowMask(false)).toBe(1);
expect([part(house,'seen').castShadow,part(house,'unseen').castShadow]).toEqual([false,true]);
@@ -180,6 +182,8 @@ test('S4: stand-ins bake exactly what the sun shadow camera draws, and every far
expect(proxies.sort()).toEqual(['Joint_Ankle','Joint_Neck','farmer']);
const ankle=part(farmer,'Joint_Ankle').children.find(n=>n.userData.kilnShadowStandIn) as Mesh;
expect(ankle.geometry.getAttribute('position').count).toBe(2*shared.pin.getAttribute('position').count);
+ const hitch=part(trailer,'Joint_Hitch').children.find(n=>n.userData.kilnShadowStandIn) as Mesh;
+ expect(hitch.geometry.getAttribute('position').count).toBe(3*shared.pin.getAttribute('position').count);
o.restore();expect(meshes(root).every(m=>m.castShadow)).toBe(true);
});
diff --git a/scenes/packages/farm/tests/unit/play.test.ts b/scenes/packages/farm/tests/unit/play.test.ts
index 18f08c8e..5f8e8379 100644
--- a/scenes/packages/farm/tests/unit/play.test.ts
+++ b/scenes/packages/farm/tests/unit/play.test.ts
@@ -7,6 +7,7 @@ const { findDoor, stepDoors, toggleDoor, doorCenter } = await import('../../src/
const { applyTractorPose, createTractorRig, driveTractor, findTractorExit, tractorAreaBlocked, TRACTOR_EXITS } = await import('../../src/play/tractor');
const { buildFarmColliders } = await import('../../src/world/colliders');
const { createFarmSim } = await import('../../src/play/sim');
+const { warmRenderables } = await import('../../src/world/prewarm');
const { FARM_STRINGS, DOOR_LABELS, doorPrompt, doorStatus } = await import('../../src/ui/strings');
const { bridgeCenter, drivingHeight, riverCenter, terrainHeight } = await import('../../src/world/site-layout');
@@ -116,11 +117,12 @@ test('U-09 Farm collider selection: walk-through assets, rotors, foliage, dynami
});
/** A farmer with the joints the empty-handed pose and the seat rig use, and a tractor with its joints. */
-function playFixture() {
+function playFixture(farmerClips?: AnimationClip[]) {
const farmer = new Group(), pelvis = node(farmer, 'Joint_Pelvis', [0, .95, 0]), chest = node(pelvis, 'Joint_Chest', [0, .3, 0]);
for (const [side, z] of [['Left', -.2], ['Right', .2]] as const) {
const shoulder = node(chest, `Joint_${side}Shoulder`, [0, .25, z]), elbow = node(shoulder, `Joint_${side}Elbow`, [0, -.28, 0]);
- if (side === 'Right') node(elbow, 'Joint_Pitchfork', [0, -.2, 0], true);
+ node(elbow, `Mesh_Consolidated_Joint_${side}Elbow_0`, [0, 0, 0], true);
+ if (side === 'Right') { const hand = node(elbow, 'Joint_RightHandToolAttachment', [.15, -.035, .113]); node(hand, 'Joint_Pitchfork', [0, 0, 0], true); }
const hip = node(pelvis, `Joint_${side}Hip`, [0, -.05, z / 2]); node(node(hip, `Joint_${side}Knee`, [0, -.382, 0]), `Joint_${side}Ankle`, [0, -.382, 0]);
}
const tractor = new Group(); node(tractor, 'Mesh_Body', [0, .8, 0], true); node(tractor, 'Joint_SeatAttach', [-.3, 1.2, 0]);
@@ -131,7 +133,7 @@ function playFixture() {
const shed = new Group(); for (const [x, z] of [[-20.4, 21.5], [-20.4, 18.5], [-17.8, 20]] as const) node(shed, 'Mesh_Bale', [x, 1 + terrainHeight(x, z), z], true);
// The ground sits well below the terrain function so that dismount capsules only meet the shed.
const ground = new Mesh(new BoxGeometry(80, 1, 80), material); ground.position.y = -10;
- const instances = [instance('farmer-yard-0', 'farmer', farmer, [new AnimationClip('Idle', 1, []), new AnimationClip('Walk', 1, [])]),
+ const instances = [instance('farmer-yard-0', 'farmer', farmer, farmerClips ?? [new AnimationClip('Idle', 1, []), new AnimationClip('Walk', 1, [])]),
instance('tractor-0', 'tractor', tractor), instance('farmhouse-0', 'farmhouse', house), instance('hay-bales-0', 'hay-bales', shed)];
const colliders = buildFarmColliders({ ground, bridge: null, instances }), sim = createFarmSim({ instances, colliders });
return { sim, colliders, farmer, tractor, door: colliders.doors[0]! };
@@ -235,3 +237,158 @@ test('walking is third person: the help says so and no pointer-capture strings r
if (process.env.ORACLE === '1') test('M2c sealed r33 play oracle: byte-identical colliders and lockstep play within 1e-9', async () => {
await import('../../scripts/audit-play-oracle');
}, 120_000);
+
+
+test('empty-handed pose follows the mixer every rendered frame, including no physics step; seat and overview retain their poses', () => {
+ // Released Rowan Walk animates only the left shoulder, about z. Any mixer update
+ // resets its procedural x angle, even when the subsequent fixed-step loop does no work.
+ const swing = new QuaternionKeyframeTrack('Joint_LeftShoulder.quaternion', [0, 1],
+ [0, 0, 0, 1, ...new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), -.24).toArray()]);
+ const { sim, colliders, farmer } = playFixture([new AnimationClip('Idle', 1, []), new AnimationClip('Walk', 1, [swing])]);
+ const left = farmer.getObjectByName('Joint_LeftShoulder')!, right = farmer.getObjectByName('Joint_RightShoulder')!;
+ const fork = farmer.getObjectByName('Joint_Pitchfork')!, h = 1 / 120, moving = { move: { x: 0, y: 1 }, run: false };
+ try {
+ sim.start(); sim.update(0, idle, south);
+ expect(left.rotation.x).toBeCloseTo(.28, 12); expect(fork.visible).toBe(false);
+ sim.update(h, moving, south); expect(sim.currentClip).toBe('Walk');
+ for (const dt of [0, h / 2, h / 2, 1 / 121, 1 / 119, h, h * 2]) {
+ sim.updateAnimation(dt); sim.update(dt, moving, south);
+ expect(left.rotation.x).toBeCloseTo(.28, 12);
+ expect(right.rotation.z).toBeCloseTo(-left.rotation.z, 12);
+ }
+ farmer.position.copy(sim.tractor.object.position); sim.update(0, idle, south); sim.interact();
+ expect(sim.driving).toBe(true); const seated = left.quaternion.clone();
+ sim.update(0, idle, south); expect(left.quaternion.equals(seated)).toBe(true);
+ expect(sim.stop(true)).toBe(true); expect(fork.visible).toBe(true);
+ const restored = left.quaternion.clone(); sim.update(h, moving, south);
+ expect(left.quaternion.equals(restored)).toBe(true); expect(left.rotation.x).toBeCloseTo(0, 12);
+ } finally { sim.dispose(); colliders.dispose(); }
+});
+
+
+test('empty-handed right arm borrows the relaxed left geometry, restores tool/seat state and removes only its derivative', () => {
+ const { sim, colliders, farmer } = playFixture();
+ const left = farmer.getObjectByName('Mesh_Consolidated_Joint_LeftElbow_0') as Mesh;
+ const lower = farmer.getObjectByName('Mesh_Consolidated_Joint_RightElbow_0')!, hand = farmer.getObjectByName('Joint_RightHandToolAttachment')!;
+ const elbow = farmer.getObjectByName('Joint_RightElbow')!, elbowRest = elbow.quaternion.clone();
+ const derivative = farmer.getObjectByName('Mesh_EmptyHandedRightArm') as Mesh;
+ let geometryDisposals = 0, materialDisposals = 0;
+ left.geometry.addEventListener('dispose', () => geometryDisposals++);
+ (left.material as MeshBasicMaterial).addEventListener('dispose', () => materialDisposals++);
+ try {
+ expect(derivative).toBeDefined(); expect(derivative.visible).toBe(false);
+ expect(warmRenderables(farmer)).toContain(derivative);
+ expect(derivative.geometry).toBe(left.geometry); expect(derivative.material).toBe(left.material);
+ sim.start(); sim.update(0, idle, south); farmer.updateMatrixWorld(true);
+ expect(derivative.visible).toBe(true); expect(lower.visible).toBe(false); expect(hand.visible).toBe(false);
+ expect(elbow.quaternion.equals(elbowRest)).toBe(true);
+ expect(derivative.matrixWorld.determinant()).toBeLessThan(0);
+ sim.interact(); expect(sim.driving).toBe(true);
+ expect(derivative.visible).toBe(false); expect(lower.visible).toBe(true); expect(hand.visible).toBe(true);
+ expect(farmer.getObjectByName('Joint_Pitchfork')!.visible).toBe(false);
+ sim.stop(true); expect(lower.visible).toBe(true); expect(hand.visible).toBe(true);
+ expect(elbow.quaternion.equals(elbowRest)).toBe(true);
+ expect(farmer.getObjectByName('Joint_Pitchfork')!.visible).toBe(true);
+ sim.start(); sim.update(0, idle, south); sim.dispose(); sim.dispose();
+ expect(derivative.parent).toBeNull(); expect(lower.visible).toBe(true); expect(hand.visible).toBe(true);
+ const detached = new Group(); detached.add(derivative); expect(warmRenderables(detached)).not.toContain(derivative); derivative.removeFromParent();
+ expect(geometryDisposals).toBe(0); expect(materialDisposals).toBe(0);
+ } finally { sim.dispose(); colliders.dispose(); }
+});
+
+
+test('empty-hand variants retain independent visibility through Farm shadow stand-ins', async () => {
+ const { shadowStandIns } = await import('@kiln-scenes/scene-kit/shadows');
+ const { farmHeroAnchors } = await import('../../src/world/shadows');
+ const { sim, colliders, farmer } = playFixture();
+ farmer.traverse(node => { if ((node as Mesh).isMesh) (node as Mesh).castShadow = true; });
+ const original = farmer.getObjectByName('Mesh_Consolidated_Joint_RightElbow_0')!, relaxed = farmer.getObjectByName('Mesh_EmptyHandedRightArm')!;
+ const keep = farmHeroAnchors(sim.player);
+ const shadows = shadowStandIns(farmer, { layer: 1, shadowMask: 3, isAnchor: node => keep.has(node) });
+ try {
+ const originalProxy = shadows.proxies.find(proxy => proxy.parent === original), relaxedProxy = shadows.proxies.find(proxy => proxy.parent === relaxed);
+ expect(originalProxy).toBeDefined(); expect(relaxedProxy).toBeDefined();
+ const visible = (object: Object3D) => { for (let node: Object3D | null = object; node; node = node.parent) if (!node.visible) return false; return true; };
+ expect(visible(originalProxy!)).toBe(true); expect(visible(relaxedProxy!)).toBe(false);
+ sim.start(); sim.update(0, idle, south);
+ expect(visible(originalProxy!)).toBe(false); expect(visible(relaxedProxy!)).toBe(true);
+ sim.interact(); expect(sim.driving).toBe(true);
+ expect(visible(originalProxy!)).toBe(true); expect(visible(relaxedProxy!)).toBe(false);
+ } finally { shadows.restore(); sim.dispose(); colliders.dispose(); }
+});
+
+
+test('player clip changes blend without resetting rendered joints, keep unit weight through reversals and retire the outgoing action', () => {
+ const shoulder = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), -.24), hip = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), .45);
+ const walk = new AnimationClip('Walk', 1, [new QuaternionKeyframeTrack('Joint_LeftShoulder.quaternion', [0, 1], [...shoulder.toArray(), ...shoulder.toArray()]),
+ new QuaternionKeyframeTrack('Joint_RightHip.quaternion', [0, 1], [...hip.toArray(), ...hip.toArray()])]);
+ const { sim, colliders, farmer } = playFixture([new AnimationClip('Idle', 1, []), walk]);
+ sim.tractor.object.position.set(20, 0, 20); sim.tractor.object.updateMatrixWorld(true); farmer.position.set(-10, 0, 0); sim.home.copy(farmer.position);
+ const left = farmer.getObjectByName('Joint_LeftShoulder')!, rightHip = farmer.getObjectByName('Joint_RightHip')!;
+ const idleAction = sim.player.mixer.clipAction(sim.player.clips[0]!), walkAction = sim.player.mixer.clipAction(walk);
+ const h = 1 / 120, moving = { move: { x: 0, y: 1 }, run: false };
+ const update = sim.player.mixer.update.bind(sim.player.mixer); let mixerUpdates = 0, rendered = 0;
+ sim.player.mixer.update = dt => { mixerUpdates++; return update(dt); };
+ const tick = (input: typeof moving, dt = h, animationDelta = dt) => {
+ sim.updateAnimation(animationDelta); rendered++; sim.update(dt, input, south);
+ expect(mixerUpdates).toBe(rendered);
+ expect(idleAction.getEffectiveWeight() + walkAction.getEffectiveWeight()).toBeCloseTo(1, 12);
+ };
+ try {
+ sim.start(); tick(idle, 0); tick(moving);
+ const before = rightHip.quaternion.clone(); tick(moving);
+ expect(before.angleTo(rightHip.quaternion)).toBeLessThan(.1); // full authored entry jump is .45 radians
+ for (let i = 0; i < 24; i++) tick(moving);
+ expect(walkAction.isScheduled()).toBe(true); expect(idleAction.isScheduled()).toBe(false);
+ const swing = left.rotation.z; tick(idle);
+ expect(left.rotation.z).toBeCloseTo(swing, 6); // selecting Idle must not reset the already mixed frame
+ tick(idle); expect(Math.abs(left.rotation.z - swing)).toBeLessThan(.04);
+ // Freeze: neither weights nor clip time move, including a physics step and a zero-dt frame.
+ const weight = walkAction.getEffectiveWeight(), time = walkAction.time, pose = rightHip.quaternion.clone();
+ tick(idle, h, 0); tick(idle, 0, 0);
+ expect(walkAction.getEffectiveWeight()).toBe(weight); expect(walkAction.time).toBe(time);
+ expect(rightHip.quaternion.toArray()).toEqual(pose.toArray());
+ // Reverse an unfinished fade repeatedly without jumping to an endpoint or resetting phase.
+ for (let i = 0; i < 12; i++) {
+ const oldWeight = walkAction.getEffectiveWeight(), oldTime = walkAction.time;
+ tick(i % 2 ? idle : moving, h / 2); tick(i % 2 ? idle : moving, h / 2);
+ expect(Math.abs(walkAction.getEffectiveWeight() - oldWeight)).toBeLessThan(.12);
+ expect(walkAction.time).toBeGreaterThanOrEqual(oldTime);
+ }
+ for (let i = 0; i < 24; i++) tick(idle);
+ expect(walkAction.isScheduled()).toBe(false); expect(idleAction.isScheduled()).toBe(true);
+ for (let i = 0; i < 5; i++) tick(moving);
+ farmer.position.copy(sim.tractor.object.position); sim.update(0, idle, south); sim.interact();
+ expect(sim.driving).toBe(true); expect(walkAction.isScheduled()).toBe(false); expect(idleAction.isScheduled()).toBe(false);
+ const seatedUpdates = mixerUpdates; sim.updateAnimation(h); expect(mixerUpdates).toBe(seatedUpdates);
+ sim.interact(); sim.update(0, idle, south);
+ expect(sim.driving).toBe(false); expect(idleAction.getEffectiveWeight()).toBe(1); expect(walkAction.getEffectiveWeight()).toBe(0);
+ expect(farmer.getObjectByName('Mesh_EmptyHandedRightArm')!.visible).toBe(true);
+ for (const reset of [() => sim.visit('yard'), () => sim.reset()]) {
+ reset(); sim.update(h, idle, south); sim.updateAnimation(0); rendered++; sim.update(0, idle, south);
+ expect(idleAction.getEffectiveWeight()).toBe(1); expect(walkAction.isScheduled()).toBe(false);
+ expect(farmer.getObjectByName('Joint_RightHandToolAttachment')!.visible).toBe(false);
+ }
+ sim.stop(true); expect(walkAction.isScheduled()).toBe(false); expect(idleAction.isScheduled()).toBe(false);
+ expect(farmer.getObjectByName('Joint_Pitchfork')!.visible).toBe(true);
+ } finally { sim.dispose(); colliders.dispose(); }
+});
+
+
+test('constructing the player blend preserves an existing overview action until play explicitly selects a clip', async () => {
+ const { createFarmerClipBlend } = await import('../../src/play/farmer-rig');
+ const object = new Group(), player = instance('farmer-yard-0', 'farmer', object, [new AnimationClip('Idle', 1, []), new AnimationClip('Walk', 1, [])]);
+ const overview = player.mixer.clipAction(player.clips[1]!).setEffectiveWeight(.6).play(); player.action = overview; player.clipIndex = '1';
+ player.mixer.update(.2); const time = overview.time;
+ const blend = createFarmerClipBlend(player, { Idle: '0', Walk: '1' });
+ expect(overview.isScheduled()).toBe(true); expect(overview.getEffectiveWeight()).toBe(.6); expect(overview.time).toBe(time);
+ expect(player.action).toBe(overview); expect(player.clipIndex).toBe('1');
+ blend.select('Idle'); blend.update(0);
+ expect(player.action!.getClip().name).toBe('Idle'); expect(player.action!.getEffectiveWeight()).toBe(1); expect(overview.isScheduled()).toBe(false);
+ blend.reset(); expect(player.action).toBeNull(); expect(overview.getEffectiveWeight()).toBe(0);
+ // An overview action chosen after stopping remains intact until the next play entry.
+ overview.reset().setEffectiveWeight(.7).play(); player.action = overview; player.clipIndex = '1'; player.mixer.update(.1);
+ expect(overview.getEffectiveWeight()).toBe(.7);
+ blend.select('Idle'); blend.update(0); expect(player.action!.getEffectiveWeight()).toBe(1); expect(overview.isScheduled()).toBe(false);
+ blend.reset(); player.mixer.uncacheRoot(object);
+});
diff --git a/scenes/packages/farm/tests/unit/prewarm.test.ts b/scenes/packages/farm/tests/unit/prewarm.test.ts
index 91d2cea5..7f695e47 100644
--- a/scenes/packages/farm/tests/unit/prewarm.test.ts
+++ b/scenes/packages/farm/tests/unit/prewarm.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test';
import { BoxGeometry, Group, InstancedMesh, Mesh, MeshStandardMaterial, PerspectiveCamera, Scene, type Object3D } from 'three/webgpu';
-import { startWarmPass, WARM_CONCURRENCY, warmChainKey, warmRenderables, type WarmPassRenderer } from '../../src/world/prewarm';
+import { startWarmPass, registerWarmPoseVariant, WARM_CONCURRENCY, warmChainKey, warmRenderables, type WarmPassRenderer } from '../../src/world/prewarm';
// SPEC 6.4 warm pass (owner decision 2026-09-29 22:05; M4 item 1). No GPU: a recording renderer stands in for three's compileAsync.
function fixture() {
@@ -115,3 +115,96 @@ describe('SPEC 6.4 warm pass', () => {
expect(seen.length).toBe(1);
});
});
+
+
+function poseFixture() {
+ const f = fixture(), variant = f.a.clone(false), proxy = new Mesh(f.a.geometry, f.a.material), hiddenChild = f.a.clone(false);
+ variant.name = 'relaxed pose'; variant.visible = false; variant.scale.z = -1;
+ proxy.name = 'pose shadow'; proxy.layers.set(1); proxy.frustumCulled = false;
+ hiddenChild.name = 'ordinary hidden child'; hiddenChild.visible = false;
+ variant.add(proxy, hiddenChild); f.root.add(variant);
+ const unregister = registerWarmPoseVariant(variant);
+ return { ...f, variant, proxy, hiddenChild, unregister };
+}
+async function settleAll(r: ReturnType<typeof recorder>, fail?: string) {
+ for (let i = 0; i < 5; i++) { for (const p of r.pending.splice(0)) p.settle(p.name === fail); await flush(); }
+}
+
+test('registered hidden pose and its shadow branch warm before ready, with exact visibility/culling restoration', async () => {
+ const f = poseFixture(), r = recorder(f.root), seen: boolean[][] = [];
+ // Registration cannot punch through an unrelated hidden ancestor.
+ const unregisterHidden = registerWarmPoseVariant(f.hiddenSource);
+ try {
+ expect(warmRenderables(f.root).map(o => o.name)).toContain('relaxed pose');
+ expect(warmRenderables(f.root).map(o => o.name)).toContain('pose shadow');
+ expect(warmRenderables(f.root).map(o => o.name)).not.toContain('ordinary hidden child');
+ expect(warmRenderables(f.root).map(o => o.name)).not.toContain('hidden source');
+ const pass = startWarmPass(r.renderer, f.scene, f.camera, f.root, { reveal: true,
+ onDraw: () => seen.push([f.variant.visible, f.proxy.frustumCulled, f.variant.frustumCulled, f.hiddenChild.visible]) });
+ await settleAll(r);
+ expect(r.calls.map(call => call.name)).toContain('relaxed pose');
+ expect(r.calls.map(call => call.name)).not.toContain('pose shadow');
+ expect(f.variant.visible).toBe(false); expect(f.variant.frustumCulled).toBe(true);
+ expect(pass.step()).toBe(false); expect(pass.phase).toBe('drawing');
+ expect(seen).toEqual([[true, false, false, false]]);
+ expect(pass.step()).toBe(true); expect(pass.phase).toBe('done');
+ expect(f.variant.visible).toBe(false); expect(f.a.visible).toBe(true);
+ expect(f.variant.frustumCulled).toBe(true); expect(f.proxy.frustumCulled).toBe(false);
+ expect(f.hiddenChild.visible).toBe(false); pass.dispose();
+ } finally { f.unregister(); unregisterHidden(); }
+});
+
+test('registered variants are visible only during each synchronous compile collection, including thrown/rejected compiles', async () => {
+ for (const mode of ['throw', 'reject'] as const) {
+ const f = poseFixture(), calls: string[] = [];
+ const renderer: WarmPassRenderer = { compileAsync(object) {
+ calls.push(object.name);
+ if (object === f.variant) {
+ expect(object.visible).toBe(true); expect(object.frustumCulled).toBe(false);
+ expect(object.children.every(child => !child.visible)).toBe(true);
+ if (mode === 'throw') throw new Error('compile fixture');
+ return Promise.reject(new Error('compile fixture'));
+ }
+ return Promise.resolve();
+ } };
+ try {
+ const pass = startWarmPass(renderer, f.scene, f.camera, f.root, { reveal: true }); await flush();
+ expect(calls).toContain('relaxed pose'); expect(pass.stats.failed).toBe(1);
+ expect(f.variant.visible).toBe(false); expect(f.proxy.visible).toBe(true); expect(f.hiddenChild.visible).toBe(false);
+ expect(pass.step()).toBe(false); expect(f.variant.visible).toBe(true);
+ expect(pass.step()).toBe(true); expect(f.variant.visible).toBe(false);
+ pass.dispose();
+ } finally { f.unregister(); }
+ }
+});
+
+test('disposing during compile or drawing restores only registered variant overrides; late compiles cannot reveal it', async () => {
+ for (const drawing of [false, true]) {
+ const f = poseFixture(), r = recorder(f.root);
+ try {
+ const pass = startWarmPass(r.renderer, f.scene, f.camera, f.root, { reveal: true });
+ if (drawing) { await settleAll(r); pass.step(); expect(f.variant.visible).toBe(true); }
+ pass.dispose(); pass.dispose(); await settleAll(r);
+ expect(pass.step()).toBe(false); expect(f.variant.visible).toBe(false);
+ expect(f.variant.frustumCulled).toBe(true); expect(f.proxy.frustumCulled).toBe(false);
+ expect(f.hiddenChild.visible).toBe(false); expect(f.root.visible).toBe(true);
+ } finally { f.unregister(); }
+ }
+});
+
+test('onDraw failure restores registered visibility and culling before propagating the error', async () => {
+ const f = poseFixture(), r = recorder(f.root);
+ try {
+ const pass = startWarmPass(r.renderer, f.scene, f.camera, f.root, { reveal: true, onDraw: () => { throw new Error('prime fixture'); } });
+ await settleAll(r);
+ expect(() => pass.step()).toThrow('prime fixture');
+ expect(f.variant.visible).toBe(false); expect(f.a.frustumCulled).toBe(true);
+ expect(f.proxy.frustumCulled).toBe(false); expect(pass.step()).toBe(false); pass.dispose();
+ } finally { f.unregister(); }
+});
+
+test('unregistered pose branches return to ordinary hidden behavior', () => {
+ const f = poseFixture(); f.unregister(); f.unregister();
+ expect(warmRenderables(f.root).map(object => object.name)).not.toContain('relaxed pose');
+ expect(warmRenderables(f.root).map(object => object.name)).not.toContain('pose shadow');
+});
diff --git a/scenes/packages/foundry-floor/package.json b/scenes/packages/foundry-floor/package.json
index a2f9cd57..ed325f74 100644
--- a/scenes/packages/foundry-floor/package.json
+++ b/scenes/packages/foundry-floor/package.json
@@ -10,13 +10,13 @@
"react": "19.3.0",
"react-dom": "19.3.0",
"@react-three/fiber": "9.8.1",
- "three": "0.186.0"
+ "three": "0.186.1"
},
"devDependencies": {
"react": "19.3.0",
"react-dom": "19.3.0",
"@react-three/fiber": "9.8.1",
- "three": "0.186.0",
+ "three": "0.186.1",
"@types/three": "0.186.0"
}
}
diff --git a/scenes/packages/foundry-floor/scripts/stage-campus.ts b/scenes/packages/foundry-floor/scripts/stage-campus.ts
index 0f21c0bf..a39a205f 100644
--- a/scenes/packages/foundry-floor/scripts/stage-campus.ts
+++ b/scenes/packages/foundry-floor/scripts/stage-campus.ts
@@ -198,7 +198,7 @@ export function stageCampus(options: CampusStageOptions = {}) {
{ from: licenceFrom, to: LICENCE_PATH },
];
const result = stageFiles({
- id: 'foundry-floor', release, three: '0.186.0', out, force: options.force,
+ id: 'foundry-floor', release, three: '0.186.1', out, force: options.force,
models: [
...interior.filter(m => m.placed).map(m => ({ id: m.id, to: m.to })),
...structures.map(m => ({ id: m.id, to: m.to })),
diff --git a/scenes/packages/foundry-floor/scripts/stage-ff3.ts b/scenes/packages/foundry-floor/scripts/stage-ff3.ts
index 6e35b371..6d36671e 100644
--- a/scenes/packages/foundry-floor/scripts/stage-ff3.ts
+++ b/scenes/packages/foundry-floor/scripts/stage-ff3.ts
@@ -329,7 +329,7 @@ export function stageFf3(options: Ff3StageOptions = {}) {
requestedModel:a.model,recordedModel:a.recordedModel??null,...(a.attributionNote?{attributionNote:a.attributionNote}:{}) }] as const;
};
const result = stageFiles({
- id: 'foundry-floor', release, three: '0.186.0', out, force: options.force,
+ id: 'foundry-floor', release, three: '0.186.1', out, force: options.force,
models: [
...interior.filter(m => m.placed).map(m => ({ id: m.id, to: m.to })),
...structures.map(m => ({ id: m.id, to: m.to })),
diff --git a/scenes/packages/foundry-floor/scripts/stage.ts b/scenes/packages/foundry-floor/scripts/stage.ts
index 4309a200..93eca6b2 100644
--- a/scenes/packages/foundry-floor/scripts/stage.ts
+++ b/scenes/packages/foundry-floor/scripts/stage.ts
@@ -103,7 +103,7 @@ export function stageFoundryFloor(options: StageOptions = {}) {
{ from: licenceFrom, to: LICENCE_PATH },
];
const result = stageFiles({
- id: 'foundry-floor', release, three: '0.186.0', out, force: options.force,
+ id: 'foundry-floor', release, three: '0.186.1', out, force: options.force,
models: models.filter(m => m.placed).map(m => ({ id: m.id, to: m.to })),
data: { 'asset-map': 'data/assets.json', ...FAB_DATA_ENTRIES, ...Object.fromEntries(warm.map(w => [w.id, w.to])) },
files, credits: assetCredits(models, map),
diff --git a/scenes/packages/foundry-floor/src/campus/loading-plan.ts b/scenes/packages/foundry-floor/src/campus/loading-plan.ts
new file mode 100644
index 00000000..f35d18d9
--- /dev/null
+++ b/scenes/packages/foundry-floor/src/campus/loading-plan.ts
@@ -0,0 +1,4 @@
+// SPDX-License-Identifier: MIT
+/** Shared by runtime loading and offline release receipts; no renderer imports. */
+export const campusStartupModel = ({ path }: { path: string }) =>
+ /^models\/(structures|vehicles|vegetation|freight)\//.test(path);
diff --git a/scenes/packages/foundry-floor/src/campus/loading.ts b/scenes/packages/foundry-floor/src/campus/loading.ts
index b0e31cf9..315a3840 100644
--- a/scenes/packages/foundry-floor/src/campus/loading.ts
+++ b/scenes/packages/foundry-floor/src/campus/loading.ts
@@ -2,8 +2,8 @@
import { disposeLoadedModels } from '@kiln-scenes/scene-kit';
import type { LoadedPack, PackReader } from '@kiln-scenes/scene-kit';
import type { GLTF } from 'three/addons/loaders/GLTFLoader.js';
-/** The exterior uses only these explicitly named pack families. Interior models are verified on entry. */
-export const campusStartupModel=({path}:{path:string})=>/^models\/(structures|vehicles|vegetation|freight)\//.test(path);
+import { campusStartupModel } from './loading-plan';
+export { campusStartupModel } from './loading-plan';
/** Atomically attach a complete interior; failed/cancelled loads never leak a partial cell into the pack. */
export async function loadInteriorModels(pack:LoadedPack,reader:PackReader,signal:AbortSignal){
diff --git a/scenes/packages/foundry-floor/src/scene/Hud.tsx b/scenes/packages/foundry-floor/src/scene/Hud.tsx
index 360a6cb0..7af8c991 100644
--- a/scenes/packages/foundry-floor/src/scene/Hud.tsx
+++ b/scenes/packages/foundry-floor/src/scene/Hud.tsx
@@ -52,8 +52,6 @@ const FF_HUD_CSS = `
.ff-bottom>.ff-dock{position:absolute;right:max(12px,env(safe-area-inset-right));bottom:max(12px,env(safe-area-inset-bottom));width:min(380px,calc(100% - 24px));
display:flex;flex-direction:column;justify-content:flex-end;gap:8px;pointer-events:none}
.ff-dock>*{pointer-events:auto}
-/* The kit joystick sits inside this layer, not directly under .ks-hud, so it takes its touches back explicitly. */
-.ff-hud>.ks-joystick{pointer-events:auto}
.ff-dock>.ks-status{position:static;transform:none;max-width:none;text-align:left;pointer-events:none;padding:8px 12px;font:13px/1.45 system-ui,sans-serif}
/* The tour caption and the follow panel show what the status line announces: it stays for assistive technology only. */
.ff-camera-tour .ff-dock>.ks-status,.ff-camera-follow .ff-dock>.ks-status{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
diff --git a/scenes/packages/foundry-floor/tests/tools/build-ff3.ts b/scenes/packages/foundry-floor/tests/tools/build-ff3.ts
index d9998a48..ba677372 100644
--- a/scenes/packages/foundry-floor/tests/tools/build-ff3.ts
+++ b/scenes/packages/foundry-floor/tests/tools/build-ff3.ts
@@ -26,7 +26,7 @@ import { CEILING } from './build.ts';
import { chunkRecords, moduleLabel } from './build-campus.ts';
import type { ChunkRecord } from './build-campus.ts';
import { FF3_RELEASE, FF3_STAGED_DIR, stageFf3 } from '../../scripts/stage-ff3.ts';
-import { campusStartupModel } from '../../src/campus/loading';
+import { campusStartupModel } from '../../src/campus/loading-plan';
import { writePublicReceipt } from './public-receipt';
export type BuildMode = 'public' | 'test' | 'dev';
diff --git a/scenes/packages/foundry-floor/tests/tools/owned.ts b/scenes/packages/foundry-floor/tests/tools/owned.ts
index 17be3e86..e68d4ffb 100644
--- a/scenes/packages/foundry-floor/tests/tools/owned.ts
+++ b/scenes/packages/foundry-floor/tests/tools/owned.ts
@@ -1,9 +1,9 @@
// Foundry Floor process ownership helpers. The FF builder may serve only on ports 4700-4749.
-// The kit's serveOwned/assertOwnedUrl/runSceneContractTests are fixed to 4400-4499
-// (kit request GG-001; FF-001 records this range), so this package binds its own range with the kit's static server.
+// This package retains its own range and avoid-set; browser ownership is shared with the kit.
// Binding is attempted directly (EADDRINUSE moves on): no listener is ever probed.
import { resolve } from 'node:path';
import { mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';
+import { chromeProfile, launchChrome } from '../../../scene-kit/src/testing/node';
// @ts-ignore Shared Node-builtins-only implementation owned by the kit builder (read-only use).
import { startStaticServer } from '../../../../scripts/static-server.mjs';
@@ -31,20 +31,11 @@ export function assertOwnedUrl(url: string, owned: ReadonlySet<number>): void {
*/
export interface OwnedBrowser { browser: import('puppeteer-core').Browser; pid: number | undefined; profile: string; close(): Promise<void> }
export async function launchHeadless(name: string, width = 1280, height = 720): Promise<OwnedBrowser> {
- const puppeteer = (await import('puppeteer-core')).default, { mkdtemp, rm } = await import('node:fs/promises');
- const scratch = resolve(PACKAGE_ROOT, '.tmp'); mkdirSync(scratch, { recursive: true });
- const profile = await mkdtemp(resolve(scratch, `${name}-chrome-`));
- const browser = await puppeteer.launch({
- executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, pipe: true, userDataDir: profile,
+ const browser = await launchChrome({ workspace: PACKAGE_ROOT, name, headless: true, windowSize: [width, height],
defaultViewport: { width, height, deviceScaleFactor: 1 },
- args: ['--enable-unsafe-webgpu', '--no-first-run', '--no-default-browser-check', `--window-size=${width},${height}`, '--hide-scrollbars'],
- env: { ...process.env, TEMP: scratch, TMP: scratch },
+ args: ['--hide-scrollbars'],
});
- let closed = false;
- return { browser, pid: browser.process()?.pid, profile, async close() {
- if (closed) return; closed = true;
- try { await browser.close(); } finally { await rm(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }).catch(() => undefined); }
- } };
+ return { browser, pid: browser.process()?.pid, profile: chromeProfile(browser)!, close: () => browser.close() };
}
export function evidencePath(...parts: string[]): string { const path = resolve(PACKAGE_ROOT, 'evidence', ...parts); mkdirSync(resolve(path, '..'), { recursive: true }); return path; }
export function writeJson(path: string, value: unknown): void { mkdirSync(resolve(path, '..'), { recursive: true }); writeFileSync(path, JSON.stringify(value, null, 2) + '\n'); }
diff --git a/scenes/packages/foundry-floor/tests/tools/rebuild-code.ts b/scenes/packages/foundry-floor/tests/tools/rebuild-code.ts
index 8b760ea7..4dc853ee 100644
--- a/scenes/packages/foundry-floor/tests/tools/rebuild-code.ts
+++ b/scenes/packages/foundry-floor/tests/tools/rebuild-code.ts
@@ -3,12 +3,14 @@
// never stages: it takes a sealed standalone (the site's pinned input by default), checks its pack against the sealed
// receipt, builds the current source in public mode, copies the pack unchanged and writes a new public receipt whose
// code fields are measured here and whose pack fields are carried from the sealed receipt.
-// The output is dist/revision2-code/standalone. It is a build, not a qualification: no browser check runs here.
+// The default output is dist/revision2-code/standalone. --out-dir selects a separate owned dist directory.
+// It is a build, not a qualification: no browser check runs here.
// Run from the scenes root:
-// ./scripts/toolchain-run.ps1 packages/foundry-floor/tests/tools/rebuild-code.ts [sealed standalone directory]
+// ./scripts/toolchain-run.ps1 packages/foundry-floor/tests/tools/rebuild-code.ts [sealed standalone directory] [--out-dir packages/foundry-floor/dist/<label>]
import { cp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
+import { realpathSync } from 'node:fs';
import { createHash } from 'node:crypto';
-import { relative, resolve } from 'node:path';
+import { dirname, isAbsolute, relative, resolve } from 'node:path';
import { build } from 'vite';
import type { Rollup } from 'vite';
import { sceneStandaloneConfig } from '../../../scene-kit/src/build/index.ts';
@@ -23,6 +25,51 @@ import { writePublicReceipt } from './public-receipt';
const PAGE_ROOT = resolve(PACKAGE_ROOT, 'standalone-campus');
const DIST = resolve(PACKAGE_ROOT, 'dist/revision2-code');
+const contains = (parent: string, child: string) => {
+ const path = relative(parent, child);
+ return path === '' || (path !== '..' && !path.startsWith('../') && !path.startsWith('..\\') && !isAbsolute(path));
+};
+function canonicalPath(path: string): string {
+ try { return realpathSync(path); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || dirname(path) === path) throw error;
+ return resolve(canonicalPath(dirname(path)), relative(dirname(path), path));
+ }
+}
+/** Validate the directory that will be replaced before reading or deleting any build input. */
+export function codeRebuildDirectory(sealed: string, outputDir = DIST): string {
+ const directory = resolve(SCENES_ROOT, outputDir);
+ const owned = resolve(PACKAGE_ROOT, 'dist'), realOwned = resolve(canonicalPath(PACKAGE_ROOT), 'dist');
+ const realDirectory = canonicalPath(directory), input = canonicalPath(resolve(sealed));
+ if (directory === owned || !contains(owned, directory) || realDirectory === realOwned || !contains(realOwned, realDirectory)) throw new Error('Expected an owned output directory below foundry-floor/dist');
+ if (contains(realDirectory, input) || contains(input, realDirectory)) throw new Error('Sealed input and output directory must not overlap');
+ return directory;
+}
+
+/** Replace only this builder's public output and receipt; a test build may share the label directory. */
+export async function prepareCodeRebuildDirectory(sealed: string, outputDir?: string): Promise<string> {
+ const directory = codeRebuildDirectory(sealed, outputDir);
+ await Promise.all(['standalone', 'receipt'].map(name => rm(resolve(directory, name), { recursive: true, force: true })));
+ return directory;
+}
+
+export function codeRebuildArguments(args: string[]): { sealed?: string; outputDir?: string } {
+ const result: { sealed?: string; outputDir?: string } = {};
+ const usage = () => new Error('Usage: rebuild-code.ts [sealed standalone directory] [--out-dir packages/foundry-floor/dist/<label>]');
+ for (let i = 0; i < args.length; i++) {
+ const argument = args[i]!;
+ if (argument === '--out-dir') {
+ const value = args[++i];
+ if (result.outputDir !== undefined || !value || value.startsWith('--')) throw usage();
+ result.outputDir = value;
+ } else {
+ if (argument.startsWith('--') || result.sealed !== undefined) throw usage();
+ result.sealed = argument;
+ }
+ }
+ return result;
+}
+
async function directoryBytes(path: string): Promise<{ files: number; bytes: number }> {
let files = 0, bytes = 0;
for (const entry of await readdir(path, { withFileTypes: true })) {
@@ -40,13 +87,14 @@ interface SealedReceipt {
moversChunk: { note: string };
}
-export async function rebuildCode(sealed: string, options: { quiet?: boolean } = {}) {
+export async function rebuildCode(sealed: string, options: { quiet?: boolean; outputDir?: string } = {}) {
+ const directory = codeRebuildDirectory(sealed, options.outputDir);
const receipt = JSON.parse(await readFile(resolve(sealed, 'bundle-public.json'), 'utf8')) as SealedReceipt;
if (receipt.mode !== 'public') throw new Error('Expected a sealed public receipt');
const packSha256 = createHash('sha256').update(await readFile(resolve(sealed, 'assets/pack.json'))).digest('hex');
if (packSha256 !== receipt.packSha256) throw new Error('Sealed pack differs from its receipt');
- const output = resolve(DIST, 'standalone');
- await rm(DIST, { recursive: true, force: true });
+ const output = resolve(directory, 'standalone');
+ await prepareCodeRebuildDirectory(sealed, directory);
const built = await build({ ...sceneStandaloneConfig({ root: PAGE_ROOT, outDir: output, mode: 'public' }), configFile: false, logLevel: options.quiet ? 'warn' : 'info' });
const rollup = (Array.isArray(built) ? built[0] : built) as Rollup.RollupOutput;
const chunks = await chunkRecords(output, rollup);
@@ -73,7 +121,7 @@ export async function rebuildCode(sealed: string, options: { quiet?: boolean } =
const initialCode = { bytes: startupCode.bytes + exteriorCode.bytes, gzipBytes: startupCode.gzipBytes + exteriorCode.gzipBytes };
const moversChunk = [...new Set(where.movers!.map(m => m.chunk))];
const withinCeiling = initialCode.bytes <= CEILING.bytes && initialCode.gzipBytes <= CEILING.gzipBytes;
- const record = writePublicReceipt(output, resolve(DIST, 'receipt/bundle-public.json'), {
+ const record = writePublicReceipt(output, resolve(directory, 'receipt/bundle-public.json'), {
mode: 'public', output: relative(PACKAGE_ROOT, output).replace(/\\/g, '/'), page: relative(PACKAGE_ROOT, PAGE_ROOT).replace(/\\/g, '/'), release: receipt.release, built: new Date().toISOString(),
chunks: chunks.map(c => ({ ...c, ceiling: againstCeiling(c) })),
startupCode, exteriorCode, interiorCode, initialCode, initialChunks: chunks.filter(c => c.role !== 'interior').map(c => c.name),
@@ -97,8 +145,9 @@ export async function rebuildCode(sealed: string, options: { quiet?: boolean } =
}
if (import.meta.main) {
- const sealed = resolve(process.argv[2] ?? resolve(SCENES_ROOT, '.cache/site-inputs/foundry-floor/standalone'));
- const record = await rebuildCode(sealed, { quiet: true });
+ const args = codeRebuildArguments(process.argv.slice(2));
+ const sealed = resolve(args.sealed ?? resolve(SCENES_ROOT, '.cache/site-inputs/foundry-floor/standalone'));
+ const record = await rebuildCode(sealed, { quiet: true, outputDir: args.outputDir });
console.log(JSON.stringify({ output: record.output, initialCode: record.initialCode, codeBytes: record.codeBytes, codeGzipBytes: record.codeGzipBytes, outputFiles: record.outputFiles, outputBytes: record.outputBytes, packSha256: record.packSha256 }));
for (const c of record.chunks) console.log(` ${c.role.padEnd(8)} ${c.kind.padEnd(13)} ${String(c.bytes).padStart(9)} B ${String(c.gzipBytes).padStart(8)} B gzip ${c.name}`);
}
diff --git a/scenes/packages/foundry-floor/tests/unit/campus-vegetation-shared.test.ts b/scenes/packages/foundry-floor/tests/unit/campus-vegetation-shared.test.ts
index 6ee25c28..8d8cc9fa 100644
--- a/scenes/packages/foundry-floor/tests/unit/campus-vegetation-shared.test.ts
+++ b/scenes/packages/foundry-floor/tests/unit/campus-vegetation-shared.test.ts
@@ -2,7 +2,7 @@
// roughness carried in its vertices, one instanced draw per plant type and LOD level. Synthetic plants (the real GLBs
// are not in a fresh clone), built the way the saved ones are: three declared levels, material objects shared by level.
import { describe, expect, test } from 'bun:test';
-import { existsSync, readFileSync } from 'node:fs';
+import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { BoxGeometry, Group, InstancedBufferGeometry, InstancedMesh, InterleavedBufferAttribute, Mesh, MeshStandardMaterial, PerspectiveCamera } from 'three/webgpu';
import type { Object3D } from 'three/webgpu';
@@ -13,6 +13,8 @@ import { campusPlantings, PLANT_SIZES } from '../../src/campus/exterior/planting
import type { PlantType } from '../../src/campus/exterior/planting';
import { buildCampusVegetation } from '../../src/campus/exterior/vegetation';
import { PLANT_COLUMNS, plantLook } from '../../src/campus/exterior/plant-material';
+import pins from '../../scripts/campus-asset-pins.json';
+import { findSceneFixture } from '../../../../scripts/release-inputs';
const PACKAGE = resolve(import.meta.dir, '../..');
const data = parseCampus(readFileSync(resolve(PACKAGE, 'data/campus.json'), 'utf8')), placements = campusPlantings(data);
@@ -173,12 +175,17 @@ describe('shared planting', () => {
});
});
-// With the saved plants (staged in the repository's pack, not in a fresh clone): every part of every level is carried.
-const STAGED = resolve(PACKAGE, 'staged/revision2/models/vegetation'), saved = existsSync(STAGED);
+// Exact saved plants, restored from the release or pinned staged copies. Required by test:release-inputs.
+const savedPlants = Object.keys(PLANT_SIZES).map(type => {
+ const pin = pins.find(p => p.id === `plant-${type}`)!;
+ return { type, path: findSceneFixture({ scene: 'foundry-floor', path: pin.to, sha256: pin.sha256, bytes: pin.bytes },
+ { fallback: [resolve(PACKAGE, 'staged/revision2', pin.to)] }) };
+});
+const saved = savedPlants.every(p => p.path);
describe.skipIf(!saved)('shared planting with the saved plants', () => {
test('every part of the eight saved plants is carried, so every plant draws through one material', async () => {
const real = new Map<string, GLTF>();
- for (const type of Object.keys(PLANT_SIZES)) { const bytes = readFileSync(resolve(STAGED, `${type}.glb`)); real.set(`plant-${type}`, await new GLTFLoader().parseAsync(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer, '')); }
+ for (const { type, path } of savedPlants) { const bytes = readFileSync(path!); real.set(`plant-${type}`, await new GLTFLoader().parseAsync(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer, '')); }
const shared = (await buildCampusVegetation(data, real, placements, { shared: true }))!;
expect(meshes(shared.root)).toHaveLength(24);
expect(new Set(meshes(shared.root).map(m => m.material)).size).toBe(1);
diff --git a/scenes/packages/foundry-floor/tests/unit/glb-world.test.ts b/scenes/packages/foundry-floor/tests/unit/glb-world.test.ts
index 02daf03f..6e42fdfc 100644
--- a/scenes/packages/foundry-floor/tests/unit/glb-world.test.ts
+++ b/scenes/packages/foundry-floor/tests/unit/glb-world.test.ts
@@ -1,10 +1,9 @@
-// The GLB world built headless from the accepted GLBs (the staged pack's copies, or the authors' files while they are
-// the pinned ones; read-only inputs): every accepted GLB bakes, every static placement and every driver runs over sim
+// The GLB world built headless from the accepted GLBs (restored release first; optional local runs may use identical
+// staged or author bytes): every accepted GLB bakes, every static placement and every driver runs over sim
// time from the stored warm start without throwing, poses stay finite, the drawn FOUPs follow the twin, and the named
// views stay inside the desktop and phone budgets (triangles and draws, D-15 / SPEC budgets). No renderer is involved:
// the counts are what the world would submit.
import { describe, expect, test } from 'bun:test';
-import { createHash } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { PerspectiveCamera } from 'three/webgpu';
@@ -19,16 +18,18 @@ import { prepareModelLevels } from '../../src/scene/glb/model-levels';
import type { GlbWorld } from '../../src/scene/world/glb-world';
import { createClock } from '../../src/sim/clock';
import { createFab, FAB_DATA, HOUR_MS } from '../../src/sim/index';
+import { findSceneFixture } from '../../../../scripts/release-inputs';
const PACKAGE = resolve(import.meta.dir, '../..'), COMMONS = resolve(PACKAGE, '../../..');
const map = parseAssetMap(readFileSync(resolve(PACKAGE, 'data/assets.json'), 'utf8'));
const snapshot = readFileSync(resolve(PACKAGE, `data/warm/seed-${FAB_DATA.config.seeds.default}.json`), 'utf8');
-const sha = (path: string) => createHash('sha256').update(readFileSync(path)).digest('hex');
const accepted = Object.entries(map.entities).filter(([, e]) => e.glb && e.pins).map(([id]) => id);
function source(id: string): string | undefined {
const e = map.entities[id]!;
- const candidates = [resolve(PACKAGE, 'staged/ff2', e.glb!), ...(e.source ? [resolve(COMMONS, 'showcase/authors', e.source.author, e.source.file)] : [])];
- return candidates.find(path => existsSync(path) && sha(path) === e.pins!.sha256);
+ return findSceneFixture({ scene: 'foundry-floor', path: e.glb!, ...e.pins! }, { fallback: [
+ resolve(PACKAGE, 'staged/revision2', e.glb!),
+ ...(e.source ? [resolve(COMMONS, 'showcase/authors', e.source.author, e.source.file)] : []),
+ ] });
}
const available = accepted.every(id => source(id));
/** Budgets (SPEC): desktop 1.2M triangles and 300 draws; phone 450k triangles and 150 draws. */
diff --git a/scenes/packages/golden-gate/README.md b/scenes/packages/golden-gate/README.md
new file mode 100644
index 00000000..07daee49
--- /dev/null
+++ b/scenes/packages/golden-gate/README.md
@@ -0,0 +1,45 @@
+# Golden Gate scene maintenance
+
+Current source is authoritative. [REPORT.md](REPORT.md) and [PERFORMANCE.md](PERFORMANCE.md)
+retain dated qualification evidence; they do not qualify later source or dependency changes.
+
+## Layout delivery
+
+`data/layout.json` is authored scene data. Staging delivers it as the manifest's `layout`
+member. The scene-kit pack loader fetches it once and checks its byte count and SHA-256;
+`src/layout.ts` parses those verified bytes separately for each world. The runtime has no
+authored-layout fallback or mutable layout singleton. Approaches, dressing, vegetation, fog
+banks and flight keys are passed from that world's layout to their constructors. The full
+layout is not imported by browser source. Offline scripts and tests can explicitly import
+`scripts/authored-layout.ts`.
+
+The camera and quality tiers must exist before the pack loads. They use the small, immutable
+`src/layout-bootstrap.json`, generated from authored data. Its projection includes cameras,
+bridge dimensions, lane configuration and stations (without polylines), approach lengths and
+end behavior, lamp configuration, reference colors, and flight names, labels and clearance.
+The runtime checks the schema, bulk data shapes and the **exact projection** before allocating
+world resources. A missing, malformed, incompatible or cancelled layout fails through the
+existing loading/error lifecycle; it never silently uses bundled bulk data. Loaded pack
+models remain owned and disposed by SceneRoot, as before.
+
+This is an explicit rebuild boundary: changes to camera, bridge, lane, approach bounds or
+other projected fields require regenerating the bootstrap and rebuilding the scene bundle
+together with the revised pack. Compatible bulk-only edits can differ between mounts, but
+still require the normal asset/scene qualification. Shape checks do not establish collision,
+flight clearance or visual quality. Other tables in `src/data.ts` remain bundled.
+
+After authored layout changes (and any required `scripts/layout.ts --write` derivation), run
+from `scenes/`:
+
+```sh
+bun packages/golden-gate/scripts/generate-layout-bootstrap.ts --write
+bun packages/golden-gate/scripts/generate-layout-bootstrap.ts --check
+bun test packages/golden-gate/tests/unit/layout-loading.test.ts
+```
+
+The generation is deterministic and records the source SHA-256. The portable test gate checks
+source/projection equality and source provenance; `--check` additionally compares the exact
+generated file bytes. Do not hand-edit the bootstrap or weaken the runtime equality check to
+make a stale bundle accept a new pack. Rebuild with `scripts/build-scene.ts`; its module receipt
+must contain the bootstrap and omit `packages/golden-gate/data/layout.json`. Browser look,
+driving, flight, count and performance qualification remains a separate release step.
diff --git a/scenes/packages/golden-gate/fixtures/x02-baseline.json b/scenes/packages/golden-gate/fixtures/x02-baseline.json
new file mode 100644
index 00000000..e295cfb8
--- /dev/null
+++ b/scenes/packages/golden-gate/fixtures/x02-baseline.json
@@ -0,0 +1,552 @@
+{
+ "id": "X-02",
+ "captured": "2026-10-02T08:42:56.568Z",
+ "note": "Counts only (renderer.info for the frame just rendered, after two equal samples 20 frames apart); no timing. Golden Gate has no pilot, so these are the baseline. The drive-chase view runs 90 frames of real time before the clock freezes, so where the car stops (drive.z) and the traffic around it vary between runs.",
+ "build": {
+ "label": "draw-after",
+ "root": "packages/golden-gate/dist/draw-after/test",
+ "chunks": [
+ "index-D-gELBet.js",
+ "route-contact-CxuZU847.js"
+ ],
+ "source": "working tree",
+ "release": "g9",
+ "packSha256": "c2a1d83fce6caf07a7b3e87070ccb8a983dd68e0c7f98eee3f1ba5255ce059cb"
+ },
+ "window": {
+ "width": 1920,
+ "height": 1080,
+ "deviceScaleFactor": 1
+ },
+ "preset": "day",
+ "time": 12,
+ "unexpectedMessages": [],
+ "cases": [
+ {
+ "backend": "webgpu",
+ "tier": "high",
+ "views": [
+ {
+ "view": "arrival",
+ "drawCalls": 103,
+ "triangles": 1426047
+ },
+ {
+ "view": "postcard",
+ "drawCalls": 101,
+ "triangles": 1329477
+ },
+ {
+ "view": "pier",
+ "drawCalls": 75,
+ "triangles": 1104205
+ },
+ {
+ "view": "topdown",
+ "drawCalls": 64,
+ "triangles": 1235407
+ },
+ {
+ "view": "horizon",
+ "drawCalls": 45,
+ "triangles": 954385
+ },
+ {
+ "view": "deck",
+ "drawCalls": 116,
+ "triangles": 1516537
+ },
+ {
+ "view": "tower",
+ "drawCalls": 94,
+ "triangles": 1009189
+ },
+ {
+ "view": "span",
+ "drawCalls": 107,
+ "triangles": 1416635
+ },
+ {
+ "view": "lanes",
+ "drawCalls": 113,
+ "triangles": 1546855
+ },
+ {
+ "view": "sidewalk",
+ "drawCalls": 116,
+ "triangles": 1547917
+ },
+ {
+ "view": "traffic",
+ "drawCalls": 106,
+ "triangles": 1503153
+ },
+ {
+ "view": "hero-orbit-0deg",
+ "drawCalls": 94,
+ "triangles": 1305259
+ },
+ {
+ "view": "hero-orbit-90deg",
+ "drawCalls": 93,
+ "triangles": 1302707
+ },
+ {
+ "view": "hero-orbit-180deg",
+ "drawCalls": 101,
+ "triangles": 1434847
+ },
+ {
+ "view": "hero-orbit-270deg",
+ "drawCalls": 91,
+ "triangles": 1293595
+ },
+ {
+ "view": "drive-chase",
+ "drawCalls": 113,
+ "triangles": 1523583
+ }
+ ]
+ },
+ {
+ "backend": "webgpu",
+ "tier": "balanced",
+ "views": [
+ {
+ "view": "arrival",
+ "drawCalls": 52,
+ "triangles": 596121
+ },
+ {
+ "view": "postcard",
+ "drawCalls": 50,
+ "triangles": 567221
+ },
+ {
+ "view": "pier",
+ "drawCalls": 35,
+ "triangles": 464234
+ },
+ {
+ "view": "topdown",
+ "drawCalls": 30,
+ "triangles": 534321
+ },
+ {
+ "view": "horizon",
+ "drawCalls": 23,
+ "triangles": 408231
+ },
+ {
+ "view": "deck",
+ "drawCalls": 52,
+ "triangles": 618823
+ },
+ {
+ "view": "tower",
+ "drawCalls": 45,
+ "triangles": 391612
+ },
+ {
+ "view": "span",
+ "drawCalls": 54,
+ "triangles": 597923
+ },
+ {
+ "view": "lanes",
+ "drawCalls": 53,
+ "triangles": 631479
+ },
+ {
+ "view": "sidewalk",
+ "drawCalls": 51,
+ "triangles": 621073
+ },
+ {
+ "view": "traffic",
+ "drawCalls": 50,
+ "triangles": 616627
+ },
+ {
+ "view": "hero-orbit-0deg",
+ "drawCalls": 49,
+ "triangles": 556939
+ },
+ {
+ "view": "hero-orbit-90deg",
+ "drawCalls": 47,
+ "triangles": 557481
+ },
+ {
+ "view": "hero-orbit-180deg",
+ "drawCalls": 50,
+ "triangles": 600065
+ },
+ {
+ "view": "hero-orbit-270deg",
+ "drawCalls": 46,
+ "triangles": 554361
+ },
+ {
+ "view": "drive-chase",
+ "drawCalls": 52,
+ "triangles": 625011
+ }
+ ]
+ },
+ {
+ "backend": "webgpu",
+ "tier": "economy",
+ "views": [
+ {
+ "view": "arrival",
+ "drawCalls": 52,
+ "triangles": 344564
+ },
+ {
+ "view": "postcard",
+ "drawCalls": 51,
+ "triangles": 318506
+ },
+ {
+ "view": "pier",
+ "drawCalls": 31,
+ "triangles": 264464
+ },
+ {
+ "view": "topdown",
+ "drawCalls": 30,
+ "triangles": 285450
+ },
+ {
+ "view": "horizon",
+ "drawCalls": 23,
+ "triangles": 232289
+ },
+ {
+ "view": "deck",
+ "drawCalls": 49,
+ "triangles": 338732
+ },
+ {
+ "view": "tower",
+ "drawCalls": 42,
+ "triangles": 250465
+ },
+ {
+ "view": "span",
+ "drawCalls": 48,
+ "triangles": 337912
+ },
+ {
+ "view": "lanes",
+ "drawCalls": 50,
+ "triangles": 344210
+ },
+ {
+ "view": "sidewalk",
+ "drawCalls": 49,
+ "triangles": 341560
+ },
+ {
+ "view": "traffic",
+ "drawCalls": 47,
+ "triangles": 336548
+ },
+ {
+ "view": "hero-orbit-0deg",
+ "drawCalls": 48,
+ "triangles": 313196
+ },
+ {
+ "view": "hero-orbit-90deg",
+ "drawCalls": 47,
+ "triangles": 310460
+ },
+ {
+ "view": "hero-orbit-180deg",
+ "drawCalls": 49,
+ "triangles": 340062
+ },
+ {
+ "view": "hero-orbit-270deg",
+ "drawCalls": 46,
+ "triangles": 308186
+ },
+ {
+ "view": "drive-chase",
+ "drawCalls": 49,
+ "triangles": 339174
+ }
+ ]
+ },
+ {
+ "backend": "webgl2",
+ "tier": "high",
+ "views": [
+ {
+ "view": "arrival",
+ "drawCalls": 103,
+ "triangles": 1426047
+ },
+ {
+ "view": "postcard",
+ "drawCalls": 101,
+ "triangles": 1329477
+ },
+ {
+ "view": "pier",
+ "drawCalls": 75,
+ "triangles": 1104205
+ },
+ {
+ "view": "topdown",
+ "drawCalls": 64,
+ "triangles": 1235407
+ },
+ {
+ "view": "horizon",
+ "drawCalls": 45,
+ "triangles": 954385
+ },
+ {
+ "view": "deck",
+ "drawCalls": 116,
+ "triangles": 1516537
+ },
+ {
+ "view": "tower",
+ "drawCalls": 94,
+ "triangles": 1009189
+ },
+ {
+ "view": "span",
+ "drawCalls": 107,
+ "triangles": 1416635
+ },
+ {
+ "view": "lanes",
+ "drawCalls": 113,
+ "triangles": 1546855
+ },
+ {
+ "view": "sidewalk",
+ "drawCalls": 116,
+ "triangles": 1547917
+ },
+ {
+ "view": "traffic",
+ "drawCalls": 106,
+ "triangles": 1503153
+ },
+ {
+ "view": "hero-orbit-0deg",
+ "drawCalls": 94,
+ "triangles": 1305259
+ },
+ {
+ "view": "hero-orbit-90deg",
+ "drawCalls": 93,
+ "triangles": 1302707
+ },
+ {
+ "view": "hero-orbit-180deg",
+ "drawCalls": 101,
+ "triangles": 1434847
+ },
+ {
+ "view": "hero-orbit-270deg",
+ "drawCalls": 91,
+ "triangles": 1293595
+ },
+ {
+ "view": "drive-chase",
+ "drawCalls": 113,
+ "triangles": 1528521
+ }
+ ]
+ },
+ {
+ "backend": "webgl2",
+ "tier": "balanced",
+ "views": [
+ {
+ "view": "arrival",
+ "drawCalls": 52,
+ "triangles": 596121
+ },
+ {
+ "view": "postcard",
+ "drawCalls": 50,
+ "triangles": 567221
+ },
+ {
+ "view": "pier",
+ "drawCalls": 35,
+ "triangles": 464234
+ },
+ {
+ "view": "topdown",
+ "drawCalls": 30,
+ "triangles": 534321
+ },
+ {
+ "view": "horizon",
+ "drawCalls": 23,
+ "triangles": 408231
+ },
+ {
+ "view": "deck",
+ "drawCalls": 52,
+ "triangles": 618823
+ },
+ {
+ "view": "tower",
+ "drawCalls": 45,
+ "triangles": 391612
+ },
+ {
+ "view": "span",
+ "drawCalls": 54,
+ "triangles": 597923
+ },
+ {
+ "view": "lanes",
+ "drawCalls": 53,
+ "triangles": 631479
+ },
+ {
+ "view": "sidewalk",
+ "drawCalls": 51,
+ "triangles": 621073
+ },
+ {
+ "view": "traffic",
+ "drawCalls": 50,
+ "triangles": 616627
+ },
+ {
+ "view": "hero-orbit-0deg",
+ "drawCalls": 49,
+ "triangles": 556939
+ },
+ {
+ "view": "hero-orbit-90deg",
+ "drawCalls": 47,
+ "triangles": 557481
+ },
+ {
+ "view": "hero-orbit-180deg",
+ "drawCalls": 50,
+ "triangles": 600065
+ },
+ {
+ "view": "hero-orbit-270deg",
+ "drawCalls": 46,
+ "triangles": 554361
+ },
+ {
+ "view": "drive-chase",
+ "drawCalls": 51,
+ "triangles": 622745
+ }
+ ]
+ },
+ {
+ "backend": "webgl2",
+ "tier": "economy",
+ "views": [
+ {
+ "view": "arrival",
+ "drawCalls": 52,
+ "triangles": 344564
+ },
+ {
+ "view": "postcard",
+ "drawCalls": 51,
+ "triangles": 318506
+ },
+ {
+ "view": "pier",
+ "drawCalls": 31,
+ "triangles": 264464
+ },
+ {
+ "view": "topdown",
+ "drawCalls": 30,
+ "triangles": 285450
+ },
+ {
+ "view": "horizon",
+ "drawCalls": 23,
+ "triangles": 232289
+ },
+ {
+ "view": "deck",
+ "drawCalls": 49,
+ "triangles": 338732
+ },
+ {
+ "view": "tower",
+ "drawCalls": 42,
+ "triangles": 250465
+ },
+ {
+ "view": "span",
+ "drawCalls": 48,
+ "triangles": 337912
+ },
+ {
+ "view": "lanes",
+ "drawCalls": 50,
+ "triangles": 344210
+ },
+ {
+ "view": "sidewalk",
+ "drawCalls": 49,
+ "triangles": 341560
+ },
+ {
+ "view": "traffic",
+ "drawCalls": 47,
+ "triangles": 336548
+ },
+ {
+ "view": "hero-orbit-0deg",
+ "drawCalls": 48,
+ "triangles": 313196
+ },
+ {
+ "view": "hero-orbit-90deg",
+ "drawCalls": 47,
+ "triangles": 310460
+ },
+ {
+ "view": "hero-orbit-180deg",
+ "drawCalls": 49,
+ "triangles": 340062
+ },
+ {
+ "view": "hero-orbit-270deg",
+ "drawCalls": 46,
+ "triangles": 308186
+ },
+ {
+ "view": "drive-chase",
+ "drawCalls": 50,
+ "triangles": 343838
+ }
+ ]
+ }
+ ],
+ "provenance": {
+ "originalReceipt": "scenes/evidence/draw-after/golden-gate/x02/draw-after/x02-counts.json",
+ "originalWorktree": "kiln-draw-optimization",
+ "originalSha256": "ec58dc339b8c56018a0a1f2ecdff137915752e30ba8c9af958249db0a4ad233d",
+ "originalBytes": 70958,
+ "documentation": "scenes/packages/golden-gate/PERFORMANCE.md#x-02-re-baseline-on-the-draw-optimized-build-od-8-d-53-2026-10-02",
+ "documentedHead": "892d103200d385f3f568608449cde555eb6b220d",
+ "transformation": "Retains the original drawCalls and triangles for every case/view. Omits other per-view diagnostics and replaces the machine-specific build root with its scene-relative path. This is a retained historical receipt, not a new measurement or a clean-source attestation.",
+ "casesSha256": "65691a2e1fe98dce5afb8cfdc8c5491d0eb3cd9f2654c424431d6eef65748997"
+ }
+}
diff --git a/scenes/packages/golden-gate/package.json b/scenes/packages/golden-gate/package.json
index 0ae32e8c..87011873 100644
--- a/scenes/packages/golden-gate/package.json
+++ b/scenes/packages/golden-gate/package.json
@@ -10,13 +10,13 @@
"react": "19.3.0",
"react-dom": "19.3.0",
"@react-three/fiber": "9.8.1",
- "three": "0.186.0"
+ "three": "0.186.1"
},
"devDependencies": {
"react": "19.3.0",
"react-dom": "19.3.0",
"@react-three/fiber": "9.8.1",
- "three": "0.186.0",
+ "three": "0.186.1",
"@types/three": "0.186.0"
}
}
diff --git a/scenes/packages/golden-gate/scripts/authored-layout.ts b/scenes/packages/golden-gate/scripts/authored-layout.ts
new file mode 100644
index 00000000..0c8f8d45
--- /dev/null
+++ b/scenes/packages/golden-gate/scripts/authored-layout.ts
@@ -0,0 +1,4 @@
+// Offline authoring/test fixture. Browser runtime consumes the verified pack through src/layout.ts.
+import authored from '../data/layout.json';
+import type { SceneLayout } from '../src/data';
+export const LAYOUT = authored as unknown as SceneLayout;
diff --git a/scenes/packages/golden-gate/scripts/generate-layout-bootstrap.ts b/scenes/packages/golden-gate/scripts/generate-layout-bootstrap.ts
new file mode 100644
index 00000000..6e39370d
--- /dev/null
+++ b/scenes/packages/golden-gate/scripts/generate-layout-bootstrap.ts
@@ -0,0 +1,16 @@
+// From scenes/: bun packages/golden-gate/scripts/generate-layout-bootstrap.ts --write (or --check).
+import { createHash } from 'node:crypto';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { projectLayoutBootstrap, stableLayoutJson } from '../src/layout-contract';
+import type { SceneLayout } from '../src/data';
+
+const root = fileURLToPath(new URL('..', import.meta.url)), source = readFileSync(resolve(root, 'data/layout.json'));
+const record = { schema: 'golden-gate-bootstrap/1', source: 'data/layout.json', sourceSha256: createHash('sha256').update(source).digest('hex'),
+ projection: projectLayoutBootstrap(JSON.parse(new TextDecoder().decode(source)) as SceneLayout) };
+const output = JSON.stringify(JSON.parse(stableLayoutJson(record)), null, 2) + '\n', path = resolve(root, 'src/layout-bootstrap.json');
+const flag = process.argv[2] ?? '--check';
+if (flag === '--write') writeFileSync(path, output);
+else if (flag !== '--check') throw new Error('Use --check or --write');
+else if (readFileSync(path, 'utf8') !== output) throw new Error('Golden Gate bootstrap is stale; run generate-layout-bootstrap.ts --write and rebuild');
diff --git a/scenes/packages/golden-gate/scripts/stage.ts b/scenes/packages/golden-gate/scripts/stage.ts
index b1ed1e76..56433c15 100644
--- a/scenes/packages/golden-gate/scripts/stage.ts
+++ b/scenes/packages/golden-gate/scripts/stage.ts
@@ -11,7 +11,8 @@ import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { stageFiles, verifyStaged, type StagePlan } from '@kiln-scenes/scene-kit/staging';
import type { CreditEntry } from '@kiln-scenes/scene-kit';
-import { DATA_FILES, LAYOUT } from '../src/data';
+import { DATA_FILES } from '../src/data';
+import { LAYOUT } from './authored-layout';
/** The behaviour specification staged beside the data (traffic, driving, flights, fog banks, lamps). */
const BEHAVIOUR_FILE = 'data/BEHAVIOUR.md';
import { laneDrift, roadGridFromBridge } from './layout';
@@ -298,7 +299,7 @@ export async function stageGoldenGate(args: readonly string[] = process.argv.sli
] };
write('credits.json', JSON.stringify(creditsFile, null, 2) + '\n', 'credits.json');
- const result = stageFiles({ id: 'golden-gate', release: options.release, three: '0.186.0', out, force: options.force, models,
+ const result = stageFiles({ id: 'golden-gate', release: options.release, three: '0.186.1', out, force: options.force, models,
data: { scene: 'data/scene.json', collision: `terrain/${collision.file}`, ...DATA_FILES }, files, credits,
source: { bridge: Object.fromEntries(Object.entries(BRIDGE_PINS).map(([k, v]) => [k, v.revision])), terrainSchema: terrain.schema, terrainManifestSha256: sha256(readFileSync(terrainManifestPath)), vehicles: Object.keys(vehicles) } });
const verification = verifyStaged(out); if (!verification.ok) throw new Error(verification.problems.join('\n'));
diff --git a/scenes/packages/golden-gate/src/World.tsx b/scenes/packages/golden-gate/src/World.tsx
index 4d01956d..e1019367 100644
--- a/scenes/packages/golden-gate/src/World.tsx
+++ b/scenes/packages/golden-gate/src/World.tsx
@@ -17,7 +17,6 @@ import { WATER_DEBUG } from './world/water-material';
import { sightlineClearance, surfaceHeight } from './world/heightfield';
import { GoldenGateCameras } from './camera/GoldenGateCameras';
import { Driving } from './play/Driving';
-import { LAYOUT } from './data';
import type { DrawOptions } from './world/draw-options';
const TEST = !!(import.meta.env.KILN_TEST || import.meta.env.KILN_DEV);
@@ -105,6 +104,7 @@ export function GoldenGateWorldContent() {
clearance: (from: Vec3, to: Vec3) => sightlineClearance(world.field, from, to, .55),
/** Diagnostics: hide or show one part of the world. */
setPartVisible: (part: 'terrain' | 'bridge' | 'water' | 'banks' | 'sky' | 'traffic', visible: boolean) => {
+ if (part === 'banks') { if (!world.banks) return false; world.banks.hidden = !visible; return true; }
const target = { terrain: world.terrain.root, bridge: world.bridge.root, water: world.water.mesh, banks: world.banks?.sprite, sky: world.atmosphere.sky, traffic: world.traffic.root }[part];
if (!target) return false; target.visible = visible; return true;
},
@@ -127,7 +127,7 @@ export function GoldenGateWorldContent() {
useRegisterTestHooks(hooks);
return world ? <>
- <GoldenGateCameras world={world} initialView={typeof params.cam === 'string' ? params.cam : LAYOUT.cameras.default}
+ <GoldenGateCameras world={world} initialView={typeof params.cam === 'string' ? params.cam : world.layout.cameras.default}
initialFlight={typeof params.flight === 'string' ? params.flight as FlightName : undefined} initialFlightAt={typeof params.flightAt === 'number' ? params.flightAt : 0}/>
<Driving world={world}/>
</> : null;
diff --git a/scenes/packages/golden-gate/src/camera/GoldenGateCameras.tsx b/scenes/packages/golden-gate/src/camera/GoldenGateCameras.tsx
index a46a8fe9..0552d3c1 100644
--- a/scenes/packages/golden-gate/src/camera/GoldenGateCameras.tsx
+++ b/scenes/packages/golden-gate/src/camera/GoldenGateCameras.tsx
@@ -1,6 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useThree } from '@react-three/fiber';
-import { LAYOUT } from '../data';
import { Box3, Vector3 } from 'three/webgpu';
import type { PerspectiveCamera } from 'three/webgpu';
import { OrbitRig, PathRig, SystemOrder, usePlayMode, useSceneRootRef, useSystem } from '@kiln-scenes/scene-kit';
@@ -40,7 +39,7 @@ export function GoldenGateCameras({ world, initialView, initialFlight, initialFl
const [mode, setModeState] = useState<CameraMode>('orbit'), modeRef = useRef<CameraMode>('orbit'), path = useRef<PathHandle | null>(null), initialized = useRef(false);
const pose = useRef<{ position: Vec3; target: Vec3; fov: number } | null>(null);
const setMode = (next: CameraMode) => { modeRef.current = next; setModeState(next); session.hud.set({ flight: next === 'flight' ? path.current?.playing as FlightName ?? null : null }); };
- const flights = useMemo(() => buildFlights(world.field), [world]);
+ const flights = useMemo(() => buildFlights(world.field, world.layout), [world]);
const floor = useMemo(() => (x: number, z: number) => surfaceHeight(world.field, x, z), [world]);
const handBack = (from: Pose | { position: Vec3; target: Vec3; fov?: number }) => {
@@ -114,7 +113,7 @@ export function GoldenGateCameras({ world, initialView, initialFlight, initialFl
});
return <>
- <OrbitRig rigRef={session.orbit} active={mode === 'orbit' && !playing} target={NAMED_CAMERAS[LAYOUT.cameras.default]!.target} minDistance={CAMERA.orbit.minDistance} maxDistance={CAMERA.orbit.maxDistance}
+ <OrbitRig rigRef={session.orbit} active={mode === 'orbit' && !playing} target={NAMED_CAMERAS[world.layout.cameras.default]!.target} minDistance={CAMERA.orbit.minDistance} maxDistance={CAMERA.orbit.maxDistance}
maxPolar={CAMERA.orbit.maxPolar} pan floor={floor} clearance={CAMERA.orbit.clearance} bounds={TARGET_BOUNDS}/>
<PathRig paths={flights.paths} active={mode === 'flight'} interruptible pathRef={path} time={session.motion.now}
onInterrupt={current => { setMode('orbit'); handBack(current); }}
diff --git a/scenes/packages/golden-gate/src/camera/flights.ts b/scenes/packages/golden-gate/src/camera/flights.ts
index 3e0af6a1..46af75b0 100644
--- a/scenes/packages/golden-gate/src/camera/flights.ts
+++ b/scenes/packages/golden-gate/src/camera/flights.ts
@@ -3,7 +3,8 @@
// (layout.json `flights`, D-21). Every path is checked against the terrain collision grid when it is
// built, and against the bridge's geometry by tests/unit/flights.test.ts.
import type { PathDef, PathKey, Vec3 } from '@kiln-scenes/scene-kit';
-import { LAYOUT } from '../data';
+import type { SceneLayout } from '../data';
+import { BOOTSTRAP } from '../layout-bootstrap';
import { sightlineClearance, surfaceHeight } from '../world/heightfield';
import type { HeightField } from '../world/heightfield';
import { FLIGHT_NAMES } from '../params';
@@ -12,27 +13,30 @@ import type { FlightName } from '../params';
export interface FlightInfo { name: FlightName; label: string; seconds: number; requiresPreset?: 'fog'; minClearance: number; start: { position: Vec3; target: Vec3; fov: number } }
export interface Flights { paths: PathDef[]; info: Record<FlightName, FlightInfo> }
-const DATA = LAYOUT.flights, BY_NAME = new Map(DATA.paths.map(path => [path.name, path]));
-if (BY_NAME.size !== FLIGHT_NAMES.length || FLIGHT_NAMES.some(name => !BY_NAME.has(name))) throw new Error(`data/layout.json flights (${[...BY_NAME.keys()].join(', ')}) differ from the scene's (${FLIGHT_NAMES.join(', ')})`);
-const flight = (name: FlightName) => BY_NAME.get(name)!;
+function byName(layout: SceneLayout) {
+ const paths = new Map(layout.flights.paths.map(path => [path.name, path]));
+ if (paths.size !== FLIGHT_NAMES.length || FLIGHT_NAMES.some(name => !paths.has(name))) throw new Error(`data/layout.json flights (${[...paths.keys()].join(', ')}) differ from the scene's (${FLIGHT_NAMES.join(', ')})`);
+ return paths;
+}
-export const FLIGHT_LABELS = Object.fromEntries(FLIGHT_NAMES.map(name => [name, flight(name).label])) as Record<FlightName, string>;
+export const FLIGHT_LABELS = BOOTSTRAP.flightLabels as Record<FlightName, string>;
/** Height above terrain or water that every key aims for (metres); keys and chords must keep at least `terrainMinimum`. */
-export const FLIGHT_CLEARANCE = DATA.clearance.terrain;
+export const FLIGHT_CLEARANCE = BOOTSTRAP.flightClearance.terrain;
/** The flights as the kit's path definitions, keys exactly as the data gives them. */
-export function flightPaths(): PathDef[] {
+export function flightPaths(layout: SceneLayout): PathDef[] {
+ const paths = byName(layout);
return FLIGHT_NAMES.map(name => {
- const data = flight(name);
+ const data = paths.get(name)!;
const keys: PathKey[] = data.keys.map(k => k.seconds === undefined ? { position: k.position, target: k.target, fov: k.fov } : { position: k.position, target: k.target, fov: k.fov, seconds: k.seconds });
return { name, keys, seconds: data.seconds, interpolation: 'catmull-rom', easing: data.easing ?? 'ease-in-out', loop: false };
});
}
-export function buildFlights(field: HeightField): Flights {
- const info = {} as Record<FlightName, FlightInfo>, paths = flightPaths();
+export function buildFlights(field: HeightField, layout: SceneLayout): Flights {
+ const info = {} as Record<FlightName, FlightInfo>, paths = flightPaths(layout), dataByName = byName(layout);
for (const path of paths) {
- const name = path.name as FlightName, data = flight(name);
+ const name = path.name as FlightName, data = dataByName.get(name)!;
// Terrain clearance at each key, and along each chord between keys.
let minClearance = Infinity;
for (let i = 0; i < path.keys.length; i++) {
@@ -40,7 +44,7 @@ export function buildFlights(field: HeightField): Flights {
minClearance = Math.min(minClearance, p[1] - surfaceHeight(field, p[0], p[2]));
if (i > 0) minClearance = Math.min(minClearance, sightlineClearance(field, path.keys[i - 1]!.position, p, 5).clearance);
}
- if (!(minClearance >= DATA.clearance.terrainMinimum)) throw new Error(`Flight ${name} passes ${minClearance.toFixed(2)} m above terrain`);
+ if (!(minClearance >= layout.flights.clearance.terrainMinimum)) throw new Error(`Flight ${name} passes ${minClearance.toFixed(2)} m above terrain`);
const first = path.keys[0]!;
info[name] = { name, label: data.label, seconds: data.seconds, requiresPreset: data.requiresPreset === 'fog' ? 'fog' : undefined, minClearance,
start: { position: first.position, target: first.target, fov: first.fov ?? 55 } };
diff --git a/scenes/packages/golden-gate/src/constants.ts b/scenes/packages/golden-gate/src/constants.ts
index 353782ba..2310a112 100644
--- a/scenes/packages/golden-gate/src/constants.ts
+++ b/scenes/packages/golden-gate/src/constants.ts
@@ -1,7 +1,8 @@
// Golden Gate scene frame (bridge REPORT.md, terrain frame.json): metres, +Y up, water at Y = 0,
// +X west (Pacific), +Z north (Marin), south tower at Z = -640.08. Right-handed.
-// Scene values come from data/layout.json (D-21); this module only gives them convenient shapes.
-import { LAYOUT } from './data';
+// Scene values come from data/layout.json (D-21), through its generated startup projection. The
+// verified runtime layout must match this projection before world construction (./layout.ts).
+import { BOOTSTRAP as LAYOUT } from './layout-bootstrap';
import type { CameraPose, Vec3 } from './data';
export type { Vec3 } from './data';
diff --git a/scenes/packages/golden-gate/src/data.ts b/scenes/packages/golden-gate/src/data.ts
index 8d7c58aa..5eb3d3d6 100644
--- a/scenes/packages/golden-gate/src/data.ts
+++ b/scenes/packages/golden-gate/src/data.ts
@@ -1,8 +1,8 @@
// The scene's truth is data (owner direction D-21): every placement, lane, light, camera, flight,
// preset, tier and behaviour parameter lives in data/*.json, in metres and seconds, and is staged
-// beside data/scene.json so another engine can read the same files. This module only types them;
-// the components render what it exports and hold no scene values of their own.
-import layoutJson from '../data/layout.json';
+// beside data/scene.json so another engine can read the same files. Layout is loaded from the verified
+// pack by layout.ts, with generated layout-bootstrap.json supplying only the checked startup contract.
+// This module supplies its types and the other bundled configuration tables.
import presetsJson from '../data/presets.json';
import tiersJson from '../data/tiers.json';
import trafficJson from '../data/traffic.json';
@@ -285,7 +285,6 @@ export interface SceneDriving {
controls: Record<'throttle' | 'reverse' | 'left' | 'right' | 'brake' | 'handbrake' | 'boost' | 'turnAround' | 'enterOrLeave' | 'leave', string[]>;
}
-export const LAYOUT = layoutJson as unknown as SceneLayout;
export const PRESET_DATA = presetsJson as unknown as ScenePresets;
export const TIER_DATA = tiersJson as unknown as SceneTiers;
export const TRAFFIC_DATA = trafficJson as unknown as SceneTraffic;
diff --git a/scenes/packages/golden-gate/src/definition.ts b/scenes/packages/golden-gate/src/definition.ts
index c2b2f009..f4905ccf 100644
--- a/scenes/packages/golden-gate/src/definition.ts
+++ b/scenes/packages/golden-gate/src/definition.ts
@@ -1,7 +1,7 @@
import { NeutralToneMapping } from 'three/webgpu';
import type { SceneDefinition } from '@kiln-scenes/scene-kit';
import { CAMERA, NAMED_CAMERAS } from './constants';
-import { LAYOUT } from './data';
+import { BOOTSTRAP as LAYOUT } from './layout-bootstrap';
import { goldenGateTiers } from './tiers';
/**
@@ -15,5 +15,6 @@ export const goldenGateDefinition: SceneDefinition = {
description: 'Orbit the Golden Gate Bridge with the camera controls, choose Day, Golden hour or Fog, and take a guided flyover. Choose Drive the sedan, or press Enter or E, to drive across the bridge: W A S D or the arrows steer and accelerate, Space brakes, Shift boosts, X is the handbrake and R turns around at the end of the deck. E or Escape leaves the car; a second Escape leaves the scene. Tab moves through and out of the controls.',
camera: { position: NAMED_CAMERAS[LAYOUT.cameras.default]!.position, fov: NAMED_CAMERAS[LAYOUT.cameras.default]!.fov, near: CAMERA.near, far: CAMERA.far },
tiers: goldenGateTiers,
+ reversedDepthBuffer: true,
look: { toneMapping: NeutralToneMapping, exposure: 1, background: '#9fb0bf' },
};
diff --git a/scenes/packages/golden-gate/src/layout-bootstrap.json b/scenes/packages/golden-gate/src/layout-bootstrap.json
new file mode 100644
index 00000000..814c850b
--- /dev/null
+++ b/scenes/packages/golden-gate/src/layout-bootstrap.json
@@ -0,0 +1,547 @@
+{
+ "projection": {
+ "approachEnds": {
+ "north": {
+ "car": 600,
+ "dissolve": [
+ 940,
+ 980
+ ]
+ },
+ "south": {
+ "car": 560,
+ "dissolve": [
+ 925,
+ 965
+ ]
+ }
+ },
+ "approachLengths": {
+ "north": 980,
+ "south": 965
+ },
+ "bridge": {
+ "anchorages": [
+ {
+ "x0": -21.5,
+ "x1": 21.5,
+ "z0": 981.98,
+ "z1": 1033.98
+ },
+ {
+ "x0": -21.5,
+ "x1": 21.5,
+ "z0": -1033.98,
+ "z1": -981.98
+ }
+ ],
+ "curbOuter": 9.6488,
+ "jointPlates": {
+ "material": "JointSteel",
+ "notes": "Fix round 3 item 0. The four expansion-joint plates (bridge review 3) lie 1.5 mm above the Roadway, which runs on beneath them, so at range a 24-bit depth buffer cannot separate the two and the plates blink. When the bridge loads, their material (used by nothing else) takes this polygon offset toward the camera; the GLB is not changed.",
+ "polygonOffset": {
+ "factor": -1,
+ "units": -1
+ }
+ },
+ "medianHalfWidth": 0.1524,
+ "medianTop": 76.113,
+ "notes": "Dimensions measured from the bridge's review-2 runtime GLB; suspender planes are |x| 13.43 to 14.0 for |z| <= 960. obstructionNodes are the node-name prefixes that the chase camera and flights keep clear of.",
+ "obstructionNodes": [
+ "SouthTower",
+ "NorthTower",
+ "SuspendersWest",
+ "SuspendersEast",
+ "MainCableWest",
+ "MainCableEast",
+ "Deck_ArtDecoLampStandards",
+ "Deck_SidewalkRailings",
+ "Deck_TowerSidewalkBrackets"
+ ],
+ "pierFootings": [
+ {
+ "x0": -23,
+ "x1": 23,
+ "z0": 628.28,
+ "z1": 651.88
+ },
+ {
+ "x0": -23,
+ "x1": 23,
+ "z0": -651.88,
+ "z1": -628.28
+ }
+ ],
+ "railOuter": 18.26,
+ "roadEndZ": 1032.98,
+ "roadHalfWidth": 9.4488,
+ "southFender": {
+ "rx": 45.72,
+ "rz": 23.622,
+ "top": 4.572,
+ "x": 0,
+ "z": -640.08
+ },
+ "suspenderInner": 13.43,
+ "towerTop": 227.4,
+ "towerZ": 640.08
+ },
+ "cameras": {
+ "chase": {
+ "castRadius": 0.45,
+ "distance": 9.5,
+ "fov": 55,
+ "fovAtTopSpeed": 63,
+ "height": 3.1,
+ "lookAhead": 4,
+ "maxAbsX": 12.2,
+ "minDistance": 3.2,
+ "notes": "spring-arm chase camera behind the driven car; a sphere of castRadius is cast from the car to the camera against the bridge obstruction nodes and the camera moves in to pad before any hit, never closer than minDistance; |x| stays within maxAbsX, inside the suspender planes; a pinch or the mouse wheel scales distance and height by a factor within zoom (times exp(zoomRate x the kit's zoom input) each frame; 1 on entering the car); a one-finger or mouse drag swings the camera around the car and it returns behind it after three seconds (the kit's orbit offset)",
+ "pad": 0.55,
+ "positionLag": 0.18,
+ "relax": 6,
+ "targetHeight": 1.35,
+ "yawLag": 0.3,
+ "zoom": [
+ 0.7,
+ 1.7
+ ],
+ "zoomRate": 0.5
+ },
+ "clip": {
+ "far": 160000,
+ "near": 0.5
+ },
+ "default": "arrival",
+ "named": {
+ "arrival": {
+ "fov": 55,
+ "notes": "Aerial arrival over the Pacific channel, looking down across the bridge with water in the foreground",
+ "position": [
+ 1800,
+ 1100,
+ -240
+ ],
+ "target": [
+ 0,
+ 85,
+ 0
+ ]
+ },
+ "deck": {
+ "fov": 55,
+ "notes": "chase-camera height in the northbound lanes, looking north",
+ "position": [
+ -4.8006,
+ 78.4,
+ -330
+ ],
+ "target": [
+ -4.8006,
+ 76.2,
+ -250
+ ]
+ },
+ "horizon": {
+ "fov": 55,
+ "notes": "deck height beside the west railing, looking west to the Pacific",
+ "position": [
+ 24,
+ 76.5,
+ 180
+ ],
+ "target": [
+ 6000,
+ 58,
+ 420
+ ]
+ },
+ "lanes": {
+ "fov": 40,
+ "notes": "traffic review: over the east railing, northbound lanes close up",
+ "position": [
+ -14,
+ 79.5,
+ -120
+ ],
+ "target": [
+ -4,
+ 76.8,
+ -100
+ ]
+ },
+ "pier": {
+ "fov": 55,
+ "notes": "low and grazing past the south pier fender, looking downstream (west on the ebb)",
+ "position": [
+ -118,
+ 4.2,
+ -596
+ ],
+ "target": [
+ 70,
+ 1.2,
+ -654
+ ]
+ },
+ "postcard": {
+ "fov": 55,
+ "notes": "Marin Headlands viewpoint; the terrain pipeline's recommended postcard pose (validation.json)",
+ "position": [
+ 357.6,
+ 137.9,
+ 1096
+ ],
+ "target": [
+ 0,
+ 105,
+ 300
+ ]
+ },
+ "sidewalk": {
+ "fov": 55,
+ "notes": "traffic review: eye height on the east sidewalk",
+ "position": [
+ -11.6,
+ 78.2,
+ -300
+ ],
+ "target": [
+ 2,
+ 76.4,
+ -262
+ ]
+ },
+ "span": {
+ "fov": 50,
+ "notes": "main span from the bay side",
+ "position": [
+ -1450,
+ 210,
+ -60
+ ],
+ "target": [
+ 0,
+ 90,
+ 0
+ ]
+ },
+ "topdown": {
+ "fov": 55,
+ "notes": "600 m over the channel, straight down",
+ "position": [
+ 260,
+ 600,
+ -40
+ ],
+ "target": [
+ 260,
+ 0,
+ -41
+ ]
+ },
+ "tower": {
+ "fov": 50,
+ "notes": "south tower paint calibration view",
+ "position": [
+ 210,
+ 150,
+ -470
+ ],
+ "target": [
+ 0,
+ 120,
+ -640
+ ]
+ },
+ "traffic": {
+ "fov": 50,
+ "notes": "traffic review: above the east railing, all six lanes toward Marin",
+ "position": [
+ -40,
+ 118,
+ -420
+ ],
+ "target": [
+ 0,
+ 76,
+ -330
+ ]
+ }
+ },
+ "orbit": {
+ "clearance": 4,
+ "maxDistance": 3500,
+ "maxPolarDeg": 89.46,
+ "minDistance": 40,
+ "notes": "the orbit target stays inside |x|, |z| <= targetBounds and targetMinY..targetMaxY; the camera keeps clearance above terrain and water",
+ "targetBounds": 2400,
+ "targetMaxY": 420,
+ "targetMinY": 0
+ },
+ "waterReview": [
+ "postcard",
+ "pier",
+ "topdown",
+ "horizon",
+ "deck"
+ ]
+ },
+ "flightClearance": {
+ "bridge": 2,
+ "terrain": 6,
+ "terrainMinimum": 3
+ },
+ "flightLabels": {
+ "deck-run": "Deck run",
+ "fog-roll": "Fog roll",
+ "postcard-sweep": "Postcard sweep",
+ "tower-rise": "Tower rise"
+ },
+ "lanes": [
+ {
+ "classes": [
+ "sedan",
+ "suv",
+ "hatchback",
+ "pickup"
+ ],
+ "direction": "north",
+ "entry": [
+ -488.821,
+ 50.389,
+ -1834.841
+ ],
+ "exit": [
+ 405.415,
+ 96.48,
+ 1874.135
+ ],
+ "id": "nb-inner",
+ "index": 0,
+ "speed": 22,
+ "stations": [
+ -1997.98,
+ 2012.98
+ ],
+ "x": -1.7018
+ },
+ {
+ "classes": [
+ "sedan",
+ "suv",
+ "hatchback",
+ "pickup",
+ "box-truck",
+ "transit-bus"
+ ],
+ "direction": "north",
+ "entry": [
+ -490.973,
+ 50.389,
+ -1832.611
+ ],
+ "exit": [
+ 402.507,
+ 96.48,
+ 1875.205
+ ],
+ "id": "nb-middle",
+ "index": 1,
+ "speed": 20.5,
+ "stations": [
+ -1997.98,
+ 2012.98
+ ],
+ "x": -4.8006
+ },
+ {
+ "classes": [
+ "sedan",
+ "suv",
+ "hatchback",
+ "pickup",
+ "box-truck",
+ "transit-bus"
+ ],
+ "direction": "north",
+ "entry": [
+ -493.125,
+ 50.389,
+ -1830.382
+ ],
+ "exit": [
+ 399.599,
+ 96.48,
+ 1876.274
+ ],
+ "id": "nb-outer",
+ "index": 2,
+ "speed": 19,
+ "stations": [
+ -1997.98,
+ 2012.98
+ ],
+ "x": -7.8994
+ },
+ {
+ "classes": [
+ "sedan",
+ "suv",
+ "hatchback",
+ "pickup"
+ ],
+ "direction": "south",
+ "entry": [
+ 408.61,
+ 96.48,
+ 1872.96
+ ],
+ "exit": [
+ -486.457,
+ 50.389,
+ -1837.289
+ ],
+ "id": "sb-inner",
+ "index": 3,
+ "speed": 22,
+ "stations": [
+ 2012.98,
+ -1997.98
+ ],
+ "x": 1.7018
+ },
+ {
+ "classes": [
+ "sedan",
+ "suv",
+ "hatchback",
+ "pickup",
+ "box-truck",
+ "transit-bus"
+ ],
+ "direction": "south",
+ "entry": [
+ 411.518,
+ 96.48,
+ 1871.89
+ ],
+ "exit": [
+ -484.304,
+ 50.389,
+ -1839.518
+ ],
+ "id": "sb-middle",
+ "index": 4,
+ "speed": 20.5,
+ "stations": [
+ 2012.98,
+ -1997.98
+ ],
+ "x": 4.8006
+ },
+ {
+ "classes": [
+ "sedan",
+ "suv",
+ "hatchback",
+ "pickup",
+ "box-truck",
+ "transit-bus"
+ ],
+ "direction": "south",
+ "entry": [
+ 414.426,
+ 96.48,
+ 1870.82
+ ],
+ "exit": [
+ -482.152,
+ 50.389,
+ -1841.748
+ ],
+ "id": "sb-outer",
+ "index": 5,
+ "speed": 19,
+ "stations": [
+ 2012.98,
+ -1997.98
+ ],
+ "x": 7.8994
+ }
+ ],
+ "lights": {
+ "bridgeLamps": {
+ "materials": [
+ "LampGlass",
+ "BeaconEmissive"
+ ],
+ "presetKey": "lamps",
+ "rule": "emissive intensity = the authored emissive intensity x lamps"
+ },
+ "environment": {
+ "presetKeys": [
+ "envIntensity",
+ "envSaturation"
+ ],
+ "size": "tiers.json features.*.envSize",
+ "source": "the sky, prefiltered"
+ },
+ "sky": {
+ "model": "Preetham",
+ "presetKeys": [
+ "turbidity",
+ "rayleigh",
+ "mie",
+ "mieG",
+ "sunDisc",
+ "skyGain",
+ "overcast",
+ "overcastColor"
+ ]
+ },
+ "sun": {
+ "presetKeys": [
+ "sunAzimuthDeg",
+ "sunElevationDeg",
+ "sunColor",
+ "sunIntensity"
+ ],
+ "shadows": "tiers.json features.*.shadows",
+ "type": "directional"
+ },
+ "vehicleLamps": {
+ "brakeOff": 0.08,
+ "gain": {
+ "brake": [
+ 1,
+ 1.6
+ ],
+ "head": [
+ 1,
+ 3.5
+ ],
+ "tail": [
+ 1,
+ 2.4
+ ]
+ },
+ "materials": {
+ "BrakeLight": "brake",
+ "Headlight": "head",
+ "Taillight": "tail"
+ },
+ "presetKey": "lights",
+ "rule": "emissive = authored emissive colour x mix(gain[0], gain[1], lights); brake lamps are further scaled by mix(brakeOff, 1, braking); taillight emissive is scaled down so its largest channel is at most taillightPeak; parked vehicles (dressing.vista.cars) have every lamp off",
+ "taillightPeak": 0.3
+ }
+ },
+ "referenceColours": {
+ "internationalOrange": "#C0362C"
+ },
+ "schema": "golden-gate-layout/1"
+ },
+ "schema": "golden-gate-bootstrap/1",
+ "source": "data/layout.json",
+ "sourceSha256": "a66a0b1d74784b47d3b6582d1781524d0b7b7af9c472cef0815b56338095fafc"
+}
diff --git a/scenes/packages/golden-gate/src/layout-bootstrap.ts b/scenes/packages/golden-gate/src/layout-bootstrap.ts
new file mode 100644
index 00000000..5574fe89
--- /dev/null
+++ b/scenes/packages/golden-gate/src/layout-bootstrap.ts
@@ -0,0 +1,9 @@
+import generated from './layout-bootstrap.json';
+import type { LayoutBootstrap } from './layout-contract';
+
+function freeze<T>(value: T): T {
+ if (value && typeof value === 'object') { for (const child of Object.values(value)) freeze(child); Object.freeze(value); }
+ return value;
+}
+/** Generated, immutable startup contract; runtime layout must match it before a world is built. */
+export const BOOTSTRAP = freeze(generated.projection as unknown as LayoutBootstrap);
diff --git a/scenes/packages/golden-gate/src/layout-contract.ts b/scenes/packages/golden-gate/src/layout-contract.ts
new file mode 100644
index 00000000..53374662
--- /dev/null
+++ b/scenes/packages/golden-gate/src/layout-contract.ts
@@ -0,0 +1,24 @@
+import type { SceneLayout } from './data';
+
+/** Early camera/tier and fixed bridge/traffic contracts. Bulk world geometry and animation remain runtime data. */
+export function projectLayoutBootstrap(layout: SceneLayout) {
+ return {
+ schema: layout.schema,
+ bridge: layout.bridge,
+ cameras: layout.cameras,
+ lanes: layout.lanes.map(({ polyline: _polyline, ...lane }) => lane),
+ lights: layout.lights,
+ referenceColours: layout.referenceColours,
+ approachEnds: { south: layout.approaches.south.ends, north: layout.approaches.north.ends },
+ approachLengths: { south: layout.approaches.south.length, north: layout.approaches.north.length },
+ flightLabels: Object.fromEntries(layout.flights.paths.map(path => [path.name, path.label])),
+ flightClearance: layout.flights.clearance,
+ };
+}
+export type LayoutBootstrap = ReturnType<typeof projectLayoutBootstrap>;
+
+/** Object key ordering is immaterial; array ordering (lanes and cameras) remains part of the contract. */
+export function stableLayoutJson(value: unknown): string {
+ return JSON.stringify(value, (_key, child) => child && typeof child === 'object' && !Array.isArray(child)
+ ? Object.fromEntries(Object.keys(child).sort().map(key => [key, child[key]])) : child);
+}
diff --git a/scenes/packages/golden-gate/src/layout.ts b/scenes/packages/golden-gate/src/layout.ts
new file mode 100644
index 00000000..85b429fe
--- /dev/null
+++ b/scenes/packages/golden-gate/src/layout.ts
@@ -0,0 +1,82 @@
+import type { SceneLayout } from './data';
+import { BOOTSTRAP } from './layout-bootstrap';
+import { projectLayoutBootstrap, stableLayoutJson } from './layout-contract';
+
+const contract = stableLayoutJson(BOOTSTRAP);
+
+// Validate the bulk fields that world constructors consume. Bootstrap fields are checked exactly below.
+// These are shape/finite-value checks, not substitutes for route, collision or visual qualification.
+type Check = (value: unknown, path: string) => void;
+const invalid = (path: string): never => { throw new Error(`Invalid Golden Gate layout ${path}`); };
+const number: Check = (value, path) => { if (typeof value !== 'number' || !Number.isFinite(value)) invalid(path); };
+const positive: Check = (value, path) => { number(value, path); if ((value as number) <= 0) invalid(path); };
+const integer: Check = (value, path) => { if (!Number.isSafeInteger(value) || (value as number) < 0) invalid(path); };
+const string: Check = (value, path) => { if (typeof value !== 'string') invalid(path); };
+const choice = (...values: unknown[]): Check => (value, path) => { if (!values.includes(value)) invalid(path); };
+const optional = (check: Check): Check => (value, path) => { if (value !== undefined) check(value, path); };
+const array = (check: Check, min = 0): Check => (value, path) => {
+ if (!Array.isArray(value) || value.length < min) invalid(path);
+ (value as unknown[]).forEach((item, index) => check(item, `${path}[${index}]`));
+};
+const tuple = (size: number): Check => (value, path) => {
+ array(number)(value, path); if ((value as unknown[]).length !== size) invalid(path);
+};
+const object = (fields: Record<string, Check>): Check => (value, path) => {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) invalid(path);
+ for (const [key, check] of Object.entries(fields)) check((value as Record<string, unknown>)[key], `${path}.${key}`);
+};
+const pair = tuple(2), triple = tuple(3), approachName = choice('south', 'north'), vegetationKind = choice('tree', 'scrub');
+const cut = object({ side: choice(-1, 1), s: pair, fade: positive, face: positive, bench: pair, reach: pair,
+ toe: object({ x: pair, height: number, s: pair }), scrub: object({ dark: triple, light: triple, region: object({ s: pair, x: pair }) }) });
+const approach = object({ length: positive, alignment: object({ pis: array(pair), radii: array(positive), end: pair }),
+ profile: array(triple, 2), centreline: array(triple, 2), start: object({ elevation: number, grade: number }),
+ segments: array(object({ kind: choice('viaduct', 'overpass', 'cut', 'fill', 'grade'), from: number, to: number,
+ supports: optional(array(number)), abutments: optional(array(number)) })), cuts: optional(array(cut)) });
+const vegetation = object({ reach: positive, clear: number, footprint: positive, ground: number,
+ kinds: object(Object.fromEntries(['tree', 'scrub'].map(kind => [kind, object({ spacing: positive, height: pair, width: pair, sink: number })]))),
+ classes: object({ tree: object({ greenOverRed: pair, luma: pair }), scrub: object({ greenOverBlue: pair, luma: pair, greenOverRed: pair }) }),
+ approaches: object({ south: array(vegetationKind), north: array(vegetationKind) }) });
+const bulk = object({
+ approaches: object({ south: approach, north: approach, crossSection: object({ pavedHalfWidth: positive, barrier: triple, medianHeight: number,
+ markings: object({ broken: array(pair), edge: pair, dash: positive, period: positive, phase: number, lift: number }), pavement: positive,
+ deck: object({ slab: positive, girder: positive, girderHalfWidth: positive }), clearance: number,
+ envelope: object({ bedMargin: number, cut: positive, fill: positive, reach: pair }),
+ supports: object({ spacing: positive, columns: array(number), column: positive, cap: pair, abutment: positive, footing: number }),
+ joint: object({ walk: pair, ramp: pair, taper: positive }) }) }),
+ dressing: object({ paint: object({ color: string, roughness: number }), vegetation,
+ plaza: object({ approach: approachName, side: choice(-1, 1), fan: tuple(4), pavedTo: positive, medianGap: pair,
+ canopy: object({ s: pair, x: pair, top: number, depth: positive }), columns: object({ size: positive, s: array(number) }),
+ islands: object({ s: pair, nose: positive, height: positive, x: array(number), halfWidth: array(positive) }) }),
+ vista: object({ approach: approachName, level: number, outline: array(pair, 3), planter: array(pair, 3), throat: object({ edge: integer }),
+ kerb: object({ height: positive, width: positive }), wall: object({ from: integer, to: integer, height: positive, width: positive }),
+ stalls: object({ width: positive, depth: positive, line: positive, rows: array(object({ edge: choice('outline', 'planter'), from: integer, to: integer })) }),
+ cars: array(object({ row: integer, stall: integer, type: string, paint: string })) }),
+ lights: object({ start: number, spacing: positive, x: number, mount: positive, reach: positive, pole: pair, arm: positive, head: triple, clear: number, far: positive }) }),
+ flights: object({ paths: array(object({ name: string, label: string, seconds: positive, requiresPreset: optional(choice('fog')),
+ easing: optional(choice('ease-in-out', 'smoothstep')), keys: array(object({ position: triple, target: triple, fov: positive, seconds: optional(positive) }), 2) }), 1) }),
+ fogBanks: object({ seed: integer, driftSpeed: number, wrap: object({ west: number, east: number }),
+ puff: object({ sizeMin: positive, sizeRange: number, heightJitter: number, heightPerSize: number, aspect: positive }),
+ banks: array(object({ x: number, y: number, z: number, spread: pair, puffs: integer })) }),
+});
+
+/** Consume the pack loader's already hash-verified bytes; never fetch again or fall back to authored source. */
+export function readGoldenGateLayout(pack: { data: ReadonlyMap<string, ArrayBuffer> }, signal: AbortSignal): SceneLayout {
+ if (signal.aborted) throw signal.reason ?? new DOMException('Golden Gate layout cancelled', 'AbortError');
+ const bytes = pack.data.get('layout');
+ if (!bytes) throw new Error('Golden Gate layout is missing from the verified pack');
+ let layout: SceneLayout;
+ try { layout = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as SceneLayout; }
+ catch (cause) { throw new Error('Invalid Golden Gate layout JSON', { cause }); }
+ if (!layout || layout.schema !== 'golden-gate-layout/1') throw new Error('Unsupported Golden Gate layout schema');
+ bulk(layout, '');
+ if (layout.fogBanks.wrap.west <= layout.fogBanks.wrap.east) invalid('fogBanks.wrap');
+ if (new Set(layout.flights.paths.map(path => path.name)).size !== layout.flights.paths.length) invalid('flights.paths duplicate name');
+ try {
+ if (stableLayoutJson(projectLayoutBootstrap(layout)) !== contract) throw new Error('Golden Gate layout bootstrap mismatch; regenerate the bootstrap from authored data and rebuild');
+ } catch (cause) {
+ if (cause instanceof Error && cause.message.includes('bootstrap mismatch')) throw cause;
+ throw new Error('Invalid Golden Gate layout bootstrap fields', { cause });
+ }
+ if (signal.aborted) throw signal.reason ?? new DOMException('Golden Gate layout cancelled', 'AbortError');
+ return layout;
+}
diff --git a/scenes/packages/golden-gate/src/play/Driving.tsx b/scenes/packages/golden-gate/src/play/Driving.tsx
index f31fcd95..85b4bf73 100644
--- a/scenes/packages/golden-gate/src/play/Driving.tsx
+++ b/scenes/packages/golden-gate/src/play/Driving.tsx
@@ -11,7 +11,7 @@ import { Object3D, Vector3 } from 'three/webgpu';
import type { PerspectiveCamera } from 'three/webgpu';
import { SystemOrder, VehicleRig, registerWorkload, useFade, useInput, usePlayMode, useRegisterTestHooks, useSceneRootRef, useSystem } from '@kiln-scenes/scene-kit';
import { CAMERA, LANES, laneX } from '../constants';
-import { DRIVING_DATA, LAYOUT } from '../data';
+import { DRIVING_DATA } from '../data';
import { laneStation } from '../traffic/config';
import { paintLinear } from '../traffic/traffic';
import type { DrivenVehicle } from '../traffic/traffic';
@@ -168,7 +168,7 @@ export function Driving({ world }: { world: GoldenGateWorld }) {
},
/** The car's road ends and end stops (route stations), the approaches' dissolve stretches and lengths, and the road centre where each dissolve starts. */
driveRoute: () => {
- const route = world.bridge.route, ends = LAYOUT.approaches, at = (sigma: number) => { const p = routePoint(route, sigma, 0); return [p.x, p.y, p.z]; };
+ const route = world.bridge.route, ends = world.layout.approaches, at = (sigma: number) => { const p = routePoint(route, sigma, 0); return [p.x, p.y, p.z]; };
return { roadEnd: { south: roadEnd(-1), north: roadEnd(1) }, endStop: { south: endStop(-1), north: endStop(1) }, roadEndZ: route.roadEndZ,
dissolve: { south: ends.south.ends.dissolve, north: ends.north.ends.dissolve }, length: { south: route.south.length, north: route.north.length },
dissolveStart: { south: at(-(route.roadEndZ + ends.south.ends.dissolve[0])), north: at(route.roadEndZ + ends.north.ends.dissolve[0]) } };
diff --git a/scenes/packages/golden-gate/src/play/car.ts b/scenes/packages/golden-gate/src/play/car.ts
index efe2bfb3..bc590b1e 100644
--- a/scenes/packages/golden-gate/src/play/car.ts
+++ b/scenes/packages/golden-gate/src/play/car.ts
@@ -10,7 +10,8 @@
// is its lane direction (0 north, pi south) plus a bounded heading offset, positive to the left.
// The car's road ends at each approach's `ends.car` station (layout.json), where it turns around;
// traffic drives on to the approach ends.
-import { DRIVING_DATA, LAYOUT, TRAFFIC_DATA } from '../data';
+import { DRIVING_DATA, TRAFFIC_DATA } from '../data';
+import { BOOTSTRAP as LAYOUT } from '../layout-bootstrap';
import type { SimBox } from '../traffic/sim';
const D = DRIVING_DATA, BRIDGE = LAYOUT.bridge, RAD = Math.PI / 180;
@@ -67,7 +68,7 @@ export function carExtents(s: Pick<CarState, 'offset'>, body: CarBody): { ex: nu
/** The carriageway of a direction: |x| of the car's footprint stays within [median, curb]. */
export const CARRIAGEWAY = { median: BRIDGE.medianHalfWidth + D.curb.clearance, curb: BRIDGE.roadHalfWidth - D.curb.clearance };
/** Station of the car's road end for a direction: the approach's `ends.car` beyond the deck end. */
-export const roadEnd = (dir: 1 | -1) => dir * (BRIDGE.roadEndZ + LAYOUT.approaches[dir > 0 ? 'north' : 'south'].ends.car);
+export const roadEnd = (dir: 1 | -1) => dir * (BRIDGE.roadEndZ + LAYOUT.approachEnds[dir > 0 ? 'north' : 'south'].car);
/** Station of the end stop ahead for a direction, stopDistance short of its road end. */
export const endStop = (dir: 1 | -1) => roadEnd(dir) - dir * D.roadEnd.stopDistance;
/** Relative speed the car may keep toward something `room` metres away: `gain` per metre near, the planned brake far out. */
diff --git a/scenes/packages/golden-gate/src/play/route-contact.ts b/scenes/packages/golden-gate/src/play/route-contact.ts
index 32a48928..00e4dbbc 100644
--- a/scenes/packages/golden-gate/src/play/route-contact.ts
+++ b/scenes/packages/golden-gate/src/play/route-contact.ts
@@ -18,7 +18,7 @@
import { Vector3 } from 'three/webgpu';
import type { BufferAttribute, Mesh, Object3D } from 'three/webgpu';
import { LANES } from '../constants';
-import { LAYOUT } from '../data';
+import { BOOTSTRAP as LAYOUT } from '../layout-bootstrap';
import { lanePose, laneStation, TRAFFIC_FLOW } from '../traffic/config';
import type { VehicleModel } from '../traffic/vehicle-models';
import type { Bridge } from '../world/bridge';
diff --git a/scenes/packages/golden-gate/src/tiers.ts b/scenes/packages/golden-gate/src/tiers.ts
index 59e9e5c7..4dfb0402 100644
--- a/scenes/packages/golden-gate/src/tiers.ts
+++ b/scenes/packages/golden-gate/src/tiers.ts
@@ -1,6 +1,7 @@
import { defineTiers } from '@kiln-scenes/scene-kit';
import type { DeviceClass, TierKnobs } from '@kiln-scenes/scene-kit';
-import { LAYOUT, TIER_DATA } from './data';
+import { TIER_DATA } from './data';
+import { BOOTSTRAP as LAYOUT } from './layout-bootstrap';
import type { FeatureData, FeatureLevel } from './data';
/** WATER-SPEC feature levels. `minimal`/`economy` are Low, `balanced` is Medium, `high` is High (Medium on phones). Values: data/tiers.json (D-21). */
diff --git a/scenes/packages/golden-gate/src/traffic/config.ts b/scenes/packages/golden-gate/src/traffic/config.ts
index 029c749c..33506380 100644
--- a/scenes/packages/golden-gate/src/traffic/config.ts
+++ b/scenes/packages/golden-gate/src/traffic/config.ts
@@ -6,8 +6,9 @@
// blue and red, a few green and others, no two adjacent cars alike, and free-flowing lanes at about
// 20 m/s with natural spacing.
import { LANES, laneX } from '../constants';
-import { LAYOUT, TRAFFIC_DATA } from '../data';
-import type { LayoutLane } from '../data';
+import { TRAFFIC_DATA } from '../data';
+import { BOOTSTRAP as LAYOUT } from '../layout-bootstrap';
+import type { LayoutBootstrap } from '../layout-contract';
import type { TrafficDensity } from '../tiers';
import { newRoutePoint, routePoint, routeYaw } from '../world/route';
import type { Route, RoutePoint } from '../world/route';
@@ -20,10 +21,10 @@ import type { VehicleType } from './vehicle-models';
* the lane's first station to its last), indices 0-2 north and 3-5 south. Anything else is a data
* error, reported here rather than simulated differently.
*/
-function directionLanes(lanes: readonly LayoutLane[]): { lanes: LayoutLane[]; length: number } {
+function directionLanes(lanes: readonly LayoutBootstrap['lanes'][number][]): { lanes: LayoutBootstrap['lanes']; length: number } {
const north = lanes.filter(l => l.direction === 'north'), south = lanes.filter(l => l.direction === 'south');
if (north.length !== 3 || south.length !== 3) throw new Error('data/layout.json must define three lanes each way');
- const length = (lane: LayoutLane) => Math.abs(lane.stations[1] - lane.stations[0]), common = length(north[0]!);
+ const length = (lane: LayoutBootstrap['lanes'][number]) => Math.abs(lane.stations[1] - lane.stations[0]), common = length(north[0]!);
north.forEach((n, k) => {
const s = south[k]!;
if (n.index !== k || s.index !== k + 3 || n.speed !== s.speed || n.classes.join() !== s.classes.join() || Math.abs(n.x + s.x) > 1e-6
@@ -41,7 +42,7 @@ const DIRECTION = directionLanes(LANES);
* traffic never fades on the deck or on the solid road before it.
*/
function laneFade(): number {
- const room = Math.min(...(['south', 'north'] as const).map(name => { const [from, to] = LAYOUT.approaches[name].ends.dissolve; return to - from; }));
+ const room = Math.min(...(['south', 'north'] as const).map(name => { const [from, to] = LAYOUT.approachEnds[name].dissolve; return to - from; }));
if (!(TRAFFIC_DATA.fade > 0 && TRAFFIC_DATA.fade <= room + 1e-9)) throw new Error(`data/traffic.json fade ${TRAFFIC_DATA.fade} m must fit the approaches' dissolve stretches (${room} m)`);
return TRAFFIC_DATA.fade;
}
diff --git a/scenes/packages/golden-gate/src/traffic/traffic.ts b/scenes/packages/golden-gate/src/traffic/traffic.ts
index f653eaef..4e73cda3 100644
--- a/scenes/packages/golden-gate/src/traffic/traffic.ts
+++ b/scenes/packages/golden-gate/src/traffic/traffic.ts
@@ -18,7 +18,7 @@ import { LAYERS, LANE_WIDTH, laneX } from '../constants';
import type { TrafficDensity } from '../tiers';
import { newRoutePoint } from '../world/route';
import type { Route } from '../world/route';
-import { LAYOUT } from '../data';
+import { BOOTSTRAP as LAYOUT } from '../layout-bootstrap';
import { DENSITY_HEADWAY, PALETTE, TRAFFIC_FLOW, lanePose, laneStation, trafficClasses } from './config';
import { TrafficSim, srgbToLinear } from './sim';
import type { SimObstacle } from './sim';
diff --git a/scenes/packages/golden-gate/src/traffic/vehicle-models.ts b/scenes/packages/golden-gate/src/traffic/vehicle-models.ts
index 92d9fd34..9fd0b256 100644
--- a/scenes/packages/golden-gate/src/traffic/vehicle-models.ts
+++ b/scenes/packages/golden-gate/src/traffic/vehicle-models.ts
@@ -17,7 +17,8 @@
import { InstancedBufferGeometry, InterleavedBuffer, InterleavedBufferAttribute, BufferAttribute, Box3, Color, Matrix3, Matrix4, Sphere, Vector3 } from 'three/webgpu';
import type { Mesh, MeshStandardMaterial, Object3D } from 'three/webgpu';
import type { GLTF } from 'three/addons/loaders/GLTFLoader.js';
-import { LAYOUT, TRAFFIC_DATA } from '../data';
+import { TRAFFIC_DATA } from '../data';
+import { BOOTSTRAP as LAYOUT } from '../layout-bootstrap';
export const VEHICLE_TYPES = ['sedan', 'hatchback', 'suv', 'pickup', 'box-truck', 'transit-bus'] as const;
export type VehicleType = typeof VEHICLE_TYPES[number];
diff --git a/scenes/packages/golden-gate/src/ui/styles.ts b/scenes/packages/golden-gate/src/ui/styles.ts
index 5f221453..7bd13223 100644
--- a/scenes/packages/golden-gate/src/ui/styles.ts
+++ b/scenes/packages/golden-gate/src/ui/styles.ts
@@ -5,18 +5,15 @@
* toolbar) sit bottom left, clear of the wrapping toolbar. The speed readout sits above the
* status line (the deck-end prompt) at the bottom centre, or beside the joystick on a narrow HUD.
*
- * Workaround for kit request GG-007: the kit's help and credits panels are absolutely positioned
- * with `max-height: calc(100% - 100px)`, which resolves against their containing block. Inside the
- * kit's `.ks-toolbar` (the kit's own usage) that block is the toolbar itself, about 44 px tall, so
- * the panel collapses to its padding and scrolls. Here the toolbar is static inside `.gg-top`,
- * which covers the whole HUD, so the panels size against the HUD. Where the toolbar wraps to a
+ * The shared kit anchors help and credits to the HUD, independently of toolbar height.
+ * The toolbar remains static here to share the top layout with the flyover menu. Where it wraps to a
* second row, they open as a sheet at the bottom instead of over the toolbar. The top layer stacks
* above the phone driving controls, so an open panel covers them rather than the reverse.
*/
export const GG_HUD_CSS = `
.gg-hud{position:absolute;inset:0;pointer-events:none;container:gg-hud/inline-size}
.gg-hud>*{pointer-events:auto}
-.gg-hud>.gg-top{position:absolute;inset:0;z-index:1;pointer-events:none;display:flex;flex-direction:column;align-items:flex-end;gap:8px;box-sizing:border-box;
+.gg-hud>.gg-top{position:absolute;inset:0;z-index:2;pointer-events:none;display:flex;flex-direction:column;align-items:flex-end;gap:8px;box-sizing:border-box;
padding:max(12px,env(safe-area-inset-top)) max(12px,env(safe-area-inset-right)) 0 max(12px,env(safe-area-inset-left))}
.gg-top>.ks-toolbar{position:static;justify-content:flex-end;pointer-events:auto}
.gg-top>.gg-flights{display:flex;flex-direction:column;gap:8px;padding:12px;pointer-events:auto}
diff --git a/scenes/packages/golden-gate/src/world/atmosphere.ts b/scenes/packages/golden-gate/src/world/atmosphere.ts
index 576e5a20..1a030f4d 100644
--- a/scenes/packages/golden-gate/src/world/atmosphere.ts
+++ b/scenes/packages/golden-gate/src/world/atmosphere.ts
@@ -45,8 +45,11 @@ export interface Atmosphere {
// TSL graphs are typed loosely: @types/three's node generics add no safety to shader construction.
type N = any; // eslint-disable-line @typescript-eslint/no-explicit-any
-function createSky(u: AtmosphereUniforms, environment: boolean): SkyMesh {
+export function createSky(u: AtmosphereUniforms, environment: boolean): SkyMesh {
const sky = new SkyMesh();
+ // SkyMesh forces clip z=w, which is the near plane under reversed depth.
+ // Drawing first without depth tests/writes works for both depth conventions.
+ sky.renderOrder = -1e6; sky.material.depthTest = false; sky.material.depthWrite = false;
sky.name = environment ? 'environment-sky' : 'sky';
sky.cloudCoverage.value = 0; // no clouds: SkyMesh's only time-dependent branch stays off
const clear = sky.material.colorNode as N;
diff --git a/scenes/packages/golden-gate/src/world/bridge.ts b/scenes/packages/golden-gate/src/world/bridge.ts
index a3bb73aa..0c83182a 100644
--- a/scenes/packages/golden-gate/src/world/bridge.ts
+++ b/scenes/packages/golden-gate/src/world/bridge.ts
@@ -18,7 +18,8 @@ import type { GLTF } from 'three/addons/loaders/GLTFLoader.js';
import { createCollisionWorld, mainOnly, mergeRigidByMaterial, passStandIn, shadowStandIns } from '@kiln-scenes/scene-kit';
import type { CollisionWorld, PassLayers, RigidMerge, ShadowStandIns } from '@kiln-scenes/scene-kit';
import { BRIDGE, LAYERS } from '../constants';
-import { LAYOUT } from '../data';
+import { BOOTSTRAP as LAYOUT } from '../layout-bootstrap';
+import type { SceneLayout } from '../data';
import type { Vec3 } from '../data';
import { rasterizeRoad } from './road';
import type { RoadGrid } from './road';
@@ -53,7 +54,10 @@ const DRAWN_FIRST = /^Curbs(East|West)$/;
const drawnLast = (m: Mesh) => m.parent?.name === 'span' && (m.material as Material).name === 'Paint';
export interface BridgeOptions {
+ layout: SceneLayout;
farSwitch: number; castShadow: boolean;
+ /** Effective initialized renderer setting, false when WebGL lacks EXT_clip_control. */
+ reversedDepthBuffer?: boolean;
/** Merge each model's parts by material inside its south, north and span groups (the `bridgeMerge` development parameter). */
merge?: boolean;
/** Shadow depth stand-ins on this layer for the web model and the near approaches; the sun's shadow camera must enable it. */
@@ -87,13 +91,14 @@ export interface Bridge {
* runs on beneath them, so their material takes a polygon offset toward the camera (both backends map it to the
* depth bias). Returns the number of materials changed.
*/
-export function offsetJointPlates(scene: Object3D): number {
+export function offsetJointPlates(scene: Object3D, reversedDepthBuffer = false): number {
const { material: name, polygonOffset: { factor, units } } = LAYOUT.bridge.jointPlates, done = new Set<Material>();
scene.traverse(node => {
const mesh = node as Mesh; if (!mesh.isMesh) return;
for (const m of (Array.isArray(mesh.material) ? mesh.material : [mesh.material]) as Material[]) {
if (m.name !== name || done.has(m)) continue;
- m.polygonOffset = true; m.polygonOffsetFactor = factor; m.polygonOffsetUnits = units; m.needsUpdate = true; done.add(m);
+ const sign = reversedDepthBuffer ? -1 : 1;
+ m.polygonOffset = true; m.polygonOffsetFactor = sign * factor; m.polygonOffsetUnits = sign * units; m.needsUpdate = true; done.add(m);
}
});
return done.size;
@@ -148,15 +153,26 @@ function polylineDistance(p: Vector3, line: readonly Vec3[]): number {
export function createBridge(web: GLTF, far: GLTF, o: BridgeOptions): Bridge {
const root = new Group(); root.name = 'bridge';
const lamps = new Set<MeshStandardMaterial>(), source = web.scene.clone(), views = { web: view(web.scene, 'web'), far: view(far.scene, 'far') };
+ // Opposite depth conventions may share one loaded pack. Own only the materials
+ // whose bias changes, leaving its standard materials and other worlds intact.
+ const jointCopies = new Map<Material, Material>();
+ if (o.reversedDepthBuffer) for (const v of Object.values(views)) v.root.traverse(node => {
+ const mesh = node as Mesh; if (!mesh.isMesh) return;
+ const own = (m: Material) => {
+ if (m.name !== LAYOUT.bridge.jointPlates.material) return m;
+ let copy = jointCopies.get(m); if (!copy) { copy = m.clone(); jointCopies.set(m, copy); } return copy;
+ };
+ mesh.material = Array.isArray(mesh.material) ? mesh.material.map(own) : own(mesh.material);
+ });
source.updateMatrixWorld(true);
const webMeshes = prepare(views.web.root, o.castShadow, lamps), farMeshes = prepare(views.far.root, false, lamps);
- const jointMaterials = offsetJointPlates(views.web.root) + offsetJointPlates(views.far.root);
+ const jointMaterials = offsetJointPlates(views.web.root, o.reversedDepthBuffer) + offsetJointPlates(views.far.root, o.reversedDepthBuffer);
root.add(views.web.root, views.far.root); views.far.root.visible = false;
root.updateMatrixWorld(true);
const roadway = source.getObjectByName('Roadway');
if (!roadway) throw new Error('Bridge runtime has no Roadway node');
- const road = rasterizeRoad(roadway), route = createRoute(road, LAYOUT.approaches, BRIDGE.roadEndZ);
- const cs = LAYOUT.approaches.crossSection, approaches = [route.south, route.north], dressing = LAYOUT.dressing;
+ const road = rasterizeRoad(roadway), route = createRoute(road, o.layout.approaches, BRIDGE.roadEndZ);
+ const cs = o.layout.approaches.crossSection, approaches = [route.south, route.north], dressing = o.layout.dressing;
const paint = new MeshStandardMaterial({ name: 'PaintedSteel', color: new Color(dressing.paint.color), roughness: dressing.paint.roughness, metalness: 0 });
const meshes = {
near: approachMeshes(approaches, cs, BRIDGE.roadEndZ, BRIDGE.medianHalfWidth, 'near', approachMaterials(views.web.root, 'web', paint), { castShadow: o.castShadow, layer: LAYERS.world }, dressing),
@@ -203,6 +219,7 @@ export function createBridge(web: GLTF, far: GLTF, o: BridgeOptions): Bridge {
for (const m of merged) m.restore();
for (const p of proxies) p.restore();
reflection?.restore(); meshes.near.dispose(); meshes.far.dispose(); paint.dispose();
+ for (const material of jointCopies.values()) material.dispose();
bridge.setLamps(1);
},
};
diff --git a/scenes/packages/golden-gate/src/world/build-world.ts b/scenes/packages/golden-gate/src/world/build-world.ts
index 6860fb1a..60ea9840 100644
--- a/scenes/packages/golden-gate/src/world/build-world.ts
+++ b/scenes/packages/golden-gate/src/world/build-world.ts
@@ -13,7 +13,7 @@ import { loadTerrain } from './terrain';
import { approachCorridorPlans } from './corridor';
import { parkedVehicles } from './dressing';
import { vegetationCandidates } from './vegetation';
-import { LAYOUT } from '../data';
+import { readGoldenGateLayout } from '../layout';
import { BRIDGE, LAYERS } from '../constants';
import { drawOptions } from './draw-options';
import type { DrawOptions } from './draw-options';
@@ -29,6 +29,7 @@ import type { Water } from './water';
import { createFogBanks } from './fog-banks';
import type { FogBanks } from './fog-banks';
import { sceneFogNode } from './fog';
+import { prewarmContactShadows } from './prewarm-contact-shadows';
import type { GoldenGatePreset } from '../presets';
import type { TrafficDensity } from '../tiers';
import { extractVehicle, VEHICLE_TYPES } from '../traffic/vehicle-models';
@@ -66,6 +67,8 @@ export async function readCollisionField(pack: LoadedPack, index: SceneIndex): P
}
export async function buildGoldenGateWorld(c: BuildContext) {
+ // The loader already fetched and verified this member. Refuse incompatible/cancelled data before allocating a world.
+ const layout = readGoldenGateLayout(c.pack, c.signal);
const features = c.knobs.gg, draw = drawOptions(features, c.draw ?? {}), index = readSceneIndex(c.pack), owned: { dispose(): void }[] = [];
const release = () => { for (const item of owned.splice(0).reverse()) { try { item.dispose(); } catch { /* keep releasing */ } } };
const tiles = index.terrain.sets[features.terrainSet].reduce((sum, level) => sum + (index.terrain.levels[level]?.tiles.length ?? 0), 0);
@@ -85,8 +88,8 @@ export async function buildGoldenGateWorld(c: BuildContext) {
const maps = index.terrain.water[features.terrainSet];
const fetch = (path: string) => c.reader.fetchFile(path, c.signal);
const settled = await Promise.allSettled([
- loadTerrain(index.terrain, (path, signal) => c.reader.fetchFile(path, signal), { set: features.terrainSet, anisotropy: features.water.anisotropy, receiveShadow: c.knobs.shadows.enabled, signal: c.signal, onTile: () => step('Terrain'), corridors: approachCorridorPlans(LAYOUT.approaches, BRIDGE.roadEndZ, LAYOUT.dressing),
- vegetation: { candidates: vegetationCandidates(LAYOUT.approaches, BRIDGE.roadEndZ, LAYOUT.dressing, features.vegetation.density), data: LAYOUT.dressing.vegetation, fade: features.vegetation.fade } }),
+ loadTerrain(index.terrain, (path, signal) => c.reader.fetchFile(path, signal), { set: features.terrainSet, anisotropy: features.water.anisotropy, receiveShadow: c.knobs.shadows.enabled, signal: c.signal, onTile: () => step('Terrain'), corridors: approachCorridorPlans(layout.approaches, BRIDGE.roadEndZ, layout.dressing),
+ vegetation: { candidates: vegetationCandidates(layout.approaches, BRIDGE.roadEndZ, layout.dressing, features.vegetation.density), data: layout.dressing.vegetation, fade: features.vegetation.fade } }),
readCollisionField(c.pack, index),
Promise.all([fetch(maps.near.depth.path), fetch(maps.near.shore.path)]).then(([d, s]) => decodeWaterLevel(maps.near, d, s)),
Promise.all([fetch(maps.mid.depth.path), fetch(maps.mid.shore.path)]).then(([d, s]) => decodeWaterLevel(maps.mid, d, s)),
@@ -106,13 +109,13 @@ export async function buildGoldenGateWorld(c: BuildContext) {
abortIfNeeded(c.signal); step('Water maps');
const web = c.pack.models.get(index.bridge.web.model), far = c.pack.models.get(index.bridge.far.model);
if (!web || !far) throw new Error('Bridge models are missing from the verified pack');
- const bridge: Bridge = createBridge(web, far, { farSwitch: features.bridgeFarSwitch, castShadow: c.knobs.shadows.enabled, merge: draw.merge, standInLayer: draw.depth ? LAYERS.shadowStandIn : undefined, passLayers: pass });
+ const bridge: Bridge = createBridge(web, far, { layout, farSwitch: features.bridgeFarSwitch, castShadow: c.knobs.shadows.enabled, reversedDepthBuffer: c.renderer.reversedDepthBuffer, merge: draw.merge, standInLayer: draw.depth ? LAYERS.shadowStandIn : undefined, passLayers: pass });
owned.push(bridge); step('Bridge');
// The vegetation impostors switch with the approaches' near representation (fix round 3 item 5).
bridge.approachMeshes.near.group.add(terrain.vegetation.root);
const water: Water = createWater(c.scene, { features: features.water, atmosphere, near: near.level, mid: mid.level, midGrid: mid.grid, passLayers: pass });
owned.push(water); step('Water');
- const banks: FogBanks | null = features.fogBanks > 0 ? createFogBanks(atmosphere.uniforms, water.textures.macroNoise, features.fogBanks) : null;
+ const banks: FogBanks | null = features.fogBanks > 0 ? createFogBanks(atmosphere.uniforms, water.textures.macroNoise, features.fogBanks, layout.fogBanks) : null;
if (banks) owned.push(banks);
// Traffic on the approved vehicles: MSFT_lod levels read through each GLTF's parser. The driven
// sedan draws with the traffic, so the vehicles load even when the development parameter empties the lanes.
@@ -126,7 +129,7 @@ export async function buildGoldenGateWorld(c: BuildContext) {
models.set(type, model); abortIfNeeded(c.signal);
}
// Vista Point's parked cars (layout.json dressing) stay whether or not the lanes carry traffic.
- const parked = parkedVehicles(LAYOUT.approaches, BRIDGE.roadEndZ, LAYOUT.dressing).map(p => {
+ const parked = parkedVehicles(layout.approaches, BRIDGE.roadEndZ, layout.dressing).map(p => {
const type = VEHICLE_TYPES.find(t => t === p.type); if (!type) throw new Error(`layout.json dressing.vista.cars: unknown vehicle ${p.type}`);
return { type, x: p.x, y: p.y, z: p.z, yaw: p.yaw, paint: paintLinear(p.paint) };
});
@@ -142,8 +145,10 @@ export async function buildGoldenGateWorld(c: BuildContext) {
root.add(terrain.root, bridge.root, traffic.root); if (banks) root.add(banks.sprite);
c.scene.add(root); owned.push({ dispose: () => root.removeFromParent() });
c.scene.fogNode = fogNode;
- // No compileAsync here: its pass has no depth copy yet, so depth-reading materials (water contact,
- // fog banks) would bind a single-sampled placeholder against a multisampled layout.
+ owned.push({ dispose() { if (c.scene.fogNode === fogNode) c.scene.fogNode = null; } });
+ // Only the hidden traffic contact quad is prepared. A whole-world compile has no depth copy
+ // yet, so water contact and fog banks would bind an incompatible placeholder.
+ owned.push(await prewarmContactShadows(c.renderer, traffic.root, c.scene, c.camera, c.signal));
abortIfNeeded(c.signal); step('Shaders');
const focus = new Vector3();
const stats = {
@@ -154,7 +159,7 @@ export async function buildGoldenGateWorld(c: BuildContext) {
};
let vehicleLights = 0;
const world = {
- index, atmosphere, terrain, field, bridge, water, banks, traffic, models, root, fogNode, stats, focus,
+ index, layout, atmosphere, terrain, field, bridge, water, banks, traffic, models, root, fogNode, stats, focus,
credits: c.pack.manifest.credits ?? [],
/** Presets: atmosphere, water wind and lamps (called while blending and once per change). */
applyPreset(p: GoldenGatePreset, force = false) {
diff --git a/scenes/packages/golden-gate/src/world/fog-banks.ts b/scenes/packages/golden-gate/src/world/fog-banks.ts
index a8230bd4..fc4db5ba 100644
--- a/scenes/packages/golden-gate/src/world/fog-banks.ts
+++ b/scenes/packages/golden-gate/src/world/fog-banks.ts
@@ -10,18 +10,19 @@ import { mulberry32 } from './detail-textures';
import { fogColorNode } from './fog';
import type { AtmosphereUniforms } from './fog';
import { LAYERS } from '../constants';
-import { LAYOUT } from '../data';
+import type { SceneLayout } from '../data';
type N = any; // eslint-disable-line @typescript-eslint/no-explicit-any
-/** Bank centres in scene metres (+X west, +Z north): west of the Gate, in the strait and over the headlands (layout.json fogBanks). */
-const FOG = LAYOUT.fogBanks, BANKS = FOG.banks, PUFF = FOG.puff;
-export const FOG_BANK_RANGE = FOG.wrap; // puffs drift toward -X and wrap
-export const FOG_BANK_SPEED = FOG.driftSpeed; // m/s
-
-export interface FogBanks { sprite: Sprite; update(time: number, opacity: number): void; readonly puffs: number; dispose(): void }
+export interface FogBanks {
+ sprite: Sprite;
+ /** Diagnostic visibility override, combined with the current weather opacity and retained across updates (D-70). */
+ hidden: boolean;
+ update(time: number, opacity: number): void; readonly puffs: number; dispose(): void;
+}
-export function createFogBanks(atmosphere: AtmosphereUniforms, noise: DataTexture, count: number): FogBanks {
+export function createFogBanks(atmosphere: AtmosphereUniforms, noise: DataTexture, count: number, FOG: SceneLayout['fogBanks']): FogBanks {
+ const BANKS = FOG.banks, PUFF = FOG.puff, FOG_BANK_RANGE = FOG.wrap, FOG_BANK_SPEED = FOG.driftSpeed;
const banks = BANKS.slice(0, Math.max(0, Math.min(BANKS.length, count))), rand = mulberry32(FOG.seed);
const base: number[] = [];
for (const bank of banks) for (let i = 0; i < bank.puffs; i++) {
@@ -56,10 +57,13 @@ export function createFogBanks(atmosphere: AtmosphereUniforms, noise: DataTextur
sprite.name = 'fog-banks'; sprite.count = puffs; sprite.frustumCulled = false; sprite.renderOrder = 20;
sprite.layers.set(LAYERS.dynamic); sprite.castShadow = sprite.receiveShadow = false;
const span = FOG_BANK_RANGE.west - FOG_BANK_RANGE.east;
+ let hidden = false;
return {
sprite, puffs,
+ get hidden() { return hidden; },
+ set hidden(value) { hidden = value; sprite.visible = !hidden && opacity.value > .001; },
update(time, value) {
- opacity.value = value; sprite.visible = value > .001;
+ opacity.value = value; sprite.visible = !hidden && value > .001;
if (!sprite.visible) return;
const a = centres.array as Float32Array;
for (let i = 0; i < puffs; i++) {
@@ -72,4 +76,3 @@ export function createFogBanks(atmosphere: AtmosphereUniforms, noise: DataTextur
dispose() { sprite.removeFromParent(); material.dispose(); sprite.geometry.dispose(); },
};
}
-export const FOG_BANK_COUNT = BANKS.length;
diff --git a/scenes/packages/golden-gate/src/world/prewarm-contact-shadows.ts b/scenes/packages/golden-gate/src/world/prewarm-contact-shadows.ts
new file mode 100644
index 00000000..7335f984
--- /dev/null
+++ b/scenes/packages/golden-gate/src/world/prewarm-contact-shadows.ts
@@ -0,0 +1,55 @@
+import { BackSide, DoubleSide, FrontSide, Mesh } from 'three/webgpu';
+import type { Camera, Group, Scene, WebGPURenderer } from 'three/webgpu';
+
+/**
+ * Prepare the hidden contact quad before the world becomes ready. Its first nearby traffic view
+ * otherwise creates two WebGPU pipelines during interaction. Compile only this material/geometry:
+ * water and fog-bank depth bindings cannot be compiled by a blanket world pass.
+ *
+ * Three's queued compileAsync sees DoubleSide after its temporary back/front side changes have
+ * been restored. Explicit sides on separate cache owners retain both actual render variants.
+ */
+export async function prewarmContactShadows(renderer: WebGPURenderer, traffic: Group, scene: Scene, camera: Camera, signal: AbortSignal): Promise<{ dispose(): void }> {
+ signal.throwIfAborted();
+ const proxies: Mesh[] = [];
+ const preparation = { dispose() {
+ const failures: unknown[] = [];
+ for (const proxy of proxies.splice(0)) { try { proxy.dispose(); } catch (error) { failures.push(error); } }
+ if (failures.length) throw new AggregateError(failures, 'Golden Gate contact-shadow preparation cleanup failed');
+ } };
+ // The measured native pipeline stall is WebGPU-only; leave the WebGL fallback unchanged.
+ if (!('isWebGPUBackend' in renderer.backend) || renderer.backend.isWebGPUBackend !== true) return preparation;
+ const target = traffic.children.find(child => child.name === 'traffic-contact-shadows');
+ if (!target) return preparation; // Shadow-map tiers have no contact quad.
+ if (!(target instanceof Mesh) || Array.isArray(target.material) || target.material.name !== 'golden-gate-contact-shadows' ||
+ target.material.side !== DoubleSide || target.material.forceSinglePass || target.visible || !camera.layers.test(target.layers)) {
+ throw new Error('Golden Gate contact-shadow preparation requires the hidden double-sided traffic quad on the active camera layer');
+ }
+ const material = target.material, originalSide = material.side;
+ target.updateWorldMatrix(true, false);
+ let sideName = 'back';
+ try {
+ try {
+ for (const [name, side] of [['back', BackSide], ['front', FrontSide]] as const) {
+ signal.throwIfAborted(); sideName = name;
+ const proxy = target.clone(false);
+ proxy.name = `traffic-contact-shadows-prewarm-${name}`; proxy.visible = true;
+ proxy.matrixAutoUpdate = false; proxy.matrix.copy(target.matrixWorld); proxy.matrixWorld.copy(target.matrixWorld);
+ proxies.push(proxy);
+ material.side = side;
+ await renderer.compileAsync(proxy, camera, scene);
+ signal.throwIfAborted();
+ }
+ } finally {
+ material.side = originalSide;
+ // No needsUpdate/version rewrite and no index-array rewind: WebGPU may initialize the
+ // existing index attribute as Uint32 while preserving all six index values.
+ }
+ return preparation;
+ } catch (error) {
+ try { preparation.dispose(); }
+ catch (cleanupError) { throw new AggregateError([error, cleanupError], 'Golden Gate contact-shadow preparation and cleanup failed'); }
+ signal.throwIfAborted();
+ throw new Error(`Golden Gate contact-shadow ${sideName} pipeline preparation failed`, { cause: error });
+ }
+}
diff --git a/scenes/packages/golden-gate/src/world/reflection-depth.ts b/scenes/packages/golden-gate/src/world/reflection-depth.ts
new file mode 100644
index 00000000..c6d0d33f
--- /dev/null
+++ b/scenes/packages/golden-gate/src/world/reflection-depth.ts
@@ -0,0 +1,35 @@
+import { Matrix4, Plane, Vector3, Vector4 } from 'three/webgpu';
+import type { Camera, PerspectiveCamera, Scene } from 'three/webgpu';
+
+interface Reflector { target: { matrixWorld: Matrix4 }; getVirtualCamera(camera: Camera): Camera }
+/** r186's ReflectorNode replaces the near plane assuming standard depth. Correct
+ * its virtual projection after Renderer updates the camera, before frustum setup.
+ * Reversed WebGPU and WebGL EXT_clip_control both use the [0,1] clip interval. */
+export function installReflectionDepth(scene: Scene, reflector: Reflector) {
+ const previous = scene.onBeforeRender;
+ const plane = new Plane(), normal = new Vector3(), point = new Vector3(), rotation = new Matrix4(), clip = new Vector4(), q = new Vector4();
+ let main: PerspectiveCamera | null = null, disposed = false;
+ const before: Scene['onBeforeRender'] = function(this: Scene, ...args) {
+ previous.apply(this, args);
+ const [renderer, , camera] = args;
+ if (disposed || !(renderer as unknown as { reversedDepthBuffer?: boolean }).reversedDepthBuffer || !main || camera === main || camera !== reflector.getVirtualCamera(main)) return;
+ const p = camera.projectionMatrix, e = p.elements, r = main.projectionMatrix.elements;
+ p.copy(main.projectionMatrix);
+ // Recover the standard zero-to-one projection, then apply its oblique plane.
+ e[2] = r[3]! - r[2]!; e[6] = r[7]! - r[6]!; e[10] = r[11]! - r[10]!; e[14] = r[15]! - r[14]!;
+ normal.set(0, 0, 1).applyMatrix4(rotation.extractRotation(reflector.target.matrixWorld));
+ point.setFromMatrixPosition(reflector.target.matrixWorld);
+ plane.setFromNormalAndCoplanarPoint(normal, point).applyMatrix4(camera.matrixWorldInverse);
+ clip.set(plane.normal.x, plane.normal.y, plane.normal.z, plane.constant);
+ q.set((Math.sign(clip.x) + e[8]!) / e[0]!, (Math.sign(clip.y) + e[9]!) / e[5]!, -1, (1 + e[10]!) / e[14]!);
+ clip.multiplyScalar(1 / clip.dot(q));
+ // Reverse row three again: water is the near plane (z=w).
+ e[2] = e[3]! - clip.x; e[6] = e[7]! - clip.y; e[10] = e[11]! - clip.z; e[14] = e[15]! - clip.w;
+ camera.projectionMatrixInverse.copy(p).invert();
+ };
+ scene.onBeforeRender = before;
+ return {
+ setCamera(camera: PerspectiveCamera) { if (!disposed) main = camera; },
+ dispose() { disposed = true; main = null; if (scene.onBeforeRender === before) scene.onBeforeRender = previous; },
+ };
+}
diff --git a/scenes/packages/golden-gate/src/world/water-material.ts b/scenes/packages/golden-gate/src/world/water-material.ts
index 0b9617fa..f53c7364 100644
--- a/scenes/packages/golden-gate/src/world/water-material.ts
+++ b/scenes/packages/golden-gate/src/world/water-material.ts
@@ -60,6 +60,7 @@ export const MACRO_TILES = WATER_DATA.macroTiles;
export const FLOW_PERIOD = WATER_DATA.flow.flowPeriod; // seconds per two-phase flow cycle
export const SHORE_BAND_PERIOD = WATER_DATA.shoreBandPeriod; // seconds between shore-foam bands
export const ORIGIN_SNAP = WATER_DATA.originSnap; // metres
+const FOAM_BREAKUP_TILE = 7.3; // metres, unrotated
export interface WaterMapBinding { texture: DataTexture; bounds: Bounds }
export interface WaterMaterialOptions {
@@ -89,6 +90,7 @@ export function createWaterUniforms() {
origin: uniform(new Vector2()),
phases: GERSTNER_WAVES.map(() => uniform(0)),
detailOffsets: DETAIL_LAYERS.map(() => uniform(new Vector2())),
+ foamOffset: uniform(new Vector2()),
macroOffsets: MACRO_TILES.map(() => uniform(new Vector2())),
flowPhase: uniform(0),
shorePhase: uniform(0),
@@ -110,6 +112,7 @@ export function updateWaterUniforms(u: WaterUniforms, time: number, cameraX: num
const ox = Math.round(cameraX / ORIGIN_SNAP) * ORIGIN_SNAP, oz = Math.round(cameraZ / ORIGIN_SNAP) * ORIGIN_SNAP;
u.origin.value.set(ox, oz);
GERSTNER_WAVES.forEach((w, i) => {
+ // The shader adds this to k dot (p - origin), leaving k dot p - omega*t.
const c = waveConstants(w), phase = c.k * (c.dx * ox + c.dz * oz) - c.omega * time;
u.phases[i]!.value = phase - Math.floor(phase / (2 * Math.PI)) * 2 * Math.PI;
});
@@ -118,6 +121,9 @@ export function updateWaterUniforms(u: WaterUniforms, time: number, cameraX: num
const a = layer.rotation * Math.PI / 180, c = Math.cos(a), s = Math.sin(a);
const px = ox + layer.drift * time, pz = oz; // the pattern moves toward -X: sample at p + drift*t
u.detailOffsets[i]!.value.set(frac((px * c - pz * s) / layer.tile), frac((px * s + pz * c) / layer.tile));
+ // Foam uses a different tile and no rotation. Preserve its existing time drift,
+ // but compensate this lookup's own origin instead of borrowing a detail-layer offset.
+ if (i === 0) u.foamOffset.value.set(frac(ox / FOAM_BREAKUP_TILE + layer.drift * time * c / layer.tile), frac(oz / FOAM_BREAKUP_TILE + layer.drift * time * s / layer.tile));
});
MACRO_TILES.forEach((tile, i) => u.macroOffsets[i]!.value.set(frac(ox / tile), frac(oz / tile)));
u.flowPhase.value = frac(time / FLOW_PERIOD);
@@ -175,7 +181,7 @@ export function createWaterMaterial(o: WaterMaterialOptions, u: WaterUniforms):
const c = waveConstants(w);
const fade = saturate(float(w.wavelength).div(effectiveSpacing).mul(.25).sub(1));
const amplitude = scale.mul(fade).mul(w.amplitude);
- const theta = rel.x.mul(c.k * c.dx).add(rel.y.mul(c.k * c.dz)).sub(u.phases[i]);
+ const theta = rel.x.mul(c.k * c.dx).add(rel.y.mul(c.k * c.dz)).add(u.phases[i]);
const horizontal = amplitude.mul(w.steepness).mul(cos(theta));
displaced.addAssign(vec3(horizontal.mul(c.dx), amplitude.mul(sin(theta)), horizontal.mul(c.dz)));
});
@@ -222,7 +228,7 @@ export function createWaterMaterial(o: WaterMaterialOptions, u: WaterUniforms):
const filtered = saturate(float(w.wavelength).div(footprint.mul(3)).sub(1));
const visible = distanceFade ? filtered.mul(distanceFade).toVar() : filtered;
const amplitude = u.wind.mul(shallow).mul(w.amplitude);
- const theta = rel.x.mul(c.k * c.dx).add(rel.y.mul(c.k * c.dz)).sub(u.phases[i]);
+ const theta = rel.x.mul(c.k * c.dx).add(rel.y.mul(c.k * c.dz)).add(u.phases[i]);
const ct = cos(theta), st = sin(theta), ka = amplitude.mul(c.k);
slope.addAssign(vec2(c.dx, c.dz).mul(ka.mul(ct).mul(visible)));
lostVariance.addAssign(float(1).sub(visible.mul(visible)).mul(ka).mul(ka).mul(.5));
@@ -325,7 +331,7 @@ export function createWaterMaterial(o: WaterMaterialOptions, u: WaterUniforms):
const specular = min(D.mul(visibility).mul(Fs).mul(NdotL), 40).mul(sun).toVar();
// Foam.
- const breakup = smoothstep(.25, .75, macro.y.mul(.6).add(texture(o.slopeMoments, rel.div(7.3).add(u.detailOffsets[0]!)).x.mul(.12)).add(.2));
+ const breakup = smoothstep(.25, .75, macro.y.mul(.6).add(texture(o.slopeMoments, rel.div(FOAM_BREAKUP_TILE).add(u.foamOffset)).x.mul(.12)).add(.2));
// (a) shore: slow bands travelling toward the shore, stronger where the west swell reaches.
// World-space gradient of the shoreline distance from screen derivatives (no extra texture taps).
const dwx = dFdx(world) as N, dwy = dFdy(world) as N, dsx = dFdx(shore) as N, dsy = dFdy(shore) as N;
@@ -372,7 +378,8 @@ const TURBULENCE_MEAN = .45;
* the streaks never fold); their contrast fades to the mean as the view looks down, from `elevation[0]` to
* `elevation[1]` (the sine of the view ray's elevation above the water: 14.5 to 40.5 degrees).
*/
-export const WAKE = { speed: 1.9, period: 23, warpPeriod: 23 * (1 + Math.sqrt(5)) / 2, warpAcross: 17, warp: .12, elevation: [.25, .65] } as const;
+export const WAKE = { speed: 1.9, period: 23, warpPeriod: 23 * (1 + Math.sqrt(5)) / 2, warpAcross: 17, warp: .12, elevation: [.25, .65],
+ decay: 110, spread: .08, edgeStrength: .15, gain: .35 } as const;
/**
* Wakes streaming downstream (with the tide) from the south fender and the north tower pier. The 23 m
* turbulence streaks are spaced irregularly by the second, incommensurate period, and fade to their mean
@@ -393,18 +400,18 @@ function wakeFoam(world: N, u: WaterUniforms, distanceFade: N | null, viewElevat
for (const ob of obstacles) {
const along = world.x.sub(ob.x).mul(direction).sub(ob.halfAlong * .7);
const across = world.y.sub(ob.z);
- const width = along.max(0).mul(.16).add(ob.halfAcross * .9);
+ const width = along.max(0).mul(WAKE.spread).add(ob.halfAcross * .9);
const core = exp(across.div(width).pow(2).negate());
const edges = exp(abs(across).sub(width).div(width.mul(.22)).pow(2).negate());
- const lengthFade = exp(along.max(0).div(280).negate()).mul(smoothstep(-ob.halfAlong * .6, 8, along));
+ const lengthFade = exp(along.max(0).div(WAKE.decay).negate()).mul(smoothstep(-ob.halfAlong * .6, 8, along));
// turbulence advected downstream with the current, its spacing warped by the second period
const warp = sin(along.div(WAKE.warpPeriod).sub(u.wakeWarpPhase).add(across.div(WAKE.warpAcross)).mul(2 * Math.PI)).mul(WAKE.warp);
const streak = fract(along.div(WAKE.period).sub(u.wakePhase).add(across.div(9).mul(.37)).add(warp));
const streaks = smoothstep(.15, .5, streak).mul(smoothstep(.95, .6, streak));
const turbulence = mix(float(TURBULENCE_MEAN), streaks, contrast);
- total = total.add(core.mul(.55).add(edges.mul(.6)).mul(lengthFade).mul(turbulence.mul(.6).add(.4)));
+ total = total.add(core.mul(.55).add(edges.mul(WAKE.edgeStrength)).mul(lengthFade).mul(turbulence.mul(.6).add(.4)));
}
- return saturate(total.mul(strength));
+ return saturate(total.mul(strength).mul(WAKE.gain));
}
/** Material features that must never change after compile, for tests and reports. */
diff --git a/scenes/packages/golden-gate/src/world/water.ts b/scenes/packages/golden-gate/src/world/water.ts
index 72740237..a943c93b 100644
--- a/scenes/packages/golden-gate/src/world/water.ts
+++ b/scenes/packages/golden-gate/src/world/water.ts
@@ -16,18 +16,19 @@ import type { GoldenGateFeatures } from '../tiers';
import { passCameraLayers } from '@kiln-scenes/scene-kit';
import type { PassLayers } from '@kiln-scenes/scene-kit';
import { LAYERS } from '../constants';
+import { installReflectionDepth } from './reflection-depth';
export interface WaterOptions {
features: GoldenGateFeatures['water'];
atmosphere: Atmosphere;
near: WaterMapLevel; mid: WaterMapLevel; midGrid: WaterGrid;
- /** Reflection stand-ins (High): the virtual camera drops `main` and takes `pass`; its other bits stay as cloned from the main camera. */
+ /** Reflection stand-ins (High): the virtual camera drops `main` and takes `pass`, in addition to excluding the dynamic layer. */
passLayers?: PassLayers;
}
export interface Water {
mesh: Mesh; uniforms: WaterUniforms; clipmap: ClipmapOptions;
textures: { macroNoise: DataTexture; slopeMoments: DataTexture; flow: DataTexture };
- /** The reflector's virtual camera (High), so the sky can hide its sun disc there; with pass layers, its two pass bits are set on every call (three may recreate it). */
+ /** The reflector's virtual camera (High): excludes traffic/player/fog, keeps world vegetation, and applies stand-in pass bits on every call (three may recreate it). */
reflectionCamera(camera: Camera): Camera | null;
update(camera: PerspectiveCamera, time: number): void;
readonly stats: { tiles: number; maxTiles: number; vertices: number; reflection: string; description: ReturnType<typeof describeWater> };
@@ -49,6 +50,8 @@ export function createWater(scene: Scene, o: WaterOptions): Water {
reflection.target.rotateX(-Math.PI / 2); reflection.target.name = 'water-reflector';
scene.add(reflection.target);
}
+ const reflectionDepth = reflection ? installReflectionDepth(scene, (reflection as unknown as { reflector: Parameters<typeof installReflectionDepth>[1] }).reflector) : null;
+ if (reflectionDepth) owned.push(reflectionDepth);
const options = {
atmosphere: o.atmosphere.uniforms, grid: f.grid, displacedWaves: f.displacedWaves, fragmentWaves: f.fragmentWaves, detailLayers: f.detailLayers,
reflection: f.reflection, reflectionNode: reflection ?? undefined, environment: o.atmosphere.environment, depthContact: f.depthContact, waveFade: f.waveFade,
@@ -70,12 +73,16 @@ export function createWater(scene: Scene, o: WaterOptions): Water {
reflectionCamera(camera) {
if (!reflection) return null;
const virtual = (reflection as unknown as { reflector: { getVirtualCamera(c: Camera): Camera } }).reflector.getVirtualCamera(camera);
+ // D-70: the clone inherits the main camera's dynamic bit; traffic (including the player car) and fog banks stay out.
+ // Vegetation cards use the world layer and remain in the reflection (D-71).
+ virtual.layers.disable(LAYERS.dynamic);
if (o.passLayers) passCameraLayers(virtual, o.passLayers, 'pass');
return virtual;
},
update(camera, time) {
+ reflectionDepth?.setCamera(camera);
camera.updateMatrixWorld();
- projection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); frustum.setFromProjectionMatrix(projection);
+ projection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); frustum.setFromProjectionMatrix(projection, camera.coordinateSystem, camera.reversedDepth);
const count = selectTiles(clipmap, camera.position.x, camera.position.z, patches.array, frustum, 3);
geometry.instanceCount = count;
patches.clearUpdateRanges(); patches.addUpdateRange(0, count * 4); patches.needsUpdate = true;
diff --git a/scenes/packages/golden-gate/tests/tools/approach-imagery.ts b/scenes/packages/golden-gate/tests/tools/approach-imagery.ts
index c602278a..f1be58fd 100644
--- a/scenes/packages/golden-gate/tests/tools/approach-imagery.ts
+++ b/scenes/packages/golden-gate/tests/tools/approach-imagery.ts
@@ -18,7 +18,7 @@ import { PACKAGE_ROOT, writeJson } from './owned.ts';
import { EXTENT, SIZE, nearAlbedo } from './imagery.ts';
import { writePng, type Image, type Rgb } from './image.ts';
import { APPROACH_NAMES, Tin, loadTileArrays } from '../../scripts/approaches.ts';
-import { LAYOUT } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
import { approachHorizontal } from '../../src/world/route';
import { horizontalAt, horizontalProject, lateral, profileAt } from '../../src/world/alignment';
diff --git a/scenes/packages/golden-gate/tests/tools/draw-parity.ts b/scenes/packages/golden-gate/tests/tools/draw-parity.ts
index 6f5a1b27..70069758 100644
--- a/scenes/packages/golden-gate/tests/tools/draw-parity.ts
+++ b/scenes/packages/golden-gate/tests/tools/draw-parity.ts
@@ -88,7 +88,7 @@ const variant = option('--variant', 'defaults'), backend = option('--backend', '
const CHANGED = 20;
const budget = Number(option('--over32-budget', '100')), writeMode = option('--write', 'all'), pageMode = option('--page', 'fresh');
if (!build) throw new Error('--build <label> is required');
-if (!(budget >= 0)) throw new Error('--over32-budget must be 0 or more');
+if (!Number.isSafeInteger(budget) || budget < 0) throw new Error('--over32-budget must be a finite nonnegative integer');
if (!['all', 'changed', 'none'].includes(writeMode)) throw new Error('--write is all, changed or none');
if (!['fresh', 'shared'].includes(pageMode)) throw new Error('--page is fresh or shared');
for (const p of presets) if (!['day', 'golden', 'fog'].includes(p)) throw new Error(`Unknown preset ${p}; the scene has day, golden and fog`);
@@ -206,13 +206,13 @@ try {
for (const [index, { tier, preset, view }] of cases.entries()) {
const c = cases[index]!;
const a = runs ? runs.a[index]! : await freshShot(hostA, owned, browser, c, reference), r = runs ? runs.r[index]! : await freshShot(hostA, owned, browser, c, reference), b = runs ? runs.b[index]! : await freshShot(hostB, owned, browser, c, on);
- const parity = compareParityImages(a.png, r.png, b.png), name = `${tier}-${preset}-${view}${tag}`, onVsOff = exact(a.png, b.png), repeatVsOff = exact(a.png, r.png);
- const lines = { over32: onVsOff.over32, noise: repeatVsOff.over32, budget, pass: onVsOff.over32 <= repeatVsOff.over32 + budget };
- const pass = parity.pass && lines.pass;
+ const parity = compareParityImages(a.png, r.png, b.png, { over32Budget: budget }), name = `${tier}-${preset}-${view}${tag}`, onVsOff = exact(a.png, b.png), repeatVsOff = exact(a.png, r.png);
+ const lines = parity.lines;
+ const pass = parity.pass;
if (writeMode === 'all' || (writeMode === 'changed' && (!pass || onVsOff.over32 >= repeatVsOff.over32 + CHANGED))) {
write(resolve(out, `${name}-${nameA}.png`), a.png); write(resolve(out, `${name}-repeat.png`), r.png); write(resolve(out, `${name}-${nameB}.png`), b.png); write(resolve(out, `${name}-diff.png`), parity.diff);
}
- const row = { tier, preset, view, variant, before: before || null, page: pageMode, backend: b.backend, pass, b06: parity.pass, lines, globalMean: parity.globalMean, noiseGlobalMean: parity.noiseGlobalMean, passingTiles: parity.passingTiles, tiles: parity.tiles.length,
+ const row = { tier, preset, view, variant, before: before || null, page: pageMode, backend: b.backend, pass, b06: parity.pass, luminancePass: parity.luminancePass, parityScope: parity.scope, lines, globalMean: parity.globalMean, noiseGlobalMean: parity.noiseGlobalMean, passingTiles: parity.passingTiles, tiles: parity.tiles.length,
failingTiles: parity.tiles.filter(t => !t.pass).map(t => ({ x: t.x, y: t.y, mean: +t.mean.toExponential(2), threshold: +t.threshold.toExponential(2) })),
onVsOff, repeatVsOff, draw: { off: a.draw, on: b.draw }, bridge: { off: a.bridge, on: b.bridge }, usingFar: { off: a.usingFar, on: b.usingFar }, camera: { off: a.camera, on: b.camera } };
results.push(row);
diff --git a/scenes/packages/golden-gate/tests/tools/dressing-imagery.ts b/scenes/packages/golden-gate/tests/tools/dressing-imagery.ts
index f8b436a3..2a91bbf5 100644
--- a/scenes/packages/golden-gate/tests/tools/dressing-imagery.ts
+++ b/scenes/packages/golden-gate/tests/tools/dressing-imagery.ts
@@ -26,7 +26,8 @@
// Writes evidence/captures/dressing/imagery.json and one <element>-imagery.png per element.
import { mkdirSync, writeFileSync } from 'node:fs';
import { relative, resolve } from 'node:path';
-import { LAYOUT, TIER_DATA } from '../../src/data';
+import { TIER_DATA } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
import { parkedVehicles, plazaWidening, polygonDistance, vistaRows } from '../../src/world/dressing';
import { frame } from '../../src/world/mesh-arrays';
import { buildApproach, type Approach } from '../../src/world/route';
diff --git a/scenes/packages/golden-gate/tests/tools/joint-depth.ts b/scenes/packages/golden-gate/tests/tools/joint-depth.ts
index c1522313..7a5e4e19 100644
--- a/scenes/packages/golden-gate/tests/tools/joint-depth.ts
+++ b/scenes/packages/golden-gate/tests/tools/joint-depth.ts
@@ -25,7 +25,7 @@ import { PACKAGE_ROOT, assertOwnedUrl, launchHeadless, serveOwned, unexpectedMes
import { outputFor } from './build.ts';
import { luma, montage, readPng, writePng, type Image } from './image.ts';
import { bridgeWebPath, nodeMeshes, readGlb } from '../../scripts/layout.ts';
-import { LAYOUT } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
type Backend = 'webgpu' | 'webgl2';
const WIDTH = 1280, HEIGHT = 720, FOV = 55, FOCAL = HEIGHT / 2 / Math.tan(FOV / 2 * Math.PI / 180);
diff --git a/scenes/packages/golden-gate/tests/tools/owned.ts b/scenes/packages/golden-gate/tests/tools/owned.ts
index 90270246..ea8cbc71 100644
--- a/scenes/packages/golden-gate/tests/tools/owned.ts
+++ b/scenes/packages/golden-gate/tests/tools/owned.ts
@@ -1,9 +1,9 @@
// Golden Gate process ownership helpers. The builder may serve only on ports 4600-4649.
-// The kit's serveOwned/assertOwnedUrl/runSceneContractTests are fixed to 4400-4499
-// (kit request GG-001), so this package binds its own range with the kit's static server.
+// This package retains its own range and avoid-set; browser ownership is shared with the kit.
// Binding is attempted directly (EADDRINUSE moves on): no listener is ever probed.
import { resolve } from 'node:path';
import { mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';
+import { chromeProfile, launchChrome } from '../../../scene-kit/src/testing/node';
// @ts-ignore Shared Node-builtins-only implementation owned by the kit builder (read-only use).
import { startStaticServer } from '../../../../scripts/static-server.mjs';
@@ -31,20 +31,11 @@ export function assertOwnedUrl(url: string, owned: ReadonlySet<number>): void {
*/
export interface OwnedBrowser { browser: import('puppeteer-core').Browser; pid: number | undefined; profile: string; close(): Promise<void> }
export async function launchHeadless(name: string, width = 1280, height = 720): Promise<OwnedBrowser> {
- const puppeteer = (await import('puppeteer-core')).default, { mkdtemp, rm } = await import('node:fs/promises');
- const scratch = resolve(PACKAGE_ROOT, '.tmp'); mkdirSync(scratch, { recursive: true });
- const profile = await mkdtemp(resolve(scratch, `${name}-chrome-`));
- const browser = await puppeteer.launch({
- executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, pipe: true, userDataDir: profile,
+ const browser = await launchChrome({ workspace: PACKAGE_ROOT, name, headless: true, windowSize: [width, height],
defaultViewport: { width, height, deviceScaleFactor: 1 },
- args: ['--enable-unsafe-webgpu', '--no-first-run', '--no-default-browser-check', `--window-size=${width},${height}`, '--hide-scrollbars'],
- env: { ...process.env, TEMP: scratch, TMP: scratch },
+ args: ['--hide-scrollbars'],
});
- let closed = false;
- return { browser, pid: browser.process()?.pid, profile, async close() {
- if (closed) return; closed = true;
- try { await browser.close(); } finally { await rm(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }).catch(() => undefined); }
- } };
+ return { browser, pid: browser.process()?.pid, profile: chromeProfile(browser)!, close: () => browser.close() };
}
export function evidencePath(...parts: string[]): string { const path = resolve(PACKAGE_ROOT, 'evidence', ...parts); mkdirSync(resolve(path, '..'), { recursive: true }); return path; }
export function writeJson(path: string, value: unknown): void { mkdirSync(resolve(path, '..'), { recursive: true }); writeFileSync(path, JSON.stringify(value, null, 2) + '\n'); }
diff --git a/scenes/packages/golden-gate/tests/unit/arrival.test.ts b/scenes/packages/golden-gate/tests/unit/arrival.test.ts
index 6e295b0a..d47d8ab2 100644
--- a/scenes/packages/golden-gate/tests/unit/arrival.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/arrival.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from 'bun:test';
-import { LAYOUT } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
test('opening view is an elevated water-side approach looking down across the bridge', () => {
const view = LAYOUT.cameras.named[LAYOUT.cameras.default]!;
diff --git a/scenes/packages/golden-gate/tests/unit/boost.test.ts b/scenes/packages/golden-gate/tests/unit/boost.test.ts
index 0eb2e4a9..69a0c5c2 100644
--- a/scenes/packages/golden-gate/tests/unit/boost.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/boost.test.ts
@@ -1,5 +1,6 @@
import { expect, test } from 'bun:test';
-import { DRIVING_DATA, LAYOUT } from '../../src/data';
+import { DRIVING_DATA } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
import { createCar, stepCar, type CarInput } from '../../src/play/car';
import { DIMS } from './helpers/vehicle-dims';
diff --git a/scenes/packages/golden-gate/tests/unit/bridge-draws.test.ts b/scenes/packages/golden-gate/tests/unit/bridge-draws.test.ts
index 216eebe3..47d57004 100644
--- a/scenes/packages/golden-gate/tests/unit/bridge-draws.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/bridge-draws.test.ts
@@ -11,8 +11,10 @@ import { Box3, BoxGeometry, FrontSide, Group, Mesh, MeshStandardMaterial, PlaneG
import type { BufferGeometry, Material, Object3D } from 'three/webgpu';
import type { GLTF } from 'three/addons/loaders/GLTFLoader.js';
import { BRIDGE, LAYERS } from '../../src/constants';
-import { LAYOUT } from '../../src/data';
-import { createBridge } from '../../src/world/bridge';
+import { LAYOUT } from '../../scripts/authored-layout';
+await import('three');
+const { createBridge } = await import('../../src/world/bridge');
+import { readGoldenGateLayout } from '../../src/layout';
import type { BridgeOptions } from '../../src/world/bridge';
import { drawOptions } from '../../src/world/draw-options';
import { FEATURES } from '../../src/tiers';
@@ -54,7 +56,7 @@ function pack() {
const materials = Object.fromEntries(NAMES.map(name => [name, new MeshStandardMaterial({ name, emissive: name === 'LampGlass' || name === 'BeaconEmissive' ? 0xffcc88 : 0, emissiveIntensity: 2 })])) as Materials;
return { materials, web: model(materials), far: model(materials) };
}
-const HIGH: BridgeOptions = { farSwitch: 5200, castShadow: true, merge: true, standInLayer: LAYERS.shadowStandIn, passLayers: { main: LAYERS.mainOnly, pass: LAYERS.reflectionOnly } };
+const HIGH: BridgeOptions = { layout: LAYOUT, farSwitch: 5200, castShadow: true, merge: true, standInLayer: LAYERS.shadowStandIn, passLayers: { main: LAYERS.mainOnly, pass: LAYERS.reflectionOnly } };
const triangles = (g: BufferGeometry) => (g.index ? g.index.count : g.attributes.position!.count) / 3;
/** What a camera on layer `layer` draws under root: visible meshes on that layer, their triangles, materials and world bounds. */
function drawn(root: Object3D, layer = LAYERS.world, cast = false) {
@@ -76,6 +78,44 @@ function snapshot(gltf: GLTF) {
const near = new Vector3(300, 120, 900), distant = new Vector3(0, 100, 8000);
describe('bridge draws', () => {
+ test('a reversed-depth world owns its joint bias without changing another world sharing the pack', () => {
+ const p=pack(), normal=createBridge(p.web,p.far,HIGH), reversed=createBridge(p.web,p.far,{...HIGH,reversedDepthBuffer:true});
+ const joints=(bridge:ReturnType<typeof createBridge>)=>[...drawn(bridge.views.web).materials].filter(m=>m.name==='JointSteel');
+ const original=p.materials.JointSteel, own=joints(reversed)[0]!;
+ expect(joints(normal)).toEqual([original]);expect(own).not.toBe(original);
+ expect(original.polygonOffsetFactor).toBeLessThan(0);expect(own.polygonOffsetFactor).toBeGreaterThan(0);
+ let released=0;own.addEventListener('dispose',()=>released++);reversed.dispose();
+ expect(released).toBe(1);expect(original.polygonOffsetFactor).toBeLessThan(0);normal.dispose();
+ });
+ test('two worlds use their own verified dressing, and disposing one retains the other’s materials', () => {
+ const layout = (color: string) => {
+ const data = structuredClone(LAYOUT); data.dressing.paint.color = color;
+ return readGoldenGateLayout({ data: new Map([['layout', new TextEncoder().encode(JSON.stringify(data)).buffer]]) }, new AbortController().signal);
+ };
+ const p = pack(), firstLayout = layout('#123456'), secondLayout = layout('#654321');
+ const first = createBridge(p.web, p.far, { ...HIGH, layout: firstLayout }), second = createBridge(p.web, p.far, { ...HIGH, layout: secondLayout });
+ const paints = (bridge: ReturnType<typeof createBridge>) => {
+ const found = new Set<MeshStandardMaterial>();
+ bridge.approachMeshes.near.group.traverse(node => {
+ const material = (node as Mesh).material;
+ for (const item of Array.isArray(material) ? material : material ? [material] : []) if (item.name === 'PaintedSteel') found.add(item as MeshStandardMaterial);
+ });
+ return [...found];
+ };
+ const a = paints(first), b = paints(second); let disposed = 0;
+ try {
+ expect(a.map(material => material.color.getHexString())).toEqual(['123456']);
+ expect(b.map(material => material.color.getHexString())).toEqual(['654321']);
+ expect(a[0]).not.toBe(b[0]);
+ expect(first.route.north.data).toBe(firstLayout.approaches.north);
+ expect(second.route.north.data).toBe(secondLayout.approaches.north);
+ b[0]!.addEventListener('dispose', () => { disposed++; });
+ } finally { first.dispose(); }
+ try { expect(disposed).toBe(0); expect(b[0]!.color.getHexString()).toBe('654321'); }
+ finally { second.dispose(); }
+ expect(disposed).toBe(1);
+ });
+
test('the merge draws south, north and span parts by material with the same triangles, bounds and materials', () => {
const p = pack(), bridge = createBridge(p.web, p.far, { ...HIGH, standInLayer: undefined, passLayers: undefined });
const source = drawn(bridge.web), web = drawn(bridge.views.web);
diff --git a/scenes/packages/golden-gate/tests/unit/car.test.ts b/scenes/packages/golden-gate/tests/unit/car.test.ts
index 56d49901..3db91929 100644
--- a/scenes/packages/golden-gate/tests/unit/car.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/car.test.ts
@@ -3,7 +3,8 @@
// follows and never overlaps (and that brakes for it), the road-end stop and turn-around (on the approach
// roads since fix round 2), determinism.
import { describe, expect, test } from 'bun:test';
-import { DRIVING_DATA, LAYOUT, TIER_DATA } from '../../src/data';
+import { DRIVING_DATA, TIER_DATA } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
import { CARRIAGEWAY, advanceCar, carExtents, createCar, endStop, nearRoadEnd, roadEnd, startCar, stepCar, turnAround } from '../../src/play/car';
import type { CarBody, CarInput, CarState, TrafficBox } from '../../src/play/car';
import { TrafficSim } from '../../src/traffic/sim';
diff --git a/scenes/packages/golden-gate/tests/unit/count-baseline.test.ts b/scenes/packages/golden-gate/tests/unit/count-baseline.test.ts
new file mode 100644
index 00000000..4235c1c2
--- /dev/null
+++ b/scenes/packages/golden-gate/tests/unit/count-baseline.test.ts
@@ -0,0 +1,34 @@
+import { expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+test('the retained X-02 count baseline covers every recorded backend, tier and camera and names its original receipt', () => {
+ const root = resolve(import.meta.dir, '../..');
+ const baseline = JSON.parse(readFileSync(resolve(root, 'fixtures/x02-baseline.json'), 'utf8'));
+ const layout = JSON.parse(readFileSync(resolve(root, 'data/layout.json'), 'utf8'));
+ expect(baseline.id).toBe('X-02');
+ expect(baseline.captured).toBe('2026-10-02T08:42:56.568Z');
+ expect(baseline.provenance.originalSha256).toBe('ec58dc339b8c56018a0a1f2ecdff137915752e30ba8c9af958249db0a4ad233d');
+ expect(baseline.build.chunks).toEqual(['index-D-gELBet.js', 'route-contact-CxuZU847.js']);
+ expect(baseline.build.source).toBe('working tree');
+ // These pins identify the recorded g9 binary, independently of later delivery labels.
+ expect(baseline.build.release).toBe('g9');
+ expect(baseline.build.packSha256).toBe('c2a1d83fce6caf07a7b3e87070ccb8a983dd68e0c7f98eee3f1ba5255ce059cb');
+ expect(createHash('sha256').update(JSON.stringify(baseline.cases)).digest('hex')).toBe(baseline.provenance.casesSha256);
+ expect(baseline.cases.map((c: { backend: string; tier: string }) => `${c.backend}/${c.tier}`).sort()).toEqual([
+ 'webgl2/balanced', 'webgl2/economy', 'webgl2/high', 'webgpu/balanced', 'webgpu/economy', 'webgpu/high',
+ ]);
+ const views = [...Object.keys(layout.cameras.named), ...[0, 90, 180, 270].map(degrees => `hero-orbit-${degrees}deg`), 'drive-chase'].sort();
+ expect(views).toHaveLength(16);
+ for (const c of baseline.cases) {
+ expect(c.views.map((v: { view: string }) => v.view).sort()).toEqual(views);
+ for (const v of c.views) {
+ expect(Number.isSafeInteger(v.drawCalls) && v.drawCalls > 0).toBe(true);
+ expect(Number.isSafeInteger(v.triangles) && v.triangles > 0).toBe(true);
+ }
+ }
+ // The published report's first high/WebGPU row is an independent witness for the extracted counts.
+ expect(baseline.cases.find((c: { backend: string; tier: string }) => c.backend === 'webgpu' && c.tier === 'high').views[0])
+ .toEqual({ view: 'arrival', drawCalls: 103, triangles: 1426047 });
+});
diff --git a/scenes/packages/golden-gate/tests/unit/data.test.ts b/scenes/packages/golden-gate/tests/unit/data.test.ts
index 8b8f5b0c..30770765 100644
--- a/scenes/packages/golden-gate/tests/unit/data.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/data.test.ts
@@ -4,7 +4,8 @@
import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
-import { DRIVING_DATA, LAYOUT, PRESET_DATA, TIER_DATA, TRAFFIC_DATA, WATER_DATA } from '../../src/data';
+import { DRIVING_DATA, PRESET_DATA, TIER_DATA, TRAFFIC_DATA, WATER_DATA } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
import type { Vec3 } from '../../src/data';
import { BRIDGE, CAMERA, LANE_CENTERS, NAMED_CAMERAS, POSTCARD, laneDirection, laneX } from '../../src/constants';
import { PRESETS, PRESET_ORDER } from '../../src/presets';
diff --git a/scenes/packages/golden-gate/tests/unit/dressing.test.ts b/scenes/packages/golden-gate/tests/unit/dressing.test.ts
index c3da3f32..3c7de850 100644
--- a/scenes/packages/golden-gate/tests/unit/dressing.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/dressing.test.ts
@@ -5,7 +5,7 @@
// the lot less its planted island triangulated whole, the stall rows inside it with aisles between them, the
// parked cars in their stalls, the terrain pads under the lot and its throat, and the edge barrier's opening.
import { describe, expect, test } from 'bun:test';
-import { LAYOUT } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
import { approachArrays } from '../../src/world/approach-mesh';
import { approachCorridorPlans, bedDepth, corridorHeight } from '../../src/world/corridor';
import { barrierGaps, earClip, parkedVehicles, plazaWidening, polygonDistance, sideWidening, vistaLot, vistaRows } from '../../src/world/dressing';
diff --git a/scenes/packages/golden-gate/tests/unit/flights.test.ts b/scenes/packages/golden-gate/tests/unit/flights.test.ts
index 709c1ad0..441ce761 100644
--- a/scenes/packages/golden-gate/tests/unit/flights.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/flights.test.ts
@@ -11,7 +11,7 @@ import { resolve } from 'node:path';
import { Vector3 } from 'three/webgpu';
import { createCollisionWorld, samplePath } from '@kiln-scenes/scene-kit';
import type { Pose } from '@kiln-scenes/scene-kit';
-import { LAYOUT } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
import { BRIDGE } from '../../src/constants';
import { buildFlights, flightPaths } from '../../src/camera/flights';
import { decodePng } from '../../src/world/png16';
@@ -36,7 +36,7 @@ function bridgeBytes(): Uint8Array {
interface Sample { t: number; position: Vector3; target: Vector3 }
function sampleFlight(index: number): Sample[] {
- const def = flightPaths()[index]!, out: Sample[] = [], pose: Pose = { position: [0, 0, 0], target: [0, 0, 0] };
+ const def = flightPaths(LAYOUT)[index]!, out: Sample[] = [], pose: Pose = { position: [0, 0, 0], target: [0, 0, 0] };
const count = Math.ceil(def.seconds * SAMPLES_PER_SECOND);
for (let i = 0; i <= count; i++) {
samplePath(def, i / count, pose);
@@ -58,7 +58,7 @@ describe('guided flyovers', () => {
/** Height of the highest terrain surface (any tier set) or the water under a point. */
const ground = (p: Vector3) => { from.set(p.x, 3000, p.z); down.set(p.x, -200, p.z); const d = terrain.rayDistance(from, down); return Math.max(0, 3000 - d); };
const report: Record<string, unknown> = {};
- flightPaths().forEach((def, index) => {
+ flightPaths(LAYOUT).forEach((def, index) => {
const samples = sampleFlight(index);
let minTerrain = Infinity, minBridge = Infinity, maxTurn = 0, maxPitch = 0, minTarget = Infinity, maxSpeed = 0, minDeck = Infinity, maxFlow = 0, speed = 0;
let previous: Vector3 | null = null;
@@ -113,7 +113,7 @@ describe('guided flyovers', () => {
const scene = JSON.parse(readFileSync(resolve(STAGED, 'data/scene.json'), 'utf8')) as { terrain: { collision: { path: string; bounds: [number, number, number, number]; metresPerUnit: number; size: [number, number] } } };
const spec = scene.terrain.collision, bytes = readFileSync(resolve(STAGED, spec.path));
const png = await decodePng(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer);
- const flights = buildFlights(heightFieldFromU16(png.data as Uint16Array, png.width, png.height, spec.bounds, spec.metresPerUnit));
+ const flights = buildFlights(heightFieldFromU16(png.data as Uint16Array, png.width, png.height, spec.bounds, spec.metresPerUnit), LAYOUT);
for (const info of Object.values(flights.info)) expect(info.minClearance).toBeGreaterThanOrEqual(LAYOUT.flights.clearance.terrainMinimum);
expect(flights.info['fog-roll'].requiresPreset).toBe('fog');
});
diff --git a/scenes/packages/golden-gate/tests/unit/joint-plates.test.ts b/scenes/packages/golden-gate/tests/unit/joint-plates.test.ts
index a04b10f2..3be4ce45 100644
--- a/scenes/packages/golden-gate/tests/unit/joint-plates.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/joint-plates.test.ts
@@ -5,8 +5,9 @@
// not changed. The material name is the GLB's; nothing else in the bridge uses it.
import { describe, expect, test } from 'bun:test';
import { BoxGeometry, Group, Mesh, MeshStandardMaterial } from 'three/webgpu';
-import { LAYOUT } from '../../src/data';
-import { offsetJointPlates } from '../../src/world/bridge';
+import { LAYOUT } from '../../scripts/authored-layout';
+await import('three');
+const { offsetJointPlates } = await import('../../src/world/bridge');
describe('joint plates', () => {
test('layout.json names the plates\' material and a polygon offset toward the camera', () => {
@@ -34,4 +35,16 @@ describe('joint plates', () => {
const root = new Group(); root.add(new Mesh(new BoxGeometry(), new MeshStandardMaterial({ name: 'Concrete' })));
expect(offsetJointPlates(root)).toBe(0);
});
+
+ test('effective reversed depth changes the bias sign once and standard fallback restores it', () => {
+ const root = new Group(), steel = new MeshStandardMaterial({ name: 'JointSteel' }), geometry = new BoxGeometry();
+ root.add(new Mesh(geometry, steel), new Mesh(geometry, steel));
+ const { factor, units } = LAYOUT.bridge.jointPlates.polygonOffset;
+ for (const reversed of [false, true, true, false]) {
+ expect(offsetJointPlates(root, reversed)).toBe(1);
+ expect(steel.polygonOffsetFactor).toBe(reversed ? -factor : factor);
+ expect(steel.polygonOffsetUnits).toBe(reversed ? -units : units);
+ }
+ geometry.dispose();steel.dispose();
+ });
});
diff --git a/scenes/packages/golden-gate/tests/unit/layout-loading.test.ts b/scenes/packages/golden-gate/tests/unit/layout-loading.test.ts
new file mode 100644
index 00000000..f60c3ead
--- /dev/null
+++ b/scenes/packages/golden-gate/tests/unit/layout-loading.test.ts
@@ -0,0 +1,134 @@
+import { afterEach, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { loadPack } from '@kiln-scenes/scene-kit/assets';
+import { readGoldenGateLayout } from '../../src/layout';
+import { projectLayoutBootstrap, stableLayoutJson } from '../../src/layout-contract';
+import { BOOTSTRAP } from '../../src/layout-bootstrap';
+import type { SceneLayout } from '../../src/data';
+
+const root = resolve(import.meta.dir, '../..'), source = readFileSync(resolve(root, 'data/layout.json'));
+const authored = (): SceneLayout => JSON.parse(source.toString());
+const bytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)).buffer;
+const pack = (value: unknown) => ({ data: new Map([['layout', bytes(value)]]) });
+const signal = () => new AbortController().signal;
+const originalFetch = globalThis.fetch;
+afterEach(() => { globalThis.fetch = originalFetch; });
+
+test('bootstrap is a reproducible projection of authored data, with bulk geometry and animation paths absent', () => {
+ const generated = JSON.parse(readFileSync(resolve(root, 'src/layout-bootstrap.json'), 'utf8'));
+ expect(generated.sourceSha256).toBe(createHash('sha256').update(source).digest('hex'));
+ expect(stableLayoutJson(generated.projection)).toBe(stableLayoutJson(projectLayoutBootstrap(authored())));
+ expect(generated.projection.approaches).toBeUndefined();
+ expect(generated.projection.dressing).toBeUndefined();
+ expect(generated.projection.fogBanks).toBeUndefined();
+ expect(generated.projection.lanes.every((lane: object) => !('polyline' in lane))).toBe(true);
+ expect([BOOTSTRAP, BOOTSTRAP.cameras.clip, BOOTSTRAP.lanes, BOOTSTRAP.lanes[0]].every(Object.isFrozen)).toBe(true);
+});
+
+test('runtime layout has no fallback for missing, malformed, unsupported or bootstrap-incompatible data', () => {
+ expect(() => readGoldenGateLayout({ data: new Map() }, signal())).toThrow('layout');
+ expect(() => readGoldenGateLayout({ data: new Map([['layout', new TextEncoder().encode('{').buffer]]) }, signal())).toThrow('layout');
+ const badSchema = authored(); (badSchema as { schema: string }).schema = 'golden-gate-layout/99';
+ expect(() => readGoldenGateLayout(pack(badSchema), signal())).toThrow('schema');
+ const changedCamera = authored(); changedCamera.cameras.clip.far += 1;
+ expect(() => readGoldenGateLayout(pack(changedCamera), signal())).toThrow('bootstrap');
+ const changedLane = authored(); changedLane.lanes[0]!.x += .1;
+ expect(() => readGoldenGateLayout(pack(changedLane), signal())).toThrow('bootstrap');
+ const changedLength = authored(); changedLength.approaches.north.length += 1;
+ expect(() => { readGoldenGateLayout(pack(changedLength), signal()); }).toThrow('bootstrap');
+ const missingBulk = authored(); delete (missingBulk as Partial<SceneLayout>).dressing;
+ expect(() => readGoldenGateLayout(pack(missingBulk), signal())).toThrow('dressing');
+ const cancelled = new AbortController(), reason = new Error('cancelled mount'); cancelled.abort(reason);
+ expect(() => readGoldenGateLayout(pack(authored()), cancelled.signal)).toThrow(reason);
+});
+
+test('independent worlds consume their own verified bulk data and cannot replace another world’s layout', () => {
+ const a = authored(), b = authored();
+ b.fogBanks.banks[0]!.x += 100;
+ b.dressing.paint.color = '#123456';
+ b.flights.paths[0]!.keys[0]!.position[1] += 20;
+ const first = readGoldenGateLayout(pack(a), signal()), second = readGoldenGateLayout(pack(b), signal());
+ expect(first).toEqual(a); expect(second).toEqual(b); expect(first).not.toBe(second);
+ second.fogBanks.banks[0]!.x += 1;
+ expect(first.fogBanks.banks[0]!.x).toBe(a.fogBanks.banks[0]!.x);
+ // The early camera, tiers and lane/bridge constants are admitted only when identical to this verified layout.
+ expect(projectLayoutBootstrap(first)).toEqual(projectLayoutBootstrap(second));
+ expect(projectLayoutBootstrap(first)).toEqual(BOOTSTRAP);
+});
+
+test.each([
+ ['approach alignment', (layout: SceneLayout) => { layout.approaches.north.alignment = null as never; }],
+ ['empty route profile', (layout: SceneLayout) => { layout.approaches.south.profile = []; }],
+ ['dressing canopy', (layout: SceneLayout) => { layout.dressing.plaza.canopy = null as never; }],
+ ['zero light spacing', (layout: SceneLayout) => { layout.dressing.lights.spacing = 0; }],
+ ['fog wrap', (layout: SceneLayout) => { layout.fogBanks.wrap.west = layout.fogBanks.wrap.east; }],
+ ['fog tuple', (layout: SceneLayout) => { layout.fogBanks.banks[0]!.spread = null as never; }],
+ ['flight coordinate', (layout: SceneLayout) => { layout.flights.paths[0]!.keys[0]!.position[0] = null as never; }],
+ ['duplicate flight', (layout: SceneLayout) => { layout.flights.paths.push(layout.flights.paths[0]!); }],
+] as const)('malformed bulk data is rejected before construction: %s', (_name, change) => {
+ const layout = authored(); change(layout);
+ expect(() => { readGoldenGateLayout(pack(layout), signal()); }).toThrow('Invalid Golden Gate layout');
+});
+
+test('the existing pack loader supplies layout exactly once, rejects corrupt bytes and preserves cancellation', async () => {
+ const body = bytes(authored()), digest = createHash('sha256').update(new Uint8Array(body)).digest('hex');
+ const manifest = { schema: 'kiln.scene-pack/1', id: 'golden-gate', release: 'fixture', three: '0.186.0', models: [], data: { layout: 'data/layout.json' },
+ files: [{ path: 'data/layout.json', bytes: body.byteLength, sha256: digest }] };
+ let requests = 0, corrupt = false;
+ globalThis.fetch = (async (input: RequestInfo | URL) => {
+ if (String(input).endsWith('pack.json')) return Response.json(manifest);
+ requests++; return new Response(corrupt ? new Uint8Array(body.byteLength) : body);
+ }) as typeof fetch;
+ const loaded = await loadPack('https://example.test/golden-gate/', { signal: signal() });
+ expect(readGoldenGateLayout(loaded, signal())).toEqual(authored()); expect(requests).toBe(1);
+ corrupt = true;
+ await expect(loadPack('https://example.test/golden-gate/', { signal: signal() })).rejects.toMatchObject({ code: 'asset-hash' });
+ const cancelled = new AbortController(), reason = new Error('cancelled layout fetch');
+ globalThis.fetch = (async (input: RequestInfo | URL) => {
+ if (String(input).endsWith('pack.json')) return Response.json(manifest);
+ cancelled.abort(reason); return new Response(body);
+ }) as typeof fetch;
+ await expect(loadPack('https://example.test/golden-gate/', { signal: cancelled.signal })).rejects.toThrow(reason);
+});
+
+test('world construction refuses missing or cancelled layout before accessing renderer or tier resources', async () => {
+ await import('three');
+ const { buildGoldenGateWorld } = await import('../../src/world/build-world');
+ const context = { pack: { data: new Map() }, signal: signal(),
+ get knobs() { throw new Error('world resources accessed'); }, get renderer() { throw new Error('renderer accessed'); } };
+ await expect(buildGoldenGateWorld(context as never)).rejects.toThrow('layout is missing');
+ const corrupt = Object.create(context), badLayout = authored(); badLayout.dressing.plaza.canopy = null as never; corrupt.pack = pack(badLayout);
+ await expect(buildGoldenGateWorld(corrupt)).rejects.toThrow('dressing.plaza.canopy');
+ const cancelled = new AbortController(); cancelled.abort(new Error('cancelled before world'));
+ const aborted = Object.create(context); aborted.signal = cancelled.signal;
+ await expect(buildGoldenGateWorld(aborted)).rejects.toThrow('cancelled before world');
+});
+
+test('the pre-load camera and tier clip planes exactly match admitted runtime data', async () => {
+ await import('three');
+ const { goldenGateDefinition } = await import('../../src/definition');
+ const { goldenGateTiers } = await import('../../src/tiers');
+ const { classifyDevice, resolveTier } = await import('@kiln-scenes/scene-kit');
+ const layout = readGoldenGateLayout(pack(authored()), signal()), pose = layout.cameras.named[layout.cameras.default]!;
+ expect(goldenGateDefinition.camera).toEqual({ position: pose.position, fov: pose.fov, near: layout.cameras.clip.near, far: layout.cameras.clip.far });
+ const { device } = classifyDevice({ backend: 'webgpu', hardwareConcurrency: 8, devicePixelRatio: 1, screenWidth: 1920, screenHeight: 1080,
+ coarsePointer: false, mobileUA: false, saveData: false, prefersReducedMotion: false }, goldenGateTiers);
+ for (const tier of goldenGateTiers.order) expect(resolveTier(goldenGateTiers, tier, device).drawDistance.far).toBe(layout.cameras.clip.far);
+});
+
+test('fog and flight constructors consume independent runtime layout values', async () => {
+ await import('three');
+ const { DataTexture } = await import('three/webgpu');
+ const { createFogBanks } = await import('../../src/world/fog-banks');
+ const { createAtmosphereUniforms } = await import('../../src/world/fog');
+ const { flightPaths } = await import('../../src/camera/flights');
+ const a = authored(), b = authored(); a.fogBanks.banks[0]!.puffs = 2; b.fogBanks.banks[0]!.puffs = 5;
+ b.flights.paths[0]!.keys[0]!.position[1] += 100;
+ const noise = new DataTexture(), first = createFogBanks(createAtmosphereUniforms(), noise, 1, a.fogBanks), second = createFogBanks(createAtmosphereUniforms(), noise, 1, b.fogBanks);
+ try {
+ expect([first.puffs, second.puffs]).toEqual([2, 5]);
+ expect(flightPaths(b)[0]!.keys[0]!.position[1] - flightPaths(a)[0]!.keys[0]!.position[1]).toBe(100);
+ } finally { first.dispose(); second.dispose(); noise.dispose(); }
+});
diff --git a/scenes/packages/golden-gate/tests/unit/lights.test.ts b/scenes/packages/golden-gate/tests/unit/lights.test.ts
index 0b72dbd3..7d962c5a 100644
--- a/scenes/packages/golden-gate/tests/unit/lights.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/lights.test.ts
@@ -5,7 +5,7 @@
// taper; every standard near, those up to station `far` in the far representation; the pole on the barrier's top
// and the lens at its mounting height over the shoulder.
import { describe, expect, test } from 'bun:test';
-import { LAYOUT } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
import { horizontalProject } from '../../src/world/alignment';
import { approachArrays } from '../../src/world/approach-mesh';
import type { MeshArrays } from '../../src/world/approach-mesh';
diff --git a/scenes/packages/golden-gate/tests/unit/marin-cut.test.ts b/scenes/packages/golden-gate/tests/unit/marin-cut.test.ts
index 906bcb48..64292496 100644
--- a/scenes/packages/golden-gate/tests/unit/marin-cut.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/marin-cut.test.ts
@@ -5,7 +5,7 @@
// envelope unchanged on the other side and outside the cut's stations; the clip grid's columns at the profile's
// edges; the scrub weight only where the cut lowers the terrain; and the toe wall in the near mesh only.
import { describe, expect, test } from 'bun:test';
-import { LAYOUT } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
import { horizontalProject } from '../../src/world/alignment';
import { approachArrays } from '../../src/world/approach-mesh';
import { approachCorridorPlans, applyCorridors, bedDepth, corridorHeight, cutProfile, cutWeight } from '../../src/world/corridor';
diff --git a/scenes/packages/golden-gate/tests/unit/prewarm-contact-shadows.test.ts b/scenes/packages/golden-gate/tests/unit/prewarm-contact-shadows.test.ts
new file mode 100644
index 00000000..7e9fb309
--- /dev/null
+++ b/scenes/packages/golden-gate/tests/unit/prewarm-contact-shadows.test.ts
@@ -0,0 +1,105 @@
+import { expect, test } from 'bun:test';
+import { BackSide, BufferAttribute, DoubleSide, Fog, FrontSide, Group, InstancedBufferAttribute, InstancedBufferGeometry, Mesh, MeshBasicNodeMaterial, PerspectiveCamera, Scene } from 'three/webgpu';
+import type { Object3D, WebGPURenderer } from 'three/webgpu';
+import { prewarmContactShadows } from '../../src/world/prewarm-contact-shadows';
+
+function fixture() {
+ const scene = new Scene(), traffic = new Group(), camera = new PerspectiveCamera();
+ scene.fog = new Fog(0, 10, 100); scene.add(traffic); camera.layers.enable(2);
+ const geometry = new InstancedBufferGeometry();
+ geometry.setAttribute('position', new BufferAttribute(new Float32Array([-1, 0, -1, 1, 0, -1, 1, 0, 1, -1, 0, 1]), 3));
+ for (const name of ['sA', 'sB']) geometry.setAttribute(name, new InstancedBufferAttribute(new Float32Array(8), 4));
+ geometry.setIndex([0, 1, 2, 0, 2, 3]); geometry.instanceCount = 0;
+ const material = new MeshBasicNodeMaterial({ name: 'golden-gate-contact-shadows', side: DoubleSide, transparent: true, depthWrite: false });
+ const target = new Mesh(geometry, material); target.name = 'traffic-contact-shadows'; target.visible = false; target.frustumCulled = false; target.layers.set(2); traffic.add(target);
+ let geometryDisposed = 0, materialDisposed = 0;
+ geometry.addEventListener('dispose', () => geometryDisposed++); material.addEventListener('dispose', () => materialDisposed++);
+ const renderer = (compile: (object: Object3D, camera: PerspectiveCamera, scene: Scene) => Promise<void>, webgpu = true) => ({ backend: { isWebGPUBackend: webgpu }, compileAsync: compile }) as unknown as WebGPURenderer;
+ return { scene, traffic, camera, target, geometry, material, renderer, sharedDisposals: () => [geometryDisposed, materialDisposed], dispose() { geometry.dispose(); material.dispose(); } };
+}
+
+test('warms only serialized back/front proxies in the actual scene, retaining their cache owners until disposal', async () => {
+ const f = fixture(), abort = new AbortController(), seen: Mesh[] = [], sides: number[] = [], disposed: string[] = [];
+ f.material.needsUpdate = true;
+ const originalVersion = f.material.version, originalIndex = f.geometry.index, originalArrays = Object.values(f.geometry.attributes).map(attribute => attribute.array), fog = f.scene.fog;
+ let finishFirst!: () => void; const first = new Promise<void>(resolve => { finishFirst = resolve; });
+ const renderer = f.renderer(async (object, camera, scene) => {
+ const proxy = object as Mesh; seen.push(proxy); sides.push(f.material.side);
+ expect(proxy).not.toBe(f.target); expect(proxy.parent).toBeNull(); expect(proxy.children).toHaveLength(0);
+ expect(proxy.geometry).toBe(f.geometry); expect(proxy.material).toBe(f.material); expect(proxy.visible).toBe(true);
+ expect(proxy.frustumCulled).toBe(false); expect(proxy.layers.mask).toBe(f.target.layers.mask);
+ expect(camera).toBe(f.camera); expect(scene).toBe(f.scene); expect(scene.fog).toBe(fog);
+ expect(f.target.visible).toBe(false); expect(f.target.parent).toBe(f.traffic);
+ proxy.addEventListener('dispose', () => disposed.push(proxy.uuid));
+ if (seen.length === 1) await first;
+ });
+ try {
+ const pending = prewarmContactShadows(renderer, f.traffic, f.scene, f.camera, abort.signal);
+ expect(seen).toHaveLength(1); expect(sides).toEqual([BackSide]); expect(disposed).toEqual([]);
+ finishFirst(); const prepared = await pending;
+ expect(seen).toHaveLength(2); expect(seen[0]).not.toBe(seen[1]); expect(sides).toEqual([BackSide, FrontSide]);
+ expect(f.material.side).toBe(DoubleSide); expect(f.material.version).toBe(originalVersion);
+ expect(f.geometry.index).toBe(originalIndex); expect(Object.values(f.geometry.attributes).map(attribute => attribute.array)).toEqual(originalArrays);
+ expect(f.traffic.children).toEqual([f.target]); expect(f.geometry.instanceCount).toBe(0); expect(disposed).toEqual([]);
+ prepared.dispose(); prepared.dispose(); expect(disposed).toEqual(seen.map(proxy => proxy.uuid)); expect(f.sharedDisposals()).toEqual([0, 0]);
+ } finally { finishFirst(); f.dispose(); }
+});
+
+test('leaves value-preserving backend index initialization intact without rewinding the material version', async () => {
+ const f = fixture(), index = f.geometry.index!, values = Array.from(index.array), version = f.material.version;
+ try {
+ const prepared = await prewarmContactShadows(f.renderer(async () => { index.array = new Uint32Array(index.array); }), f.traffic, f.scene, f.camera, new AbortController().signal);
+ expect(index.array).toBeInstanceOf(Uint32Array); expect(Array.from(index.array)).toEqual(values); expect(f.geometry.index).toBe(index);
+ expect(f.material.side).toBe(DoubleSide); expect(f.material.version).toBe(version); prepared.dispose(); expect(f.sharedDisposals()).toEqual([0, 0]);
+ } finally { f.dispose(); }
+});
+
+test('aborting before preparation allocates no proxies and preserves the caller reason', async () => {
+ const f = fixture(), abort = new AbortController(), reason = new Error('world abandoned'); abort.abort(reason); let calls = 0;
+ try { await expect(prewarmContactShadows(f.renderer(async () => { calls++; }), f.traffic, f.scene, f.camera, abort.signal)).rejects.toBe(reason); expect(calls).toBe(0); expect(f.sharedDisposals()).toEqual([0, 0]); }
+ finally { f.dispose(); }
+});
+
+test('an abort during compilation awaits that compile, releases its proxy and never starts the other side', async () => {
+ const f = fixture(), abort = new AbortController(), reason = new Error('world replaced'), seen: Object3D[] = [], disposed: Object3D[] = [];
+ let settle!: () => void; const blocked = new Promise<void>(resolve => { settle = resolve; });
+ try {
+ const pending = prewarmContactShadows(f.renderer(async object => { seen.push(object); object.addEventListener('dispose', () => disposed.push(object)); await blocked; }), f.traffic, f.scene, f.camera, abort.signal);
+ expect(seen).toHaveLength(1); abort.abort(reason); expect(disposed).toEqual([]); settle();
+ await expect(pending).rejects.toBe(reason); expect(seen).toHaveLength(1); expect(disposed).toEqual(seen);
+ expect(f.material.side).toBe(DoubleSide); expect(f.material.version).toBe(0); expect(f.sharedDisposals()).toEqual([0, 0]);
+ } finally { settle(); f.dispose(); }
+});
+
+test('an abort completing the second side also releases both retained proxies', async () => {
+ const f = fixture(), abort = new AbortController(), reason = new Error('world abandoned during front compile'), seen: Object3D[] = [], disposed: Object3D[] = [];
+ try {
+ await expect(prewarmContactShadows(f.renderer(async object => {
+ seen.push(object); object.addEventListener('dispose', () => disposed.push(object));
+ if (f.material.side === FrontSide) abort.abort(reason);
+ }), f.traffic, f.scene, f.camera, abort.signal)).rejects.toBe(reason);
+ expect(seen).toHaveLength(2); expect(disposed).toEqual(seen); expect(f.material.side).toBe(DoubleSide); expect(f.sharedDisposals()).toEqual([0, 0]);
+ } finally { f.dispose(); }
+});
+
+for (const failedSide of [BackSide, FrontSide]) test(`compile failure on side ${failedSide} is contextual and releases only preparation proxies`, async () => {
+ const f = fixture(), failure = new Error('driver rejected shader'), seen: Object3D[] = [], disposed: Object3D[] = [];
+ try {
+ let caught: unknown;
+ try { await prewarmContactShadows(f.renderer(async object => { seen.push(object); object.addEventListener('dispose', () => disposed.push(object)); if (f.material.side === failedSide) throw failure; }), f.traffic, f.scene, f.camera, new AbortController().signal); }
+ catch (error) { caught = error; }
+ expect(caught).toBeInstanceOf(Error); expect((caught as Error).message).toContain('Golden Gate contact-shadow'); expect((caught as Error).cause).toBe(failure);
+ expect(disposed).toEqual(seen); expect(seen).toHaveLength(failedSide === BackSide ? 1 : 2);
+ expect(f.material.side).toBe(DoubleSide); expect(f.material.version).toBe(0); expect(f.target.parent).toBe(f.traffic); expect(f.sharedDisposals()).toEqual([0, 0]);
+ } finally { f.dispose(); }
+});
+
+test('tiers without contact shadows and the WebGL fallback do not compile unrelated world objects', async () => {
+ const f = fixture(); let calls = 0;
+ try {
+ (await prewarmContactShadows(f.renderer(async () => { calls++; }, false), f.traffic, f.scene, f.camera, new AbortController().signal)).dispose();
+ f.target.removeFromParent(); f.traffic.add(new Group());
+ (await prewarmContactShadows(f.renderer(async () => { calls++; }), f.traffic, f.scene, f.camera, new AbortController().signal)).dispose();
+ expect(calls).toBe(0); expect(f.sharedDisposals()).toEqual([0, 0]);
+ } finally { f.dispose(); }
+});
diff --git a/scenes/packages/golden-gate/tests/unit/reflection-content.test.ts b/scenes/packages/golden-gate/tests/unit/reflection-content.test.ts
new file mode 100644
index 00000000..65c3b212
--- /dev/null
+++ b/scenes/packages/golden-gate/tests/unit/reflection-content.test.ts
@@ -0,0 +1,56 @@
+import { LAYOUT } from '../../scripts/authored-layout';
+import { expect, test } from 'bun:test';
+import { DataTexture, Layers, PerspectiveCamera, Scene, Texture } from 'three/webgpu';
+import type { Atmosphere } from '../../src/world/atmosphere';
+import { LAYERS } from '../../src/constants';
+import { FEATURES } from '../../src/tiers';
+import { createAtmosphereUniforms } from '../../src/world/fog';
+import { createFogBanks } from '../../src/world/fog-banks';
+import type { WaterMapLevel } from '../../src/world/water-maps';
+await import('three');
+const { createWater } = await import('../../src/world/water');
+
+test('High reflections exclude traffic, player and fog layers while retaining world vegetation and reflection stand-ins', () => {
+ for (const standIns of [false, true]) {
+ const scene = new Scene(), environment = new Texture();
+ const level = (): WaterMapLevel => ({ level: 'test', bounds: [-10, -10, 10, 10], size: [2, 2], texture: new DataTexture() });
+ const water = createWater(scene, {
+ features: { ...FEATURES.high.water, grid: 1, levels: 1 },
+ atmosphere: { uniforms: createAtmosphereUniforms(), environment } as Atmosphere,
+ near: level(), mid: level(), midGrid: { bounds: [-10, -10, 10, 10], width: 2, height: 2, depth: new Float32Array(4).fill(2), shore: new Float32Array(4).fill(2) },
+ passLayers: standIns ? { main: LAYERS.mainOnly, pass: LAYERS.reflectionOnly } : undefined,
+ });
+ try {
+ const camera = new PerspectiveCamera(); camera.layers.enable(LAYERS.water); camera.layers.enable(LAYERS.dynamic); camera.layers.enable(7);
+ if (standIns) camera.layers.enable(LAYERS.mainOnly);
+ const mask = camera.layers.mask, virtual = water.reflectionCamera(camera)!;
+ const objectLayers = (layer: number) => { const layers = new Layers(); layers.set(layer); return layers; };
+ expect(virtual.layers.test(objectLayers(LAYERS.dynamic))).toBe(false); // traffic, driven car and fog banks
+ expect(virtual.layers.test(objectLayers(LAYERS.world))).toBe(true); // terrain's vegetation cards remain reflected (D-71)
+ expect(virtual.layers.isEnabled(7)).toBe(true);
+ expect(virtual.layers.isEnabled(LAYERS.mainOnly)).toBe(false);
+ expect(virtual.layers.isEnabled(LAYERS.reflectionOnly)).toBe(standIns);
+ expect(camera.layers.mask).toBe(mask);
+ // Every call reapplies the policy, including another camera's newly cloned virtual camera.
+ virtual.layers.enable(LAYERS.dynamic);
+ expect(water.reflectionCamera(camera)!.layers.isEnabled(LAYERS.dynamic)).toBe(false);
+ const next = camera.clone(); expect(water.reflectionCamera(next)!.layers.isEnabled(LAYERS.dynamic)).toBe(false);
+ } finally { water.dispose(); environment.dispose(); }
+ }
+});
+
+test('fog-bank diagnostic hiding persists across updates and showing still respects weather opacity', () => {
+ const noise = new DataTexture(), banks = createFogBanks(createAtmosphereUniforms(), noise, 1, LAYOUT.fogBanks);
+ try {
+ expect(banks.hidden).toBe(false); expect(banks.puffs).toBeGreaterThan(0);
+ banks.update(0, .7); expect(banks.sprite.visible).toBe(true);
+ banks.hidden = true; expect(banks.sprite.visible).toBe(false);
+ banks.update(10, 1); banks.update(11, .7); expect(banks.sprite.visible).toBe(false);
+ banks.hidden = false; expect(banks.sprite.visible).toBe(true);
+ banks.update(12, 0); expect(banks.sprite.visible).toBe(false);
+ banks.hidden = true; banks.update(13, 0); banks.hidden = false;
+ expect(banks.sprite.visible).toBe(false);
+ banks.update(14, .8); expect(banks.sprite.visible).toBe(true);
+ expect(banks.sprite.layers.isEnabled(LAYERS.dynamic)).toBe(true);
+ } finally { banks.dispose(); noise.dispose(); }
+});
diff --git a/scenes/packages/golden-gate/tests/unit/reversed-depth.test.ts b/scenes/packages/golden-gate/tests/unit/reversed-depth.test.ts
new file mode 100644
index 00000000..def5b1e8
--- /dev/null
+++ b/scenes/packages/golden-gate/tests/unit/reversed-depth.test.ts
@@ -0,0 +1,64 @@
+import { expect, test } from 'bun:test';
+import { DataTexture, Matrix4, PerspectiveCamera, Scene, Texture, Vector3, WebGLCoordinateSystem, WebGPUCoordinateSystem } from 'three/webgpu';
+import type { Atmosphere } from '../../src/world/atmosphere';
+import { createAtmosphereUniforms } from '../../src/world/fog';
+import { FEATURES } from '../../src/tiers';
+import { goldenGateDefinition } from '../../src/definition';
+await import('three');
+const atmosphereModule = await import('../../src/world/atmosphere');
+const { createWater } = await import('../../src/world/water');
+
+test('Golden Gate opts in and its visible/environment skies draw first without depth testing or writing', () => {
+ expect(goldenGateDefinition.reversedDepthBuffer).toBe(true);
+ for (const environment of [false, true]) {
+ const sky = atmosphereModule.createSky(createAtmosphereUniforms(), environment);
+ expect(sky.renderOrder).toBeLessThan(0);expect(sky.material.depthTest).toBe(false);expect(sky.material.depthWrite).toBe(false);
+ sky.geometry.dispose();sky.material.dispose();
+ }
+});
+
+function fixture(scene: Scene) {
+ const environment=new Texture(), level=()=>({level:'test',bounds:[-10,-10,10,10] as [number,number,number,number],size:[2,2] as [number,number],texture:new DataTexture()});
+ const water=createWater(scene,{features:{...FEATURES.high.water,grid:2,levels:2,tile0:8},atmosphere:{uniforms:createAtmosphereUniforms(),environment} as Atmosphere,
+ near:level(),mid:level(),midGrid:{bounds:[-10,-10,10,10],width:2,height:2,depth:new Float32Array(4).fill(2),shore:new Float32Array(4).fill(2)}});
+ return {water,dispose(){water.dispose();environment.dispose();}};
+}
+function cameraAt(reversed: boolean, coordinateSystem: typeof WebGPUCoordinateSystem | typeof WebGLCoordinateSystem) {
+ const camera=new PerspectiveCamera(60,1,.5,160000);camera.coordinateSystem=coordinateSystem;
+ (camera as unknown as {_reversedDepth:boolean})._reversedDepth=reversed;
+ camera.position.set(20,50,100);camera.lookAt(0,0,0);camera.updateMatrixWorld();camera.updateProjectionMatrix();return camera;
+}
+test('reversed reflection clips below water, retains distant above-water geometry and preserves main/other passes', () => {
+ for (const coordinateSystem of [WebGPUCoordinateSystem,WebGLCoordinateSystem]) {
+ const scene=new Scene();let called=0;const prior=scene.onBeforeRender=()=>{called++;};const f=fixture(scene);
+ try {
+ const camera=cameraAt(true,coordinateSystem);f.water.update(camera,0);
+ const virtual=f.water.reflectionCamera(camera)! as PerspectiveCamera;
+ virtual.position.set(20,-50,100);virtual.up.set(0,-1,0);virtual.lookAt(0,0,0);virtual.updateMatrixWorld();
+ scene.updateMatrixWorld();const before=camera.projectionMatrix.clone();
+ const call=(c:PerspectiveCamera,reversedDepthBuffer=true)=>scene.onBeforeRender({reversedDepthBuffer} as never,scene,c,null as never);
+ call(camera);expect(camera.projectionMatrix.equals(before)).toBe(true);
+ const other=camera.clone(),otherBefore=other.projectionMatrix.clone();call(other);expect(other.projectionMatrix.equals(otherBefore)).toBe(true);
+ virtual.projectionMatrix.copy(camera.projectionMatrix);const untouched=virtual.projectionMatrix.clone();
+ call(virtual,false);expect(virtual.projectionMatrix.equals(untouched)).toBe(true);
+ call(virtual);
+ const z=(y:number,z=0)=>new Vector3(0,y,z).project(virtual).z;
+ expect(z(0)).toBeCloseTo(1,9);expect(z(-10)).toBeGreaterThan(1);
+ expect(z(10)).toBeGreaterThan(0);expect(z(10)).toBeLessThan(1);
+ expect(z(10,-10000)).toBeGreaterThan(0);expect(z(10,-10000)).toBeLessThan(1);
+ expect(new Matrix4().multiplyMatrices(virtual.projectionMatrix,virtual.projectionMatrixInverse).elements.every((v,i)=>Math.abs(v-(i%5===0?1:0))<1e-8)).toBe(true);
+ expect(camera.projectionMatrix.equals(before)).toBe(true);expect(called).toBe(4);
+ }finally{f.dispose();expect(scene.onBeforeRender).toBe(prior);}
+ }
+});
+
+test('water tile visibility respects both backend depth conventions including reversed near/far planes', () => {
+ const scene=new Scene(),f=fixture(scene),counts:number[]=[];
+ try {
+ for(const system of [WebGLCoordinateSystem,WebGPUCoordinateSystem]) for(const reversed of [false,true]) {
+ const camera=cameraAt(reversed,system);camera.position.set(0,10,0);camera.lookAt(0,0,-10);camera.near=4;camera.far=15;camera.updateMatrixWorld();camera.updateProjectionMatrix();
+ f.water.update(camera,0);counts.push(f.water.stats.tiles);
+ }
+ expect(counts[0]).toBeGreaterThan(0);expect(counts).toEqual(Array(4).fill(counts[0]));
+ }finally{f.dispose();}
+});
diff --git a/scenes/packages/golden-gate/tests/unit/route.test.ts b/scenes/packages/golden-gate/tests/unit/route.test.ts
index 37045514..67028ede 100644
--- a/scenes/packages/golden-gate/tests/unit/route.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/route.test.ts
@@ -6,7 +6,7 @@
// end grade (the Roadway itself is checked by scripts/layout.ts --check and tests/tools/drive-check.ts).
import { describe, expect, test } from 'bun:test';
import { LANES, laneX } from '../../src/constants';
-import { LAYOUT } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
import { lanePose, laneStation, TRAFFIC_FLOW } from '../../src/traffic/config';
import { checkProfile, horizontalAt, horizontalProject, lateral, profileAt } from '../../src/world/alignment';
import type { RoadGrid } from '../../src/world/road';
diff --git a/scenes/packages/golden-gate/tests/unit/vegetation.test.ts b/scenes/packages/golden-gate/tests/unit/vegetation.test.ts
index 77a7fa3a..ea4c010f 100644
--- a/scenes/packages/golden-gate/tests/unit/vegetation.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/vegetation.test.ts
@@ -7,7 +7,8 @@
import { describe, expect, test } from 'bun:test';
import { MeshStandardNodeMaterial, Vector3 } from 'three/webgpu';
import type { InstancedBufferGeometry } from 'three/webgpu';
-import { LAYOUT, TIER_DATA } from '../../src/data';
+import { TIER_DATA } from '../../src/data';
+import { LAYOUT } from '../../scripts/authored-layout';
import { horizontalProject } from '../../src/world/alignment';
import { polygonDistance, sideWidening } from '../../src/world/dressing';
import { buildApproach } from '../../src/world/route';
diff --git a/scenes/packages/golden-gate/tests/unit/vehicle-models.test.ts b/scenes/packages/golden-gate/tests/unit/vehicle-models.test.ts
index 1c5cffb4..5d9b7476 100644
--- a/scenes/packages/golden-gate/tests/unit/vehicle-models.test.ts
+++ b/scenes/packages/golden-gate/tests/unit/vehicle-models.test.ts
@@ -1,20 +1,20 @@
import { describe, expect, test } from 'bun:test';
-import { existsSync, readFileSync } from 'node:fs';
+import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import type { GLTF } from 'three/addons/loaders/GLTFLoader.js';
-import { createHash } from 'node:crypto';
import { extractVehicle, LAMP_KIND, VEHICLE_TYPES, VERTEX_LAYOUT, VERTEX_STRIDE, WHEEL_KIND } from '../../src/traffic/vehicle-models';
import type { VehicleType } from '../../src/traffic/vehicle-models';
import { VEHICLE_PROVENANCE } from '../../scripts/stage';
import { stagedDir } from '../../scripts/release';
+import { findSceneFixture } from '../../../../scripts/release-inputs';
-// The approved vehicle GLBs (pinned bytes in scripts/stage.ts): the staged copy, or the author's
-// file while it is still the approved one (read-only inputs, the folders the staging script reads).
+// The approved vehicle GLBs (pinned bytes in scripts/stage.ts): restored release first; optional local runs
+// may use identical staged or author files. test:release-inputs requires the restored release.
const PACKAGE = resolve(import.meta.dir, '../..'), COMMONS = resolve(PACKAGE, '../../..');
const ROOTS = ['showcase/authors/sonnet-vehicles-a/outputs', 'showcase/authors/sonnet-vehicles-b/outputs'].map(r => resolve(COMMONS, r));
-const approved = (path: string, type: VehicleType) => existsSync(path) && createHash('sha256').update(readFileSync(path)).digest('hex') === VEHICLE_PROVENANCE[type].sha256;
-const source = (type: VehicleType) => [resolve(stagedDir(), 'vehicles', `${type}.glb`), ...ROOTS.map(root => resolve(root, type, `${type}.glb`))].find(path => approved(path, type));
+const source = (type: VehicleType) => findSceneFixture({ scene: 'golden-gate', path: `vehicles/${type}.glb`, sha256: VEHICLE_PROVENANCE[type].sha256 },
+ { fallback: [resolve(stagedDir(), 'vehicles', `${type}.glb`), ...ROOTS.map(root => resolve(root, type, `${type}.glb`))] });
const available = VEHICLE_TYPES.every(type => source(type));
async function load(type: VehicleType): Promise<GLTF> {
diff --git a/scenes/packages/golden-gate/tests/unit/water-origin.test.ts b/scenes/packages/golden-gate/tests/unit/water-origin.test.ts
new file mode 100644
index 00000000..cc2f48e2
--- /dev/null
+++ b/scenes/packages/golden-gate/tests/unit/water-origin.test.ts
@@ -0,0 +1,165 @@
+import { afterAll, expect, test } from 'bun:test';
+import { DataTexture, Texture } from 'three/webgpu';
+import { getCurrentStack, setCurrentStack, stack } from 'three/tsl';
+import { createAtmosphereUniforms } from '../../src/world/fog';
+import { createWaterMaterial, createWaterUniforms, DETAIL_LAYERS, GERSTNER_WAVES, ORIGIN_SNAP, updateWaterUniforms, waveConstants } from '../../src/world/water-material';
+
+// Inspect real TSL arithmetic, without compiling/rendering it or copying the shader expression.
+// Three's shader graph has heterogeneous node fields which its public typings do not describe.
+type GraphNode = any; // eslint-disable-line @typescript-eslint/no-explicit-any
+const uniforms = createWaterUniforms(), maps = new DataTexture(), slopes = new DataTexture(), macro = new DataTexture(), environment = new Texture();
+const bounds: [number, number, number, number] = [-1000, -1000, 1000, 1000];
+const material = createWaterMaterial({ atmosphere: createAtmosphereUniforms(), grid: 8,
+ displacedWaves: GERSTNER_WAVES.length, fragmentWaves: GERSTNER_WAVES.length,
+ // Isolate the foam's slope-map lookup from the optional normal-detail layers.
+ detailLayers: 0, reflection: 'environment', environment, depthContact: false,
+ near: { texture: maps, bounds }, mid: { texture: maps, bounds }, flow: { texture: maps, bounds }, slopeMoments: slopes, macroNoise: macro }, uniforms);
+afterAll(() => { material.dispose(); for (const texture of [maps, slopes, macro, environment]) texture.dispose(); });
+
+function graph(entry: GraphNode): GraphNode[] {
+ while (entry.isVarNode) entry = entry.node;
+ const previous = getCurrentStack(), scope = stack();
+ let result: GraphNode;
+ setCurrentStack(scope);
+ try { result = entry.shaderNode.jsFunc(); } finally { setCurrentStack(previous); }
+ const seen = new Set<GraphNode>();
+ const visit = (node: GraphNode) => {
+ if (!node?.isNode || seen.has(node)) return;
+ seen.add(node); for (const child of node.getChildren()) visit(child);
+ };
+ visit(result); visit(scope);
+ return [...seen];
+}
+const stages = { vertex: graph(material.positionNode), fragment: graph(material.colorNode) };
+
+/** Evaluate the small arithmetic subgraph at a fixed, already-morphed world surface point.
+ * The vertex's p-origin and fragment's vWaterRel represent that same surface parameter.
+ * Texture sampling, perspective footprint filtering and shading are outside this CPU test. */
+function evaluate(node: GraphNode, world: readonly [number, number]): number[] {
+ const rel = () => [world[0] - uniforms.origin.value.x, world[1] - uniforms.origin.value.y];
+ if (node.isVaryingNode && node.name === 'vWaterRel') return rel();
+ if (node.isOperatorNode && node.op === '-' && node.bNode === uniforms.origin) return rel();
+ if (node.isVarNode || node.isConvertNode) return evaluate(node.node, world);
+ if (node.isConstNode || node.isUniformNode) return typeof node.value === 'number' ? [node.value] : node.value.toArray();
+ if (node.isSplitNode) {
+ const value = evaluate(node.node, world);
+ return [...node.components].map(component => value['xyzw'.indexOf(component)]!);
+ }
+ if (node.isOperatorNode) {
+ const a = evaluate(node.aNode, world), b = evaluate(node.bNode, world);
+ return Array.from({ length: Math.max(a.length, b.length) }, (_, i) => {
+ const left = a[a.length === 1 ? 0 : i]!, right = b[b.length === 1 ? 0 : i]!;
+ if (node.op === '+') return left + right;
+ if (node.op === '-') return left - right;
+ if (node.op === '*') return left * right;
+ if (node.op === '/') return left / right;
+ throw new Error(`Unsupported arithmetic ${node.op}`);
+ });
+ }
+ throw new Error(`Unexpected coordinate graph node ${node.constructor.name}`);
+}
+function waveNodes(stage: keyof typeof stages): GraphNode[] {
+ return uniforms.phases.map(phase => {
+ const matches = stages[stage].filter(node => node.isOperatorNode && (node.aNode === phase || node.bNode === phase));
+ expect(matches).toHaveLength(1);
+ return matches[0]!;
+ });
+}
+const world: readonly [number, number] = [73.25, -619.5];
+const crossings = [
+ [[ORIGIN_SNAP / 2 - .001, 0], [ORIGIN_SNAP / 2 + .001, 0]],
+ [[-ORIGIN_SNAP / 2 - .001, 0], [-ORIGIN_SNAP / 2 + .001, 0]],
+ [[0, ORIGIN_SNAP / 2 - .001], [0, ORIGIN_SNAP / 2 + .001]],
+ [[0, -ORIGIN_SNAP / 2 - .001], [0, -ORIGIN_SNAP / 2 + .001]],
+] as const;
+
+for (const stage of ['vertex', 'fragment'] as const) {
+ test(`${stage} wave phases at a fixed world point survive every camera-origin snap`, () => {
+ const nodes = waveNodes(stage);
+ for (const [before, after] of crossings) {
+ updateWaterUniforms(uniforms, 17.25, ...before);
+ const first = nodes.map(node => evaluate(node, world)[0]!);
+ updateWaterUniforms(uniforms, 17.25, ...after);
+ nodes.forEach((node, i) => {
+ const second = evaluate(node, world)[0]!;
+ expect(Math.sin(second)).toBeCloseTo(Math.sin(first[i]!), 9);
+ expect(Math.cos(second)).toBeCloseTo(Math.cos(first[i]!), 9);
+ });
+ }
+ });
+
+ test(`${stage} waves propagate along their declared direction`, () => {
+ const nodes = waveNodes(stage), time = 5.75, dt = .13;
+ updateWaterUniforms(uniforms, time, 0, 0);
+ const first = nodes.map(node => evaluate(node, world)[0]!);
+ updateWaterUniforms(uniforms, time + dt, 0, 0);
+ nodes.forEach((node, i) => {
+ const { omega } = waveConstants(GERSTNER_WAVES[i]!);
+ const change = evaluate(node, world)[0]! - first[i]!;
+ // Constant phase moves in +direction only for k dot p - omega*t.
+ expect(Math.sin(change)).toBeCloseTo(Math.sin(-omega * dt), 9);
+ expect(Math.cos(change)).toBeCloseTo(Math.cos(-omega * dt), 9);
+ });
+ });
+
+ test(`${stage} phase wrapping stays world-anchored across distant origin cells`, () => {
+ const nodes = waveNodes(stage), tau = 2 * Math.PI;
+ // Includes negative cells and a numerical stress case at the clipmap's ~130 km extent.
+ // This checks CPU compensation arithmetic, not GPU float precision or camera reachability.
+ for (const [ox, oz] of [[0, 0], [-16 * ORIGIN_SNAP, 16 * ORIGIN_SNAP], [512 * ORIGIN_SNAP, -512 * ORIGIN_SNAP]]) {
+ const point: readonly [number, number] = [ox! + 37.25, oz! - 19.5];
+ nodes.forEach((node, i) => {
+ const { k, dx, dz, omega } = waveConstants(GERSTNER_WAVES[i]!);
+ const originPhase = k * (dx * ox! + dz * oz!);
+ // Straddle an actual CPU phase wrap after four hours of scene time while
+ // also crossing an origin boundary. Continuity must not rely on either wrap aligning.
+ const turns = Math.floor((originPhase - omega * 14400) / tau);
+ const wrapTime = (originPhase - turns * tau) / omega;
+ for (const delta of [-.0001, .0001]) {
+ const time = wrapTime + delta;
+ updateWaterUniforms(uniforms, time, ox! + ORIGIN_SNAP / 2 + delta, oz!);
+ const actual = evaluate(node, point)[0]!, expected = k * (dx * point[0] + dz * point[1]) - omega * time;
+ expect(Math.sin(actual)).toBeCloseTo(Math.sin(expected), 8);
+ expect(Math.cos(actual)).toBeCloseTo(Math.cos(expected), 8);
+ expect(uniforms.phases[i]!.value).toBeGreaterThanOrEqual(0);
+ expect(uniforms.phases[i]!.value).toBeLessThan(tau);
+ }
+ });
+ }
+ });
+}
+
+test('foam-breakup texture coordinates at a fixed world point survive camera-origin snaps', () => {
+ const lookups = stages.fragment.filter(node => node.isTextureNode && node.value === slopes);
+ expect(lookups).toHaveLength(1);
+ const uv = lookups[0]!.uvNode;
+ for (const [before, after] of crossings) {
+ updateWaterUniforms(uniforms, 17.25, ...before); const first = evaluate(uv, world);
+ updateWaterUniforms(uniforms, 17.25, ...after); const second = evaluate(uv, world);
+ // RepeatWrapping permits integer shifts, never a different texel phase.
+ for (let axis = 0; axis < 2; axis++) {
+ const delta = second[axis]! - first[axis]!;
+ expect(delta - Math.round(delta)).toBeCloseTo(0, 9);
+ }
+ }
+});
+
+test('foam-breakup keeps its unrotated tile and time drift through offset wraps and distant origins', () => {
+ const uv = stages.fragment.find(node => node.isTextureNode && node.value === slopes)!.uvNode;
+ const layer = DETAIL_LAYERS[0]!, angle = layer.rotation * Math.PI / 180;
+ for (const [ox, oz] of [[0, 0], [-4096, 4096], [131072, -131072]]) {
+ const point: readonly [number, number] = [ox! + world[0], oz! + world[1]];
+ const rate = layer.drift * Math.cos(angle) / layer.tile;
+ const wrapTime = (Math.ceil(ox! / 7.3 + rate * 14400) - ox! / 7.3) / rate;
+ for (const time of [0, 12, wrapTime - .0001, wrapTime + .0001]) {
+ updateWaterUniforms(uniforms, time, ox!, oz!);
+ const actual = evaluate(uv, point);
+ const expected = [point[0] / 7.3 + layer.drift * time * Math.cos(angle) / layer.tile,
+ point[1] / 7.3 + layer.drift * time * Math.sin(angle) / layer.tile];
+ for (let axis = 0; axis < 2; axis++) {
+ const delta = actual[axis]! - expected[axis]!;
+ expect(delta - Math.round(delta)).toBeCloseTo(0, 9);
+ }
+ }
+ }
+});
diff --git a/scenes/packages/scene-kit/README.md b/scenes/packages/scene-kit/README.md
index 8a0c3460..948bd597 100644
--- a/scenes/packages/scene-kit/README.md
+++ b/scenes/packages/scene-kit/README.md
@@ -127,6 +127,8 @@ The kit owns the only R3F `useFrame` registration. Add imperative work with `use
Use `InputProvider`, `useInput`, `VirtualJoystick` and `TouchButtons` for root-scoped keyboard/pointer handling and named actions. For driving on touch (D-22), `VirtualJoystick axes="throttle"` is the only driving input: `move.y` is a signed throttle (forward accelerates, back brakes or reverses) and `move.x` steers, each with its own dead zone. Pinch and the wheel accumulate into `input.state.zoom` each frame. Native HUD controls keep their keyboard behavior. Tab is never captured; Escape leaves play before a subsequent Escape can reach the page. `OrbitRig` and `FollowRig` scope their OrbitControls listeners to the scene root and canvas, including the addon’s pointer-capture and Control-key tracking.
+Custom movement controls can pass a stable owner object to `input.setMove(x, y, run, owner)` and call `input.releaseMove(owner)` on release, cancellation or unmount. Cleanup then clears only that control's latest contribution. Keyboard movement and unowned `setMove` calls supersede the old owner; `clear()`, disable and disposal invalidate all movement. `VirtualJoystick` uses this ownership contract so hiding it cannot erase the first keyboard movement.
+
`usePlayMode()` exposes the root’s shared `{ playing, setPlaying }` state. Use it to drive the scene’s simulation, camera mode and HUD together, so Enter on the root and the first Escape control the same mode. `useSceneRootRef()` exposes the focus target and the element for any additional scene-local listeners:
```tsx
@@ -144,6 +146,10 @@ function PlayButton() {
`SceneRoot` already supplies the normal root input bindings. To declare extra named actions, call `useInput().configureActions(...)` in an effect. Avoid wrapping the same root in another `InputProvider`, which would duplicate its bindings.
+`HudLayer` establishes the containing block for the default fixed help and credits panels, so a short positioned toolbar does not collapse their scroll area. Panels receive pointer events and stack above the kit's touch controls; a scene that creates its own stacking contexts must keep its panel layer above its play controls. Scene CSS can still choose an inline panel (`position: static`), a bottom sheet, or other placement. Nested `VirtualJoystick` and `TouchButtons` receive input even under a layer with `pointer-events: none`; no scene-specific pointer override is needed.
+
+Run `bun packages/scene-kit/tests/browser/run-hud-layout.ts` from `scenes/` for the DOM-only panel and touch contract. It uses real kit controls with the current Farm, Golden Gate and Foundry styles at embedded narrow, short and desktop sizes, checking scrolling, stacking, Tab/Escape focus, touch movement/release and click-through. It does not replace the scenes' full browser or physical-device qualification.
+
`PathRig` provides linear or centripetal Catmull-Rom paths, seeking and interruption. On interruption, activate `OrbitRig` and pass the supplied pose to `rigRef.current.setView(pose)` for a continuous hand-back. `VehicleRig` uses a critically damped chase camera and five obstruction rays. The demo shows all four rigs and a BVH-backed capsule, door and vehicle.
## Quality and the r186 DPR fallback
diff --git a/scenes/packages/scene-kit/demo/stage-demo.ts b/scenes/packages/scene-kit/demo/stage-demo.ts
index 0c23c49b..9fdd646d 100644
--- a/scenes/packages/scene-kit/demo/stage-demo.ts
+++ b/scenes/packages/scene-kit/demo/stage-demo.ts
@@ -45,7 +45,7 @@ for (const [name, bytes] of authored) writeFileSync(resolve(input, name), bytes)
const destinations: Record<string, string> = { 'amber.glb': 'models/amber.glb', 'blue.glb': 'models/blue.glb', 'cell.glb': 'cells/0-0-0.glb', 'layout.json': 'data/layout.json', 'LICENSE.txt': 'licenses/ASSET-LICENSE.txt' };
const out = resolve(demo, 'staged/assets');
const result = stageFiles({
- id: 'scene-kit-demo', release: 'synthetic-1', three: '0.186.0', out,
+ id: 'scene-kit-demo', release: 'synthetic-1', three: '0.186.1', out,
models: [{ id: 'amber', to: 'models/amber.glb' }, { id: 'blue', to: 'models/blue.glb' }], data: { layout: 'data/layout.json' },
files: [...authored].map(([name, bytes]) => ({ from: resolve(input, name), to: destinations[name]!, sha256: sha256Pure(bytes) })),
cells: [{ id: '0,0,0', center: [0, 0, 0], radius: 16, files: ['cells/0-0-0.glb'] }],
diff --git a/scenes/packages/scene-kit/package.json b/scenes/packages/scene-kit/package.json
index bf33a989..f75fff94 100644
--- a/scenes/packages/scene-kit/package.json
+++ b/scenes/packages/scene-kit/package.json
@@ -28,13 +28,13 @@
"react": "19.3.0",
"react-dom": "19.3.0",
"@react-three/fiber": "9.8.1",
- "three": "0.186.0"
+ "three": "0.186.1"
},
"devDependencies": {
"react": "19.3.0",
"react-dom": "19.3.0",
"@react-three/fiber": "9.8.1",
- "three": "0.186.0",
+ "three": "0.186.1",
"@types/three": "0.186.0"
}
}
diff --git a/scenes/packages/scene-kit/src/build/index.ts b/scenes/packages/scene-kit/src/build/index.ts
index be55d0cc..bf170156 100644
--- a/scenes/packages/scene-kit/src/build/index.ts
+++ b/scenes/packages/scene-kit/src/build/index.ts
@@ -1,6 +1,7 @@
import { defineConfig } from 'vite';
import type { Plugin, UserConfig } from 'vite';
import react from '@vitejs/plugin-react';
+import { sceneProducerReceipt } from './producer';
export type SceneBuildMode = 'public' | 'test' | 'dev';
export const SCENE_DEDUPE = ['three', 'react', 'react-dom', '@react-three/fiber'];
@@ -17,11 +18,16 @@ export function sceneSourceConfig(mode: SceneBuildMode = 'public'): UserConfig {
};
}
export function bundleModuleManifest(): Plugin {
- return { name: 'kiln-bundle-modules', generateBundle(_options, bundle) {
+ return { name: 'kiln-bundle-modules', generateBundle: { order: 'post', handler(_options, bundle) {
const modules = new Set<string>();
- for (const chunk of Object.values(bundle)) if (chunk.type === 'chunk') for (const id of Object.keys(chunk.modules)) modules.add(id);
- this.emitFile({ type: 'asset', fileName: 'bundle-modules.json', source: JSON.stringify({ modules: [...modules].sort() }, null, 2) + '\n' });
- } };
+ const chunks: { file: string; code: string }[] = [];
+ for (const chunk of Object.values(bundle)) if (chunk.type === 'chunk') {
+ for (const id of Object.keys(chunk.modules)) modules.add(id);
+ chunks.push({ file: chunk.fileName, code: chunk.code });
+ }
+ const ordered = [...modules].sort();
+ this.emitFile({ type: 'asset', fileName: 'bundle-modules.json', source: JSON.stringify({ modules: ordered, producer: sceneProducerReceipt(ordered, chunks) }, null, 2) + '\n' });
+ } } };
}
export function sceneStandaloneConfig(options: { root: string; outDir: string; mode?: SceneBuildMode }): UserConfig {
const config = sceneSourceConfig(options.mode);
diff --git a/scenes/packages/scene-kit/src/build/producer.ts b/scenes/packages/scene-kit/src/build/producer.ts
new file mode 100644
index 00000000..83175169
--- /dev/null
+++ b/scenes/packages/scene-kit/src/build/producer.ts
@@ -0,0 +1,43 @@
+import { createHash } from 'node:crypto';
+import { existsSync, readFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { dirname, join } from 'node:path';
+
+const require = createRequire(import.meta.url);
+const DEPENDENCIES = ['three', 'react', 'react-dom', '@react-three/fiber'] as const;
+const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
+
+function packageVersion(name: string, root: string): string {
+ const metadata = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
+ if (metadata.name !== name || typeof metadata.version !== 'string' || !VERSION.test(metadata.version)) throw new Error(`Invalid producer package metadata for ${name}`);
+ return metadata.version;
+}
+
+function toolVersion(name: string): string {
+ let directory = dirname(require.resolve(name));
+ while (true) {
+ const path = join(directory, 'package.json');
+ if (existsSync(path) && JSON.parse(readFileSync(path, 'utf8')).name === name) return packageVersion(name, directory);
+ const parent = dirname(directory);
+ if (parent === directory) throw new Error(`Cannot identify the ${name} producer version`);
+ directory = parent;
+ }
+}
+
+/** Build-time evidence only: resolve dependencies from modules actually included, never declaration ranges. */
+export function sceneProducerReceipt(modules: readonly string[], chunks: readonly { file: string; code: string }[]) {
+ const roots = new Map<string, Set<string>>(DEPENDENCIES.map(name => [name, new Set<string>()]));
+ for (const id of modules) {
+ const root = /^(.*\/node_modules\/((?:@[^/]+\/)?[^/]+))\//.exec(id.replaceAll('\\', '/').split('?')[0]!);
+ if (root) roots.get(root[2]!)?.add(root[1]!);
+ }
+ const dependencies = Object.fromEntries([...roots].map(([name, copies]) => {
+ if (copies.size > 1) throw new Error(`Producer has multiple ${name} roots`);
+ return [name, copies.size ? packageVersion(name, [...copies][0]!) : null];
+ }));
+ return {
+ schema: 'kiln.scene-producer/1', dependencies,
+ build: { vite: toolVersion('vite'), pluginReact: toolVersion('@vitejs/plugin-react') },
+ chunks: chunks.map(({ file, code }) => ({ file, bytes: new TextEncoder().encode(code).length, sha256: createHash('sha256').update(code).digest('hex') })).sort((a, b) => a.file.localeCompare(b.file, 'en')),
+ };
+}
diff --git a/scenes/packages/scene-kit/src/camera/follow.ts b/scenes/packages/scene-kit/src/camera/follow.ts
new file mode 100644
index 00000000..4b276645
--- /dev/null
+++ b/scenes/packages/scene-kit/src/camera/follow.ts
@@ -0,0 +1,47 @@
+import { PerspectiveCamera, Vector3 } from 'three/webgpu';
+import type { Object3D } from 'three/webgpu';
+import type { FollowOptions, Pose, RigHandle } from './core';
+import { createOrbitController } from './orbit';
+
+export interface ManagedFollow { handle: RigHandle; update(): void; dispose(): void }
+export function createFollowController(camera: PerspectiveCamera, canvas: HTMLCanvasElement, root: HTMLElement, current: () => FollowOptions & { active: boolean }): ManagedFollow {
+ // OrbitControls reads its camera before every pointer/wheel update. Keep that desired pose
+ // separate: feeding it the collision-shortened view turns an ordinary drag into a zoom-in.
+ const desiredCamera = new PerspectiveCamera().copy(camera, false);
+ const orbit = createOrbitController(desiredCamera, canvas, root, () => ({ active: current().active, minDistance: current().minDistance, maxDistance: current().maxDistance, maxPolar: current().maxPolar, pan: false }));
+ const target = new Vector3(), previous = new Vector3(), delta = new Vector3(), offset = new Vector3();
+ const pose: Pose = { position: camera.position.toArray(), target: orbit.controls.target.toArray(), fov: camera.fov, roll: 0 };
+ let initialized = false, visible = true, subject: Object3D | null = null, targetHeight = current().targetHeight;
+ function update() {
+ const options = current(), nextSubject = options.subject.current;
+ orbit.controls.enabled = options.active;
+ if (!options.active || !nextSubject) { initialized = false; if (!visible) { visible = true; options.obstruction?.onSubjectVisible(true); } return; }
+ orbit.controls.minDistance = options.minDistance; orbit.controls.maxDistance = options.maxDistance;
+ nextSubject.getWorldPosition(target); target.y += options.targetHeight;
+ if (!initialized || subject !== nextSubject || targetHeight !== options.targetHeight) {
+ desiredCamera.position.copy(target).add(offset.fromArray(options.offset()));
+ desiredCamera.fov = options.fov; desiredCamera.updateProjectionMatrix(); orbit.controls.maxPolarAngle = options.maxPolar;
+ initialized = true; subject = nextSubject; targetHeight = options.targetHeight;
+ } else desiredCamera.position.add(delta.subVectors(target, previous));
+ previous.copy(target); orbit.controls.target.copy(target);
+ // User distance and polar bounds apply to the intended orbit, before collision pull-in.
+ orbit.controls.update(); orbit.sync(); offset.subVectors(desiredCamera.position, target);
+ const length = offset.length();
+ let distance = length;
+ if (options.obstruction) distance = Math.min(length, Math.max(options.obstruction.minDistance, options.obstruction.ray(target, desiredCamera.position) - options.obstruction.pad));
+ camera.position.copy(target).addScaledVector(offset, distance / Math.max(1e-9, length));
+ camera.quaternion.copy(desiredCamera.quaternion);
+ if (camera.fov !== desiredCamera.fov) { camera.fov = desiredCamera.fov; camera.updateProjectionMatrix(); }
+ camera.position.toArray(pose.position); target.toArray(pose.target); pose.fov = camera.fov;
+ const nextVisible = distance >= (options.obstruction?.hideSubjectBelow ?? 0);
+ if (visible !== nextVisible) { visible = nextVisible; options.obstruction?.onSubjectVisible(visible); }
+ }
+ const handle: RigHandle = {
+ controls: orbit.controls, pose,
+ setView(view) { orbit.handle.setView(view); update(); },
+ zoomBy(factor) { orbit.handle.zoomBy(factor); update(); },
+ panBy(dx, dz) { orbit.handle.panBy(dx, dz); update(); },
+ reset() { orbit.handle.reset(); update(); },
+ };
+ return { handle, update, dispose() { orbit.dispose(); current().obstruction?.onSubjectVisible(true); } };
+}
diff --git a/scenes/packages/scene-kit/src/camera/index.tsx b/scenes/packages/scene-kit/src/camera/index.tsx
index 96627081..d1f1158d 100644
--- a/scenes/packages/scene-kit/src/camera/index.tsx
+++ b/scenes/packages/scene-kit/src/camera/index.tsx
@@ -2,12 +2,12 @@ import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';
import type { JSX, Ref, RefObject } from 'react';
import { useThree } from '@react-three/fiber';
import { PerspectiveCamera, Vector3 } from 'three/webgpu';
-import type { Object3D } from 'three/webgpu';
import { SystemOrder, useSystem } from '../lifecycle';
import { useRuntime } from '../internal/runtime';
import { createChaseDrag, createPathController, stepChase, stepChaseZoom } from './core';
import type { ChaseOptions, ChaseState, FollowOptions, OrbitOptions, PathDef, PathHandle, Pose, RigHandle, Vec3 } from './core';
import { createOrbitController, type ManagedOrbit } from './orbit';
+import { createFollowController, type ManagedFollow } from './follow';
export * from './core';
export { createScopedControlsElement } from './scoped-controls';
export * from './orbit';
@@ -36,41 +36,15 @@ export function OrbitRig(p: OrbitOptions): JSX.Element {
return <></>;
}
export function FollowRig(p: FollowOptions & { active: boolean; rigRef?: Ref<RigHandle> }): JSX.Element {
- const runtime = useRuntime(), state = useThree(), current = useRef(p);
- const managed = useRef<(ManagedOrbit & { offset: Vector3; target: Vector3; previous: Vector3; desired: Vector3; delta: Vector3; correcting: boolean; initialized: boolean; visible: boolean; subject: Object3D | null; targetHeight: number }) | null>(null);
+ const runtime = useRuntime(), state = useThree(), current = useRef(p), managed = useRef<ManagedFollow | null>(null);
useLayoutEffect(() => { current.current = p; });
useEffect(() => {
const root = runtime.rootRef.current; if (!root) return;
- const orbit = createOrbitController(state.camera as PerspectiveCamera, state.gl.domElement, root, () => ({ active: current.current.active, minDistance: current.current.minDistance, maxDistance: current.current.maxDistance, maxPolar: current.current.maxPolar, pan: false }));
- const entry = Object.assign(orbit, { offset: new Vector3(), target: new Vector3(), previous: new Vector3(), desired: new Vector3(), delta: new Vector3(), correcting: false, initialized: false, visible: true, subject: null as Object3D | null, targetHeight: current.current.targetHeight });
- const changed = () => { if (!entry.correcting && current.current.active) entry.offset.subVectors(state.camera.position, entry.controls.target); };
- entry.controls.addEventListener('change', changed); managed.current = entry; setRef(p.rigRef, entry.handle);
- return () => { setRef(p.rigRef, null); entry.controls.removeEventListener('change', changed); entry.dispose(); managed.current = null; current.current.obstruction?.onSubjectVisible(true); };
+ const follow = createFollowController(state.camera as PerspectiveCamera, state.gl.domElement, root, () => current.current);
+ managed.current = follow; setRef(p.rigRef, follow.handle);
+ return () => { setRef(p.rigRef, null); follow.dispose(); managed.current = null; };
}, [runtime, state.camera, state.gl, p.rigRef]);
- useSystem('follow-camera', SystemOrder.camera, () => {
- const rig = managed.current, options = current.current, subject = options.subject.current; if (!rig) return;
- rig.controls.enabled = options.active;
- if (!options.active || !subject) { rig.initialized = false; if (!rig.visible) { rig.visible = true; options.obstruction?.onSubjectVisible(true); } return; }
- const camera = state.camera as PerspectiveCamera;
- rig.controls.minDistance = options.minDistance; rig.controls.maxDistance = options.maxDistance;
- subject.getWorldPosition(rig.target); rig.target.y += options.targetHeight;
- rig.correcting = true;
- if (!rig.initialized || rig.subject !== subject || rig.targetHeight !== options.targetHeight) {
- rig.offset.fromArray(options.offset()); rig.previous.copy(rig.target); camera.position.copy(rig.target).add(rig.offset);
- rig.controls.target.copy(rig.target); camera.fov = options.fov; camera.updateProjectionMatrix(); rig.controls.maxPolarAngle = options.maxPolar; rig.initialized = true; rig.subject = subject; rig.targetHeight = options.targetHeight;
- } else { rig.delta.subVectors(rig.target, rig.previous); camera.position.add(rig.delta); rig.controls.target.copy(rig.target); }
- rig.previous.copy(rig.target);
- // Keep the user-controlled offset separate from the camera shortened by an obstruction.
- rig.desired.copy(rig.target).add(rig.offset); const length = rig.offset.length();
- let distance = length;
- if (options.obstruction) distance = Math.min(length, Math.max(options.obstruction.minDistance, options.obstruction.ray(rig.target, rig.desired) - options.obstruction.pad));
- camera.position.copy(rig.target).addScaledVector(rig.offset, distance / Math.max(1e-9, length));
- // User zoom limits constrain the stored offset; collision pull-in may go below them.
- const min = rig.controls.minDistance; rig.controls.minDistance = options.obstruction?.minDistance ?? min;
- rig.controls.update(); rig.controls.minDistance = min; rig.sync(); rig.correcting = false;
- const visible = distance >= (options.obstruction?.hideSubjectBelow ?? 0);
- if (visible !== rig.visible) { rig.visible = visible; options.obstruction?.onSubjectVisible(visible); }
- });
+ useSystem('follow-camera', SystemOrder.camera, () => managed.current?.update());
return <></>;
}
export function VehicleRig(p: ChaseOptions): JSX.Element {
diff --git a/scenes/packages/scene-kit/src/contract/index.tsx b/scenes/packages/scene-kit/src/contract/index.tsx
index 5f2fde29..acaa51ce 100644
--- a/scenes/packages/scene-kit/src/contract/index.tsx
+++ b/scenes/packages/scene-kit/src/contract/index.tsx
@@ -192,7 +192,7 @@ export function SceneRoot({ options, definition, children }: { options: ScenePro
if (rt.disposed) return;
fiber = createRoot(canvas);
unbindFiberErrors = bindFiberErrors(_roots.get(canvas)?.fiber, rt.fatal);
- const factory = createGlFactory({ forceWebGL: options.backend === 'webgl2', isDisposed: () => rt.disposed, onBackend: backend => {
+ const factory = createGlFactory({ forceWebGL: options.backend === 'webgl2', reversedDepthBuffer: definition.reversedDepthBuffer, isDisposed: () => rt.disposed, onBackend: backend => {
rt.backend = backend; element.dataset.kilnBackend = backend.backend; callback('onBackend', backend);
} });
await fiber.configure({
diff --git a/scenes/packages/scene-kit/src/contract/types.ts b/scenes/packages/scene-kit/src/contract/types.ts
index 5411f987..5be0b166 100644
--- a/scenes/packages/scene-kit/src/contract/types.ts
+++ b/scenes/packages/scene-kit/src/contract/types.ts
@@ -16,6 +16,8 @@ export interface SceneDefinition {
id: string; label: string; description: string; tiers: TierTable; look: RendererLook;
hud?: ReactNode; devPanel?: ReactNode;
camera?: { position?: [number,number,number]; fov?: number; near?: number; far?: number };
+ /** Default false. The scene must adapt skies, oblique reflection planes and polygon offsets to the effective backend setting. */
+ reversedDepthBuffer?: boolean;
/** Optional initial model subset. Omitted models remain integrity-checked through usePackReader when requested. */
startupModel?: (model:{id:string;path:string})=>boolean;
/** Synchronous, idempotent CPU preparation as verified data arrives. Register owned resources immediately; the current mount owns their disposal. */
diff --git a/scenes/packages/scene-kit/src/input/core.ts b/scenes/packages/scene-kit/src/input/core.ts
index a64795b1..15166ce8 100644
--- a/scenes/packages/scene-kit/src/input/core.ts
+++ b/scenes/packages/scene-kit/src/input/core.ts
@@ -7,7 +7,9 @@ export interface ActionDef { id: string; keys: readonly string[]; mode: 'edge' |
export interface InputApi {
readonly state: InputState; readonly enabled: boolean;
setEnabled(on: boolean): void; press(action: 'interact' | 'cancel'): void;
- setMove(x: number, y: number, run: boolean): void; setAction(id: string, value: number): void; clear(): void;
+ /** An owner lets a control release its movement without clearing a newer writer. */
+ setMove(x: number, y: number, run: boolean, owner?: object): void; releaseMove(owner: object): void;
+ setAction(id: string, value: number): void; clear(): void;
endFrame(): void; configureActions(actions: readonly ActionDef[]): void;
key(code: string, down: boolean, repeat?: boolean): boolean;
setPointerKind(kind: InputState['lastPointer']): void;
@@ -17,14 +19,15 @@ const movement = new Set(['KeyW', 'KeyA', 'KeyS', 'KeyD', 'ArrowUp', 'ArrowDown'
const clamp = (n: number, min: number, max: number) => Math.max(min, Math.min(max, Number.isFinite(n) ? n : 0));
export function createInputApi(definitions: readonly ActionDef[] = []): InputApi {
const actions: Record<string, number> = Object.create(null), defs = new Map<string, ActionDef>(), keys = new Set<string>(), listeners = new Set<() => void>();
- let enabled = false, disposed = false;
+ let enabled = false, disposed = false, moveOwner: object | undefined;
const state: InputState = { move: { x: 0, y: 0 }, run: false, look: { x: 0, y: 0 }, zoom: 0, interact: false, cancel: false, helpToggle: false, lastPointer: 'mouse', actions };
const api: InputApi = {
state, get enabled() { return enabled && !disposed; },
setEnabled(on) { if (disposed) return; enabled = on; if (!on) api.clear(); },
- clear() { keys.clear(); state.move.x = state.move.y = state.look.x = state.look.y = state.zoom = 0; state.run = state.interact = state.cancel = state.helpToggle = false; for (const id in actions) actions[id] = 0; },
+ clear() { keys.clear(); moveOwner = undefined; state.move.x = state.move.y = state.look.x = state.look.y = state.zoom = 0; state.run = state.interact = state.cancel = state.helpToggle = false; for (const id in actions) actions[id] = 0; },
press(action) { if (enabled && !disposed) state[action] = true; },
- setMove(x, y, run) { if (!enabled || disposed) return; state.move.x = clamp(x, -1, 1); state.move.y = clamp(y, -1, 1); state.run = run; },
+ setMove(x, y, run, owner) { if (!enabled || disposed) return; moveOwner = owner; state.move.x = clamp(x, -1, 1); state.move.y = clamp(y, -1, 1); state.run = run; },
+ releaseMove(owner) { if (!owner || moveOwner !== owner) return; moveOwner = undefined; state.move.x = state.move.y = 0; state.run = false; },
setAction(id, value) {
if (!enabled || disposed) return;
if (id === 'interact' || id === 'cancel') { if (value > 0) api.press(id); return; }
@@ -45,6 +48,7 @@ export function createInputApi(definitions: readonly ActionDef[] = []): InputApi
const edge = down && !repeat && !keys.has(code);
if (down) keys.add(code); else keys.delete(code);
if (movement.has(code)) {
+ moveOwner = undefined;
state.move.x = Number(keys.has('KeyD') || keys.has('ArrowRight')) - Number(keys.has('KeyA') || keys.has('ArrowLeft'));
state.move.y = Number(keys.has('KeyW') || keys.has('ArrowUp')) - Number(keys.has('KeyS') || keys.has('ArrowDown'));
state.run = keys.has('ShiftLeft') || keys.has('ShiftRight');
diff --git a/scenes/packages/scene-kit/src/input/index.tsx b/scenes/packages/scene-kit/src/input/index.tsx
index 88f0d179..a3f2e4d0 100644
--- a/scenes/packages/scene-kit/src/input/index.tsx
+++ b/scenes/packages/scene-kit/src/input/index.tsx
@@ -18,22 +18,23 @@ export function InputProvider(p: { target: RefObject<HTMLElement | null>; action
export function useInput(): InputApi { return useRuntime().input; }
/** A movement stick; `axes="throttle"` makes it the only driving input (forward accelerates, back brakes or reverses, sideways steers). */
export function VirtualJoystick(p: { label: string; axes?: JoystickAxes; runThreshold?: number | null }): JSX.Element {
- const input = useInput(), active = useRef<number | null>(null), thumb = useRef<HTMLSpanElement>(null);
+ const input = useInput(), active = useRef<number | null>(null), thumb = useRef<HTMLSpanElement>(null), owner = useRef({});
const center = useRef({ x: 0, y: 0 });
const move = (event: ReactPointerEvent<HTMLDivElement>) => {
if (active.current !== event.pointerId) return;
const dx = event.clientX - center.current.x, dy = p.axes === 'x' ? 0 : event.clientY - center.current.y;
const value = joystickAxes(dx, dy, 66, p.axes, p.runThreshold === undefined ? .92 : p.runThreshold);
- input.setMove(value.x, value.y, value.run);
+ input.setMove(value.x, value.y, value.run, owner.current);
// The thumb stays inside the ring (the throttle axes can both be full at a diagonal).
const reach = Math.max(1, Math.hypot(value.x, value.y));
if (thumb.current) thumb.current.style.transform = `translate(${value.x / reach * 38}px, ${-value.y / reach * 38}px)`;
};
const release = (event?: ReactPointerEvent<HTMLDivElement>) => {
if (event && active.current !== event.pointerId) return;
- active.current = null; input.setMove(0, 0, false); if (thumb.current) thumb.current.style.transform = 'translate(0px, 0px)';
+ active.current = null; input.releaseMove(owner.current); if (thumb.current) thumb.current.style.transform = 'translate(0px, 0px)';
};
- useEffect(() => () => { input.setMove(0, 0, false); }, [input]);
+ // A keyboard event can hide this joystick. Its cleanup must not erase that new movement.
+ useEffect(() => () => { input.releaseMove(owner.current); }, [input]);
return <div className="ks-joystick" role="application" aria-label={p.label}
onPointerDown={event => {
if (active.current !== null) return;
diff --git a/scenes/packages/scene-kit/src/renderer/index.ts b/scenes/packages/scene-kit/src/renderer/index.ts
index 4c2d4e2b..e9ad7267 100644
--- a/scenes/packages/scene-kit/src/renderer/index.ts
+++ b/scenes/packages/scene-kit/src/renderer/index.ts
@@ -15,6 +15,8 @@ export interface BackendInfo { backend: 'webgpu' | 'webgl2'; forced: boolean; fe
export interface GlDefaults { canvas: HTMLCanvasElement | OffscreenCanvas; powerPreference: 'high-performance'; antialias: boolean; alpha: boolean }
export interface RendererFactoryOptions {
forceWebGL?: boolean; antialias?: boolean; alpha?: boolean; onBackend?: (b: BackendInfo) => void; isDisposed: () => boolean;
+ /** Opt-in depth precision for long-range scenes. Inspect renderer.reversedDepthBuffer after init: WebGL may fall back. */
+ reversedDepthBuffer?: boolean;
makeRenderer?: (options: ConstructorParameters<typeof WebGPURenderer>[0]) => WebGPURenderer;
}
type Device = { destroy(): void; lost: Promise<{reason: string; message: string}>; adapterInfo?: Partial<NonNullable<BackendInfo['adapter']>> };
@@ -51,7 +53,7 @@ export function createGlFactory(o: RendererFactoryOptions): (defaults: GlDefault
let renderer: WebGPURenderer | undefined, supplied: Device | undefined;
try {
if (!o.makeRenderer && typeof navigator !== 'undefined') supplied = await requestWindowsDevice({ platform:navigator.platform,forceWebGL:!!o.forceWebGL,gpu:(navigator as unknown as {gpu?: Parameters<typeof requestWindowsDevice<Device>>[0]['gpu']}).gpu });
- const params = { canvas:defaults.canvas,antialias:o.antialias ?? true,alpha:o.alpha ?? false,powerPreference:'high-performance' as const,forceWebGL:!!o.forceWebGL,...(supplied ? {device:supplied as unknown as GPUDevice} : {}) };
+ const params = { canvas:defaults.canvas,antialias:o.antialias ?? true,alpha:o.alpha ?? false,powerPreference:'high-performance' as const,forceWebGL:!!o.forceWebGL,reversedDepthBuffer:o.reversedDepthBuffer ?? false,...(supplied ? {device:supplied as unknown as GPUDevice} : {}) };
renderer = o.makeRenderer ? o.makeRenderer(params) : new WebGPURenderer(params);
ownRenderer(renderer,supplied);
await renderer.init();
diff --git a/scenes/packages/scene-kit/src/shadows/cache.ts b/scenes/packages/scene-kit/src/shadows/cache.ts
index 0721374b..02a0b686 100644
--- a/scenes/packages/scene-kit/src/shadows/cache.ts
+++ b/scenes/packages/scene-kit/src/shadows/cache.ts
@@ -5,7 +5,7 @@ import { keepsShadowMask, layerBit, ShadowLayers, suppressedCasters } from './la
import type { ShadowLayerSet } from './layers';
type Shadow = LightShadow & { shadowNode?: Node; filterNode?: unknown; map?: unknown };
-interface Watch { m: Float64Array; v: boolean; c: boolean; iv: number; n: number; live: boolean; quiet: number }
+interface Watch { m: Float64Array; v: boolean; c: boolean; iv: number; n: number; morph?: number[]; live: boolean; quiet: number }
export interface CachedSunShadowOptions {
light: DirectionalLight; liveMapSize?: number; settleFrames?: number; layers?: ShadowLayerSet;
/**
@@ -16,9 +16,19 @@ export interface CachedSunShadowOptions {
}
export interface CachedSunShadowStats { staticRenders: number; liveRenders: number; staticCasters: number; liveCasters: number; readonly pendingSettle: number; invalidations: number; reasons: Record<string, number> }
export interface CachedSunShadowTrackOptions {
- /** Casters under a movable() node are watched: one whose matrix, visibility, casting or instances change goes live until still. */
+ /**
+ * Casters under a movable() node are watched: matrixWorld, ancestor visibility, castShadow, instanceMatrix.version,
+ * instance count and morphTargetInfluences changes go live until still. Watched skins remain live. Morph weights are
+ * compared exactly; the matrix tolerance does not apply to them. One current snapshot per watched caster is retained,
+ * replaced only on change and released with untrack/dispose; geometry/attribute contents are not scanned.
+ */
movable?(n: Object3D): boolean;
- /** Casters under a live() node always draw in the live map: motion the watch cannot see (instance attributes, vertex or morph animation). */
+ /**
+ * Casters under a live() node always draw in the live map while shown. Use on the first track for continuous motion
+ * outside the watch: shader/positionNode uniforms, custom instance attributes, GPU deformation or geometry edits.
+ * The cache does not inspect shader graphs or guarantee that a material's deformation supports the shadow pass.
+ * For a discrete edit of a static caster, call invalidate() after the edit instead. live takes priority over movable.
+ */
live?(n: Object3D): boolean;
}
export interface TrackedCasters { readonly added: number; untrack(): void }
@@ -31,6 +41,7 @@ export interface CachedSunShadow {
* the meshes this call tagged and re-arms the static map (a world replaced while the cache survives).
*/
track(root: Object3D, o?: CachedSunShadowTrackOptions): TrackedCasters;
+ /** Re-render static casters after an unobserved discrete change; continuous unobserved motion belongs in live(). */
invalidate(reason: string): void; prime(): void; update(): void; dispose(): void;
}
const CAMERA = ['left', 'right', 'top', 'bottom', 'near', 'far', 'zoom'] as const, VALUES = ['bias', 'normalBias', 'radius', 'intensity', 'blurSamples'] as const;
@@ -76,6 +87,8 @@ export function cachedSunShadow(o: CachedSunShadowOptions): CachedSunShadow {
const changed = (n: Object3D, w: Watch) => {
const e = n.matrixWorld.elements, im = n as InstancedMesh, v = shown(n), iv = im.isInstancedMesh ? im.instanceMatrix.version : 0, count = im.isInstancedMesh ? im.count : 0;
let d = v !== w.v || n.castShadow !== w.c || iv !== w.iv || count !== w.n || !!(n as SkinnedMesh).isSkinnedMesh;
+ const morph = (n as Mesh).morphTargetInfluences;
+ if (morph?.length !== w.morph?.length || morph?.some((value, i) => !Object.is(value, w.morph?.[i]))) { w.morph = morph?.slice(); d = true; }
for (let i = 0; i < 16; i++) if (!(Math.abs(w.m[i]! - e[i]!) <= tol)) { w.m.set(e); d = true; break; }
w.v = v; w.c = n.castShadow; w.iv = iv; w.n = count; return d;
};
diff --git a/scenes/packages/scene-kit/src/staging/index.ts b/scenes/packages/scene-kit/src/staging/index.ts
index 8f2b951d..5aef5555 100644
--- a/scenes/packages/scene-kit/src/staging/index.ts
+++ b/scenes/packages/scene-kit/src/staging/index.ts
@@ -6,7 +6,7 @@ import { unzipSync } from 'fflate';
import { assertPackPath, validateManifest } from '../assets/manifest';
import type { CreditEntry, PackCell, PackFile, PackManifest } from '../assets/manifest';
export interface StageFile {from:string;to:string;sha256?:string}
-export interface StagePlan {id:string;release:string;three:'0.186.0';out:string;force?:boolean;models:{id:string;to:string}[];data:Record<string,string>;files:StageFile[];credits?:CreditEntry[];cells?:PackCell[];source?:Record<string,unknown>}
+export interface StagePlan {id:string;release:string;three:'0.186.1';out:string;force?:boolean;models:{id:string;to:string}[];data:Record<string,string>;files:StageFile[];credits?:CreditEntry[];cells?:PackCell[];source?:Record<string,unknown>}
const hash=(b:Uint8Array)=>createHash('sha256').update(b).digest('hex');
function within(dir:string,path:string):string{assertPackPath(path);const root=resolve(dir),target=resolve(root,path);if(!target.startsWith(root+sep))throw new Error(`Path outside output: ${path}`);let parent=target;while(parent!==root){if(existsSync(parent)&&lstatSync(parent).isSymbolicLink())throw new Error(`Symbolic link in output: ${path}`);parent=dirname(parent);}if(existsSync(root)&&lstatSync(root).isSymbolicLink())throw new Error(`Symbolic output: ${root}`);return target;}
export function readZip(path:string,expected?:{bytes:number;sha256:string}):Map<string,Uint8Array>{const bytes=readFileSync(path);if(expected&&(bytes.length!==expected.bytes||hash(bytes)!==expected.sha256))throw new Error(`Archive integrity mismatch: ${path}`);let entries:ReturnType<typeof unzipSync>;try{entries=unzipSync(bytes);}catch(cause){throw new Error(`Cannot read zip: ${path}`,{cause});}const result=new Map<string,Uint8Array>();for(const [name,body]of Object.entries(entries)){if(name.endsWith('/'))continue;assertPackPath(name);result.set(name,body);}return result;}
@@ -14,7 +14,7 @@ export function readZip(path:string,expected?:{bytes:number;sha256:string}):Map<
export function verifyArchiveMembers(entries:Map<string,Uint8Array>,files:readonly PackFile[],ignore:ReadonlySet<string>=new Set()):void{const listed=new Set<string>();for(const file of files){assertPackPath(file.path);if(listed.has(file.path))throw new Error(`Duplicate member: ${file.path}`);listed.add(file.path);const b=entries.get(file.path);if(!b)throw new Error(`Missing member: ${file.path}`);if(b.length!==file.bytes||hash(b)!==file.sha256.replace(/^sha256:/,''))throw new Error(`Member integrity mismatch: ${file.path}`);}for(const path of entries.keys())if(!listed.has(path)&&!ignore.has(path))throw new Error(`Extra member: ${path}`);}
function walk(dir:string,prefix=''):string[]{if(!existsSync(dir))return[];const result:string[]=[];for(const entry of readdirSync(dir,{withFileTypes:true})){const path=prefix+entry.name;if(entry.isSymbolicLink())throw new Error(`Symbolic staged entry: ${path}`);if(entry.isDirectory())result.push(...walk(resolve(dir,entry.name),path+'/'));else result.push(path);}return result;}
export function stageFiles(plan:StagePlan):{files:number;bytes:number}{
- if(plan.three!=='0.186.0')throw new Error('Stage plan three pin must be 0.186.0');const out=resolve(plan.out),copies=new Map<string,Uint8Array>(),files:PackFile[]=[];for(const file of plan.files){assertPackPath(file.to);if(file.to==='pack.json'||file.to==='SHA256SUMS'||copies.has(file.to))throw new Error(`Reserved or duplicate output: ${file.to}`);if(!isAbsolute(file.from))throw new Error(`Source must be absolute: ${file.from}`);const from=resolve(file.from);if(from===out||from.startsWith(out+sep))throw new Error(`Source is inside output: ${from}`);const b=readFileSync(from),sha256=hash(b);if(file.sha256&&file.sha256.replace(/^sha256:/,'')!==sha256)throw new Error(`Source integrity mismatch: ${file.from}`);copies.set(file.to,b);files.push({path:file.to,bytes:b.length,sha256});}
+ if(plan.three!=='0.186.1')throw new Error('Stage plan three pin must be 0.186.1');const out=resolve(plan.out),copies=new Map<string,Uint8Array>(),files:PackFile[]=[];for(const file of plan.files){assertPackPath(file.to);if(file.to==='pack.json'||file.to==='SHA256SUMS'||copies.has(file.to))throw new Error(`Reserved or duplicate output: ${file.to}`);if(!isAbsolute(file.from))throw new Error(`Source must be absolute: ${file.from}`);const from=resolve(file.from);if(from===out||from.startsWith(out+sep))throw new Error(`Source is inside output: ${from}`);const b=readFileSync(from),sha256=hash(b);if(file.sha256&&file.sha256.replace(/^sha256:/,'')!==sha256)throw new Error(`Source integrity mismatch: ${file.from}`);copies.set(file.to,b);files.push({path:file.to,bytes:b.length,sha256});}
const manifest:PackManifest&{source?:Record<string,unknown>}={schema:'kiln.scene-pack/1',id:plan.id,release:plan.release,three:plan.three,models:plan.models.map(m=>({id:m.id,path:m.to})),data:plan.data,files};if(plan.credits)manifest.credits=plan.credits;if(plan.cells)manifest.cells=plan.cells;if(plan.source)manifest.source=plan.source;validateManifest(manifest);
copies.set('pack.json',new TextEncoder().encode(JSON.stringify(manifest,null,2)+'\n'));copies.set('SHA256SUMS',new TextEncoder().encode(files.map(f=>`${f.sha256} ${f.path}\n`).join('')));
// All validation occurs before the first write; partial invalid outputs never overwrite an existing pack.
diff --git a/scenes/packages/scene-kit/src/testing/node.ts b/scenes/packages/scene-kit/src/testing/node.ts
index 0ee3e511..e954a5a3 100644
--- a/scenes/packages/scene-kit/src/testing/node.ts
+++ b/scenes/packages/scene-kit/src/testing/node.ts
@@ -1,15 +1,46 @@
// Node-only helpers. This entry is never re-exported by the browser testing module.
import assert from 'node:assert/strict';
-import { mkdir, mkdtemp, writeFile } from 'node:fs/promises';
-import { resolve, relative, isAbsolute, sep } from 'node:path';
+import { constants } from 'node:fs';
+import { access, mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises';
+import { resolve, relative, isAbsolute, sep, posix, win32 } from 'node:path';
import { createServer } from 'node:http';
import puppeteer from 'puppeteer-core';
-import type { Browser, Page, HTTPRequest } from 'puppeteer-core';
+import type { Browser, Page, HTTPRequest, Viewport } from 'puppeteer-core';
import axe from 'axe-core';
// @ts-ignore Shared Node-builtins-only implementation copied into standalone outputs.
import { startStaticServer } from '../../../../scripts/static-server.mjs';
+// @ts-ignore Shared Node-only browser configuration, also used by website scene checks.
+import { sceneBrowserOptions } from '../../../../scripts/browser-options.mjs';
-export const INSTALLED_CHROME = 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+/** Ordered local candidates only: never installs a browser or invokes a shell. */
+export function chromeExecutableCandidates(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string[] {
+ const windows = platform === 'win32', paths = windows ? win32 : posix;
+ const names = windows ? ['chrome.exe', 'chromium.exe'] : ['google-chrome-stable', 'google-chrome', 'chromium', 'chromium-browser', 'chrome'];
+ const path = env.PATH ?? (windows ? env.Path : '') ?? '';
+ const candidates = path.split(windows ? ';' : ':').filter(Boolean).flatMap(directory => names.map(name => paths.join(directory.replace(/^"(.*)"$/, '$1'), name)));
+ if (windows) {
+ for (const directory of [env.ProgramFiles ?? 'C:/Program Files', env['ProgramFiles(x86)'] ?? 'C:/Program Files (x86)', env.LOCALAPPDATA]) {
+ if (directory) candidates.push(win32.join(directory, 'Google/Chrome/Application/chrome.exe'));
+ }
+ } else if (platform === 'darwin') candidates.push('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium');
+ else candidates.push('/opt/google/chrome/chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium');
+ return [...new Set(candidates)];
+}
+/** Explicit path wins over KILN_CHROME, CHROME and PUPPETEER_EXECUTABLE_PATH, then installed Chrome/Chromium discovery. */
+export async function resolveChromeExecutable(o: { executablePath?: string; env?: NodeJS.ProcessEnv; platform?: NodeJS.Platform } = {}): Promise<string> {
+ const env = o.env ?? process.env, platform = o.platform ?? process.platform;
+ const configured = o.executablePath ?? env.KILN_CHROME ?? env.CHROME ?? env.PUPPETEER_EXECUTABLE_PATH;
+ const executable = async (path: string) => {
+ try { await access(path, platform === 'win32' ? constants.F_OK : constants.X_OK); return (await stat(path)).isFile(); }
+ catch { return false; }
+ };
+ if (configured !== undefined) {
+ if (!configured || !await executable(configured)) throw new Error('Configured Chrome executable is not an executable file; set executablePath or KILN_CHROME to an installed Chrome/Chromium binary');
+ return configured;
+ }
+ for (const candidate of chromeExecutableCandidates(platform, env)) if (await executable(candidate)) return candidate;
+ throw new Error('No installed Chrome/Chromium found; set executablePath or KILN_CHROME to its executable (no browser was downloaded)');
+}
export const CORRECTNESS_TIMEOUT = 120_000;
/** A loopback port range a runner owns (GG-001 / FF-001): each builder serves only in its own range. */
export interface PortRange { first: number; last: number }
@@ -53,6 +84,8 @@ export interface SceneContractTestReport {
}
const expectedFallback = /THREE\.WebGPURenderer: WebGPU is not available, running under WebGL2 backend\./;
const browserProfiles = new WeakMap<Browser, string>();
+/** The temporary profile owned by launchChrome; retained for evidence after close. */
+export function chromeProfile(browser: Browser): string | undefined { return browserProfiles.get(browser); }
export function workspacePath(workspace: string, path: string): string {
const base = resolve(workspace), value = resolve(base, path), rel = relative(base, value);
if (rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)) throw new Error('Test output must remain in the scenes workspace');
@@ -63,15 +96,34 @@ export function assertOwnedUrl(url: string, ownedPorts: ReadonlySet<number>, por
if (value.protocol !== 'http:' || value.hostname !== '127.0.0.1' || value.username || value.password || port < first || port > last || !ownedPorts.has(port)) throw new Error(`Browser tests may only connect to their own loopback server on ports ${first}–${last}`);
}
/** `windowSize` adds an explicit `--window-size` (owner rule 2026-09-29 11:40: headless runs on the dev PC name their window size); `args` are extra Chrome flags. Both optional and additive. */
-export async function launchChrome(o: { workspace?: string; executablePath?: string; headless?: boolean; name?: string; windowSize?: readonly [number, number]; args?: readonly string[] } = {}): Promise<Browser> {
+export async function launchChrome(o: { workspace?: string; executablePath?: string; headless?: boolean; name?: string; windowSize?: readonly [number, number]; defaultViewport?: Viewport | null; args?: readonly string[] } = {}): Promise<Browser> {
+ const configured = sceneBrowserOptions(o);
+ const executablePath = await resolveChromeExecutable(o);
const workspace = o.workspace ?? process.cwd(), scratch = workspacePath(workspace, '.tmp');
await mkdir(scratch, { recursive: true });
const profile = await mkdtemp(workspacePath(scratch, `${o.name ?? 'contract'}-chrome-`));
- const browser = await puppeteer.launch({ executablePath: o.executablePath ?? INSTALLED_CHROME, headless: o.headless ?? true, pipe: true,
- userDataDir: profile,
- args: ['--enable-unsafe-webgpu', '--no-first-run', '--no-default-browser-check', ...(o.windowSize ? [`--window-size=${o.windowSize[0]},${o.windowSize[1]}`] : []), ...(o.args ?? [])],
- env: { ...process.env, TEMP: scratch, TMP: scratch },
- });
+ const cleanup = () => rm(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
+ let browser: Browser;
+ try {
+ browser = await puppeteer.launch({ executablePath, headless: configured.headless, pipe: true,
+ userDataDir: profile, ...(o.defaultViewport !== undefined ? { defaultViewport: o.defaultViewport } : {}),
+ args: ['--enable-unsafe-webgpu', '--no-first-run', '--no-default-browser-check', ...(o.windowSize ? [`--window-size=${o.windowSize[0]},${o.windowSize[1]}`] : []), ...configured.args],
+ env: { ...process.env, TEMP: scratch, TMP: scratch },
+ });
+ } catch (error) {
+ try { await cleanup(); } catch (cleanupError) { throw new AggregateError([error, cleanupError], 'Chrome launch failed and its temporary profile could not be removed'); }
+ throw error;
+ }
+ const close = browser.close.bind(browser); let closing: Promise<void> | undefined;
+ browser.close = () => closing ??= (async () => {
+ let failed = false, closeError: unknown;
+ try { await close(); } catch (error) { failed = true; closeError = error; }
+ try { await cleanup(); } catch (error) {
+ if (failed) throw new AggregateError([closeError, error], 'Chrome close failed and its temporary profile could not be removed');
+ throw error;
+ }
+ if (failed) throw closeError;
+ })();
browserProfiles.set(browser, profile);
return browser;
}
diff --git a/scenes/packages/scene-kit/src/ui/escape.ts b/scenes/packages/scene-kit/src/ui/escape.ts
index 71803e19..e42e2825 100644
--- a/scenes/packages/scene-kit/src/ui/escape.ts
+++ b/scenes/packages/scene-kit/src/ui/escape.ts
@@ -3,3 +3,20 @@ export function closeScenePanelOnEscape(event: Pick<KeyboardEvent, 'key' | 'defa
if (event.key !== 'Escape' || event.defaultPrevented) return;
event.preventDefault(); event.stopPropagation(); close();
}
+
+/** Restore panel focus even when a containing HUD menu has collapsed. */
+export function restoreScenePanelFocus(trigger: HTMLElement | null): void {
+ if (!trigger) return;
+ const focus = (target: HTMLElement | null): boolean => {
+ if (!target?.isConnected || target.getClientRects().length === 0) return false;
+ target.focus({ preventScroll: true });
+ return target.ownerDocument.activeElement === target;
+ };
+ if (focus(trigger)) return;
+ let menu = trigger.closest<HTMLElement>('.ks-menu');
+ while (menu) {
+ if (focus(menu.querySelector<HTMLElement>(':scope > .ks-menu-trigger'))) return;
+ menu = menu.parentElement?.closest<HTMLElement>('.ks-menu') ?? null;
+ }
+ focus(trigger.closest<HTMLElement>('.ks-root'));
+}
diff --git a/scenes/packages/scene-kit/src/ui/index.tsx b/scenes/packages/scene-kit/src/ui/index.tsx
index 4c18d631..11272ce6 100644
--- a/scenes/packages/scene-kit/src/ui/index.tsx
+++ b/scenes/packages/scene-kit/src/ui/index.tsx
@@ -7,7 +7,7 @@ import { TouchButtons, useInput } from '../input';
import type { TouchButtonDef } from '../input';
import type { HudStore } from './store';
import type { LiveKnobs } from '../quality';
-import { closeScenePanelOnEscape } from './escape';
+import { closeScenePanelOnEscape, restoreScenePanelFocus } from './escape';
export * from './store';
export * from './fade';
export * from './styles';
@@ -23,7 +23,7 @@ export function usePanelEscape(open: boolean, id: string, trigger: RefObject<HTM
if (focusedPanel && focusedPanel !== panel) return;
const expanded = target?.closest('button[aria-expanded="true"]');
if (expanded && expanded !== trigger.current && !panel?.contains(expanded)) return;
- closeScenePanelOnEscape(event, () => { latest.current(); trigger.current?.focus({ preventScroll: true }); });
+ closeScenePanelOnEscape(event, () => { latest.current(); restoreScenePanelFocus(trigger.current); });
};
root.addEventListener('keydown', key, true);
return () => root.removeEventListener('keydown', key, true);
@@ -119,7 +119,7 @@ export function HelpOverlay(p: { children?: ReactNode; desktop?: ReactNode; touc
const key = p.storageKey ?? `kiln.scene.${runtime.definition.id}.help`;
const change = (value: boolean) => {
setLocalOpen(value); p.onOpenChange?.(value);
- if (!value) { dismissed.current = true; p.onClose?.(); trigger.current?.focus(); try { runtime.rootRef.current?.ownerDocument.defaultView?.localStorage.setItem(key, 'dismissed'); } catch {} }
+ if (!value) { dismissed.current = true; p.onClose?.(); restoreScenePanelFocus(trigger.current); try { runtime.rootRef.current?.ownerDocument.defaultView?.localStorage.setItem(key, 'dismissed'); } catch {} }
};
usePanelEscape(open, id, trigger, () => change(false));
useEffect(() => {
@@ -151,7 +151,7 @@ function safeCreditUrl(source: string): string | undefined { try { const url = n
export function CreditsPanel(p: { credits?: readonly CreditEntry[]; open?: boolean; onOpenChange?(open: boolean): void; label?: string; includeKit?: boolean }): JSX.Element {
const runtime = useRuntime(), id = `ks-credits-${useId()}`, [localOpen, setLocalOpen] = useState(false), open = p.open ?? localOpen;
const trigger = useRef<HTMLButtonElement>(null);
- const change = (value: boolean) => { setLocalOpen(value); p.onOpenChange?.(value); if (!value) trigger.current?.focus(); };
+ const change = (value: boolean) => { setLocalOpen(value); p.onOpenChange?.(value); if (!value) restoreScenePanelFocus(trigger.current); };
usePanelEscape(open, id, trigger, () => change(false));
const credits = [...(p.credits ?? runtime.pack?.manifest.credits ?? []), ...(p.includeKit === false ? [] : KIT_NOTICES)];
return <><HudButton ref={trigger} className="ks-credits-button" aria-expanded={open} aria-controls={id} onClick={() => change(!open)}>{p.label ?? 'Credits'}</HudButton>
diff --git a/scenes/packages/scene-kit/src/ui/styles.tsx b/scenes/packages/scene-kit/src/ui/styles.tsx
index 7fc86a38..1c7c74f9 100644
--- a/scenes/packages/scene-kit/src/ui/styles.tsx
+++ b/scenes/packages/scene-kit/src/ui/styles.tsx
@@ -1,17 +1,21 @@
import type { JSX } from 'react';
// Scoped, instance-owned stylesheet: no document.body/head mutation or global reset.
+// Layout containment anchors fixed help/credits to this HUD, even inside a short
+// positioned toolbar. Scene-specific inline panels can still override position.
export const HUD_CSS = `
.ks-root{position:relative;width:100%;height:100%;overflow:hidden;overscroll-behavior:none;color:#fff;font:14px/1.45 system-ui,sans-serif}
.ks-root canvas{touch-action:none;display:block}.ks-root:focus-visible{outline:3px solid #fff;outline-offset:-4px}
-.ks-hud{position:absolute;inset:0;pointer-events:none;z-index:2;container:ks-hud/inline-size}.ks-hud>*{pointer-events:auto}
+.ks-hud{position:absolute;inset:0;pointer-events:none;z-index:2;container:ks-hud/inline-size;contain:layout}.ks-hud>*{pointer-events:auto}
.ks-button,.ks-select{min-width:44px;min-height:44px;border:1px solid #879593;border-radius:9px;background:#142522;color:#fff;padding:10px 14px;font:inherit;cursor:pointer;touch-action:none;user-select:none}
.ks-button:hover{background:#29433d}.ks-button:disabled{opacity:.7;cursor:default}.ks-button:focus-visible,.ks-select:focus-visible{outline:3px solid #fff;outline-offset:3px}
.ks-panel{background:rgba(11,24,22,.94);color:#fff;border:1px solid #879593;border-radius:12px;padding:16px;max-width:min(420px,calc(100% - 32px));box-sizing:border-box}
.ks-panel a{color:#baf0ef}.ks-panel a:focus-visible{outline:3px solid #fff}.ks-panel h2,.ks-panel h3{margin:0 0 8px;font-size:1.1em}.ks-panel p{margin:8px 0}
.ks-toolbar{position:absolute;top:max(12px,env(safe-area-inset-top));right:max(12px,env(safe-area-inset-right));display:flex;gap:8px;flex-wrap:wrap}
-.ks-help,.ks-credits{position:absolute;top:max(70px,calc(env(safe-area-inset-top) + 58px));right:max(12px,env(safe-area-inset-right));max-height:calc(100% - 100px);overflow:auto}
+.ks-help,.ks-credits{position:fixed;z-index:3;pointer-events:auto;top:max(70px,calc(env(safe-area-inset-top) + 58px));right:max(12px,env(safe-area-inset-right));max-height:calc(100% - 100px);overflow:auto}
.ks-help-button,.ks-credits-button{pointer-events:auto}.ks-segmented{display:flex;gap:4px;flex-wrap:wrap}.ks-segmented [aria-checked=true]{background:#3b6659;border-color:#dafff2}
.ks-menu,.ks-menu-items{display:contents}.ks-menu-break{display:none;flex-basis:100%;height:0;order:9}
+/* Reopened menus can wrap beneath fixed panels; keep their controls reachable without lifting the panels. */
+.ks-menu-trigger,.ks-menu[data-open]>.ks-menu-items>:not(.ks-panel){position:relative;z-index:4}
.ks-menu-caret{display:inline-block;margin-left:8px;border:4px solid transparent;border-top-color:currentColor;border-bottom:0;vertical-align:middle}
.ks-menu[data-open]>.ks-menu-trigger{background:#3b6659;border-color:#dafff2}.ks-menu[data-open] .ks-menu-caret{transform:rotate(180deg)}
.ks-menu[data-collapse=narrow]>.ks-menu-trigger{display:none}
@@ -31,6 +35,7 @@ export const HUD_CSS = `
.ks-joystick{position:absolute;left:max(20px,env(safe-area-inset-left));bottom:max(24px,env(safe-area-inset-bottom));width:132px;height:132px;box-sizing:border-box;border:2px solid #c5ddd7;border-radius:50%;background:rgba(11,24,22,.85);touch-action:none;user-select:none;display:grid;place-items:center}
.ks-joystick-thumb{width:56px;height:56px;box-sizing:border-box;border:2px solid #fff;border-radius:50%;background:#456e62;pointer-events:none}
.ks-touch-buttons{position:absolute;right:max(16px,env(safe-area-inset-right));bottom:max(20px,env(safe-area-inset-bottom));display:grid;grid-template-columns:auto auto;gap:10px;touch-action:none;user-select:none}
+.ks-joystick,.ks-touch-buttons{pointer-events:auto}
.ks-touch-button{min-width:56px;min-height:56px}.ks-slot-primary{grid-column:1;grid-row:2}.ks-slot-secondary{grid-column:1;grid-row:1}.ks-slot-pedal-upper{grid-column:2;grid-row:1}.ks-slot-pedal-lower{grid-column:2;grid-row:2}
.ks-touch-buttons.ks-exit-play{left:max(12px,env(safe-area-inset-left));top:max(12px,env(safe-area-inset-top));right:auto;bottom:auto}
.ks-fade{position:absolute;inset:0;background:#000;opacity:0;pointer-events:none;z-index:10}.ks-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
diff --git a/scenes/packages/scene-kit/tests/browser/hud-fixture.tsx b/scenes/packages/scene-kit/tests/browser/hud-fixture.tsx
new file mode 100644
index 00000000..87a0d53f
--- /dev/null
+++ b/scenes/packages/scene-kit/tests/browser/hud-fixture.tsx
@@ -0,0 +1,42 @@
+// DOM-only qualification: real kit components and input, without a renderer or asset pack.
+import { useRef } from 'react';
+import { flushSync } from 'react-dom';
+import { createRoot } from 'react-dom/client';
+import { RuntimeContext } from '../../src/internal/runtime';
+import type { SceneRuntime } from '../../src/internal/runtime';
+import { createInputApi, TouchButtons, VirtualJoystick } from '../../src/input';
+import { CreditsPanel, HelpOverlay, HudButton, HudHideButton, HudLayer, HudMenu, HudToolbar, SceneStyles, createHudStore } from '../../src/ui';
+
+const input = createInputApi(), hud = createHudStore();
+input.setEnabled(true);
+const text = Array.from({ length: 35 }, (_, i) => <p key={i}>Control {i + 1}: use the scene keyboard or touch controls.</p>);
+function Fixture({ variant }: { variant: string }) {
+ const rootRef = useRef<HTMLDivElement>(null);
+ const runtime = useRef({ rootRef, input, hud, playing: false, definition: { id: 'hud-layout' },
+ subscribe: () => () => {}, getSnapshot: () => 0, systems: { add: () => () => {} }, pack: null } as unknown as SceneRuntime);
+ const panels = <><HelpOverlay playing={false}>{text}</HelpOverlay><CreditsPanel credits={Array.from({ length: 30 }, (_, i) => ({ name: `Fixture ${i}`, licence: 'MIT' }))}/></>;
+ // Match the campus's actual control order and labels: on a narrow HUD More
+ // wraps over two rows, including one beneath the fixed Controls panel.
+ const toolbar = variant === 'foundry-campus' ? <HudToolbar>
+ <HudMenu label="View" collapse="narrow"><HudButton>Campus</HudButton><HudButton>One pair</HudButton><HudButton>Arrival</HudButton><HudButton>The split</HudButton><HudButton>Reset view</HudButton></HudMenu>
+ <HudButton>Drive the sedan</HudButton>
+ <HudMenu label="More"><HudButton>Pause motion</HudButton><HudButton>About the campus</HudButton>{panels}</HudMenu>
+ <HudHideButton/>
+ </HudToolbar> : <HudToolbar>{variant === 'menu' ? <HudMenu label="More">{panels}</HudMenu> : panels}</HudToolbar>;
+ const controls = <><VirtualJoystick label="Move"/><TouchButtons buttons={[{ action: 'boost', label: 'Interact', slot: 'primary', hold: true }]}/></>;
+ return <RuntimeContext.Provider value={runtime.current}><div ref={rootRef} tabIndex={0} className="ks-root" data-fixture={variant}>
+ <SceneStyles/><div className="canvas-hit-target" style={{ position: 'absolute', inset: 0 }} onPointerDown={() => (window as any).__canvasHits++}/>
+ <HudLayer>{variant === 'kit' ? <div className="fixture-nested">{toolbar}{controls}</div>
+ : variant === 'farm' ? <div className="farm-hud farm-play-touch">{toolbar}{controls}</div>
+ : variant === 'golden-gate' || variant === 'menu' ? <div className="gg-hud"><div className="gg-top">{toolbar}</div>{controls}</div>
+ : variant === 'foundry-campus' ? <div className="fc-hud"><div className="fc-top">{toolbar}</div>{controls}</div>
+ : <div className="ff-hud ff-joystick"><div className="ff-top">{toolbar}</div>{controls}</div>}</HudLayer>
+ </div></RuntimeContext.Provider>;
+}
+const root = createRoot(document.getElementById('fixture')!);
+let mountId = 0;
+Object.assign(window, { __input: input, __canvasHits: 0, __mountHud: (variant: string) => {
+ // Isolate every size/case, including after a failed assertion leaves a panel open.
+ flushSync(() => root.render(<Fixture key={++mountId} variant={variant}/>));
+} });
+(window as any).__mountHud('kit');
diff --git a/scenes/packages/scene-kit/tests/browser/input-handoff-fixture.tsx b/scenes/packages/scene-kit/tests/browser/input-handoff-fixture.tsx
new file mode 100644
index 00000000..c9e9adea
--- /dev/null
+++ b/scenes/packages/scene-kit/tests/browser/input-handoff-fixture.tsx
@@ -0,0 +1,32 @@
+// DOM-only: actual input binding and joystick lifecycle, without a scene renderer or assets.
+import { useRef, useState, useSyncExternalStore } from 'react';
+import { flushSync } from 'react-dom';
+import { createRoot } from 'react-dom/client';
+import { RuntimeContext } from '../../src/internal/runtime';
+import type { SceneRuntime } from '../../src/internal/runtime';
+import { createInputApi, InputProvider, VirtualJoystick } from '../../src/input';
+import type { InputApi } from '../../src/input';
+
+let input: InputApi, serial = 0;
+function Fixture({ mode, api }: { mode: 'switch' | 'always'; api: InputApi }) {
+ const rootRef = useRef<HTMLDivElement>(null), [shown, setShown] = useState(true);
+ const pointer = useSyncExternalStore(api.subscribe, () => api.state.lastPointer);
+ const runtime = useRef({ rootRef, input: api, hud: { set() {} }, notify() {} } as unknown as SceneRuntime);
+ (window as any).__hideStick = () => flushSync(() => setShown(false));
+ return <RuntimeContext.Provider value={runtime.current}><InputProvider target={rootRef}>
+ <div ref={rootRef} tabIndex={0} className="ks-root" style={{ width: 700, height: 400, outline: 'none' }}>
+ {shown && (mode === 'always' || pointer !== 'keyboard') && <VirtualJoystick label="Move"/>}
+ </div>
+ </InputProvider></RuntimeContext.Provider>;
+}
+const root = createRoot(document.getElementById('fixture')!);
+Object.assign(window, {
+ __mountInput(mode: 'switch' | 'always' = 'switch') {
+ input = createInputApi(); input.setEnabled(true); input.setPointerKind('touch');
+ flushSync(() => root.render(<Fixture key={++serial} mode={mode} api={input}/>));
+ },
+ __inputState: () => ({ enabled: input.enabled, move: { ...input.state.move }, run: input.state.run, pointer: input.state.lastPointer, joystick: !!document.querySelector('.ks-joystick') }),
+ __disableInput: () => input.setEnabled(false),
+ __disposeInput: () => input.dispose(),
+});
+(window as any).__mountInput();
diff --git a/scenes/packages/scene-kit/tests/browser/run-hud-layout.ts b/scenes/packages/scene-kit/tests/browser/run-hud-layout.ts
new file mode 100644
index 00000000..6f8060bb
--- /dev/null
+++ b/scenes/packages/scene-kit/tests/browser/run-hud-layout.ts
@@ -0,0 +1,149 @@
+// Explicit browser gate, separate from portable source tests. No assets, renderer, or GPU timing.
+// From scenes/: bun packages/scene-kit/tests/browser/run-hud-layout.ts
+import assert from 'node:assert/strict';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { launchChrome, serveOwned } from '../../src/testing/node';
+
+const workspace = resolve(import.meta.dir, '../../../..');
+await mkdir(resolve(workspace, '.tmp'), { recursive: true });
+const out = await mkdtemp(resolve(workspace, '.tmp/hud-layout-'));
+let server: Awaited<ReturnType<typeof serveOwned>> | undefined, browser: Awaited<ReturnType<typeof launchChrome>> | undefined;
+const results: { name: string; pass: boolean; error?: string }[] = [];
+try {
+ const build = await Bun.build({ entrypoints: [resolve(import.meta.dir, 'hud-fixture.tsx')], outdir: out, target: 'browser',
+ define: { 'import.meta.env.KILN_TEST': 'false', 'import.meta.env.KILN_DEV': 'false', 'process.env.NODE_ENV': '"production"' } });
+ assert(build.success, build.logs.join('\n'));
+ const css: string[] = [];
+ for (const [file, name] of [['farm/src/ui/FarmHud.tsx', 'FARM_HUD_CSS'], ['golden-gate/src/ui/styles.ts', 'GG_HUD_CSS'], ['foundry-floor/src/scene/Hud.tsx', 'FF_HUD_CSS'], ['foundry-floor/src/campus/exterior/Hud.tsx', 'CSS']]) {
+ const source = await readFile(resolve(workspace, 'packages', file!), 'utf8');
+ const match = source.match(new RegExp(`const ${name} = \x60([\\s\\S]*?)\x60;`)); assert(match, `${name} remains a literal stylesheet`); css.push(match[1]!);
+ }
+ await writeFile(resolve(out, 'index.html'), `<!doctype html><html><body><style>body{margin:0}#fixture{position:absolute;left:40px;top:30px;width:360px;height:280px}.fixture-nested{position:absolute;inset:0;pointer-events:none!important}${css.join('\n')}</style><div id="fixture"></div><script type="module" src="./hud-fixture.js"></script></body></html>`);
+ server = await serveOwned(out);
+ browser = await launchChrome({ workspace, name: 'hud-layout', windowSize: [1280, 900] });
+ const page = await browser.newPage(); await page.setViewport({ width: 1280, height: 900, hasTouch: true });
+ const errors: string[] = []; page.on('pageerror', error => errors.push(String(error)));
+ await page.goto(server.url); await page.waitForSelector('.ks-help-button');
+ const check = async (name: string, run: () => Promise<void>) => {
+ try { await run(); results.push({ name, pass: true }); }
+ catch (error) { results.push({ name, pass: false, error: error instanceof Error ? error.stack ?? error.message : String(error) }); }
+ };
+ for (const variant of ['kit', 'farm', 'golden-gate', 'foundry-floor']) {
+ for (const [width, height] of [[360, 280], [760, 320], [1120, 720]]) {
+ await page.evaluate(({ variant, width, height }) => {
+ Object.assign(document.getElementById('fixture')!.style, { width: `${width}px`, height: `${height}px` });
+ (window as any).__mountHud(variant);
+ }, { variant, width, height });
+ await page.waitForFunction(variant => document.querySelector('.ks-root')?.getAttribute('data-fixture') === variant && document.querySelector('.ks-help-button')?.getAttribute('aria-expanded') === 'false', {}, variant);
+ for (const kind of ['help', 'credits']) {
+ await page.click(`.ks-${kind}-button`); await page.waitForSelector(`.ks-${kind}`);
+ await check(`${variant} ${width}x${height} ${kind}: bounds, scroll and hit-testing`, async () => {
+ const measured = await page.$eval(`.ks-${kind}`, panel => {
+ const box = panel.getBoundingClientRect(), root = panel.closest('.ks-root')!.getBoundingClientRect();
+ const node = panel as HTMLElement; node.scrollTop = node.scrollHeight;
+ return { x: box.x, y: box.y, right: box.right, bottom: box.bottom, width: box.width, height: box.height,
+ root: { x: root.x, y: root.y, right: root.right, bottom: root.bottom }, scroll: node.scrollTop,
+ hit: panel.contains(document.elementFromPoint(box.right - 20, box.bottom - 20)) };
+ });
+ assert(measured.height >= 80, `Usable panel height: ${JSON.stringify(measured)}`);
+ assert(measured.x >= measured.root.x && measured.y >= measured.root.y && measured.right <= measured.root.right + 1 && measured.bottom <= measured.root.bottom + 1, `Panel stays in embedded HUD: ${JSON.stringify(measured)}`);
+ assert(measured.scroll > 0, 'Long content scrolls'); assert(measured.hit, 'Panel receives the hit above controls');
+ });
+ await check(`${variant} ${width}x${height} ${kind}: keyboard entry and Escape restore focus`, async () => {
+ await page.keyboard.press('Tab');
+ assert.equal(await page.$eval(`.ks-${kind}`, panel => panel.contains(document.activeElement)), true, 'Tab enters panel controls');
+ await page.keyboard.press('Escape');
+ await page.waitForFunction(selector => !document.querySelector(selector), {}, `.ks-${kind}`);
+ assert.equal(await page.$eval(`.ks-${kind}-button`, button => document.activeElement === button), true);
+ });
+ }
+ await check(`${variant} ${width}x${height}: nested touch controls`, async () => {
+ const before = await page.evaluate(() => (window as any).__canvasHits);
+ const box = await page.$eval('.ks-joystick', node => { const r = node.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; });
+ const stick = await page.touchscreen.touchStart(box.x, box.y); await stick.move(box.x + 25, box.y - 25);
+ const moving = await page.evaluate(() => ({ ...(window as any).__input.state.move }));
+ await stick.end(); assert(moving.x > 0 && moving.y > 0, 'Nested touch joystick changes movement');
+ assert.equal(await page.evaluate(() => (window as any).__input.state.move.x + (window as any).__input.state.move.y), 0, 'Releasing touch stops movement');
+ await page.$eval('.ks-touch-button', node => (node as HTMLElement).scrollIntoView({ block: 'nearest' }));
+ const action = await page.$eval('.ks-touch-button', node => { const r = node.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; });
+ const touch = await page.touchscreen.touchStart(action.x, action.y);
+ assert.equal(await page.evaluate(() => (window as any).__input.state.actions.boost), 1);
+ await touch.end(); assert.equal(await page.evaluate(() => (window as any).__input.state.actions.boost), 0);
+ assert.equal(await page.evaluate(() => (window as any).__canvasHits), before, 'Controls do not click through');
+ });
+ }
+ }
+ // Public GG/Foundry panels live inside More. Selecting a panel closes that menu,
+ // so its own trigger is hidden by CSS even while the panel remains open.
+ for (const [width, height] of [[360, 280], [1120, 720]]) {
+ await page.evaluate(({ width, height }) => {
+ Object.assign(document.getElementById('fixture')!.style, { width: `${width}px`, height: `${height}px` });
+ (window as any).__mountHud('menu');
+ }, { width, height });
+ await page.waitForFunction(() => document.querySelector('.ks-root')?.getAttribute('data-fixture') === 'menu');
+ for (const kind of ['help', 'credits']) for (const method of ['Escape', 'Close']) {
+ await check(`collapsed More ${width}x${height} ${kind}: ${method} restores visible menu focus`, async () => {
+ await page.waitForSelector('.ks-menu-trigger', { visible: true });
+ assert.equal(await page.$eval('.ks-menu-trigger', button => {
+ const rect = button.getBoundingClientRect();
+ return button.contains(document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2));
+ }), true, 'The public-style More toolbar must receive the click');
+ await page.click('.ks-menu-trigger');
+ await page.waitForFunction(() => document.querySelector('.ks-menu-trigger')?.getAttribute('aria-expanded') === 'true');
+ await page.waitForSelector(`.ks-${kind}-button`, { visible: true });
+ await page.click(`.ks-${kind}-button`); await page.waitForSelector(`.ks-${kind}`, { visible: true });
+ assert.equal(await page.$eval(`.ks-${kind}-button`, button => button.checkVisibility()), false, 'The original panel trigger is hidden in the collapsed menu');
+ const close = await page.$(`.ks-${kind} button`); assert(close);
+ if (method === 'Escape') { await close.focus(); await page.keyboard.press('Escape'); }
+ else await close.click();
+ await page.waitForSelector(`.ks-${kind}`, { hidden: true });
+ assert.equal(await page.$eval('.ks-menu-trigger', button => document.activeElement === button && button.checkVisibility()), true, 'Focus returns to visible More');
+ });
+ }
+ }
+ // Foundry campus has a second row of More controls underneath the fixed help
+ // panel. Reopening More must make those actual touch targets reachable while
+ // keeping both panels mounted; visibility alone does not establish that.
+ for (const [width, height] of [[390, 844], [360, 280], [760, 320], [1120, 720]]) {
+ await page.evaluate(({ width, height }) => {
+ Object.assign(document.getElementById('fixture')!.style, { width: `${width}px`, height: `${height}px` });
+ (window as any).__mountHud('foundry-campus');
+ }, { width, height });
+ await page.waitForFunction(() => document.querySelector('.ks-root')?.getAttribute('data-fixture') === 'foundry-campus');
+ await check(`Foundry campus ${width}x${height}: reopened More remains touchable above stacked panels`, async () => {
+ const tap = async (selector: string) => {
+ await page.waitForSelector(selector, { visible: true });
+ const point = await page.$eval(selector, node => {
+ const r = node.getBoundingClientRect(), x = r.x + r.width / 2, y = r.y + r.height / 2;
+ const hit = document.elementFromPoint(x, y);
+ return { x, y, hit: hit?.outerHTML, receivesTouch: node.contains(hit) };
+ });
+ assert(point.receivesTouch, `Actual touch target ${selector} is covered: ${JSON.stringify(point)}`);
+ await page.touchscreen.tap(point.x, point.y);
+ };
+ const more = '.ks-menu-trigger[aria-label="More"]';
+ await tap(more); await page.waitForFunction(selector => document.querySelector(selector)?.getAttribute('aria-expanded') === 'true', {}, more);
+ await tap('.ks-help-button'); await page.waitForSelector('.ks-help', { visible: true });
+ assert.equal(await page.$eval(more, button => button.getAttribute('aria-expanded')), 'false', 'Choosing Controls collapses More');
+ await tap(more); await page.waitForFunction(selector => document.querySelector(selector)?.getAttribute('aria-expanded') === 'true', {}, more);
+ await tap('.ks-credits-button'); await page.waitForSelector('.ks-credits', { visible: true });
+ assert.equal(await page.$eval('.ks-help', panel => panel.checkVisibility()), true, 'Opening Credits preserves Controls');
+ const panel = await page.$eval('.ks-credits', node => {
+ const element = node as HTMLElement; element.scrollTop = element.scrollHeight;
+ const r = element.getBoundingClientRect();
+ return { scroll: element.scrollTop, receivesTouch: element.contains(document.elementFromPoint(r.right - 20, r.bottom - 20)) };
+ });
+ assert(panel.scroll > 0 && panel.receivesTouch, 'The stacked Credits panel still scrolls and receives touch');
+ await tap(more); await page.waitForFunction(selector => document.querySelector(selector)?.getAttribute('aria-expanded') === 'true', {}, more);
+ await tap('.ks-help-button'); await page.waitForSelector('.ks-help', { hidden: true });
+ assert.equal(await page.$eval('.ks-credits', panel => panel.checkVisibility()), true, 'A menu action can close Controls while Credits stays open');
+ await page.$eval('.ks-credits button', button => (button as HTMLButtonElement).focus());
+ await page.keyboard.press('Escape'); await page.waitForSelector('.ks-credits', { hidden: true });
+ assert.equal(await page.$eval(more, button => document.activeElement === button && button.checkVisibility()), true, 'Escape returns focus to visible More');
+ });
+ }
+ console.log(JSON.stringify({ scope: 'DOM-only shared HUD with current Farm, Golden Gate and Foundry styles; no renderer qualification', results }, null, 2));
+ assert.deepEqual(errors, [], 'No browser errors');
+ assert(results.every(result => result.pass), `${results.filter(result => !result.pass).length} HUD browser contracts failed`);
+} finally { try { await browser?.close(); } finally { await server?.close(); await rm(out, { recursive: true, force: true }); } }
diff --git a/scenes/packages/scene-kit/tests/browser/run-input-handoff.ts b/scenes/packages/scene-kit/tests/browser/run-input-handoff.ts
new file mode 100644
index 00000000..3b040831
--- /dev/null
+++ b/scenes/packages/scene-kit/tests/browser/run-input-handoff.ts
@@ -0,0 +1,75 @@
+// Explicit DOM-only gate: root runs it before and after the source fix. No scene/GPU/timing work.
+// From scenes: bun packages/scene-kit/tests/browser/run-input-handoff.ts new-label
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { launchChrome, serveOwned } from '../../src/testing/node';
+import { cleanupTimingResources } from '../../../../scripts/timing-evidence';
+const workspace = resolve(import.meta.dir, '../../../..'), label = process.argv[2];
+assert(/^[a-z0-9][a-z0-9-]*$/.test(label ?? ''), 'New output label required');
+const out = resolve(workspace, '.tmp/alignment-motion', label); assert(!existsSync(out), 'Refusing to overwrite evidence'); mkdirSync(out);
+const hash = (path: string) => createHash('sha256').update(readFileSync(path)).digest('hex');
+const report: any = { schema: 'kiln.input-handoff-dom/1', scope: 'Real React VirtualJoystick lifecycle and InputProvider binding; emulated pointers, no scene renderer/assets or physical-device claim.', sources: {}, results: [], errors: [] };
+for (const file of ['../../src/input/core.ts', '../../src/input/index.tsx', './input-handoff-fixture.tsx', './run-input-handoff.ts']) report.sources[file] = hash(resolve(import.meta.dir, file));
+const resources: { name: string; close(): Promise<void>; timeoutMs?: number }[] = [];
+try {
+ const build = await Bun.build({ entrypoints: [resolve(import.meta.dir, 'input-handoff-fixture.tsx')], outdir: out, target: 'browser', define: { 'process.env.NODE_ENV': '"production"' } }); assert(build.success, build.logs.join('\n'));
+ writeFileSync(resolve(out, 'index.html'), '<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{margin:0}.ks-joystick{position:absolute;left:60px;top:80px;width:132px;height:132px;background:#789;touch-action:none}.ks-sr-only{display:none}</style><div id="fixture"></div><script type="module" src="./input-handoff-fixture.js"></script>');
+ const hosted = await serveOwned(out); resources.unshift({ name: 'server', close: hosted.close, timeoutMs: 5000 });
+ const browser = await launchChrome({ workspace, name: label, headless: true, windowSize: [800, 500] }); resources.unshift({ name: 'browser', close: () => browser.close(), timeoutMs: 10000 });
+ const page = await browser.newPage(); resources.unshift({ name: 'page', close: () => page.close(), timeoutMs: 5000 });
+ page.on('pageerror', error => report.errors.push(String(error))); await page.setViewport({ width: 800, height: 500, hasTouch: true });
+ await page.goto(hosted.url); await page.waitForSelector('.ks-joystick');
+ const cdp = await page.createCDPSession(); resources.unshift({ name: 'cdp', close: () => cdp.detach(), timeoutMs: 5000 });
+ const settle = () => page.evaluate(() => new Promise<void>(done => requestAnimationFrame(() => requestAnimationFrame(() => done()))));
+ const state = () => page.evaluate(() => (window as any).__inputState());
+ const focus = () => page.$eval('.ks-root', element => (element as HTMLElement).focus());
+ async function mount(mode = 'switch') { await page.evaluate(mode => (window as any).__mountInput(mode), mode); await settle(); }
+ let touchActive = false;
+ async function down() {
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: 126, y: 146, id: 1 }] }); touchActive = true;
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: 158, y: 96, id: 1 }] }); await settle();
+ const moving = await state(); assert(moving.move.x > 0 && moving.move.y > 0, 'Joystick acquired movement'); return moving;
+ }
+ const end = async (cancel = false) => { if (!touchActive) return; touchActive = false; await cdp.send('Input.dispatchTouchEvent', { type: cancel ? 'touchCancel' : 'touchEnd', touchPoints: [] }); };
+ const check = async (name: string, run: (row: any) => Promise<void>) => {
+ const row: any = { name, pass: false }; report.results.push(row);
+ try { await run(row); row.pass = true; }
+ catch (error) { row.failure = error instanceof Error ? error.stack : String(error); }
+ finally { await page.keyboard.up('w'); await page.keyboard.up('Shift'); await end(); await settle(); }
+ console.log(`${row.pass ? 'pass' : 'FAIL'} ${name}`);
+ };
+ await check('idle joystick unmount preserves first keyboard movement', async row => {
+ await mount(); await focus(); await page.keyboard.down('w'); await settle(); row.after = await state();
+ assert.equal(row.after.joystick, false); assert.deepEqual(row.after.move, { x: 0, y: 1 });
+ });
+ await check('active joystick to keyboard unmount preserves newer key and release', async row => {
+ await mount(); row.touch = await down(); await focus(); await page.keyboard.down('w'); await settle(); row.keyboard = await state();
+ assert.equal(row.keyboard.joystick, false); assert.deepEqual(row.keyboard.move, { x: 0, y: 1 });
+ await page.keyboard.down('Shift'); await settle(); row.shifted = await state(); assert.equal(row.shifted.run, true);
+ await end(); await settle(); row.releasedTouch = await state(); assert.deepEqual(row.releasedTouch.move, { x: 0, y: 1 });
+ await page.keyboard.up('w'); await page.keyboard.up('Shift'); await settle(); row.releasedKeys = await state(); assert.deepEqual(row.releasedKeys.move, { x: 0, y: 0 }); assert.equal(row.releasedKeys.run, false);
+ });
+ await check('old touch cancel cannot clear newer keyboard while joystick stays mounted', async row => {
+ await mount('always'); row.touch = await down(); await focus(); await page.keyboard.down('w'); await settle(); row.keyboard = await state();
+ await end(true); await settle(); row.canceled = await state(); assert.deepEqual(row.canceled.move, { x: 0, y: 1 });
+ });
+ for (const canceled of [false, true]) await check(`owned touch ${canceled ? 'cancel' : 'release'} stops movement`, async row => {
+ await mount('always'); row.touch = await down(); await end(canceled); await settle(); row.after = await state(); assert.deepEqual(row.after.move, { x: 0, y: 0 }); assert.equal(row.after.run, false);
+ });
+ await check('unmount active joystick releases its own movement', async row => {
+ await mount('always'); row.touch = await down(); await page.evaluate(() => (window as any).__hideStick()); await settle(); row.after = await state();
+ assert.equal(row.after.joystick, false); assert.deepEqual(row.after.move, { x: 0, y: 0 });
+ });
+ for (const action of ['__disableInput', '__disposeInput']) await check(`${action} clears movement and later cancel stays inactive`, async row => {
+ await mount('always'); row.touch = await down(); await page.evaluate(action => (window as any)[action](), action); await end(true); await settle(); row.after = await state();
+ assert.equal(row.after.enabled, false); assert.deepEqual(row.after.move, { x: 0, y: 0 }); assert.equal(row.after.run, false);
+ });
+} catch (error) { report.failure = error instanceof Error ? error.stack : String(error); }
+finally {
+ report.cleanup = await cleanupTimingResources(resources);
+ report.pass = !report.failure && report.errors.length === 0 && report.results.length === 8 && report.results.every((row: any) => row.pass) && report.cleanup.every((row: any) => row.ok);
+ writeFileSync(resolve(out, 'receipt.json'), JSON.stringify(report, null, 2) + '\n'); console.log(JSON.stringify({ out, pass: report.pass, results: report.results.map((row: any) => ({ name: row.name, pass: row.pass })), failure: report.failure, errors: report.errors, cleanup: report.cleanup }));
+ if (!report.pass) process.exitCode = 1;
+}
diff --git a/scenes/packages/scene-kit/tests/build/producer.test.ts b/scenes/packages/scene-kit/tests/build/producer.test.ts
new file mode 100644
index 00000000..be8f0079
--- /dev/null
+++ b/scenes/packages/scene-kit/tests/build/producer.test.ts
@@ -0,0 +1,32 @@
+import { afterEach, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { bundleModuleManifest } from '../../src/build';
+
+const directories: string[] = [];
+afterEach(async () => { for (const path of directories.splice(0)) await rm(path, { recursive: true, force: true }); });
+
+test('standalone builds emit exact producer versions and byte-bound chunks beside their modules', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'kiln-scene-producer-')); directories.push(root);
+ const packageRoot = join(root, 'node_modules/three');
+ await mkdir(packageRoot, { recursive: true });
+ await writeFile(join(packageRoot, 'package.json'), JSON.stringify({ name: 'three', version: '0.186.1' }));
+ const module = join(packageRoot, 'build/three.core.js');
+ const code = 'export const label = "scène";\n';
+ const emitted: any[] = [];
+ const plugin = bundleModuleManifest();
+ const hook: any = plugin.generateBundle;
+ const generate = typeof hook === 'function' ? hook : hook.handler;
+ generate.call({ emitFile: (file: unknown) => emitted.push(file) }, {}, { 'assets/index-a.js': { type: 'chunk', fileName: 'assets/index-a.js', code, modules: { [module]: {} } } });
+ expect(emitted).toHaveLength(1);
+ const record = JSON.parse(emitted[0].source);
+ expect(record.modules).toEqual([module]);
+ expect(record.producer).toMatchObject({ schema: 'kiln.scene-producer/1', dependencies: { three: '0.186.1', react: null, 'react-dom': null, '@react-three/fiber': null }, chunks: [{ file: 'assets/index-a.js', bytes: Buffer.byteLength(code), sha256: createHash('sha256').update(code).digest('hex') }] });
+ expect(record.producer.build.vite).toMatch(/^\d+\.\d+\.\d+$/);
+ expect(record.producer.build.pluginReact).toMatch(/^\d+\.\d+\.\d+$/);
+ expect(JSON.stringify(record.producer)).not.toContain(root);
+ await writeFile(join(packageRoot, 'package.json'), JSON.stringify({ name: 'wrong', version: '0.186.1' }));
+ expect(() => generate.call({ emitFile: () => {} }, {}, { 'assets/index-a.js': { type: 'chunk', fileName: 'assets/index-a.js', code, modules: { [module]: {} } } })).toThrow('three');
+});
diff --git a/scenes/packages/scene-kit/tests/camera/follow.test.ts b/scenes/packages/scene-kit/tests/camera/follow.test.ts
new file mode 100644
index 00000000..94cdc18a
--- /dev/null
+++ b/scenes/packages/scene-kit/tests/camera/follow.test.ts
@@ -0,0 +1,130 @@
+import { describe, expect, test } from 'bun:test';
+import { Object3D, PerspectiveCamera, Vector3 } from 'three/webgpu';
+import type { FollowOptions } from '../../src/camera/core';
+import { createFollowController } from '../../src/camera/follow';
+
+/** Native OrbitControls events, with a rendered follow frame after every pointer move. */
+function fixture() {
+ const root = new EventTarget(), captured = new Set<number>();
+ const canvas = Object.assign(new EventTarget(), {
+ style: { touchAction: '', cursor: '' }, ownerDocument: root, getRootNode: () => root,
+ clientWidth: 412, clientHeight: 915,
+ setPointerCapture: (id: number) => captured.add(id), releasePointerCapture: (id: number) => captured.delete(id),
+ getBoundingClientRect: () => ({ left: 0, top: 0, width: 412, height: 915 }),
+ });
+ const camera = new PerspectiveCamera(), subject = new Object3D(); subject.position.set(4, 1.9, -7);
+ const visibility: boolean[] = [];
+ let hit = Infinity;
+ const options: FollowOptions & { active: boolean } = {
+ active: true, subject: { current: subject }, targetHeight: 0, offset: () => [0, .6, 4.8],
+ fov: 58, maxPolar: Math.PI * .54, minDistance: 1.6, maxDistance: 10,
+ obstruction: { ray: (from, to) => Math.min(hit, from.distanceTo(to)), pad: .14, minDistance: .22,
+ hideSubjectBelow: 1.11, onSubjectVisible: v => visibility.push(v) },
+ };
+ const follow = createFollowController(camera, canvas as unknown as HTMLCanvasElement, root as HTMLElement, () => options);
+ follow.update();
+ const pointer = (type: string, id: number, x: number, y = 350, pointerType = 'touch') => {
+ const event = Object.assign(new Event(type, { cancelable: true }), { pointerId: id, pointerType, button: 0, buttons: type === 'pointerup' ? 0 : 1, pageX: x, pageY: y, clientX: x, clientY: y, ctrlKey: false, metaKey: false, shiftKey: false });
+ (type === 'pointerdown' || type === 'pointercancel' ? canvas : root).dispatchEvent(event);
+ follow.update();
+ };
+ const pinch = (from: number, to: number, steps = 24) => {
+ pointer('pointerdown', 1, 206 - from); pointer('pointerdown', 2, 206 + from);
+ for (let i = 1; i <= steps; i++) { const half = from + (to - from) * i / steps; pointer('pointermove', 1, 206 - half); pointer('pointermove', 2, 206 + half); }
+ pointer('pointerup', 2, 206 + to); pointer('pointerup', 1, 206 - to);
+ };
+ return { follow, options, camera, subject, visibility, pointer, pinch, captured,
+ distance: () => camera.position.distanceTo(follow.handle.controls.target),
+ direction: () => camera.position.clone().sub(follow.handle.controls.target).normalize(),
+ obstruct(distance: number) { hit = distance; follow.update(); },
+ wheel(deltaY: number) { canvas.dispatchEvent(Object.assign(new Event('wheel', { cancelable: true }), { deltaY, deltaMode: 0, clientX: 206, clientY: 350, ctrlKey: false })); follow.update(); },
+ };
+}
+const initialDistance = Math.hypot(.6, 4.8);
+
+describe('follow camera desired orbit versus collision view', () => {
+ test.each(['touch', 'mouse'])('%s one-pointer orbit preserves zoom across many collision-padded frames', pointerType => {
+ const f = fixture();
+ try {
+ const before = f.direction(), target = f.subject.position.clone();
+ f.pointer('pointerdown', 1, 180, 350, pointerType);
+ for (let i = 1; i <= 48; i++) f.pointer('pointermove', 1, 180 + i * 2, 350, pointerType);
+ f.pointer('pointerup', 1, 276, 350, pointerType);
+ expect(f.distance()).toBeCloseTo(initialDistance - .14, 9);
+ expect(before.angleTo(f.direction())).toBeGreaterThan(.5);
+ expect(f.follow.handle.controls.target.distanceTo(target)).toBeLessThan(1e-10);
+ expect(f.subject.position.equals(target)).toBe(true);
+ expect(f.captured.size).toBe(0);
+ } finally { f.follow.dispose(); }
+ });
+ test('pinch scales desired distance in both directions and clamps at follow limits', () => {
+ const f = fixture();
+ try {
+ const before = f.direction(), target = f.subject.position.clone();
+ f.pinch(60, 90); expect(f.distance()).toBeCloseTo(initialDistance * 2 / 3 - .14, 8);
+ f.pinch(90, 60); expect(f.distance()).toBeCloseTo(initialDistance - .14, 8);
+ f.pinch(120, 10); expect(f.distance()).toBeCloseTo(10 - .14, 8);
+ f.pinch(10, 180); expect(f.distance()).toBeCloseTo(1.6 - .14, 8);
+ expect(before.angleTo(f.direction())).toBeLessThan(1e-7);
+ expect(f.subject.position.equals(target)).toBe(true);
+ expect(f.follow.handle.controls.target.distanceTo(target)).toBeLessThan(1e-10);
+ } finally { f.follow.dispose(); }
+ });
+ test('orbit behind a close obstacle retains requested distance when the obstacle clears', () => {
+ const f = fixture();
+ try {
+ f.obstruct(.5); expect(f.distance()).toBeCloseTo(.36, 9); expect(f.visibility).toEqual([false]);
+ expect(f.follow.handle.pose.position).toEqual(f.camera.position.toArray());
+ expect(f.follow.handle.pose.target).toEqual(f.subject.position.toArray());
+ f.pointer('pointerdown', 1, 180);
+ for (let i = 1; i <= 20; i++) f.pointer('pointermove', 1, 180 + i * 2);
+ f.pointer('pointerup', 1, 220);
+ f.obstruct(Infinity); expect(f.distance()).toBeCloseTo(initialDistance - .14, 9);
+ expect(f.visibility).toEqual([false, true]);
+ expect(f.follow.handle.pose.position).toEqual(f.camera.position.toArray());
+ } finally { f.follow.dispose(); }
+ });
+ test('pinch and wheel change the desired zoom while obstructed without putting the camera through a wall', () => {
+ const f = fixture();
+ try {
+ f.obstruct(.3); f.pinch(120, 10); expect(f.distance()).toBeCloseTo(.22, 9);
+ f.obstruct(Infinity); expect(f.distance()).toBeCloseTo(9.86, 8);
+ f.obstruct(.3); f.wheel(-100); expect(f.distance()).toBeCloseTo(.22, 9);
+ f.obstruct(Infinity); expect(f.distance()).toBeLessThan(9.86); expect(f.distance()).toBeGreaterThan(8);
+ f.follow.handle.zoomBy(.0001); f.follow.update(); expect(f.distance()).toBeCloseTo(1.46, 8);
+ f.follow.handle.zoomBy(10000); f.follow.update(); expect(f.distance()).toBeCloseTo(9.86, 8);
+ } finally { f.follow.dispose(); }
+ });
+ test('subject translation preserves orbit; inactive controls leave overview alone; reentry and vehicle target reset offset', () => {
+ const f = fixture();
+ try {
+ const relative = f.camera.position.clone().sub(f.subject.position);
+ f.subject.position.add(new Vector3(3, 1, -2)); f.follow.update();
+ expect(f.camera.position.clone().sub(f.subject.position).distanceTo(relative)).toBeLessThan(1e-10);
+ f.options.active = false; f.follow.update(); f.camera.position.set(10, 20, 30);
+ f.pointer('pointerdown', 1, 100); f.pointer('pointermove', 1, 160); f.pointer('pointerup', 1, 160);
+ expect(f.camera.position.toArray()).toEqual([10, 20, 30]);
+ f.options.active = true; f.follow.update(); expect(f.distance()).toBeCloseTo(initialDistance - .14, 9);
+ const tractor = new Object3D(); tractor.position.set(10, 1.6, 6);
+ f.options.subject.current = tractor; f.options.offset = () => [0, 2.6, 4.8]; f.follow.update();
+ expect(f.follow.handle.controls.target.distanceTo(tractor.position)).toBeLessThan(1e-10);
+ expect(f.distance()).toBeCloseTo(Math.hypot(2.6, 4.8) - .14, 9);
+ } finally { f.follow.dispose(); }
+ });
+ test('canceling both touches releases capture and ends the gesture; a fresh drag still orbits', () => {
+ const f = fixture();
+ try {
+ f.pointer('pointerdown', 1, 140); f.pointer('pointerdown', 2, 260);
+ f.pointer('pointermove', 1, 120); f.pointer('pointermove', 2, 280);
+ f.pointer('pointercancel', 2, 280); f.pointer('pointercancel', 1, 120);
+ expect(f.captured.size).toBe(0);
+ const position = f.camera.position.clone(), distance = f.distance(), direction = f.direction();
+ f.pointer('pointermove', 1, 180); f.pointer('pointermove', 2, 220);
+ expect(f.camera.position.distanceTo(position)).toBeLessThan(1e-10);
+ f.pointer('pointerdown', 3, 180); f.pointer('pointermove', 3, 240); f.pointer('pointerup', 3, 240);
+ expect(direction.angleTo(f.direction())).toBeGreaterThan(.3);
+ expect(f.distance()).toBeCloseTo(distance, 9);
+ expect(f.captured.size).toBe(0);
+ } finally { f.follow.dispose(); }
+ });
+});
diff --git a/scenes/packages/scene-kit/tests/input/input.test.ts b/scenes/packages/scene-kit/tests/input/input.test.ts
index 60f8e5c8..86f4e2a1 100644
--- a/scenes/packages/scene-kit/tests/input/input.test.ts
+++ b/scenes/packages/scene-kit/tests/input/input.test.ts
@@ -55,4 +55,31 @@ describe('U-17 input core', () => {
cleanup(); input.setMove(1, 0, false); doc.defaultView.dispatchEvent(new Event('blur')); expect(input.state.move.x).toBe(1);
input.dispose(); expect(input.state.move.x).toBe(0);
});
+ test('movement release belongs to its writer; keyboard and unowned writes supersede joystick cleanup', () => {
+ const input = createInputApi(), first = {}, second = {};
+ input.setEnabled(true);
+ input.setMove(.4, .8, true, first); input.releaseMove(second);
+ expect(input.state.move).toEqual({ x: .4, y: .8 }); expect(input.state.run).toBe(true);
+ input.setMove(-.6, 1, false, second); input.releaseMove(first);
+ expect(input.state.move).toEqual({ x: -.6, y: 1 });
+ input.releaseMove(second); expect(input.state.move).toEqual({ x: 0, y: 0 });
+ input.setMove(.4, .8, true, first);
+ // A pointer-mode subscriber may synchronously unmount/release a joystick at keydown.
+ const stop = input.subscribe(() => input.releaseMove(first));
+ input.key('KeyW', true); expect(input.state.move).toEqual({ x: 0, y: 1 }); expect(input.state.run).toBe(false);
+ input.key('ShiftLeft', true); input.releaseMove(first); expect(input.state.run).toBe(true);
+ input.key('KeyW', false); input.key('ShiftLeft', false); expect(input.state.move).toEqual({ x: 0, y: 0 }); expect(input.state.run).toBe(false);
+ input.setMove(1, 0, true, first); input.setMove(.2, -.3, false); input.releaseMove(first);
+ expect(input.state.move).toEqual({ x: .2, y: -.3 }); stop(); input.dispose();
+ });
+ test('clear, disabling and disposal invalidate movement ownership', () => {
+ const input = createInputApi(), owner = {};
+ input.setEnabled(true); input.setMove(1, 1, true, owner); input.clear(); input.releaseMove(owner);
+ expect(input.state.move).toEqual({ x: 0, y: 0 }); expect(input.state.run).toBe(false);
+ input.setMove(.5, .5, true, owner); input.setEnabled(false); input.setMove(1, 1, true, owner); input.releaseMove(owner);
+ expect(input.state.move).toEqual({ x: 0, y: 0 }); expect(input.state.run).toBe(false);
+ input.setEnabled(true); input.key('KeyD', true); input.releaseMove(owner); expect(input.state.move).toEqual({ x: 1, y: 0 });
+ input.dispose(); input.setMove(1, 1, true, owner); input.releaseMove(owner);
+ expect(input.state.move).toEqual({ x: 0, y: 0 }); expect(input.state.run).toBe(false);
+ });
});
diff --git a/scenes/packages/scene-kit/tests/renderer/core.test.ts b/scenes/packages/scene-kit/tests/renderer/core.test.ts
index c621415c..6350c5ae 100644
--- a/scenes/packages/scene-kit/tests/renderer/core.test.ts
+++ b/scenes/packages/scene-kit/tests/renderer/core.test.ts
@@ -25,3 +25,15 @@ test('factory awaits init and drops late results with terminal disposal', async
const result=factory({canvas:{} as any,powerPreference:'high-performance',antialias:true,alpha:false});
finish(); await expect(result).rejects.toHaveProperty('name','AbortError'); expect(disposed).toBe(true);
});
+test('reversed depth is opt-in and preserves the initialized backend fallback', async () => {
+ for (const request of [undefined, false, true]) for (const supported of [false, true]) {
+ let params: any;
+ const renderer = { backend:{isWebGLBackend:true}, reversedDepthBuffer:false,
+ async init(){this.reversedDepthBuffer=!!params.reversedDepthBuffer && supported;},
+ hasInitialized:()=>true,dispose:async()=>{} } as any;
+ const factory=createGlFactory({reversedDepthBuffer:request,isDisposed:()=>false,makeRenderer:p=>{params=p;return renderer;}});
+ const ready=await factory({canvas:{} as any,powerPreference:'high-performance',antialias:true,alpha:false});
+ expect(params.reversedDepthBuffer).toBe(request ?? false);
+ expect(ready.reversedDepthBuffer).toBe(!!request && supported);await ready.dispose();
+ }
+});
diff --git a/scenes/packages/scene-kit/tests/shadows/cache.test.ts b/scenes/packages/scene-kit/tests/shadows/cache.test.ts
index 211fb067..c98da268 100644
--- a/scenes/packages/scene-kit/tests/shadows/cache.test.ts
+++ b/scenes/packages/scene-kit/tests/shadows/cache.test.ts
@@ -1,5 +1,6 @@
import { expect, test } from 'bun:test';
-import { BoxGeometry, DirectionalLight, Group, HalfFloatType, InstancedMesh, Layers, Mesh, MeshStandardMaterial, OrthographicCamera, PerspectiveCamera, Scene, SkinnedMesh } from 'three/webgpu';
+import { BoxGeometry, DirectionalLight, Group, HalfFloatType, InstancedBufferAttribute, InstancedMesh, Layers, Mesh, MeshStandardMaterial, MeshStandardNodeMaterial, OrthographicCamera, PerspectiveCamera, Scene, SkinnedMesh } from 'three/webgpu';
+import { attribute, positionLocal, uniform, vec3 } from 'three/tsl';
import { cachedSunShadow } from '../../src/shadows/cache';
import type { CachedSunShadowOptions } from '../../src/shadows/cache';
import { keepsShadowMask, layerBit, ShadowLayers, suppressedCasters } from '../../src/shadows/layers';
@@ -126,6 +127,67 @@ test('watched casters also go live on ancestor visibility, castShadow and instan
expect(skinned.layers.mask).toBe(1 | D_BIT); // bones move without a matrixWorld change
});
+test('watched morph influences promote with an unchanged matrix, settle, and release their history on untrack', () => {
+ const { scene, cache, S, D, step } = setup(), g = geometry.clone();
+ g.morphAttributes.position = [g.getAttribute('position').clone(), g.getAttribute('position').clone()];
+ for (const [target, positions] of g.morphAttributes.position.entries()) {
+ for (let i = 0; i < positions.count; i++) positions.setY(i, positions.getY(i) + target + 1);
+ }
+ const morph = new Mesh(g, material); morph.name = 'morph'; morph.castShadow = true;
+ scene.add(morph); scene.updateMatrixWorld(true);
+ const matrix = [...morph.matrixWorld.elements], tracked = cache.track(scene, { movable: n => n === morph });
+ step(); step(); step();
+ morph.morphTargetInfluences![1] = .75; step([main, mirror]);
+ expect(morph.matrixWorld.elements).toEqual(matrix);
+ expect(morph.layers.mask).toBe(1 | D_BIT);
+ expect([S.log.at(-1), D.log.at(-1)]).toEqual([[3], [3, 'morph']]);
+ step(); step(); expect(morph.layers.mask).toBe(1 | D_BIT);
+ step(); expect(morph.layers.mask).toBe(1 | S_BIT); // unchanged influence values calm after settleFrames
+ const settled = [S.log.length, D.log.length];
+ morph.morphTargetInfluences = [...morph.morphTargetInfluences!]; step();
+ expect([S.log.length, D.log.length]).toEqual(settled); // array identity is not deformation
+ morph.morphTargetInfluences![1] = 0; step(); expect(morph.layers.mask).toBe(1 | D_BIT);
+ tracked.untrack(); morph.morphTargetInfluences![0] = 1; step();
+ expect(morph.layers.mask).toBe(1); expect(cache.stats.liveCasters).toBe(0);
+ // Re-adding snapshots today's pose, not the previous registration's influences.
+ cache.track(scene, { movable: n => n === morph }); step(); step(); step();
+ expect(morph.layers.mask).toBe(1 | S_BIT);
+ cache.dispose(); g.dispose();
+});
+
+test('a watched caster also notices morph target addition and removal', () => {
+ const { scene, cache, step } = setup(), morph = box('morph'); scene.add(morph); scene.updateMatrixWorld(true);
+ cache.track(scene, { movable: n => n === morph }); step(); step();
+ morph.morphTargetInfluences = [0, 1]; step(); expect(morph.layers.mask).toBe(1 | D_BIT);
+ for (let i = 0; i < 3; i++) step(); expect(morph.layers.mask).toBe(1 | S_BIT);
+ morph.morphTargetInfluences = [0]; step(); expect(morph.layers.mask).toBe(1 | D_BIT);
+ for (let i = 0; i < 3; i++) step();
+ delete morph.morphTargetInfluences; step(); expect(morph.layers.mask).toBe(1 | D_BIT);
+ cache.dispose();
+});
+
+test('shader uniforms and custom instance attributes use explicit live or invalidation, without inspecting shader graphs', () => {
+ const { scene, cache, S, D, step } = setup(), liveRoot = new Group(), offset = uniform(0);
+ const g = geometry.clone(), motion = new InstancedBufferAttribute(new Float32Array([0, 1]), 1);
+ g.setAttribute('motion', motion);
+ const shader = new MeshStandardNodeMaterial(); shader.positionNode = positionLocal.add(vec3(offset, 0, 0));
+ const instanceShader = new MeshStandardNodeMaterial(); instanceShader.positionNode = positionLocal.add(vec3(attribute('motion', 'float'), 0, 0));
+ const vertex = new Mesh(geometry, shader), instances = new InstancedMesh(g, instanceShader, 2), discrete = new Mesh(geometry, shader);
+ vertex.name = 'vertex'; instances.name = 'instances'; discrete.name = 'discrete';
+ for (const m of [vertex, instances, discrete]) m.castShadow = true;
+ liveRoot.add(vertex, instances); scene.add(liveRoot, discrete); scene.updateMatrixWorld(true);
+ const matrices = [vertex, instances, discrete].map(m => [...m.matrixWorld.elements]), instanceVersion = instances.instanceMatrix.version;
+ cache.track(scene, { live: n => n === liveRoot, movable: () => true }); step(); step(); step();
+ const staticRenders = S.log.length;
+ offset.value = 2; motion.setX(0, 5); motion.needsUpdate = true; step([main, mirror]);
+ expect([vertex, instances, discrete].map(m => m.matrixWorld.elements)).toEqual(matrices);
+ expect(instances.instanceMatrix.version).toBe(instanceVersion);
+ expect(S.log.length).toBe(staticRenders); expect(D.log.at(-1)).toEqual([3, 'vertex', 'instances']);
+ // A discrete edit of the unpinned caster is the caller's responsibility.
+ cache.invalidate('shader pose'); step(); expect(S.log.at(-1)).toEqual([4, 'discrete']);
+ cache.dispose(); g.dispose(); shader.dispose(); instanceShader.dispose();
+});
+
test('invalidate re-arms the static map and records why; prime fills the live map once, then clears it', () => {
const { scene, cache, S, D, step } = setup(), still = box('still'), mover = box('mover'), rig = new Group();
rig.add(mover); scene.add(still, rig); scene.updateMatrixWorld(true); cache.track(scene, { movable: n => n === rig });
diff --git a/scenes/packages/scene-kit/tests/shadows/shadow-contract.test.ts b/scenes/packages/scene-kit/tests/shadows/shadow-contract.test.ts
index 147a5eda..81ec7414 100644
--- a/scenes/packages/scene-kit/tests/shadows/shadow-contract.test.ts
+++ b/scenes/packages/scene-kit/tests/shadows/shadow-contract.test.ts
@@ -121,10 +121,10 @@ function pinFailures(src: string, core: string, tsl: string): Record<string, str
const clean = (pins: Record<string, string[]>) => Object.fromEntries(Object.entries(pins).filter(([, bad]) => bad.length));
describe('three r186 contract for the cached sun shadow, once-per-frame and threshold', () => {
- test('the builds three/webgpu and three/tsl resolve to are 0.186.0', () => {
+ test('the builds three/webgpu and three/tsl resolve to are 0.186.1', () => {
expect(BUILD.replaceAll('\\', '/')).toEndWith('three/build/three.webgpu.js');
expect(TSL_BUILD.replaceAll('\\', '/')).toEndWith('three/build/three.tsl.js');
- expect(VERSION).toBe('0.186.0'); expect(REVISION).toBe('186');
+ expect(VERSION).toBe('0.186.1'); expect(REVISION).toBe('186');
});
test('every pinned snippet is present and in order', () => {
expect(clean(pinFailures(SOURCE, CORE, TSL))).toEqual({});
diff --git a/scenes/packages/scene-kit/tests/staging/staging.test.ts b/scenes/packages/scene-kit/tests/staging/staging.test.ts
index 2781ffaf..b01e900b 100644
--- a/scenes/packages/scene-kit/tests/staging/staging.test.ts
+++ b/scenes/packages/scene-kit/tests/staging/staging.test.ts
@@ -6,9 +6,19 @@ import { createHash } from 'node:crypto';
import { stageFiles, verifyStaged, readZip, verifyArchiveMembers } from '../../src/staging/index';
const root=resolve('packages/scene-kit/tests/staging/.tmp');
const hash=(b:Uint8Array)=>createHash('sha256').update(b).digest('hex');
+test('new packs require the current renderer pin while historical packs remain verifiable unchanged',()=>{
+ const plan={id:'pin',release:'r1',three:'0.186.1' as const,out:join(root,'pin'),models:[],data:{},files:[]};
+ try{
+ expect(()=>Reflect.apply(stageFiles,null,[{...plan,three:'0.186.0'}])).toThrow('Stage plan three pin must be 0.186.1');
+ stageFiles(plan);const path=join(plan.out,'pack.json'),current=JSON.parse(readFileSync(path,'utf8'));
+ expect(current.three).toBe('0.186.1');
+ const historical=JSON.stringify({...current,three:'0.186.0'},null,2)+'\n';writeFileSync(path,historical);
+ expect(verifyStaged(plan.out)).toEqual({ok:true,problems:[]});expect(readFileSync(path,'utf8')).toBe(historical);
+ }finally{rmSync(root,{recursive:true,force:true});}
+});
test('U-03/04 directory staging, zip verification, corruption and idempotence',()=>{
mkdirSync(root,{recursive:true});const b=new TextEncoder().encode('synthetic glb');writeFileSync(join(root,'a.glb'),b);
- const plan={id:'demo',release:'r1',three:'0.186.0' as const,out:join(root,'out'),models:[{id:'a',to:'models/a.glb'}],data:{},files:[{from:join(root,'a.glb'),to:'models/a.glb',sha256:hash(b)}]};
+ const plan={id:'demo',release:'r1',three:'0.186.1' as const,out:join(root,'out'),models:[{id:'a',to:'models/a.glb'}],data:{},files:[{from:join(root,'a.glb'),to:'models/a.glb',sha256:hash(b)}]};
try{expect(stageFiles(plan)).toEqual({files:1,bytes:b.length});expect(verifyStaged(plan.out)).toEqual({ok:true,problems:[]});expect(stageFiles(plan)).toEqual({files:1,bytes:b.length});
writeFileSync(join(plan.out,'models/a.glb'),'corrupt');expect(verifyStaged(plan.out).problems[0]).toContain('models/a.glb');expect(()=>stageFiles(plan)).toThrow('models/a.glb');stageFiles({...plan,force:true});
const zip=zipSync({'models/a.glb':b});writeFileSync(join(root,'test.zip'),zip);expect(readZip(join(root,'test.zip'),{bytes:zip.length,sha256:hash(zip)}).get('models/a.glb')).toEqual(b);expect(()=>readZip(join(root,'test.zip'),{bytes:zip.length,sha256:'0'.repeat(64)})).toThrow('test.zip');
@@ -21,6 +31,6 @@ test('U-03/04 synthetic runtime and scene archives share a verified model and st
mkdirSync(root,{recursive:true});const glb=new TextEncoder().encode('self-contained synthetic GLB payload'),layout=new TextEncoder().encode('{"placements":[]}\n'),scene=new TextEncoder().encode(JSON.stringify({assets:[{id:'a',runtimeSha256:'sha256:'+hash(glb)}]}));
const runtimeZip=zipSync({'models/a.glb':glb}),sceneZip=zipSync({'assets/a.glb':glb,'layout.json':layout,'scene.json':scene});writeFileSync(join(root,'runtime.zip'),runtimeZip);writeFileSync(join(root,'scene.zip'),sceneZip);
try{const runtime=readZip(join(root,'runtime.zip'),{bytes:runtimeZip.length,sha256:hash(runtimeZip)}),source=readZip(join(root,'scene.zip'),{bytes:sceneZip.length,sha256:hash(sceneZip)});verifyArchiveMembers(runtime,[{path:'models/a.glb',bytes:glb.length,sha256:hash(glb)}]);verifyArchiveMembers(source,[...source].map(([path,b])=>({path,bytes:b.length,sha256:hash(b)})));const expected=JSON.parse(new TextDecoder().decode(source.get('scene.json'))).assets[0].runtimeSha256.replace('sha256:','');expect(hash(runtime.get('models/a.glb')!)).toBe(expected);expect(hash(source.get('assets/a.glb')!)).toBe(expected);
- writeFileSync(join(root,'extracted.glb'),runtime.get('models/a.glb')!);writeFileSync(join(root,'layout.json'),source.get('layout.json')!);const plan={id:'synthetic',release:'r1',three:'0.186.0' as const,out:join(root,'out'),models:[{id:'a',to:'models/a.glb'}],data:{layout:'data/layout.json'},files:[{from:join(root,'extracted.glb'),to:'models/a.glb',sha256:expected},{from:join(root,'layout.json'),to:'data/layout.json',sha256:hash(layout)}]};expect(stageFiles(plan)).toEqual({files:2,bytes:glb.length+layout.length});expect(verifyStaged(plan.out).ok).toBe(true);expect(JSON.parse(readFileSync(join(plan.out,'pack.json'),'utf8')).data.layout).toBe('data/layout.json');writeFileSync(join(root,'extracted.glb'),'different model');expect(()=>stageFiles({...plan,force:true})).toThrow('extracted.glb');
+ writeFileSync(join(root,'extracted.glb'),runtime.get('models/a.glb')!);writeFileSync(join(root,'layout.json'),source.get('layout.json')!);const plan={id:'synthetic',release:'r1',three:'0.186.1' as const,out:join(root,'out'),models:[{id:'a',to:'models/a.glb'}],data:{layout:'data/layout.json'},files:[{from:join(root,'extracted.glb'),to:'models/a.glb',sha256:expected},{from:join(root,'layout.json'),to:'data/layout.json',sha256:hash(layout)}]};expect(stageFiles(plan)).toEqual({files:2,bytes:glb.length+layout.length});expect(verifyStaged(plan.out).ok).toBe(true);expect(JSON.parse(readFileSync(join(plan.out,'pack.json'),'utf8')).data.layout).toBe('data/layout.json');writeFileSync(join(root,'extracted.glb'),'different model');expect(()=>stageFiles({...plan,force:true})).toThrow('extracted.glb');
}finally{rmSync(root,{recursive:true,force:true});}
});
diff --git a/scenes/packages/scene-kit/tests/ui/browser-launch.test.ts b/scenes/packages/scene-kit/tests/ui/browser-launch.test.ts
new file mode 100644
index 00000000..cf2ca29f
--- /dev/null
+++ b/scenes/packages/scene-kit/tests/ui/browser-launch.test.ts
@@ -0,0 +1,114 @@
+import { afterEach, expect, spyOn, test } from 'bun:test';
+import { existsSync } from 'node:fs';
+import { chmod, mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, win32 } from 'node:path';
+import puppeteer from 'puppeteer-core';
+import type { Browser, LaunchOptions } from 'puppeteer-core';
+import * as helpers from '../../src/testing/node';
+import { launchHeadless as launchGoldenGate } from '../../../golden-gate/tests/tools/owned';
+import { launchHeadless as launchFoundry } from '../../../foundry-floor/tests/tools/owned';
+
+const workspaces: string[] = [];
+afterEach(async () => { await Promise.all(workspaces.splice(0).map(path => rm(path, { recursive: true, force: true }))); });
+async function fixture() {
+ const workspace = await mkdtemp(join(tmpdir(), 'kiln chrome tests ')); workspaces.push(workspace);
+ const executablePath = join(workspace, 'chrome');
+ await writeFile(executablePath, '#!/bin/sh\nexit 0\n'); await chmod(executablePath, 0o700);
+ return { workspace, executablePath };
+}
+
+test('Chrome discovery prefers explicit configuration, then environment, then executable PATH entries', async () => {
+ const { workspace, executablePath } = await fixture();
+ const env = { KILN_CHROME: executablePath, CHROME: '/not-selected', PATH: '' };
+ expect(await helpers.resolveChromeExecutable({ env })).toBe(executablePath);
+ expect(await helpers.resolveChromeExecutable({ executablePath, env: { KILN_CHROME: '/not-selected' } })).toBe(executablePath);
+ expect(await helpers.resolveChromeExecutable({ env: { CHROME: executablePath, PATH: '' } })).toBe(executablePath);
+ expect(await helpers.resolveChromeExecutable({ env: { PUPPETEER_EXECUTABLE_PATH: executablePath, PATH: '' } })).toBe(executablePath);
+ expect(await helpers.resolveChromeExecutable({ env: { PATH: workspace }, platform: 'linux' })).toBe(executablePath);
+ await expect(helpers.resolveChromeExecutable({ executablePath: join(workspace, 'missing'), env })).rejects.toThrow('Configured Chrome executable');
+ await expect(helpers.resolveChromeExecutable({ executablePath: workspace, env })).rejects.toThrow('Configured Chrome executable');
+ if (process.platform !== 'win32') {
+ await chmod(executablePath, 0o600);
+ await expect(helpers.resolveChromeExecutable({ executablePath, env })).rejects.toThrow('Configured Chrome executable');
+ }
+});
+
+test('Windows discovery covers PATH, system and per-user installs without consulting Linux paths', () => {
+ const candidates = helpers.chromeExecutableCandidates('win32', {
+ PATH: 'D:\\Tools;E:\\Browser', ProgramFiles: 'D:\\Apps', 'ProgramFiles(x86)': 'D:\\Apps32', LOCALAPPDATA: 'D:\\User\\Local',
+ });
+ expect(candidates).toContain(win32.join('D:\\Tools', 'chrome.exe'));
+ expect(candidates).toContain(win32.join('D:\\Apps', 'Google/Chrome/Application/chrome.exe'));
+ expect(candidates).toContain(win32.join('D:\\Apps32', 'Google/Chrome/Application/chrome.exe'));
+ expect(candidates).toContain(win32.join('D:\\User\\Local', 'Google/Chrome/Application/chrome.exe'));
+ expect(candidates.some(path => path.startsWith('/'))).toBe(false);
+ expect(helpers.chromeExecutableCandidates('linux', { PATH: '/browser/bin' })).toContain('/browser/bin/chromium');
+});
+
+test('a failed launch removes only its newly created profile and preserves the launch error', async () => {
+ const options = await fixture(), scratch = join(options.workspace, '.tmp');
+ await mkdir(join(scratch, 'someone-elses-profile'), { recursive: true });
+ const failure = new Error('Chrome startup failed'); let profile = '';
+ const launch = spyOn(puppeteer, 'launch').mockImplementation(async o => {
+ profile = o!.userDataDir!; expect(existsSync(profile)).toBe(true); throw failure;
+ });
+ try {
+ await expect(helpers.launchChrome(options)).rejects.toBe(failure);
+ expect(existsSync(profile)).toBe(false);
+ expect(await readdir(scratch)).toEqual(['someone-elses-profile']);
+ } finally { launch.mockRestore(); }
+});
+
+test('closing a shared browser is idempotent and waits for close before removing its profile', async () => {
+ const options = await fixture(); let profile = '', closes = 0;
+ let finish!: () => void;
+ const browser = { close: async () => { closes++; await new Promise<void>(resolve => { finish = resolve; }); } } as Browser;
+ const launch = spyOn(puppeteer, 'launch').mockImplementation(async o => { profile = o!.userDataDir!; return browser; });
+ try {
+ const owned = await helpers.launchChrome({ ...options, windowSize: [800, 600], args: ['--hide-scrollbars'] });
+ const first = owned.close(), second = owned.close();
+ expect(existsSync(profile)).toBe(true); expect(closes).toBe(1);
+ finish(); await Promise.all([first, second]);
+ expect(existsSync(profile)).toBe(false);
+ await owned.close(); expect(closes).toBe(1);
+ } finally { launch.mockRestore(); }
+});
+
+test('close failure still cleans the owned profile and remains visible to the caller', async () => {
+ const options = await fixture(); let profile = '';
+ const failure = new Error('browser close failed');
+ const browser = { close: async () => { throw failure; } } as Browser;
+ const launch = spyOn(puppeteer, 'launch').mockImplementation(async o => { profile = o!.userDataDir!; return browser; });
+ try {
+ const owned = await helpers.launchChrome(options);
+ await expect(owned.close()).rejects.toBe(failure);
+ expect(existsSync(profile)).toBe(false);
+ } finally { launch.mockRestore(); }
+});
+
+test('Golden Gate and Foundry use the shared executable and retain their window, viewport and cleanup contract', async () => {
+ const { executablePath } = await fixture(), prior = process.env.KILN_CHROME;
+ process.env.KILN_CHROME = executablePath;
+ let options: LaunchOptions | undefined, closes = 0;
+ const launch = spyOn(puppeteer, 'launch').mockImplementation(async o => {
+ options = o; return { process: () => ({ pid: 123 }), close: async () => { closes++; } } as unknown as Browser;
+ });
+ try {
+ for (const start of [launchGoldenGate, launchFoundry]) {
+ const owned = await start('portable-test', 777, 555);
+ try {
+ expect(options!.executablePath).toBe(executablePath);
+ expect(options!.defaultViewport).toEqual({ width: 777, height: 555, deviceScaleFactor: 1 });
+ expect(options!.args).toContain('--window-size=777,555');
+ expect(options!.args).toContain('--hide-scrollbars');
+ expect(owned.pid).toBe(123); expect(owned.profile).toBe(options!.userDataDir!);
+ } finally { await owned.close(); }
+ expect(existsSync(owned.profile)).toBe(false);
+ }
+ expect(closes).toBe(2);
+ } finally {
+ launch.mockRestore();
+ if (prior === undefined) delete process.env.KILN_CHROME; else process.env.KILN_CHROME = prior;
+ }
+});
diff --git a/scenes/packages/scene-kit/tests/ui/escape.test.ts b/scenes/packages/scene-kit/tests/ui/escape.test.ts
index 772495af..28691431 100644
--- a/scenes/packages/scene-kit/tests/ui/escape.test.ts
+++ b/scenes/packages/scene-kit/tests/ui/escape.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from 'bun:test';
-import { closeScenePanelOnEscape } from '../../src/ui/escape';
+import { closeScenePanelOnEscape, restoreScenePanelFocus } from '../../src/ui/escape';
test('Escape closes one open scene control and is consumed before host exit', () => {
let closed = 0;
@@ -11,3 +11,51 @@ test('Escape closes one open scene control and is consumed before host exit', ()
closeScenePanelOnEscape(Object.assign(new Event('keydown', { cancelable: true }), { key: 'Enter' }), () => closed++);
expect(closed).toBe(1);
});
+
+/** Models the browser's relevant focus rule: hidden/disabled/detached controls cannot take focus.
+ * The DOM browser regression separately exercises the real HudMenu CSS and React dismissal.
+ */
+function focusFixture() {
+ const document = { activeElement: null as FocusTarget | null };
+ class FocusTarget {
+ ownerDocument = document;
+ visible = true;
+ isConnected = true;
+ disabled = false;
+ calls: FocusOptions[] = [];
+ constructor(public kind: string, public parentElement: FocusTarget | null = null, public trigger: FocusTarget | null = null) {}
+ focus(options: FocusOptions) { this.calls.push(options); if (this.visible && this.isConnected && !this.disabled) document.activeElement = this; }
+ getClientRects() { return this.visible && this.isConnected ? [{}] : []; }
+ closest(selector: string): FocusTarget | null { return this.kind === selector ? this : this.parentElement?.closest(selector) ?? null; }
+ querySelector() { return this.trigger; }
+ }
+ const root = new FocusTarget('.ks-root'), menu = new FocusTarget('.ks-menu', root);
+ const more = new FocusTarget('button', menu), trigger = new FocusTarget('button', menu);
+ menu.trigger = more;
+ return { document, root, menu, more, trigger, Target: FocusTarget };
+}
+
+test('closing a panel from a collapsed menu restores visible More focus instead of its hidden trigger', () => {
+ const f = focusFixture(); f.trigger.visible = false;
+ restoreScenePanelFocus(f.trigger as unknown as HTMLElement);
+ expect(f.document.activeElement).toBe(f.more);
+ expect(f.more.calls).toEqual([{ preventScroll: true }]);
+});
+
+test('panel focus keeps its original visible trigger and handles nested collapsed menus', () => {
+ const f = focusFixture();
+ restoreScenePanelFocus(f.trigger as unknown as HTMLElement);
+ expect(f.document.activeElement).toBe(f.trigger); expect(f.more.calls).toEqual([]);
+ f.trigger.visible = false; f.more.visible = false;
+ const outer = new f.Target('.ks-menu', f.root), outerTrigger = new f.Target('button', outer);
+ outer.trigger = outerTrigger; f.menu.parentElement = outer;
+ restoreScenePanelFocus(f.trigger as unknown as HTMLElement);
+ expect(f.document.activeElement).toBe(outerTrigger);
+});
+
+test('panel focus falls back to its own scene root if all containing controls are unavailable', () => {
+ const f = focusFixture(); f.trigger.disabled = true; f.more.visible = false;
+ restoreScenePanelFocus(f.trigger as unknown as HTMLElement);
+ expect(f.document.activeElement).toBe(f.root);
+ expect(() => restoreScenePanelFocus(null)).not.toThrow();
+});
diff --git a/scenes/packages/scene-kit/tests/ui/menu.test.tsx b/scenes/packages/scene-kit/tests/ui/menu.test.tsx
index abdfbf6d..4d98e1b5 100644
--- a/scenes/packages/scene-kit/tests/ui/menu.test.tsx
+++ b/scenes/packages/scene-kit/tests/ui/menu.test.tsx
@@ -26,7 +26,7 @@ test('the HUD layer offers Hide and renders Show controls only once hidden', ()
});
test('the kit stylesheet collapses menus by the HUD width and keeps touch controls while hidden', () => {
- expect(HUD_CSS).toContain('.ks-hud{position:absolute;inset:0;pointer-events:none;z-index:2;container:ks-hud/inline-size}');
+ expect(HUD_CSS).toContain('.ks-hud{position:absolute;inset:0;pointer-events:none;z-index:2;container:ks-hud/inline-size;contain:layout}');
expect(HUD_CSS).toMatch(/@container ks-hud \(max-width:\d+px\)\{[^@]*\.ks-menu\[data-collapse=narrow\]/);
expect(HUD_CSS).toContain('.ks-hud[data-ks-hidden]>:not(.ks-hud-show){visibility:hidden}');
expect(HUD_CSS).toContain('.ks-hud[data-ks-hidden] :is(.ks-joystick,.ks-touch-buttons){visibility:visible}');
diff --git a/scenes/scripts/browser-options.mjs b/scenes/scripts/browser-options.mjs
new file mode 100644
index 00000000..e6b2ef9a
--- /dev/null
+++ b/scenes/scripts/browser-options.mjs
@@ -0,0 +1,16 @@
+/** Host-only scene QA options. No shell parsing, browser download or production runtime policy. */
+export function sceneBrowserOptions(options = {}, env = process.env) {
+ const headed = env.KILN_SCENE_HEADED;
+ if (options.headless === undefined && headed !== undefined && !['0', '1'].includes(headed)) {
+ throw new Error('KILN_SCENE_HEADED must be 0 or 1');
+ }
+ let extra = [];
+ if (env.KILN_SCENE_CHROME_ARGS !== undefined) {
+ try { extra = JSON.parse(env.KILN_SCENE_CHROME_ARGS); }
+ catch { throw new Error('KILN_SCENE_CHROME_ARGS must be a JSON array of browser flags'); }
+ if (!Array.isArray(extra) || extra.some(flag => typeof flag !== 'string' || !flag.startsWith('--') || /[\u0000-\u001f]/.test(flag))) {
+ throw new Error('KILN_SCENE_CHROME_ARGS must be a JSON array of browser flags');
+ }
+ }
+ return { headless: options.headless ?? headed !== '1', args: [...extra, ...(options.args ?? [])] };
+}
diff --git a/scenes/scripts/browser-startup.ts b/scenes/scripts/browser-startup.ts
new file mode 100644
index 00000000..fe2b5c22
--- /dev/null
+++ b/scenes/scripts/browser-startup.ts
@@ -0,0 +1,4 @@
+/** Keep one startup tab until browser.close(): closing its last window exits headed Chrome. */
+export async function closeExtraStartupPages(browser: { pages(): Promise<{ close(): Promise<void> }[]> }): Promise<void> {
+ for (const page of (await browser.pages()).slice(1)) await page.close();
+}
diff --git a/scenes/scripts/capture-farm-draw-parity.ts b/scenes/scripts/capture-farm-draw-parity.ts
index 18b8c165..8d2a07d3 100644
--- a/scenes/scripts/capture-farm-draw-parity.ts
+++ b/scenes/scripts/capture-farm-draw-parity.ts
@@ -34,6 +34,26 @@ const option = (name: string, fallback: string) => { const at = args.indexOf(nam
export const LEVERS = { off: 'heroMerge=false&shadowCache=false&standIns=false&casterTexels=0', merge: 'shadowCache=false&standIns=false&casterTexels=0', shadow: 'heroMerge=false' } as const;
export type Lever = keyof typeof LEVERS;
+/** Judge this invocation's requested cells, never stale rows accumulated by another backend/run. */
+export function farmDrawParityVerdict(request: { tiers: readonly string[]; views: readonly string[]; backend: string }, rows: readonly {
+ tier: string; view: string; backend: string; pass: boolean; error?: unknown; messages?: Record<string, readonly unknown[]>;
+}[]) {
+ const required = request.tiers.flatMap(tier => request.views.map(view => `${tier}/${view}/${request.backend}`));
+ const key = (row: typeof rows[number]) => `${row.tier}/${row.view}/${row.backend}`, keys = rows.map(key);
+ const missing = required.filter(value => !keys.includes(value)), extra = keys.filter(value => !required.includes(value));
+ const duplicate = keys.filter((value, i) => keys.indexOf(value) !== i);
+ const failed = rows.filter(row => row.pass !== true || row.error !== undefined || Object.values(row.messages ?? {}).some(messages => messages.some(message => typeof message === 'string' && /^(?:error|pageerror):/.test(message)))).map(key);
+ const pass = required.length > 0 && !missing.length && !extra.length && !duplicate.length && !failed.length;
+ return { scope: 'Requested tier/view cells on this backend only', pass, exitCode: pass ? 0 : 1,
+ expected: required.length, checked: rows.length, missing, extra, duplicate, failed };
+}
+
+export function farmDrawParityMarkdownRow(r: any): string {
+ const number = (value: unknown, exponential = false) => typeof value === 'number' && Number.isFinite(value) ? exponential ? value.toExponential(2) : String(value) : 'unavailable';
+ const lever = (name: Lever) => r.levers?.[name] ? `${number(r.levers[name].vsBefore?.over8)}/${number(r.levers[name].vsBefore?.over32)}` : '-';
+ return `| ${r.backend} | ${r.tier} | ${r.view} | ${r.pass ? 'yes' : '**NO**'} | ${r.b06 ? 'yes' : 'NO'} | ${number(r.passingTiles)}/144 | ${number(r.globalMean, true)} | ${number(r.noiseGlobalMean, true)} | ${number(r.afterVsBefore?.over32)} / ${number(r.repeatVsBefore?.over32)} | ${number(r.afterVsBefore?.differing)} / ${number(r.repeatVsBefore?.differing)} | ${number(r.afterVsBefore?.max)} | ${lever('off')} | ${lever('merge')} | ${lever('shadow')} |`;
+}
+
/** Exact differences: pixels differing at all, by more than 8 and by more than 32 levels in any channel, the largest delta, and where. */
export function exactDifference(a: RgbaImage, b: RgbaImage) {
let differing = 0, over8 = 0, over32 = 0, max = 0, x0 = Infinity, y0 = Infinity, x1 = -1, y1 = -1;
@@ -107,21 +127,24 @@ async function capture(browser: Browser, server: { url: string; port: number },
if (import.meta.main) {
const before = option('--before', 'draw-base'), after = option('--after', 'draw-after'), tiers = option('--tiers', 'minimal,economy,balanced,high').split(',');
- const views = option('--views', 'all') === 'all' ? FARM_PARITY_VIEWS : option('--views', '').split(','), backend = (option('--backend', 'webgpu') === 'webgl2' ? 'webgl2' : 'webgpu') as FarmBackend;
+ const views = option('--views', 'all') === 'all' ? FARM_PARITY_VIEWS : option('--views', '').split(','), backend = option('--backend', 'webgpu') as FarmBackend;
const out = resolve(ROOT, option('--out', 'evidence/draw-after/farm/parity')), budget = Number(option('--over32-budget', '100')), decompose = option('--decompose', 'auto');
for (const v of views) if (!FARM_PARITY_VIEWS.includes(v)) throw new Error(`Unknown Farm parity view ${v}`);
- if (!(budget >= 0)) throw new Error('--over32-budget must be 0 or more');
+ if (!['webgpu', 'webgl2'].includes(backend)) throw new Error('Unknown Farm parity backend');
+ if (!tiers.length || tiers.some(tier => !['minimal', 'economy', 'balanced', 'high'].includes(tier)) || new Set(tiers).size !== tiers.length || new Set(views).size !== views.length) throw new Error('Select unique valid Farm tiers and views');
+ if (!Number.isSafeInteger(budget) || budget < 0) throw new Error('--over32-budget must be a finite nonnegative integer');
mkdirSync(out, { recursive: true });
const servers = { before: await serveOwned(sceneOutput('farm', before, 'test')), after: await serveOwned(sceneOutput('farm', after, 'test')) };
const browser = await launchChrome({ workspace: ROOT, name: 'farm-draw-parity', windowSize: [1280, 720] }), results: any[] = [], tag = backend === 'webgl2' ? '-webgl2' : '';
+ const request = { tiers, views, backend };
const json = resolve(out, 'parity.json'), key = (r: any) => `${r.tier}|${r.view}|${r.backend}`;
const flush = () => {
const previous: any[] = existsSync(json) ? JSON.parse(readFileSync(json, 'utf8')).results ?? [] : [], fresh = new Set(results.map(key));
const all = [...previous.filter(r => !fresh.has(key(r))), ...results];
- writeFileSync(json, JSON.stringify({ before, after, size: [1280, 720], levers: LEVERS, over32Budget: budget, results: all }, null, 1) + '\n');
- const lever = (r: any, name: Lever) => r.levers?.[name] ? `${r.levers[name].vsBefore.over8}/${r.levers[name].vsBefore.over32}` : '-';
+ writeFileSync(json, JSON.stringify({ before, after, size: [1280, 720], levers: LEVERS, over32Budget: budget, results: all,
+ latestRun: { request, ...farmDrawParityVerdict(request, results) } }, null, 1) + '\n');
writeFileSync(resolve(out, 'parity.md'), ['| Backend | Tier | View | Pass | B-06 | Tiles | Mean Δ | Repeat mean | >32 levels (after / repeat) | Pixels differing (after / repeat) | Max Δ | >8 / >32 with levers off | merge alone | shadow alone |', '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|',
- ...all.sort((a, b) => a.backend.localeCompare(b.backend) || tiers.indexOf(a.tier) - tiers.indexOf(b.tier) || FARM_PARITY_VIEWS.indexOf(a.view) - FARM_PARITY_VIEWS.indexOf(b.view)).map(r => `| ${r.backend} | ${r.tier} | ${r.view} | ${r.pass ? 'yes' : '**NO**'} | ${r.b06 ? 'yes' : 'NO'} | ${r.passingTiles}/144 | ${r.globalMean.toExponential(2)} | ${r.noiseGlobalMean.toExponential(2)} | ${r.afterVsBefore.over32} / ${r.repeatVsBefore.over32} | ${r.afterVsBefore.differing} / ${r.repeatVsBefore.differing} | ${r.afterVsBefore.max} | ${lever(r, 'off')} | ${lever(r, 'merge')} | ${lever(r, 'shadow')} |`)].join('\n') + '\n');
+ ...all.sort((a, b) => a.backend.localeCompare(b.backend) || tiers.indexOf(a.tier) - tiers.indexOf(b.tier) || FARM_PARITY_VIEWS.indexOf(a.view) - FARM_PARITY_VIEWS.indexOf(b.view)).map(farmDrawParityMarkdownRow)].join('\n') + '\n');
};
try {
for (const tier of tiers) for (const view of views) {
@@ -129,10 +152,10 @@ if (import.meta.main) {
try {
const pin = FARM_WORKLOADS.has(view) ? await discover(browser, servers.before, tier, backend, view) : null;
const a = await capture(browser, servers.before, tier, backend, view, pin), r = await capture(browser, servers.before, tier, backend, view, pin), b = await capture(browser, servers.after, tier, backend, view, pin);
- const metric = compareParityImages(a.png, r.png, b.png), afterVsBefore = exactDifference(a.png, b.png), repeatVsBefore = exactDifference(a.png, r.png);
- const lines = { over32: afterVsBefore.over32, noise: repeatVsBefore.over32, budget, pass: afterVsBefore.over32 <= repeatVsBefore.over32 + budget };
+ const metric = compareParityImages(a.png, r.png, b.png, { over32Budget: budget }), afterVsBefore = exactDifference(a.png, b.png), repeatVsBefore = exactDifference(a.png, r.png);
+ const lines = metric.lines;
const differs = afterVsBefore.differing > repeatVsBefore.differing || afterVsBefore.over8 > repeatVsBefore.over8;
- const row: any = { tier, view, backend, pass: metric.pass && lines.pass, b06: metric.pass, lines, globalMean: metric.globalMean, noiseGlobalMean: metric.noiseGlobalMean, passingTiles: metric.passingTiles,
+ const row: any = { tier, view, backend, pass: metric.pass, b06: metric.pass, luminancePass: metric.luminancePass, parityScope: metric.scope, lines, globalMean: metric.globalMean, noiseGlobalMean: metric.noiseGlobalMean, passingTiles: metric.passingTiles,
failingTiles: metric.tiles.filter(t => !t.pass).map(t => ({ x: t.x, y: t.y, mean: +t.mean.toExponential(2), threshold: +t.threshold.toExponential(2) })), afterVsBefore, repeatVsBefore, differs,
pose: a.pose, settle: { before: a.settle, after: b.settle }, counts: { before: a.counts, after: b.counts }, messages: { before: a.messages, repeat: r.messages, after: b.messages } };
if (differs || !row.pass) {
@@ -143,8 +166,8 @@ if (import.meta.main) {
if (decompose === 'always' || (decompose === 'auto' && differs)) {
row.levers = {};
for (const [lever, query] of Object.entries(LEVERS) as [Lever, string][]) {
- const c = await capture(browser, servers.after, tier, backend, view, a.pose, query), m = compareParityImages(a.png, r.png, c.png), vs = exactDifference(a.png, c.png);
- row.levers[lever] = { query, b06: m.pass, passingTiles: m.passingTiles, globalMean: m.globalMean, vsBefore: vs, vsAfter: exactDifference(b.png, c.png), counts: c.counts, messages: c.messages };
+ const c = await capture(browser, servers.after, tier, backend, view, a.pose, query), m = compareParityImages(a.png, r.png, c.png, { over32Budget: budget }), vs = exactDifference(a.png, c.png);
+ row.levers[lever] = { query, b06: m.pass, luminancePass: m.luminancePass, parityScope: m.scope, passingTiles: m.passingTiles, globalMean: m.globalMean, vsBefore: vs, vsAfter: exactDifference(b.png, c.png), counts: c.counts, messages: c.messages };
if (vs.differing > repeatVsBefore.differing) { writePng(resolve(out, `${name}-${lever}.png`), c.png); writePng(resolve(out, `${name}-${lever}-crop.png`), cropSheet(a.png, c.png).image); }
}
}
@@ -157,4 +180,6 @@ if (import.meta.main) {
flush();
}
} finally { await browser.close(); await servers.before.close(); await servers.after.close(); flush(); }
+ const verdict = farmDrawParityVerdict(request, results);
+ console.log(JSON.stringify(verdict)); if (!verdict.pass) process.exitCode = verdict.exitCode;
}
diff --git a/scenes/scripts/capture-farm-paired.ts b/scenes/scripts/capture-farm-paired.ts
new file mode 100644
index 00000000..8985cfd7
--- /dev/null
+++ b/scenes/scripts/capture-farm-paired.ts
@@ -0,0 +1,135 @@
+/** D-68: explicit accepted/candidate builds against one sealed pilot pair and phase. No timing. */
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { existsSync } from 'node:fs';
+import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { PNG } from 'pngjs';
+import { launchChrome, serveOwned, workspacePath } from '../packages/scene-kit/src/testing/node';
+import { verifyStaged } from '../packages/scene-kit/src/staging';
+import { captureFarmNew, capturePilotPair, PLAY_FIXTURES, serveSealedPilot, type ParityBackend } from './capture-farm-parity';
+import { compareParityImages, type RgbaImage } from './parity-images';
+import { closeExtraStartupPages } from './browser-startup';
+
+export function pairedFarmVerdict(accepted: { pass: boolean }, candidate: { pass: boolean }) {
+ assert(typeof accepted.pass === 'boolean' && typeof candidate.pass === 'boolean', 'Both paired verdicts must be present');
+ const regression = accepted.pass && !candidate.pass;
+ return { pass: !regression, regression };
+}
+
+/** A capture error never becomes an accepted shared failure. Each capture opens a fresh page. */
+export async function captureSamePhasePair<T extends { png: RgbaImage }>(o: {
+ pilot: { first: RgbaImage; repeat: RgbaImage; phase: number };
+ capture(side: 'accepted' | 'candidate', phase: number): Promise<T>;
+}) {
+ const { first, repeat, phase } = o.pilot;
+ assert(Number.isFinite(phase) && phase >= 0, 'Pilot phase must be a finite nonnegative number');
+ const accepted = await o.capture('accepted', phase), candidate = await o.capture('candidate', phase);
+ const a = compareParityImages(first, repeat, accepted.png), b = compareParityImages(first, repeat, candidate.png);
+ return { phase, accepted: { capture: accepted, metric: a }, candidate: { capture: candidate, metric: b }, verdict: pairedFarmVerdict(a, b) };
+}
+
+export function pairedFarmCoverage(views: readonly string[], rows: readonly { view: string; backend: string; status: string }[], acceptedBuildVerified = false) {
+ const required = views.flatMap(view => ['webgpu', 'webgl2'].map(backend => `${view}/${backend}`));
+ const keys = rows.map(row => `${row.view}/${row.backend}`), missing = required.filter(key => !keys.includes(key));
+ const duplicate = keys.filter((key, i) => keys.indexOf(key) !== i), extra = keys.filter(key => !required.includes(key));
+ const passing = rows.filter(row => row.status === 'pass').length;
+ return { releaseQualified: acceptedBuildVerified && required.length > 0 && !missing.length && !duplicate.length && !extra.length && passing === required.length, acceptedBuildVerified,
+ expected: required.length, checked: rows.length, passing, missing, duplicate, extra };
+}
+
+/** A path or Git label alone is not a build identity. Recheck the same bytes after capture. */
+async function buildIdentity(root: string) {
+ const problems = verifyStaged(resolve(root, 'assets')).problems.filter(problem => !/^[^/]+\.(?:js|css): extra staged file$/.test(problem));
+ assert(!problems.length, `Paired build assets failed verification: ${problems.join('; ')}`);
+ const hasBuild = existsSync(resolve(root, 'build.json'));
+ const names = ['index.html', 'assets/pack.json', 'bundle-modules.json', ...(hasBuild ? ['build.json'] : []), ...(await readdir(resolve(root, 'assets'))).filter(name => /\.(js|css)$/.test(name)).map(name => `assets/${name}`)];
+ const files = await Promise.all(names.sort().map(async path => { const bytes = await readFile(resolve(root, path)); return { path, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') }; }));
+ return { root, files, source: hasBuild ? JSON.parse(await readFile(resolve(root, 'build.json'), 'utf8')).source : 'unknown: no build.json source receipt', sha256: createHash('sha256').update(JSON.stringify(files)).digest('hex') };
+}
+
+/** An acceptance record must identify these exact bytes and an owner decision; a source reconstruction is not acceptance. */
+export function acceptedBuildEvidence(receipt: unknown, buildSha256: string) {
+ if (receipt === undefined) return { verified: false, status: 'unknown', reason: 'No exact accepted-build receipt; this comparison is diagnostic, even when every pair passes' };
+ const value = receipt as { schema?: unknown; buildSha256?: unknown; ownerAccepted?: unknown; decision?: unknown };
+ assert(value?.schema === 'kiln.farm-accepted-build/1' && value.buildSha256 === buildSha256 && value.ownerAccepted === true
+ && typeof value.decision === 'string' && value.decision.trim().length > 0, 'Accepted-build receipt must identify the exact build hash and recorded owner decision');
+ return { verified: true, status: 'recorded', decision: value.decision, buildSha256 };
+}
+
+export async function runPairedFarmParity(o: { workspace?: string; label: string; acceptedRoot: string; newRoot: string; acceptedReceipt?: string; release?: 'r33' | 'r34'; views?: string[]; backend?: ParityBackend | 'both' }) {
+ const workspace = resolve(o.workspace ?? process.cwd()), release = o.release ?? 'r34';
+ assert(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(o.label), 'Evidence label must be a simple directory name');
+ assert(['r33', 'r34'].includes(release), 'Unknown sealed pilot release');
+ const acceptedRoot = workspacePath(workspace, o.acceptedRoot), newRoot = workspacePath(workspace, o.newRoot);
+ assert(acceptedRoot !== newRoot, 'Accepted and candidate builds must be separate inputs');
+ const layout = JSON.parse(await readFile(workspacePath(workspace, `.tmp/pilot-${release}/scene/layout.json`), 'utf8'));
+ const pilotDelivery = await readFile(workspacePath(workspace, `.tmp/pilot-${release}/delivery.json`));
+ const required = [...Object.keys(layout.views), ...Object.keys(PLAY_FIXTURES)], views = o.views ?? required;
+ assert(views.length && new Set(views).size === views.length && views.every(view => required.includes(view)), 'Every view must be a unique named or play fixture');
+ const backends: ParityBackend[] = !o.backend || o.backend === 'both' ? ['webgpu', 'webgl2'] : [o.backend];
+ assert(backends.every(backend => ['webgpu', 'webgl2'].includes(backend)), 'Unknown backend');
+ const builds = { accepted: await buildIdentity(acceptedRoot), candidate: await buildIdentity(newRoot) };
+ const acceptanceBytes = o.acceptedReceipt ? await readFile(workspacePath(workspace, o.acceptedReceipt)) : undefined;
+ const acceptance = { ...acceptedBuildEvidence(acceptanceBytes ? JSON.parse(acceptanceBytes.toString('utf8')) : undefined, builds.accepted.sha256),
+ ...(acceptanceBytes ? { receiptSha256: createHash('sha256').update(acceptanceBytes).digest('hex') } : {}) };
+ const out = workspacePath(workspace, `evidence/parity/${o.label}`);
+ assert(!existsSync(out), 'Refusing to overwrite existing parity evidence'); await mkdir(out, { recursive: true });
+ const results: any[] = [], ledger: any = { closed: false };
+ const report: any = { schema: 'kiln.farm-paired-parity/1', decision: 'D-68', builds, acceptance, release,
+ pilotDeliverySha256: createHash('sha256').update(pilotDelivery).digest('hex'),
+ conditions: { width: 1280, height: 720, dpr: 1, tier: 'high', phase: 'One read-only sealed-pilot phase shared by accepted and candidate fresh-page captures',
+ rule: 'Fail a view only when the candidate fails B-06/D18 against the pilot and the accepted build passes; errors always fail',
+ metric: 'Full-view B-06 luminance and >32-channel budget of 100 pixels beyond repeat noise (D-67)',
+ scope: 'Paired pilot audit only; direct before/after parity, count gates and performance remain separate', timing: 'not collected' }, views, backends, results, ledger };
+ const save = () => writeFile(resolve(out, 'results.json'), JSON.stringify(report, null, 2) + '\n');
+ let pilot: Awaited<ReturnType<typeof serveSealedPilot>> | undefined, accepted: Awaited<ReturnType<typeof serveOwned>> | undefined, candidate: Awaited<ReturnType<typeof serveOwned>> | undefined, browser: Awaited<ReturnType<typeof launchChrome>> | undefined;
+ try {
+ pilot = await serveSealedPilot(workspace, release); ledger.pilot = { port: pilot.port, pid: pilot.pid, log: pilot.log };
+ accepted = await serveOwned(acceptedRoot); candidate = await serveOwned(newRoot); ledger.acceptedPort = accepted.port; ledger.candidatePort = candidate.port;
+ browser = await launchChrome({ workspace, name: `paired-${o.label}` }); report.browser = await browser.version();
+ await closeExtraStartupPages(browser);
+ const ports = new Set([pilot.port, accepted.port, candidate.port]);
+ for (const backend of backends) for (const view of views) {
+ const dir = resolve(out, `${view}-${backend}`); await mkdir(dir, { recursive: true });
+ const row: any = { view, backend, status: 'error' };
+ try {
+ const play = PLAY_FIXTURES[view];
+ const old = await capturePilotPair({ browser, url: pilot.url, ports, backend, view, dir, play });
+ const pair = await captureSamePhasePair({ pilot: old, capture: (side, phase) => captureFarmNew({ browser: browser!, url: side === 'accepted' ? accepted!.url : candidate!.url,
+ ports, backend, view, file: resolve(dir, `${view}-${side}-${backend}.png`), play, ambientTime: phase }) });
+ row.phase = pair.phase; row.pilot = { first: old.firstStats, repeat: old.repeatStats, diagnostics: old.diagnostics };
+ for (const side of ['accepted', 'candidate'] as const) {
+ const { diff, ...metric } = pair[side].metric;
+ await writeFile(resolve(dir, `${view}-${side}-diff-${backend}.png`), PNG.sync.write({ ...diff, data: Buffer.from(diff.data) }));
+ row[side] = { metric, stats: pair[side].capture.stats, diagnostics: pair[side].capture.diagnostics };
+ }
+ row.verdict = pair.verdict; row.status = pair.verdict.pass ? 'pass' : 'regression';
+ } catch (error) { row.error = error instanceof Error ? error.stack : String(error); }
+ results.push(row); await save(); console.log(`${view}/${backend}: ${row.status}`);
+ }
+ assert.deepEqual(await buildIdentity(acceptedRoot), builds.accepted, 'Accepted build changed during audit');
+ assert.deepEqual(await buildIdentity(newRoot), builds.candidate, 'Candidate build changed during audit');
+ } catch (error) { report.error = error instanceof Error ? error.stack : String(error); throw error; }
+ finally {
+ const errors: string[] = [];
+ for (const [name, resource] of [['browser', browser], ['candidate', candidate], ['accepted', accepted], ['pilot', pilot]] as const) {
+ try { await resource?.close(); ledger[`${name}Closed`] = true; } catch (error) { errors.push(`${name}: ${String(error)}`); }
+ }
+ ledger.closed = !errors.length; ledger.cleanupErrors = errors;
+ report.summary = pairedFarmCoverage(required, results, acceptance.verified);
+ if (report.error || errors.length) report.summary.releaseQualified = false;
+ await save(); if (errors.length) throw new AggregateError(errors, 'Paired parity resources did not all close');
+ }
+ return { out, pass: results.length > 0 && results.every(row => row.status === 'pass'), report };
+}
+
+if (import.meta.main) {
+ const args = process.argv.slice(2), option = (name: string) => { const i = args.indexOf(name); return i < 0 ? undefined : args[i + 1]; };
+ if (args.includes('--help')) console.log('Usage: bun scripts/capture-farm-paired.ts --label <new-evidence> --accepted-root <comparison-test-build> --new-root <candidate-test-build> [--accepted-receipt <exact-owner-acceptance.json>] [--release r34|r33] [--backend both|webgpu|webgl2] [--views hero,...]. Default covers all named/play views on both backends. Subsets or absent exact accepted-build evidence cannot qualify a release.');
+ else {
+ for (const flag of ['--label', '--accepted-root', '--new-root']) assert(option(flag) && !option(flag)!.startsWith('--'), `Required ${flag}`);
+ const result = await runPairedFarmParity({ label: option('--label')!, acceptedRoot: option('--accepted-root')!, newRoot: option('--new-root')!, acceptedReceipt: option('--accepted-receipt'), release: option('--release') as 'r33' | 'r34' | undefined, backend: option('--backend') as ParityBackend | 'both' | undefined, views: option('--views')?.split(',') });
+ console.log(JSON.stringify({ out: result.out, pass: result.pass, releaseQualified: result.report.summary.releaseQualified })); if (!result.pass) process.exitCode = 1;
+ }
+}
diff --git a/scenes/scripts/capture-farm-parity.ts b/scenes/scripts/capture-farm-parity.ts
index 19c0e1e4..77fd5d17 100644
--- a/scenes/scripts/capture-farm-parity.ts
+++ b/scenes/scripts/capture-farm-parity.ts
@@ -6,8 +6,9 @@ import { resolve } from 'node:path';
import type { Browser, Page } from 'puppeteer-core';
import { PNG } from 'pngjs';
import { assertOwnedUrl, launchChrome, serveOwned, waitForReady, waitFrames, workspacePath } from '../packages/scene-kit/src/testing/node';
-import { compareParityImages } from './parity-images';
+import { compareLuminanceImages, compareParityImages } from './parity-images';
import { cropImage, type CropRectangle } from './capture-woodland-ab';
+import { closeExtraStartupPages } from './browser-startup';
import { readPilotRendererCounts, readPilotShaderClock } from './farm-renderer-counts';
import { compareFarmOptimizationCounts, compareStaticRendererCounts, compareX02Reference, summarizeStaticCountCoverage, validateX02Baseline, X02_BASELINE_PATH, type ColliderCounts, type X02Baseline } from './farm-count-gates';
@@ -56,7 +57,9 @@ export async function serveSealedPilot(workspace: string, release: 'r33' | 'r34'
} };
} catch (error) {
clearTimeout(timer); if (child.exitCode === null && !child.killed) child.kill(); await exited;
- if (!/EADDRINUSE|address already in use/i.test(entry.stderr)) throw error;
+ // The immutable pilot prints error.message only. Bun omits EADDRINUSE in that message.
+ const bunBusy = entry.stderr.split(/\r?\n/).some(line => line.trim() === `Failed to start server. Is port ${port} in use?`);
+ if (!bunBusy && !/EADDRINUSE|address already in use/i.test(entry.stderr)) throw error;
}
}
throw new Error('No permitted port is available for the sealed pilot');
@@ -188,7 +191,7 @@ export async function captureFarmNew(o: { browser: Browser; url: string; ports:
await page.close();
}
}
-async function capturePilotPair(o: { browser: Browser; url: string; ports: ReadonlySet<number>; backend: ParityBackend; view: string; dir: string; play?: PlayFixture }) {
+export async function capturePilotPair(o: { browser: Browser; url: string; ports: ReadonlySet<number>; backend: ParityBackend; view: string; dir: string; play?: PlayFixture }) {
const page = await o.browser.newPage(), diagnostics: Diagnostic[] = [];
try {
await configurePage(page, o.ports, diagnostics);
@@ -231,9 +234,9 @@ export async function runFarmParity(options: { workspace?: string; release?: 'r3
// M2d calibration (PROGRESS R4-07): the pilot's 3 s old-old pair cannot bound grass-wind and stream
// differences between time 0 and its elapsed shader clock, so the frozen rewrite takes that phase.
const alignPhase = options.stage === 'm2d';
- const results: any[] = [], ledger: any = { runnerPid: process.pid, closed: false }, report: any = { schema: 'kiln.farm-parity/1', date: new Date().toISOString(), release, stage: options.stage ?? 'm2a', conditions: { width: WIDTH, height: HEIGHT, dpr: 1, tier: 'high', captureDelay: '3 seconds after readiness; repeat 3 seconds later', rewriteTime: alignPhase ? "the pilot's shader clock at its first capture (midpoint of a read-only bracket), then frozen: grass wind and stream phase match; clip mixers are not aligned and stay within the old-old noise rule" : 0, rewriteHerd: false, liveGovernor: 'disabled with empty synthetic trace', oracle: 'unmodified sealed serve.mjs verifies delivery.json', normalizationCss: normalizedCss, imageMetric: 'sRGB-decoded linear luminance, Rec.709 coefficients, 16×9 tiles', tileThreshold: 'max(3 * old-old tile noise, 0.02)', tilePassFraction: .97, globalMeanExclusiveLimit: .02, diffVisualGain: 4, performanceTiming: 'not collected', countGate: countGateEnabled ? 'B-07 optimization goldens and collider counts (frozen pilot fixture) and X-02 counts at every named view and play fixture: inclusive ±2% draws/triangles, pipelines <=105% of the committed reference of the optimized build (' + X02_BASELINE_PATH + ', OD-8/D-53; the two pilot samples are recorded beside it, not gated); qualification requires every named view and play fixture on both backends' : 'Not applied: this stage records observations only',
+ const results: any[] = [], ledger: any = { runnerPid: process.pid, closed: false }, report: any = { schema: 'kiln.farm-parity/1', date: new Date().toISOString(), release, stage: options.stage ?? 'm2a', conditions: { width: WIDTH, height: HEIGHT, dpr: 1, tier: 'high', captureDelay: '3 seconds after readiness; repeat 3 seconds later', rewriteTime: alignPhase ? "the pilot's shader clock at its first capture (midpoint of a read-only bracket), then frozen: grass wind and stream phase match; clip mixers are not aligned and stay within the old-old noise rule" : 0, rewriteHerd: false, liveGovernor: 'disabled with empty synthetic trace', oracle: 'unmodified sealed serve.mjs verifies delivery.json', normalizationCss: normalizedCss, imageMetric: 'B-06/D18 full-view sRGB-decoded linear luminance, Rec.709 coefficients, 16×9 tiles; >32-channel budget 100 pixels beyond repeat noise', tileThreshold: 'max(3 * old-old tile noise, 0.02)', tilePassFraction: .97, globalMeanExclusiveLimit: .02, diffVisualGain: 4, performanceTiming: 'not collected', countGate: countGateEnabled ? 'B-07 optimization goldens and collider counts (frozen pilot fixture) and X-02 counts at every named view and play fixture: inclusive ±2% draws/triangles, pipelines <=105% of the committed reference of the optimized build (' + X02_BASELINE_PATH + ', OD-8/D-53; the two pilot samples are recorded beside it, not gated); qualification requires every named view and play fixture on both backends' : 'Not applied: this stage records observations only',
playFixtures: Object.fromEntries(playViews.map(view => [view, PLAY_FIXTURES[view]])), playConditions: 'Rewrite: setPlaying(true) then the teleport hook (the pilot visit) under the frozen clock; the player clip is held at its start. Pilot: its #visit destination menu; E on the canvas for the door; its play status line records the farmer position',
- streamCrop: views.includes('watermill-wheel') ? { view: 'watermill-wheel', rectangle: STREAM_CROP, rule: 'Same tile metric on the crop (16 by 9 tiles of 40 by 28 px)' } : undefined }, views, backends, results, ledger };
+ streamCrop: views.includes('watermill-wheel') ? { view: 'watermill-wheel', rectangle: STREAM_CROP, rule: 'Luminance-only historical crop diagnostic (16 by 9 tiles of 40 by 28 px); not full-view D18 qualification' } : undefined }, views, backends, results, ledger };
const save = () => writeFile(resolve(out, 'results.json'), JSON.stringify(report, null, 2));
let pilot: Awaited<ReturnType<typeof serveSealedPilot>> | undefined, hosted: Awaited<ReturnType<typeof serveOwned>> | undefined, browser: Browser | undefined;
// OD-8 (D-53): X-02 compares against the committed reference of the optimized build; B-06 pixels and B-07 still use the pilot.
@@ -245,7 +248,7 @@ export async function runFarmParity(options: { workspace?: string; release?: 'r3
pilot = await serveSealedPilot(workspace, release); ledger.pilot = { port: pilot.port, pid: pilot.pid, log: pilot.log };
hosted = await serveOwned(workspacePath(workspace, options.newRoot ?? 'packages/farm/dist/test')); ledger.rewrite = { port: hosted.port, pid: process.pid };
browser = await launchChrome({ workspace, name: `parity-${options.label}` }); ledger.browserPid = browser.process()?.pid; ledger.browserProfile = browser.process()?.spawnargs.find(arg => arg.startsWith('--user-data-dir='))?.slice('--user-data-dir='.length); report.browser = await browser.version();
- for (const blank of await browser.pages()) await blank.close();
+ await closeExtraStartupPages(browser);
const ports = new Set([pilot.port, hosted.port]);
for (const backend of backends) for (const view of views) {
for (let attempt = 1; attempt <= 2; attempt++) {
@@ -260,7 +263,7 @@ export async function runFarmParity(options: { workspace?: string; release?: 'r3
const writePng = (name: string, image: { width: number; height: number; data: Uint8Array }) => writeFile(resolve(dir, name), PNG.sync.write({ width: image.width, height: image.height, data: Buffer.from(image.data) }));
await writePng(`${view}-diff-${backend}.png`, diff);
Object.assign(result, { fixture: play ? 'play fixture' : 'named view', metric: numbers, pilot: { first: old.firstStats, repeat: old.repeatStats, diagnostics: old.diagnostics }, rewrite: { stats: fresh.stats, diagnostics: fresh.diagnostics }, status: metric.pass ? 'pass' : 'fail' });
- const failures: string[] = metric.pass ? [] : ['B-06 linear-luminance parity thresholds failed'];
+ const failures: string[] = metric.pass ? [] : ['B-06 luminance/thin-line parity thresholds failed'];
if (play) {
// Both sides stand at the same destination: the pilot's status line rounds x and z to .1 m and y to .01 m.
const pilotAt = parsePilotPlayState((old.firstStats as any).play.state)!.position, rewriteAt = fresh.stats.sim.player.position as number[];
@@ -269,7 +272,7 @@ export async function runFarmParity(options: { workspace?: string; release?: 'r3
if (!result.playPosition.pass) failures.push('Play fixture positions differ beyond the pilot status rounding');
}
if (view === 'watermill-wheel') {
- const a = cropImage(old.first, STREAM_CROP), b = cropImage(old.repeat, STREAM_CROP), c = cropImage(fresh.png, STREAM_CROP), crop = compareParityImages(a, b, c);
+ const a = cropImage(old.first, STREAM_CROP), b = cropImage(old.repeat, STREAM_CROP), c = cropImage(fresh.png, STREAM_CROP), crop = compareLuminanceImages(a, b, c);
await writePng(`stream-crop-pilot-${backend}.png`, a); await writePng(`stream-crop-pilot-repeat-${backend}.png`, b); await writePng(`stream-crop-new-${backend}.png`, c); await writePng(`stream-crop-diff-${backend}.png`, crop.diff);
const { diff: _cropDiff, ...cropNumbers } = crop; result.streamCrop = { rectangle: STREAM_CROP, metric: cropNumbers };
if (!crop.pass) failures.push('SPEC 19.7 stream crop at the mill bank failed');
@@ -280,7 +283,7 @@ export async function runFarmParity(options: { workspace?: string; release?: 'r3
const kind = play ? 'play fixture' : 'named view';
const x02 = compareX02Reference(x02Reference!, { view, backend, tier: 'high', viewport: [WIDTH, HEIGHT], freshPage: true }, rewriteCounts);
const first = compareStaticRendererCounts(old.firstStats, rewriteCounts, kind), repeat = compareStaticRendererCounts(old.repeatStats, rewriteCounts, kind);
- const b07 = compareFarmOptimizationCounts({ release, counts: fresh.stats.counts, pilot: old.firstStats, pilotRepeat: old.repeatStats, rewrite: rewriteCounts, colliders: { actual: fresh.stats.colliders, fixture: colliderFixture } });
+ const b07 = compareFarmOptimizationCounts({ release, counts: fresh.stats.counts, pilot: old.firstStats, pilotRepeat: old.repeatStats, rewrite: rewriteCounts, textureProfile: fresh.stats.counts.shadow === null ? 'prewarmed' : 'cached-shadows', colliders: { actual: fresh.stats.colliders, fixture: colliderFixture } });
result.countChecks = { b07, x02: { ...x02, baseline: `${X02_BASELINE_PATH} (OD-8, D-53: re-baselined on the optimized build)`, pilotObservation: { first, repeat, gated: false, note: 'Both pilot samples, recorded only: the optimized build lowers draws on purpose' } } };
if (!b07.pass) failures.push('B-07 optimization statistics failed');
if (!result.countChecks.x02.pass) failures.push(`X-02 renderer count limits failed at this ${kind}`);
diff --git a/scenes/scripts/capture-foundry-draw-parity.ts b/scenes/scripts/capture-foundry-draw-parity.ts
index 1be5abb5..bed1953b 100644
--- a/scenes/scripts/capture-foundry-draw-parity.ts
+++ b/scenes/scripts/capture-foundry-draw-parity.ts
@@ -70,7 +70,7 @@ if (args.includes('--merge')) { console.log(JSON.stringify(summarize(out))); pro
const beforeBuild = option('--before', 'draw-base'), afterBuild = option('--after', 'draw-after'), tiers = option('--tiers', TIER_ORDER.join(',')).split(',');
const afterQuery = option('--after-query', ''), variant = afterQuery ? afterQuery.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_|_$/g, '') : 'defaults', variantTag = afterQuery ? `-${variant}` : '';
const views = option('--views', ALL_VIEWS.join(',')).split(','), backend = option('--backend', '') === 'webgl2' ? 'webgl2' : 'webgpu', save = option('--save', 'high'), budget = Number(option('--over32-budget', '100'));
-if (!(budget >= 0)) throw new Error('--over32-budget must be 0 or more');
+if (!Number.isSafeInteger(budget) || budget < 0) throw new Error('--over32-budget must be a finite nonnegative integer');
for (const v of views) if (!ALL_VIEWS.includes(v)) throw new Error(`Unknown view ${v}`);
for (const t of tiers) if (!TIER_ORDER.includes(t)) throw new Error(`Unknown tier ${t}`);
@@ -144,15 +144,15 @@ const hostedBefore = await serveOwned(sceneOutput('foundry-floor', beforeBuild,
const owned = new Set([hostedBefore.port, hostedAfter.port]), browser = await launchChrome({ workspace: ROOT, name: 'ff-draw-parity', windowSize: [WIDTH, HEIGHT] });
const results: any[] = [], afterParams = Object.fromEntries(new URLSearchParams(afterQuery));
function record(tier: string, view: string, before: Shot, repeat: Shot, after: Shot) {
- const parity = compareParityImages(before.png, repeat.png, after.png), name = `${tier}-${view}${variantTag}`;
+ const parity = compareParityImages(before.png, repeat.png, after.png, { over32Budget: budget }), name = `${tier}-${view}${variantTag}`;
const afterVsBefore = exact(before.png, after.png), repeatVsBefore = exact(before.png, repeat.png);
- const lines = { over32: afterVsBefore.over32, noise: repeatVsBefore.over32, budget, pass: afterVsBefore.over32 <= repeatVsBefore.over32 + budget };
- const pass = parity.pass && lines.pass;
+ const lines = parity.lines;
+ const pass = parity.pass;
if (save === 'all' || (save === 'high' && tier === 'high' && backend === 'webgpu') || !pass) {
const dir = resolve(out, 'captures', backend); write(resolve(dir, `${name}-before.png`), before.png); write(resolve(dir, `${name}-after.png`), after.png); write(resolve(dir, `${name}-diff.png`), parity.diff);
if (!pass) write(resolve(dir, `${name}-repeat.png`), repeat.png);
}
- const row = { variant, backend, tier, view, pass, b06: parity.pass, lines, globalMean: parity.globalMean, noiseGlobalMean: parity.noiseGlobalMean, passingTiles: parity.passingTiles, tiles: parity.tiles.length,
+ const row = { variant, backend, tier, view, pass, b06: parity.pass, luminancePass: parity.luminancePass, parityScope: parity.scope, lines, globalMean: parity.globalMean, noiseGlobalMean: parity.noiseGlobalMean, passingTiles: parity.passingTiles, tiles: parity.tiles.length,
failingTiles: parity.tiles.filter(t => !t.pass).map(t => ({ x: t.x, y: t.y, mean: +t.mean.toExponential(2), threshold: +t.threshold.toExponential(2) })), afterVsBefore, repeatVsBefore,
backends: { before: before.backend, after: after.backend }, msaaPolicyAfter: after.msaa, messages: { before: before.messages, repeat: repeat.messages, after: after.messages } };
results.push(row);
diff --git a/scenes/scripts/capture-woodland-ab.ts b/scenes/scripts/capture-woodland-ab.ts
index 2b5b3e25..96867702 100644
--- a/scenes/scripts/capture-woodland-ab.ts
+++ b/scenes/scripts/capture-woodland-ab.ts
@@ -3,7 +3,7 @@ import { existsSync } from 'node:fs';
import { mkdir, writeFile } from 'node:fs/promises';
import { isAbsolute, relative, resolve, sep } from 'node:path';
import { PNG } from 'pngjs';
-import { compareParityImages } from './parity-images';
+import { compareLuminanceImages, compareParityImages } from './parity-images';
import type { RgbaImage } from './parity-images';
interface WoodlandCapture {
@@ -77,7 +77,7 @@ export async function captureWoodlandAb(options: {
await record('unsafe', unsafe);
validateWoodlandAb(safe, repeat, unsafe, options.backend);
const a = cropImage(safe.png, WOODLAND_CROP), b = cropImage(repeat.png, WOODLAND_CROP), c = cropImage(unsafe.png, WOODLAND_CROP);
- const full = compareParityImages(safe.png, repeat.png, unsafe.png), crop = compareParityImages(a, b, c);
+ const full = compareParityImages(safe.png, repeat.png, unsafe.png), crop = compareLuminanceImages(a, b, c);
await writePng('safe-crop.png', a); await writePng('safe-repeat-crop.png', b); await writePng('unsafe-crop.png', c);
await writePng('diff-full.png', full.diff); await writePng('diff-crop.png', crop.diff);
const { diff: _full, ...fullMetric } = full, { diff: _crop, ...cropMetric } = crop;
diff --git a/scenes/scripts/check-pins.ts b/scenes/scripts/check-pins.ts
index 88370a18..ce0d0110 100644
--- a/scenes/scripts/check-pins.ts
+++ b/scenes/scripts/check-pins.ts
@@ -1,13 +1,13 @@
import { existsSync, readFileSync } from 'node:fs';
-import { dirname, join, relative } from 'node:path';
+import { dirname, join, relative, resolve } from 'node:path';
import { ROOT, dependencySpecifier, filesUnder, findInstalledPackage, parseLock, printCheck, readJson, slash, workspaceManifests, type Manifest } from './check-common';
import { inspectToolchain, REQUIRED_TOOLCHAIN, type Toolchain } from './check-toolchain';
export const APPROVED_PINS: Record<string, string> = {
- react: '19.3.0', 'react-dom': '19.3.0', '@react-three/fiber': '9.8.1', three: '0.186.0',
+ react: '19.3.0', 'react-dom': '19.3.0', '@react-three/fiber': '9.8.1', three: '0.186.1',
'@types/three': '0.186.0', '@types/react': '^19.3.0', '@types/react-dom': '^19.3.0', 'three-mesh-bvh': '0.9.15',
- typescript: '7.0.2', 'typescript-6': 'npm:[email protected]', vite: '8.3.0', '@vitejs/plugin-react': '6.1.1',
- 'puppeteer-core': '25.12.0', 'axe-core': '4.13.0', fflate: '0.8.3', pngjs: '7.0.0', pixelmatch: '7.2.0', npm: '12.0.2',
+ typescript: '7.0.2', 'typescript-6': 'npm:[email protected]', vite: '8.3.2', '@vitejs/plugin-react': '6.1.1',
+ 'puppeteer-core': '25.12.0', 'axe-core': '4.13.0', fflate: '0.8.3', pngjs: '7.0.0', pixelmatch: '7.2.0', npm: '12.2.0',
};
const RUNTIME_PEERS = ['react', 'react-dom', '@react-three/fiber', 'three'] as const;
export interface PinSnapshot {
@@ -45,17 +45,17 @@ export function validatePins(s: PinSnapshot): string[] {
}
for (const name of RUNTIME_PEERS) if (dependencySpecifier(s.site, name) !== APPROVED_PINS[name]) problems.push(`website ${name} must equal scenes pin ${APPROVED_PINS[name]}`);
for (const [label, manifest] of [['engine', s.engine], ['render service', s.renderService]] as const) {
- if (dependencySpecifier(manifest, 'three') !== '0.186.0') problems.push(`${label} three must equal scenes pin 0.186.0`);
+ if (dependencySpecifier(manifest, 'three') !== '0.186.1') problems.push(`${label} three must equal scenes pin 0.186.1`);
}
if (dependencySpecifier(s.site, '@types/three') !== '0.186.0') problems.push('website @types/three must be 0.186.0');
if (dependencySpecifier(s.site, 'typescript') !== '6.0.3') problems.push('website typescript must match typescript-6 alias 6.0.3');
if (!s.siteViteVersions.includes(APPROVED_PINS.vite!)) problems.push(`website lockfile does not resolve approved Vite ${APPROVED_PINS.vite}`);
if (s.lockfiles.length !== 1 || s.lockfiles[0] !== 'bun.lock') problems.push(`expected one lockfile at bun.lock; found ${s.lockfiles.join(', ') || 'none'}`);
const three = Object.entries(s.lock.packages ?? {}).filter(([name, entry]) => name === 'three' || (Array.isArray(entry) && /^three@/.test(String(entry[0]))));
- if (three.length !== 1 || !Array.isArray(three[0]?.[1]) || three[0]![1][0] !== '[email protected]') {
- problems.push(`lockfile must contain exactly one three resolution at 0.186.0; got ${three.map(([name, entry]) => `${name}: ${JSON.stringify(entry)}`).join(', ') || 'none'}`);
+ if (three.length !== 1 || !Array.isArray(three[0]?.[1]) || three[0]![1][0] !== '[email protected]') {
+ problems.push(`lockfile must contain exactly one three resolution at 0.186.1; got ${three.map(([name, entry]) => `${name}: ${JSON.stringify(entry)}`).join(', ') || 'none'}`);
}
- if (s.installedThree.length !== 1 || s.installedThree[0]?.version !== '0.186.0') problems.push(`expected one physical three installation at 0.186.0; got ${JSON.stringify(s.installedThree)}`);
+ if (s.installedThree.length !== 1 || s.installedThree[0]?.version !== '0.186.1') problems.push(`expected one physical three installation at 0.186.1; got ${JSON.stringify(s.installedThree)}`);
for (const name of Object.keys(REQUIRED_TOOLCHAIN) as (keyof Toolchain)[]) {
if (s.toolchain[name] !== REQUIRED_TOOLCHAIN[name]) problems.push(`toolchain ${name} must be ${REQUIRED_TOOLCHAIN[name]}`);
if (s.toolchain[name] !== s.siteToolchain[name]) problems.push(`toolchain ${name} differs from website`);
@@ -63,10 +63,11 @@ export function validatePins(s: PinSnapshot): string[] {
return problems;
}
export function collectPinSnapshot(root = ROOT): PinSnapshot {
- const siteRoot = 'C:/Users/Mattm/X/kiln-site-workbench';
+ const repoRoot = resolve(root, '..');
+ const siteRoot = join(repoRoot, 'site');
const manifests = workspaceManifests(root);
- const siteLockFile = [join(siteRoot, 'site/bun.lock'), join(siteRoot, 'bun.lock')].find(existsSync);
- if (!siteLockFile) throw new Error('website Bun lockfile is missing');
+ const siteLockFile = join(siteRoot, 'bun.lock');
+ if (!existsSync(siteLockFile)) throw new Error(`website Bun lockfile is missing: ${siteLockFile}`);
const siteLock = parseLock(readFileSync(siteLockFile, 'utf8'));
const siteViteVersions = Object.values(siteLock.packages ?? {}).flatMap(entry => Array.isArray(entry) && /^vite@/.test(String(entry[0])) ? [String(entry[0]).slice(5)] : []);
const installed = new Map<string, string>();
@@ -78,9 +79,9 @@ export function collectPinSnapshot(root = ROOT): PinSnapshot {
return {
manifests, lockfiles: filesUnder(root).filter(p => /(?:^|[\\/])(?:bun\.lockb?|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml)$/.test(p)).map(p => slash(relative(root, p))).sort(),
lock: parseLock(readFileSync(join(root, 'bun.lock'), 'utf8')),
- site: readJson(join(siteRoot, 'site/package.json')),
- engine: readJson('C:/Users/Mattm/X/kiln-oss/package.json'), renderService: readJson('C:/Users/Mattm/X/kiln-oss/render-service/package.json'),
- toolchain: readJson(join(root, 'toolchain.json')), siteToolchain: readJson(join(siteRoot, 'toolchain.json')), siteViteVersions,
+ site: readJson(join(siteRoot, 'package.json')),
+ engine: readJson(join(repoRoot, 'package.json')), renderService: readJson(join(repoRoot, 'render-service/package.json')),
+ toolchain: readJson(join(root, 'toolchain.json')), siteToolchain: readJson(join(repoRoot, 'toolchain.json')), siteViteVersions,
installedThree: [...installed].map(([path, version]) => ({ path: slash(path), version })),
};
}
@@ -88,6 +89,6 @@ if (import.meta.main) {
try {
const snapshot = collectPinSnapshot();
const problems = [...validatePins(snapshot), ...inspectToolchain().problems];
- printCheck('pins', problems, { manifests: snapshot.manifests.map(m => m.path), lockfiles: snapshot.lockfiles, installedThree: snapshot.installedThree, websiteVite: snapshot.siteViteVersions, deliberateLatestThreeMismatch: '0.186.1 is not approved; retain 0.186.0' });
+ printCheck('pins', problems, { manifests: snapshot.manifests.map(m => m.path), lockfiles: snapshot.lockfiles, installedThree: snapshot.installedThree, websiteVite: snapshot.siteViteVersions });
} catch (error) { printCheck('pins', [String(error)]); }
}
diff --git a/scenes/scripts/check-toolchain.ts b/scenes/scripts/check-toolchain.ts
index 8139f084..9eed49ea 100644
--- a/scenes/scripts/check-toolchain.ts
+++ b/scenes/scripts/check-toolchain.ts
@@ -2,7 +2,7 @@ import { spawnSync } from 'node:child_process';
import { readJson, ROOT, printCheck } from './check-common';
import { join } from 'node:path';
-export const REQUIRED_TOOLCHAIN = { bun: '1.4.2', node: '22.23.2', npm: '12.0.2' } as const;
+export const REQUIRED_TOOLCHAIN = { bun: '1.4.2', node: '22.23.3', npm: '12.2.0' } as const;
export type Toolchain = Record<keyof typeof REQUIRED_TOOLCHAIN, string>;
export function validateToolchain(expected: Toolchain, actual: Toolchain): string[] {
const problems: string[] = [];
diff --git a/scenes/scripts/farm-count-gates.ts b/scenes/scripts/farm-count-gates.ts
index 78603198..22f532f5 100644
--- a/scenes/scripts/farm-count-gates.ts
+++ b/scenes/scripts/farm-count-gates.ts
@@ -123,7 +123,12 @@ export const FARM_OPTIMIZATION_GOLDENS = {
currentSealed96m: { cellSize: 96, cellOffset: 48, batchGroups: 83, dynamicGroups: 54, sourceMeshes: 2000, eligibleSourceMeshes: 2004, visibleSourceMeshes: 2194,
tangentDerivatives: 11, hiddenRoots: 575, frozenPlacements: 555, frozenNodes: 4191 },
} as const;
-export function compareFarmOptimizationCounts(options: { release: 'r33' | 'r34'; counts: any; pilot: PilotOptimizationReference; pilotRepeat: PilotOptimizationReference; rewrite: RendererCountSnapshot; colliders?: { actual: Partial<ColliderCounts> | null | undefined; fixture: ColliderCounts } }) {
+/** D-68 retains the prewarm observation and names the additional two cached-shadow textures. */
+export const FARM_TEXTURE_GOLDENS = {
+ decision: 'D-68', prewarmed: 39, 'cached-shadows': 41,
+ provenance: { prewarmed: 'DECISIONS.md D-68: 39 at every view since prewarm', 'cached-shadows': 'packages/farm/fixtures/x02-baseline.json: draw-after 0174e7d, 16 views on WebGPU and WebGL2, settled cached shadows' },
+} as const;
+export function compareFarmOptimizationCounts(options: { release: 'r33' | 'r34'; counts: any; pilot: PilotOptimizationReference; pilotRepeat: PilotOptimizationReference; rewrite: RendererCountSnapshot; textureProfile?: 'prewarmed' | 'cached-shadows'; colliders?: { actual: Partial<ColliderCounts> | null | undefined; fixture: ColliderCounts } }) {
const { counts, pilot, pilotRepeat, rewrite } = options;
const at = (path: string) => path.split('.').reduce((value, key) => value?.[key], counts);
const checks: { name: string; expected: unknown; actual: unknown; pass: boolean }[] = [];
@@ -150,15 +155,18 @@ export function compareFarmOptimizationCounts(options: { release: 'r33' | 'r34';
checks.push({ name: `texturePooling.${key} versus ${sampleName}`, expected: expected ?? null, actual: actual ?? null,
pass: validCount(expected) && validCount(actual) && actual === expected });
}
- checks.push({ name: `renderer textures versus ${sampleName}`, expected: sample.textures, actual: rewrite.textures,
- pass: validCount(sample.textures) && validCount(rewrite.textures) && sample.textures === rewrite.textures });
+ observedCount(`${sampleName} renderer textures (observation only)`, sample.textures);
}
+ const profile = options.textureProfile ?? 'cached-shadows';
+ const textureGolden = { decision: FARM_TEXTURE_GOLDENS.decision, profile, expected: FARM_TEXTURE_GOLDENS[profile], provenance: FARM_TEXTURE_GOLDENS.provenance[profile] };
+ equal(`renderer textures (${profile}, D-68)`, rewrite.textures, textureGolden.expected);
if (options.colliders) checks.push(...compareColliderCounts(options.colliders.actual, options.colliders.fixture));
const reviewNotes: string[] = [];
if (validCount(derivativeCount) && derivativeCount !== 9) reviewNotes.push(`Batch tangent derivatives are ${derivativeCount}, versus SPEC's reported pilot 9; R3-08 documents the reproduced historical 24m versus current sealed 96m difference (SPEC12.6).`);
if (options.release === 'r34') reviewNotes.push('r34 must retain shared optimization counts; record any source-backed farmhouse-only difference from r33 (D-07).');
return { id: 'B-07', release: options.release, scope: options.colliders ? 'Optimization statistics and collider counts' : 'Optimization statistics only; collider counts not supplied to this comparison',
- pass: checks.every(check => check.pass), checks, reviewNotes, goldens: FARM_OPTIMIZATION_GOLDENS,
+ pass: checks.every(check => check.pass), checks, reviewNotes, goldens: FARM_OPTIMIZATION_GOLDENS, textureGolden,
+ pilotTextureObservations: { first: pilot.textures, repeat: pilotRepeat.textures, gatedAsEquality: false },
pending: [...(options.colliders ? [] : ['Collider counts not supplied to this comparison']), ...(options.release === 'r34' ? ['r34 visible-source total versus its sealed farmhouse-only delta'] : [])],
observed: { batchingSourceMeshes: { batched: at('optimization.batching.sourceMeshes') ?? null, total: at('optimization.batching.totalSourceMeshes') ?? null, eligible: at('optimization.batching.eligibleSourceMeshes') ?? null,
interpretation: 'R3-08: 1,967 refers to historical 24m batching; current sealed 96m batching represents 2,000 of 2,004 eligible meshes, among 2,194 visible placement meshes (r33)' },
diff --git a/scenes/scripts/farm-x02-baseline.ts b/scenes/scripts/farm-x02-baseline.ts
index 36f3581e..a8ed34fd 100644
--- a/scenes/scripts/farm-x02-baseline.ts
+++ b/scenes/scripts/farm-x02-baseline.ts
@@ -15,18 +15,24 @@ import { launchChrome, serveOwned } from '../packages/scene-kit/src/testing/node
import { sceneOutput } from './build-scene';
import { checkX02Rows, FARM_X02_VIEWS, validateX02Baseline, X02_BASELINE_PATH, X02_BASELINE_SCHEMA, type X02Backend, type X02Baseline, type X02ReferenceEntry } from './farm-count-gates';
import { enterFarmView, openFarmPage, settleFarmShadow, stableFarmCounts } from './farm-capture-pages';
+import { sceneBrowserOptions } from './browser-options.mjs';
const ROOT = resolve(import.meta.dir, '..'), args = process.argv.slice(2), command = args[0];
const option = (name: string, fallback: string) => { const at = args.indexOf(name); return at < 0 ? fallback : args[at + 1] ?? fallback; };
const PLAY = new Set(['play-yard', 'play-house', 'play-bridge', 'play-house-door']);
+export function farmX02BrowserProvenance(version: string, options: { headless: boolean }) {
+ return { browser: `${options.headless ? 'headless' : 'headed'} ${version}`, browserLaunch: { headless: options.headless } };
+}
+
async function measure(build: string, backends: X02Backend[], out: string) {
const dir = sceneOutput('farm', build, 'test'), built = JSON.parse(readFileSync(resolve(dir, 'build.json'), 'utf8')) as { chunks: { name: string }[]; source?: unknown };
// A working-tree build names no commit: record the last commit that changed the scene sources, and whether they are clean now.
const git = (...a: string[]) => execFileSync('git', a, { cwd: ROOT, encoding: 'utf8' }).trim();
const fromBuild = (built.source as { commit?: string } | null)?.commit, head = git('rev-parse', 'HEAD'), commit = fromBuild ?? git('log', '-1', '--format=%H', '--', 'packages/scene-kit/src', 'packages/farm/src', 'packages/farm/fixtures/layout.json');
const dirty = git('status', '--porcelain', '--', 'packages/scene-kit/src', 'packages/farm/src');
- const hosted = await serveOwned(dir), owned = new Set([hosted.port]), browser: Browser = await launchChrome({ workspace: ROOT, name: 'farm-x02-baseline', windowSize: [1280, 720] });
+ const launch = sceneBrowserOptions();
+ const hosted = await serveOwned(dir), owned = new Set([hosted.port]), browser: Browser = await launchChrome({ workspace: ROOT, name: 'farm-x02-baseline', windowSize: [1280, 720], headless: launch.headless });
const reference: X02Baseline['backends'] = {}, details: Record<string, unknown>[] = [], version = await browser.version();
try {
for (const backend of backends) {
@@ -50,7 +56,7 @@ async function measure(build: string, backends: X02Backend[], out: string) {
schema: X02_BASELINE_SCHEMA, decision: 'OD-8 (D-53): X-02 re-baselined on the optimized build; pixel parity against the sealed pilot (B-06) is unchanged',
rule: 'Inclusive ±2% draws (renderer.info drawCalls of one frame, shadow passes included) and triangles; pipeline cache at most +5% of this reference',
provenance: { build, commit, chunks: built.chunks.map(c => c.name).sort(), source: fromBuild ? JSON.stringify(built.source) : `${String(built.source)}; Farm and kit sources last changed in ${commit.slice(0, 7)}, ${dirty ? 'with uncommitted changes' : 'clean'} at HEAD ${head.slice(0, 7)} when measured`,
- tool: `scripts/farm-x02-baseline.ts measure --build ${build}`, date: new Date().toISOString().slice(0, 10), browser: `headless ${version}`, viewport: '1280x720 CSS at device scale 1 (B-06 normalization)', pagePolicy: 'one fresh page per view and backend' },
+ tool: `scripts/farm-x02-baseline.ts measure --build ${build}`, date: new Date().toISOString().slice(0, 10), ...farmX02BrowserProvenance(version, launch), viewport: '1280x720 CSS at device scale 1 (B-06 normalization)', pagePolicy: 'one fresh page per view and backend' },
conditions: { tier: 'high', viewport: [1280, 720], freshPage: true, clock: 'frozen', settled: true },
backends: reference,
};
diff --git a/scenes/scripts/gpu-work.ts b/scenes/scripts/gpu-work.ts
new file mode 100644
index 00000000..a80f4d43
--- /dev/null
+++ b/scenes/scripts/gpu-work.ts
@@ -0,0 +1,55 @@
+/** D16 activity proxy, not measured energy or a hardware-independent count of GPU work. */
+export function gpuWorkSummary(samples: readonly unknown[]) {
+ const rows: { clock: number; work: number; source: string }[] = [];
+ for (const sample of samples) {
+ if (!sample || typeof sample !== 'object') continue;
+ const s = sample as { gpu?: Record<string, unknown> | null; gpuBusyPercent?: unknown; gpuClockKHz?: unknown };
+ const busy = s.gpu ? s.gpu['utilization.gpu'] : s.gpuBusyPercent;
+ const raw = s.gpu ? s.gpu['clocks.gr'] : s.gpuClockKHz;
+ if (typeof busy !== 'number' || !Number.isFinite(busy) || busy < 0 || busy > 100 || typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0) continue;
+ const clock = s.gpu ? raw : raw / 1000;
+ rows.push({ clock, work: busy / 100 * clock, source: s.gpu ? 'nvidia-smi-MHz' : 'mali-sysfs-kHz' });
+ }
+ return {
+ units: { clock: 'MHz', busyClock: 'busy fraction × MHz' },
+ method: 'Arithmetic mean of same-sample busy-percent / 100 × clock-MHz; zero or unreadable clock omitted. An activity proxy, not energy or a cross-device comparison.',
+ sources: [...new Set(rows.map(r => r.source))].sort(), samples: rows.length, omitted: samples.length - rows.length,
+ clockMHzMean: rows.length ? rows.reduce((sum, r) => sum + r.clock, 0) / rows.length : null,
+ busyClockMHzMean: rows.length ? rows.reduce((sum, r) => sum + r.work, 0) / rows.length : null,
+ };
+}
+
+interface TabletRun {
+ pair: number; side: 'A' | 'B'; valid: boolean; seconds?: number;
+ gpuWork?: ReturnType<typeof gpuWorkSummary>;
+ metrics: { p95: number | null; withinOne: number | null; over50: number; over100: number; gpuBusyClockMHz?: number | null };
+}
+/** D16: three paired 60-second tablet runs; missing evidence never implies acceptance. */
+export function tabletPairVerdict(runs: readonly TabletRun[]) {
+ const ids = [...new Set(runs.map(r => r.pair))].sort((a, b) => a - b), reasons: string[] = [];
+ const finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n);
+ if (ids.length !== 3 || runs.length !== 6) reasons.push('Exactly three A/B pairs are required');
+ const pairs = ids.flatMap(pair => {
+ const a = runs.filter(r => r.pair === pair && r.side === 'A'), b = runs.filter(r => r.pair === pair && r.side === 'B');
+ if (a.length !== 1 || b.length !== 1) { reasons.push(`Pair ${pair} needs one run per side`); return []; }
+ if ([a[0]!, b[0]!].some(r => !r.valid || !finite(r.seconds) || r.seconds < 60 || !finite(r.metrics.p95) || r.metrics.p95 < 0 || !finite(r.metrics.withinOne) || r.metrics.withinOne < 0 || r.metrics.withinOne > 1 || !finite(r.metrics.gpuBusyClockMHz) || r.metrics.gpuBusyClockMHz < 0 || !Number.isInteger(r.metrics.over50) || r.metrics.over50 < 0 || !Number.isInteger(r.metrics.over100) || r.metrics.over100 < 0)) {
+ reasons.push(`Pair ${pair} lacks valid 60-second frame and GPU samples`); return [];
+ }
+ // This runner samples the tablet every two seconds. As with frame coverage,
+ // require 90% of the planned window and 90% readable matching sample pairs.
+ if ([a[0]!, b[0]!].some(r => {
+ const w = r.gpuWork;
+ return !w || !finite(w.busyClockMHzMean) || w.busyClockMHzMean < 0 || w.sources.length !== 1 || w.sources[0] !== 'mali-sysfs-kHz' ||
+ w.samples < Math.ceil(r.seconds! / 2 * .9) || w.samples < (w.samples + w.omitted) * .9;
+ })) { reasons.push(`Pair ${pair} lacks Mali provenance or 90% paired GPU sample coverage`); return []; }
+ const ma = a[0]!.metrics, mb = b[0]!.metrics, wa = a[0]!.gpuWork!.busyClockMHzMean!, wb = b[0]!.gpuWork!.busyClockMHzMean!;
+ if (wa === 0) { reasons.push(`Pair ${pair} has no nonzero GPU-work baseline`); return []; }
+ return [{ pair, refreshDeltaPoints: (mb.withinOne! - ma.withinOne!) * 100, gpuWorkChangePercent: (wb / wa - 1) * 100,
+ frameGate: mb.p95! <= 33.3 && mb.over50 <= 2 && mb.over100 === 0 }];
+ });
+ // Epsilon keeps exact decimal margins from failing through floating point roundoff.
+ const refreshRegressions = pairs.filter(p => p.refreshDeltaPoints < -1 - 1e-9).length;
+ const gpuWorkRegressions = pairs.filter(p => p.gpuWorkChangePercent > 3 + 1e-9).length;
+ return { decision: 'D16', pass: reasons.length ? null : pairs.every(p => p.frameGate) && refreshRegressions === 0 && gpuWorkRegressions === 0,
+ reasons, refreshRegressions, gpuWorkRegressions, pairs };
+}
diff --git a/scenes/scripts/make-timing-kit.ts b/scenes/scripts/make-timing-kit.ts
index c042e03f..b1c693a4 100644
--- a/scenes/scripts/make-timing-kit.ts
+++ b/scenes/scripts/make-timing-kit.ts
@@ -11,6 +11,7 @@ import { join, relative, resolve, sep } from 'node:path';
import { execFileSync } from 'node:child_process';
const root = resolve(import.meta.dir, '..'), args = process.argv.slice(2);
+const toolchain = JSON.parse(readFileSync(resolve(root, 'toolchain.json'), 'utf8')) as { node: string };
const option = (name: string, fallback: string) => { const at = args.indexOf(name); return at >= 0 && args[at + 1] && !args[at + 1]!.startsWith('--') ? args[at + 1]! : fallback; };
const a = option('--a', 'draw-base'), b = option('--b', 'wavea'), scenes = option('--scenes', 'farm,foundry-floor,golden-gate').split(',');
const kit = resolve(root, option('--out', `dist/timing-kit/${a}-vs-${b}`));
@@ -168,7 +169,7 @@ WHAT IT MEASURES (owner decisions OD-3, OD-5, OD-6, OD-7, OD-12; D-25, D-28, D-4
CONTENTS
builds/${a}/<scene>/ ${a} test builds (packages/<scene>/dist/${a}/test), served as A
builds/${b}/<scene>/ ${b} test builds, served as B (same asset pack per scene as A; checked when the kit was made)
- runner/timing-ab.mjs scripts/timing-ab.ts bundled for Node (ESM; puppeteer-core inside); Node 22.23.2 is the pin
+ runner/timing-ab.mjs scripts/timing-ab.ts bundled for Node (ESM; puppeteer-core inside); Node ${toolchain.node} is the pin
hub/run.sh headed runner on the hub's display from SSH (session env, PRIME offload, kde-inhibit, hub flags)
hub/mkenv.py the Plasma session environment (2026-09-30 campaign method)
hub/display.sh display mode record / ensure 120 Hz / restore (kscreen-doctor)
@@ -189,7 +190,7 @@ HUB (ssh hub; CachyOS, Plasma on Wayland, GTX 1660 Ti Max-Q with PRIME offload,
TABLET (from this PC; Samsung SM-X518U, serial R52X405L12T; the device kit's adb at
C:/Users/Mattm/AppData/Local/Microsoft/WinGet/Packages/Google.PlatformTools_Microsoft.Winget.Source_8wekyb3d8bbwe/platform-tools/adb.exe)
- Run from this kit directory with the maintainer Node (C:/Users/Mattm/AppData/Roaming/fnm/node-versions/v22.23.2/installation/node.exe):
+ Run from this kit directory with the maintainer Node (C:/Users/Mattm/AppData/Roaming/fnm/node-versions/v${toolchain.node}/installation/node.exe):
node runner/timing-ab.mjs transient --device tablet --out results/transient-tablet.json (read-only WebGPU check)
node runner/timing-ab.mjs ab --device tablet --cells farm:minimal:hero --pairs 1 --seconds 10 --prime 0 --block tablet-dry-<date>
node runner/timing-ab.mjs ab --device tablet --cells farm:minimal:hero,farm:economy:hero,golden-gate:minimal:arrival --pairs 3 --seconds 60 --block tablet-msaa-<date>
@@ -236,6 +237,6 @@ await writeFile(resolve(kit, 'README.txt'), readme);
const files = walk(kit).map(f => posix(kit, f)).filter(p => p !== 'MANIFEST.json').sort().map(path => { const data = readFileSync(resolve(kit, path)); return { path, bytes: data.length, sha256: sha256(data) }; });
const runnerSource = await readFile(resolve(root, 'scripts/timing-ab.ts'));
await writeFile(resolve(kit, 'MANIFEST.json'), JSON.stringify({ schema: 'kiln.timing-kit/1', created: new Date().toISOString(), scenesCommit: commit, runnerFilesStatus: status || 'committed',
- labels: { A: a, B: b }, scenes, builds, runner: { source: 'scripts/timing-ab.ts', sourceSha256: sha256(runnerSource), bundled: 'runner/timing-ab.mjs', nodePin: '22.23.2' },
+ labels: { A: a, B: b }, scenes, builds, runner: { source: 'scripts/timing-ab.ts', sourceSha256: sha256(runnerSource), bundled: 'runner/timing-ab.mjs', nodePin: toolchain.node },
totals: { files: files.length, bytes: files.reduce((s, f) => s + f.bytes, 0) }, files }, null, 2) + '\n');
console.log(JSON.stringify({ kit: kitName, files: files.length, bytes: files.reduce((s, f) => s + f.bytes, 0), runnerBytes: files.find(f => f.path === 'runner/timing-ab.mjs')?.bytes }));
diff --git a/scenes/scripts/parity-images.ts b/scenes/scripts/parity-images.ts
index e4ac2b79..4c7dce0c 100644
--- a/scenes/scripts/parity-images.ts
+++ b/scenes/scripts/parity-images.ts
@@ -2,20 +2,27 @@ export interface RgbaImage { width: number; height: number; data: Uint8Array }
export interface ParityTile { x: number; y: number; pixels: number; noise: number; mean: number; threshold: number; pass: boolean }
const linear = Float64Array.from({ length: 256 }, (_, n) => { const s = n / 255; return s <= .04045 ? s / 12.92 : ((s + .055) / 1.055) ** 2.4; });
const luminance = (data: Uint8Array, i: number) => .2126 * linear[data[i]!]! + .7152 * linear[data[i + 1]!]! + .0722 * linear[data[i + 2]!]!;
-/** SPEC 19: fixed thresholds; raw old-old noise is reported and never used to alter the global gate. */
-export function compareParityImages(pilot: RgbaImage, repeat: RgbaImage, rewrite: RgbaImage) {
+function measureImages(pilot: RgbaImage, repeat: RgbaImage, rewrite: RgbaImage) {
const { width, height } = pilot;
if (width < 16 || height < 9 || width % 16 || height % 9) throw new Error('Image dimensions must partition into 16 by 9 equal tiles');
for (const image of [pilot, repeat, rewrite]) if (image.width !== width || image.height !== height || image.data.length !== width * height * 4) throw new Error('Image dimensions differ');
const counts = new Uint32Array(144), noise = new Float64Array(144), differences = new Float64Array(144), diff = new Uint8Array(width * height * 4);
- let sum = 0, noiseSum = 0;
+ let sum = 0, noiseSum = 0, over32 = 0, noiseOver32 = 0;
for (let pixel = 0; pixel < width * height; pixel++) {
const i = pixel * 4;
if (pilot.data[i + 3] !== 255 || repeat.data[i + 3] !== 255 || rewrite.data[i + 3] !== 255) throw new Error('Parity inputs must be opaque');
const a = luminance(pilot.data, i), oldDelta = Math.abs(a - luminance(repeat.data, i)), delta = Math.abs(a - luminance(rewrite.data, i));
+ let channelDelta = 0, repeatDelta = 0;
+ for (let c = 0; c < 3; c++) {
+ channelDelta = Math.max(channelDelta, Math.abs(pilot.data[i + c]! - rewrite.data[i + c]!));
+ repeatDelta = Math.max(repeatDelta, Math.abs(pilot.data[i + c]! - repeat.data[i + c]!));
+ }
+ if (channelDelta > 32) over32++;
+ if (repeatDelta > 32) noiseOver32++;
const x = pixel % width, y = Math.floor(pixel / width), tile = Math.floor(y * 9 / height) * 16 + Math.floor(x * 16 / width);
counts[tile]++; noise[tile] += oldDelta; differences[tile] += delta; sum += delta; noiseSum += oldDelta;
- // Fourfold gain is only a visual aid; all metrics use unamplified linear luminance.
+ // Fourfold gain is only a visual aid. Tile/global means use unamplified linear luminance;
+ // the thin-line count above uses the adopted >32 sRGB-channel difference.
diff[i] = diff[i + 1] = diff[i + 2] = Math.min(255, Math.round(delta * 255 * 4)); diff[i + 3] = 255;
}
const tiles: ParityTile[] = Array.from(counts, (pixels, n) => {
@@ -23,6 +30,29 @@ export function compareParityImages(pilot: RgbaImage, repeat: RgbaImage, rewrite
return { x: n % 16, y: Math.floor(n / 16), pixels, noise: oldNoise, mean, threshold, pass: mean <= threshold };
});
const passingTiles = tiles.filter(tile => tile.pass).length, passingFraction = passingTiles / tiles.length, globalMean = sum / (width * height);
+ const luminancePass = passingFraction >= .97 && globalMean < .02;
return { width, height, globalMean, noiseGlobalMean: noiseSum / (width * height), passingTiles, passingFraction,
- pass: passingFraction >= .97 && globalMean < .02, tiles, diff: { width, height, data: diff } };
+ luminancePass, over32, noiseOver32, tiles, diff: { width, height, data: diff } };
+}
+
+/** SPEC 19 + D18: fixed luminance thresholds AND a thin-line budget beyond repeat noise.
+ * The adopted default is 100 pixels per 1280×720 full view. Other sizes require an explicit
+ * custom budget, or compareLuminanceImages for the original crop diagnostic. No area scaling.
+ */
+export function compareParityImages(pilot: RgbaImage, repeat: RgbaImage, rewrite: RgbaImage, options: { over32Budget?: number } = {}) {
+ const fullView = pilot.width === 1280 && pilot.height === 720;
+ if (!fullView && options.over32Budget === undefined) throw new Error('Non-full-view parity requires an explicit thin-line budget or compareLuminanceImages');
+ const budget = options.over32Budget ?? 100;
+ if (!Number.isSafeInteger(budget) || budget < 0) throw new Error('Thin-line budget must be a finite nonnegative integer');
+ const { over32, noiseOver32, ...metric } = measureImages(pilot, repeat, rewrite);
+ const lines = { over32, noise: noiseOver32, budget, pass: over32 <= noiseOver32 + budget };
+ return { ...metric, scope: fullView && budget === 100 ? 'b06-d18' as const : 'custom-budget' as const, pass: metric.luminancePass && lines.pass, lines };
+}
+
+/** Original SPEC 19 tile/global luminance comparison, for explicit crop or historical diagnostics.
+ * `pass` applies only to this scope; it never grants full-view D18 qualification.
+ */
+export function compareLuminanceImages(pilot: RgbaImage, repeat: RgbaImage, rewrite: RgbaImage) {
+ const { over32: _over32, noiseOver32: _noiseOver32, ...metric } = measureImages(pilot, repeat, rewrite);
+ return { ...metric, scope: 'luminance-only' as const, pass: metric.luminancePass };
}
diff --git a/scenes/scripts/qualify-farm-static.ts b/scenes/scripts/qualify-farm-static.ts
index 70e50a7d..77ed0a0f 100644
--- a/scenes/scripts/qualify-farm-static.ts
+++ b/scenes/scripts/qualify-farm-static.ts
@@ -3,14 +3,20 @@ import { createHash } from 'node:crypto';
import { readFile, writeFile } from 'node:fs/promises';
import { isAbsolute, relative, resolve, sep } from 'node:path';
import { PNG } from 'pngjs';
-import { compareParityImages } from './parity-images';
+import { compareLuminanceImages, type RgbaImage } from './parity-images';
import { cropImage, validateWoodlandAb, WOODLAND_CROP } from './capture-woodland-ab';
const BACKENDS = ['webgpu', 'webgl2'] as const, WINDOW = 'house-window-out';
const near = (actual: number, expected: number, message: string) => assert(Number.isFinite(actual) && Math.abs(actual - expected) <= 1e-12, message);
-/** Validate all144 tiles and derive the gate from raw numeric fields, never just the stored pass flag. */
+/** Replay the exact pre-D18 r33/M2a receipt shape. This archival verifier never qualifies current scene changes. */
+export function compareHistoricalStaticImages(pilot: RgbaImage, repeat: RgbaImage, rewrite: RgbaImage) {
+ const { scope: _scope, luminancePass: _luminancePass, ...metric } = compareLuminanceImages(pilot, repeat, rewrite);
+ return metric;
+}
+/** Validate all144 historical tiles and derive the original gate from raw numeric fields, never a stored pass flag. */
export function validateMetric(metric: any, requirePass = true) {
+ assert(metric.scope === undefined && metric.lines === undefined && metric.luminancePass === undefined, 'This historical r33 verifier predates D18; use current qualification for newer receipts');
assert.equal(metric.width, 1280); assert.equal(metric.height, 720); assert.equal(metric.tiles?.length, 144, 'Exactly144 tile metrics are required');
let passing = 0, mean = 0, noise = 0;
for (let i = 0; i < 144; i++) {
@@ -96,7 +102,7 @@ export async function qualifyFarmStatic(baseLabel: string, correctionLabel: stri
const onDisk = JSON.parse(await readFile(resolve(expectedDir, 'result.json'), 'utf8')); assert.deepEqual(onDisk, result, 'Per-attempt receipt differs from aggregate report');
const prefix = `${result.view}-`, suffix = `-${result.backend}.png`;
const pilot = await readPng(resolve(expectedDir, prefix + 'pilot' + suffix)), repeat = await readPng(resolve(expectedDir, prefix + 'pilot-repeat' + suffix)), rewrite = await readPng(resolve(expectedDir, prefix + 'new' + suffix));
- const measured = compareParityImages(pilot, repeat, rewrite), { diff, ...numeric } = measured;
+ const measured = compareHistoricalStaticImages(pilot, repeat, rewrite), { diff, ...numeric } = measured;
assert.deepEqual(numeric, result.metric, 'Archived PNGs do not reproduce the stored metrics');
const savedDiff = await readPng(resolve(expectedDir, prefix + 'diff' + suffix)); assert.equal(hash(savedDiff.data), hash(diff.data), 'Diff artifact does not match the source images');
qualified.push({ view: result.view, backend: result.backend, attempt: result.attempt, source: reportPaths[source], evidence: portable(resolve(expectedDir, 'result.json')), globalMean: numeric.globalMean, noiseGlobalMean: numeric.noiseGlobalMean, passingTiles: numeric.passingTiles, tiles: 144, counts: result.rewrite.stats.counts });
@@ -112,16 +118,16 @@ export async function qualifyFarmStatic(baseLabel: string, correctionLabel: stri
captures[name] = { ...capture, png: await readPng(capture.file) };
}
validateWoodlandAb(captures.safe, captures.repeat, captures.unsafe, backend);
- const full = compareParityImages(captures.safe.png, captures.repeat.png, captures.unsafe.png), { diff: _full, ...fullMetric } = full;
+ const full = compareHistoricalStaticImages(captures.safe.png, captures.repeat.png, captures.unsafe.png), { diff: _full, ...fullMetric } = full;
assert.deepEqual(fullMetric, ab.full); validateMetric(fullMetric, false);
- const crop = compareParityImages(cropImage(captures.safe.png, WOODLAND_CROP), cropImage(captures.repeat.png, WOODLAND_CROP), cropImage(captures.unsafe.png, WOODLAND_CROP)), { diff: _crop, ...cropMetric } = crop;
+ const crop = compareHistoricalStaticImages(cropImage(captures.safe.png, WOODLAND_CROP), cropImage(captures.repeat.png, WOODLAND_CROP), cropImage(captures.unsafe.png, WOODLAND_CROP)), { diff: _crop, ...cropMetric } = crop;
assert.deepEqual(cropMetric, ab.cropMetric); assert.equal(ab.visualReviewRequired, !full.pass || !crop.pass);
for (const file of ab.images as string[]) if (!file.endsWith('-full.png') || file.startsWith('diff-')) await readPng(resolve(directory, file));
woodland.push({ backend, evidence: portable(resolve(directory, 'result.json')), safeOffenders: 0, unsafeOffenders: 16, fullMean: full.globalMean, cropMean: crop.globalMean, noiseGlobalMean: full.noiseGlobalMean, visualReviewRequired: ab.visualReviewRequired });
}
const historical = base.results.filter((result: Result) => result.status === 'fail').map((result: Result) => ({ view: result.view, backend: result.backend, attempt: result.attempt, evidence: portable(resolve(local(result.directory), 'result.json')), error: result.error, globalMean: result.metric?.globalMean, passingTiles: result.metric?.passingTiles }));
assert(historical.length >= 2 && historical.every((entry: any) => entry.view === WINDOW), 'Only the explained window defect may be superseded');
- const qualification = { schema: 'kiln.farm-static-qualification/1', date: correction.date, milestone: 'M2a', status: 'pass', release: 'r33', scope: '12 static named views on both backends, pre-batching counts, and D-06 woodland A/B; M2b optimization and M2c/M2d play parity remain outstanding',
+ const qualification = { schema: 'kiln.farm-static-qualification/1', date: correction.date, milestone: 'M2a', status: 'pass', release: 'r33', scope: 'Historical r33/M2a luminance-only evidence: 12 static named views on both backends, pre-batching counts, and D-06 woodland A/B; not current D18 qualification. M2b optimization and M2c/M2d play parity remain outstanding',
reports: { base: { path: reportPaths.base, sha256: hash(baseBytes), ledger: base.ledger }, correction: { path: reportPaths.correction, sha256: hash(correctionBytes), ledger: correction.ledger } },
correction: { view: WINDOW, reason: 'Farm port incorrectly imposed a3m minimum orbit distance; restored the pilot0m minimum so the authored close window camera is preserved', reportMetadata: 'Runner stage label changed from M2a static pre-batching to m2a and countGate explanatory wording changed; all actual capture conditions and pre-batching counts remain identical', originalFailuresRetained: historical },
summary: { staticCases: qualified.length, pass: qualified.length, fail: 0, backends: [...BACKENDS], views: 12, tilesPerImage: 144 }, results: qualified, woodlandAb: woodland, artifacts, timing: 'not collected' };
diff --git a/scenes/scripts/release-inputs.ts b/scenes/scripts/release-inputs.ts
new file mode 100644
index 00000000..1b3fbacb
--- /dev/null
+++ b/scenes/scripts/release-inputs.ts
@@ -0,0 +1,48 @@
+/** Read-only qualification of the exact asset packs restored by site/scripts/scene-inputs.mjs. */
+import { createHash } from 'node:crypto';
+import { existsSync, readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { assertPackPath, validateManifest } from '../packages/scene-kit/src/assets/manifest';
+import { verifyStaged } from '../packages/scene-kit/src/staging';
+
+export const RELEASE_SCENES = ['farm', 'golden-gate', 'foundry-floor'] as const;
+type Scene = typeof RELEASE_SCENES[number];
+export type ReleasePins = Record<Scene, { id: string; release: string; three: string; packJsonSha256: string; sha256sumsSha256: string }>;
+const ROOT = resolve(import.meta.dir, '..');
+const sha = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex');
+export const releasedAssetRoot = (root: string, scene: Scene) => resolve(root, '.cache/site-inputs', scene, 'standalone/assets');
+
+export function verifyReleasedSceneInputs({ root = ROOT, pins = JSON.parse(readFileSync(resolve(root, '../site/src/data/scene-packs.json'), 'utf8')) as ReleasePins }: { root?: string; pins?: ReleasePins } = {}) {
+ return RELEASE_SCENES.map(scene => {
+ const assets = releasedAssetRoot(root, scene), pin = pins[scene];
+ if (!existsSync(resolve(assets, 'pack.json')) || !existsSync(resolve(assets, 'SHA256SUMS'))) {
+ throw new Error(`${scene}: released inputs are missing. Restore them with node ../site/scripts/scene-inputs.mjs before running test:release-inputs.`);
+ }
+ if (!pin || pin.id !== scene) throw new Error(`${scene}: missing or invalid external release pin`);
+ const packBytes = readFileSync(resolve(assets, 'pack.json'));
+ if (sha(packBytes) !== pin.packJsonSha256) throw new Error(`${scene}: pack.json pin mismatch`);
+ if (sha(readFileSync(resolve(assets, 'SHA256SUMS'))) !== pin.sha256sumsSha256) throw new Error(`${scene}: SHA256SUMS pin mismatch`);
+ const pack = validateManifest(JSON.parse(packBytes.toString('utf8')));
+ if (pack.id !== pin.id || pack.release !== pin.release || pack.three !== pin.three) throw new Error(`${scene}: release identity mismatch`);
+ // Standalone archives also contain their old build's top-level code chunks. Like build-scene,
+ // this gate qualifies asset/data inputs for current source, not the archived renderer runtime.
+ const problems = verifyStaged(assets).problems.filter(problem => !/^[^/]+\.(?:js|css): extra staged file$/.test(problem));
+ if (problems.length) throw new Error(`${scene}: released inputs failed verification:\n${problems.join('\n')}`);
+ return { scene, release: pack.release, models: pack.models.length, files: pack.files.length, packSha256: pin.packJsonSha256 };
+ });
+}
+
+/** Optional local tests may use the same pinned author/staged bytes; release qualification never falls back. */
+export function findSceneFixture(input: { scene: Scene; path: string; sha256: string; bytes?: number },
+ { root = ROOT, fallback = [], required = process.env.KILN_SCENE_RELEASE_INPUTS === '1' }: { root?: string; fallback?: string[]; required?: boolean } = {}): string | undefined {
+ assertPackPath(input.path);
+ const released = resolve(releasedAssetRoot(root, input.scene), input.path);
+ const matches = (path: string) => {
+ if (!existsSync(path)) return false;
+ const bytes = readFileSync(path);
+ return (input.bytes === undefined || input.bytes === bytes.length) && sha(bytes) === input.sha256;
+ };
+ if (matches(released)) return released;
+ if (required || existsSync(released)) throw new Error(`Required released fixture is missing or differs from its pin: ${input.scene}/${input.path}`);
+ return fallback.find(matches);
+}
diff --git a/scenes/scripts/run-farm-instance-ab.ts b/scenes/scripts/run-farm-instance-ab.ts
index d768d203..c9320a66 100644
--- a/scenes/scripts/run-farm-instance-ab.ts
+++ b/scenes/scripts/run-farm-instance-ab.ts
@@ -16,6 +16,7 @@ import type { Browser } from 'puppeteer-core';
import { launchChrome, serveOwned, workspacePath } from '../packages/scene-kit/src/testing/node';
import { captureFarmNew, type CapturedFarm, type ParityBackend } from './capture-farm-parity';
import { compareParityImages } from './parity-images';
+import { closeExtraStartupPages } from './browser-startup';
const args = process.argv.slice(2), value = (key: string, fallback: string) => { const at = args.indexOf(key); return at < 0 ? fallback : args[at + 1] ?? fallback; };
const workspace = resolve(import.meta.dir, '..');
@@ -49,7 +50,7 @@ try {
hosted = await serveOwned(workspacePath(workspace, build));
browser = await launchChrome({ workspace, name: 'instance-ab', windowSize: [1280, 720] });
report.browser = await browser.version(); report.port = hosted.port;
- for (const blank of await browser.pages()) await blank.close();
+ await closeExtraStartupPages(browser);
const ports = new Set([hosted.port]);
for (const b of backends) for (const view of views) {
const dir = resolve(out, `${view}-${b}`); await mkdir(dir, { recursive: true });
diff --git a/scenes/scripts/run-farm-look.ts b/scenes/scripts/run-farm-look.ts
index eebcc15d..512d4f01 100644
--- a/scenes/scripts/run-farm-look.ts
+++ b/scenes/scripts/run-farm-look.ts
@@ -18,8 +18,9 @@ import { cpus } from 'node:os';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { Browser, Page } from 'puppeteer-core';
-import { INSTALLED_CHROME, launchChrome, serveOwned, waitForReady, waitFrames, workspacePath } from '../packages/scene-kit/src/testing/node';
+import { launchChrome, serveOwned, waitForReady, waitFrames, workspacePath } from '../packages/scene-kit/src/testing/node';
import { FARM_LOOK_PRESETS, formatFarmLook, parseFarmLook, resolveFarmLook } from '../packages/farm/src/look/options';
+import { closeExtraStartupPages } from './browser-startup';
import { adbFor, connectDevtools, deviceState, forwardDevtools, listMappings, pcLoadSample, removeForward, removeReverse, requireNominal, reversePort, wakeAndOpenChrome } from './device-kit';
export const LOOK_TIERS = ['high', 'balanced', 'economy', 'minimal'] as const;
@@ -36,9 +37,9 @@ const list = (value: string) => value === 'none' ? [] : value.split(',').map(ent
const workspace = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const target = option('--target', 'pc') as 'pc' | 'tablet' | 'hub';
const many = (name: string) => args.flatMap((value, at) => args[at - 1] === name ? [value] : []);
-// The hub (the laptop) launches its own Chrome: --chrome <path> (required off Windows), --chrome-arg <flag> (repeatable) and
+// The hub (the laptop) launches its own Chrome: --chrome <path> overrides shared discovery, --chrome-arg <flag> (repeatable) and
// --headless as in runner/perf-farm.mjs; a headed window opens at 0,0. This PC always runs headless (owner rule 11:40).
-const chrome = option('--chrome', process.platform === 'win32' ? INSTALLED_CHROME : ''), headless = target !== 'hub' || args.includes('--headless');
+const chrome = option('--chrome', ''), headless = target !== 'hub' || args.includes('--headless');
const root = option('--root', 'packages/farm/dist/m3/dev'), backend = option('--backend', 'webgpu') as 'webgpu' | 'webgl2';
const presets = option('--presets', 'all') === 'all' ? Object.keys(FARM_LOOK_PRESETS) : list(option('--presets', ''));
const frameTiers = list(option('--frame-tiers', target === 'pc' ? 'high,balanced,economy,minimal' : 'economy,minimal,balanced,high')) as Tier[];
@@ -189,11 +190,10 @@ try {
await wakeAndOpenChrome(adb); forward = await forwardDevtools(adb); ledger.devtoolsForward = forward.port;
browser = await connectDevtools(forward.browserURL);
} else {
- if (!chrome) throw new Error('Pass --chrome <path to the installed Chrome> (Linux WebGPU flags are unverified; add them with --chrome-arg)');
- browser = await launchChrome({ workspace, name: 'look', executablePath: chrome, headless, windowSize: [WIDTH, HEIGHT],
+ browser = await launchChrome({ workspace, name: 'look', executablePath: chrome || undefined, headless, windowSize: [WIDTH, HEIGHT],
args: ['--disable-gpu-vsync', '--disable-frame-rate-limit', ...(headless ? [] : ['--window-position=0,0']), ...many('--chrome-arg')] });
ledger.window = { width: WIDTH, height: HEIGHT, headless, position: headless ? null : '0,0' };
- for (const blank of await browser.pages()) await blank.close();
+ await closeExtraStartupPages(browser);
}
report.browser = await browser.version();
const sideState = adb ? () => requireNominal(adb, 'between look blocks') : target === 'hub' ? hubLoad : pcLoad;
diff --git a/scenes/scripts/run-farm-mobile.ts b/scenes/scripts/run-farm-mobile.ts
index 83a8a7ce..40149ead 100644
--- a/scenes/scripts/run-farm-mobile.ts
+++ b/scenes/scripts/run-farm-mobile.ts
@@ -8,6 +8,7 @@ import axe from 'axe-core';
import { assertOwnedUrl, contrastRatio, launchChrome, serveOwned, waitForReady, waitFrames, workspacePath } from '../packages/scene-kit/src/testing/node';
import { DOOR_LABELS, doorPrompt, doorStatus, FARM_STRINGS } from '../packages/farm/src/ui/strings';
import { FARM_CAMERA, FARM_DOORS, FARM_WALK } from '../packages/farm/src/constants';
+import { closeExtraStartupPages } from './browser-startup';
/**
* B-09 mobile flows (SPEC 14 and 18, D-22) on the Farm test output, driven by touch: CDP
@@ -232,7 +233,7 @@ export async function runFarmMobile(o: MobileRunOptions) {
: await launchChrome({ workspace, name: `b09-${o.backend}`, windowSize: [PHONE.width, PHONE.height] });
ledger.browserPid = device ? 'device Chrome (not owned; only this run\'s tab is closed)' : browser.process()?.pid;
report.browser = await browser.version();
- if (!device) for (const blank of await browser.pages()) await blank.close();
+ if (!device) await closeExtraStartupPages(browser);
const p = page = await browser.newPage(); await configurePage(p, new Set([hosted.port]), diagnostics);
// A device has a real touch screen: no emulation there, only the dispatched touch events.
const cdp = device ? await p.createCDPSession() : await emulatePhone(p, String(report.browser), PHONE);
diff --git a/scenes/scripts/run-farm-play.ts b/scenes/scripts/run-farm-play.ts
index c54bd4a3..63a80965 100644
--- a/scenes/scripts/run-farm-play.ts
+++ b/scenes/scripts/run-farm-play.ts
@@ -7,6 +7,7 @@ import { assertOwnedUrl, launchChrome, serveOwned, waitForReady, waitFrames, wor
import { DOOR_LABELS, doorPrompt, doorStatus, FARM_STRINGS } from '../packages/farm/src/ui/strings';
import { FARM_CAMERA, FARM_DESTINATIONS, FARM_DOORS, FARM_WALK } from '../packages/farm/src/constants';
import { bridgeCenter } from '../packages/farm/src/world/site-layout';
+import { closeExtraStartupPages } from './browser-startup';
/**
* B-08 desktop play flows (SPEC 18) on the rewrite's test output, driven by real puppeteer keyboard
@@ -131,7 +132,7 @@ export async function runFarmPlay(o: { workspace?: string; backend: Backend; lab
hosted = await serveOwned(root); ledger.server = { port: hosted.port, pid: process.pid };
browser = await launchChrome({ workspace, name: `b08-${o.backend}`, windowSize: [WIDTH, HEIGHT] }); ledger.browserPid = browser.process()?.pid;
ledger.browserProfile = browser.process()?.spawnargs.find(arg => arg.startsWith('--user-data-dir='))?.slice('--user-data-dir='.length); report.browser = await browser.version();
- for (const blank of await browser.pages()) await blank.close();
+ await closeExtraStartupPages(browser);
const p = page = await browser.newPage(); await configurePage(p, new Set([hosted.port]), diagnostics);
const url = new URL(hosted.url); url.searchParams.set('tier', 'high'); if (o.backend === 'webgl2') url.searchParams.set('backend', 'webgl2'); report.url = url.href;
await p.goto(url.href, { waitUntil: 'load', timeout: TIMEOUT }); await waitForReady(p);
diff --git a/scenes/scripts/run-farm-tiering.ts b/scenes/scripts/run-farm-tiering.ts
index 9679b4ae..0fae618a 100644
--- a/scenes/scripts/run-farm-tiering.ts
+++ b/scenes/scripts/run-farm-tiering.ts
@@ -6,7 +6,7 @@ import { PNG } from 'pngjs';
import type { Browser, Page } from 'puppeteer-core';
import { classifyDevice, type DeviceProbe } from '../packages/scene-kit/src/quality/core';
import { assertOwnedUrl, launchChrome, serveOwned, waitForReady, waitFrames, workspacePath } from '../packages/scene-kit/src/testing/node';
-import { compareParityImages, type RgbaImage } from './parity-images';
+import { compareLuminanceImages, compareParityImages, type RgbaImage } from './parity-images';
/**
* B-10 (tiering) and B-13 (governor path and resize on the full scene) on the Farm test output.
@@ -192,9 +192,9 @@ export async function runFarmTiering(o: { workspace?: string; label: string; roo
await test.page.setViewport({ width: 1280, height: 720, deviceScaleFactor: 1 }); await waitFrames(test.page, 6); await settle(test.page);
const after = await capture(test.page, resolve(out, `${view}-stepped-resized.png`), 1280, 720);
const full = compareParityImages(reference, noise, after), control = compareParityImages(reference, noise, level0);
- const stream = view === 'watermill-wheel' ? compareParityImages(crop(reference, STREAM_RECT), crop(noise, STREAM_RECT), crop(after, STREAM_RECT)) : null;
+ const stream = view === 'watermill-wheel' ? compareLuminanceImages(crop(reference, STREAM_RECT), crop(noise, STREAM_RECT), crop(after, STREAM_RECT)) : null;
await writeFile(resolve(out, `${view}-diff.png`), PNG.sync.write(Object.assign(new PNG({ width: full.diff.width, height: full.diff.height }), { data: Buffer.from(full.diff.data) })));
- results[view] = { before, stepped, reference: refState, full: { pass: full.pass, passingTiles: full.passingTiles, globalMean: full.globalMean, noiseGlobalMean: full.noiseGlobalMean }, stream: stream && { pass: stream.pass, passingTiles: stream.passingTiles, globalMean: stream.globalMean, noiseGlobalMean: stream.noiseGlobalMean },
+ results[view] = { before, stepped, reference: refState, full: { scope: full.scope, luminancePass: full.luminancePass, lines: full.lines, pass: full.pass, passingTiles: full.passingTiles, globalMean: full.globalMean, noiseGlobalMean: full.noiseGlobalMean }, stream: stream && { scope: stream.scope, pass: stream.pass, passingTiles: stream.passingTiles, globalMean: stream.globalMean, noiseGlobalMean: stream.noiseGlobalMean },
control: { meaning: 'grass 1 (before the step) against grass .75: the difference the gate must be able to see', pass: control.pass, passingTiles: control.passingTiles, globalMean: control.globalMean } };
if (view === 'eye-height') assert(control.globalMean > 10 * Math.max(full.globalMean, 1e-6), `grass control: the grass step is visible to the metric (${control.passingTiles}/144 tiles, mean ${control.globalMean})`);
assert(full.pass, `${view}: ${full.passingTiles}/144 tiles, global mean ${full.globalMean}`); if (stream) assert(stream.pass, `stream crop: ${stream.passingTiles}/144, mean ${stream.globalMean}`);
diff --git a/scenes/scripts/run-farm-x11-x12.ts b/scenes/scripts/run-farm-x11-x12.ts
index 3d14d60a..2af5b083 100644
--- a/scenes/scripts/run-farm-x11-x12.ts
+++ b/scenes/scripts/run-farm-x11-x12.ts
@@ -17,6 +17,7 @@ import { resolve } from 'node:path';
import { gzipSync } from 'node:zlib';
import type { Browser, CDPSession, Page } from 'puppeteer-core';
import { launchChrome, serveOwned, workspacePath } from '../packages/scene-kit/src/testing/node';
+import { closeExtraStartupPages } from './browser-startup';
const argv = process.argv.slice(2), option = (name: string, fallback: string) => { const at = argv.indexOf(name); return at < 0 ? fallback : argv[at + 1] ?? fallback; };
const workspace = resolve(import.meta.dir, '..'), label = option('--label', 'm4'), release = option('--release', 'r34');
@@ -158,7 +159,7 @@ try {
for (const root of Object.values(builds)) assert(existsSync(resolve(root, 'index.html')), `${root} is built`);
const [publicHost, testHost] = [await serveOwned(builds.public), await serveOwned(builds.test)]; servers.push(publicHost!, testHost!);
browser = await launchChrome({ workspace, name: 'farm-x11-x12', windowSize: [WIDTH, HEIGHT] });
- for (const blank of await browser.pages()) await blank.close();
+ await closeExtraStartupPages(browser);
report.browser = await browser.version(); report.ports = servers.map(s => s.port);
if (run('x11')) {
const loadBefore = await loadSample(), loads: unknown[] = [];
diff --git a/scenes/scripts/static-server.mjs b/scenes/scripts/static-server.mjs
index b2d5ead8..5ef0ff88 100644
--- a/scenes/scripts/static-server.mjs
+++ b/scenes/scripts/static-server.mjs
@@ -5,7 +5,7 @@ import { resolve, relative, isAbsolute, extname, sep, basename } from 'node:path
import { pathToFileURL, fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
-const mime = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.glb': 'model/gltf-binary', '.bin': 'application/octet-stream', '.txt': 'text/plain; charset=utf-8', '.png': 'image/png', '.svg': 'image/svg+xml', '.ico': 'image/x-icon' };
+const mime = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.glb': 'model/gltf-binary', '.bin': 'application/octet-stream', '.txt': 'text/plain; charset=utf-8', '.png': 'image/png', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.ico': 'image/x-icon' };
const inside = (base, file) => { const rel = relative(base, file); return rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel); };
export async function verifyAssets(root) {
diff --git a/scenes/scripts/stream-crop-from-evidence.ts b/scenes/scripts/stream-crop-from-evidence.ts
index 829ab964..13f0b223 100644
--- a/scenes/scripts/stream-crop-from-evidence.ts
+++ b/scenes/scripts/stream-crop-from-evidence.ts
@@ -1,11 +1,11 @@
// SPEC 19.7 stream crop at the mill bank, computed from an existing parity run's retained watermill-wheel
-// captures (no new capture). Same tile metric and thresholds as B-06, on the crop only.
+// captures (no new capture). Original SPEC 19 luminance metric on the crop only; not full-view D18 qualification.
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { PNG } from 'pngjs';
import { cropImage } from './capture-woodland-ab';
import { STREAM_CROP } from './capture-farm-parity';
-import { compareParityImages, type RgbaImage } from './parity-images';
+import { compareLuminanceImages, type RgbaImage } from './parity-images';
const workspace = resolve(import.meta.dir, '..'), run = process.argv[2];
if (!run || !/^[a-z0-9-]+$/.test(run)) throw new Error('Usage: stream-crop-from-evidence.ts <parity run directory under evidence/parity>');
@@ -17,7 +17,7 @@ for (const backend of ['webgpu', 'webgl2']) {
const dir = resolve(root, `watermill-wheel-${backend}`), attempts = (await readdir(dir)).filter(name => /^attempt-\d+$/.test(name)).sort();
const attempt = attempts.at(-1)!, base = resolve(dir, attempt);
const [pilot, repeat, rewrite] = await Promise.all(['pilot', 'pilot-repeat', 'new'].map(kind => read(resolve(base, `watermill-wheel-${kind}-${backend}.png`))));
- const a = cropImage(pilot!, STREAM_CROP), b = cropImage(repeat!, STREAM_CROP), c = cropImage(rewrite!, STREAM_CROP), metric = compareParityImages(a, b, c);
+ const a = cropImage(pilot!, STREAM_CROP), b = cropImage(repeat!, STREAM_CROP), c = cropImage(rewrite!, STREAM_CROP), metric = compareLuminanceImages(a, b, c);
await write(`stream-crop-pilot-${backend}.png`, a); await write(`stream-crop-pilot-repeat-${backend}.png`, b); await write(`stream-crop-new-${backend}.png`, c); await write(`stream-crop-diff-${backend}.png`, metric.diff);
const { diff: _diff, tiles, ...numbers } = metric;
results.push({ backend, source: `evidence/parity/${run}/watermill-wheel-${backend}/${attempt}`, ...numbers, failingTiles: tiles.filter(tile => !tile.pass) });
diff --git a/scenes/scripts/test-portable.ts b/scenes/scripts/test-portable.ts
index 834127d8..b458f3c3 100644
--- a/scenes/scripts/test-portable.ts
+++ b/scenes/scripts/test-portable.ts
@@ -2,16 +2,17 @@ import { readdirSync } from 'node:fs';
import { resolve } from 'node:path';
// These retained author-workspace qualification suites require historical GLBs,
-// saved asset revisions or capture receipts. They remain runnable via test:integration.
+// saved asset revisions or capture receipts. They remain runnable via test:integration;
+// current release fixtures also have the fail-closed test:release-inputs gate.
// The portable gate covers source-only contracts on a fresh checkout; it does not
// claim to replace the exact-asset and browser qualification of a released scene.
const authoredInputs = new Set([
'packages/farm/tests/unit/hand-clearance.test.ts',
...['campus-assets', 'campus-drive', 'campus-freight', 'campus-vegetation', 'campus',
- 'determinism', 'ff3-pack', 'ff3-replacements', 'floor-rig', 'revision2-context',
+ 'determinism', 'ff3-pack', 'ff3-replacements', 'floor-rig', 'glb-world', 'revision2-context',
'revision2-drive', 'revision2-pack', 'revision2-vehicle-intake', 'sanity'].map(name =>
`packages/foundry-floor/tests/unit/${name}.test.ts`),
- ...['data', 'flights', 'review2-vehicles', 'workloads'].map(name =>
+ ...['data', 'flights', 'review2-vehicles', 'vehicle-models', 'workloads'].map(name =>
`packages/golden-gate/tests/unit/${name}.test.ts`),
]);
const root = resolve(import.meta.dir, '..');
@@ -24,7 +25,7 @@ function walk(directory: string) {
}
}
for (const directory of ['packages/scene-kit/tests', 'packages/farm/tests/unit',
- 'packages/golden-gate/tests/unit', 'packages/foundry-floor/tests/unit']) walk(directory);
-console.log(`Portable source contracts: ${files.length} files; ${authoredInputs.size} author-input suites remain in test:integration.`);
+ 'packages/golden-gate/tests/unit', 'packages/foundry-floor/tests/unit', 'scripts/tests']) walk(directory);
+console.log(`Portable source contracts: ${files.length} files; ${authoredInputs.size} input-dependent suites remain in test:integration (current fixtures: test:release-inputs).`);
const run = Bun.spawnSync([process.execPath, 'test', ...files.sort(), '--timeout', '20000'], { cwd: root, stdout: 'inherit', stderr: 'inherit' });
process.exitCode = run.exitCode;
diff --git a/scenes/scripts/test-release-inputs.ts b/scenes/scripts/test-release-inputs.ts
new file mode 100644
index 00000000..caba7f13
--- /dev/null
+++ b/scenes/scripts/test-release-inputs.ts
@@ -0,0 +1,21 @@
+// CPU integration against restored, externally pinned packs. No browser, renderer or provider calls.
+import { resolve } from 'node:path';
+import { verifyReleasedSceneInputs, type ReleasePins } from './release-inputs';
+
+const ROOT = resolve(import.meta.dir, '..');
+const SUITES = [
+ './packages/foundry-floor/tests/unit/glb-world.test.ts',
+ './packages/foundry-floor/tests/unit/campus-vegetation-shared.test.ts',
+ './packages/golden-gate/tests/unit/vehicle-models.test.ts',
+];
+interface GateOptions {
+ root?: string;
+ pins?: ReleasePins;
+ run?: (command: string[], options: { cwd: string; env: Record<string, string | undefined> }) => number;
+}
+export function runReleaseInputGate({ root = ROOT, pins, run = (command, options) => Bun.spawnSync(command, { ...options, stdout: 'inherit', stderr: 'inherit' }).exitCode }: GateOptions = {}): number {
+ const inputs = verifyReleasedSceneInputs({ root, pins });
+ console.log(`Exact released inputs verified: ${inputs.map(r => `${r.scene} ${r.release} (${r.models} models, ${r.files} files)`).join('; ')}.`);
+ return run([process.execPath, 'test', ...SUITES, '--timeout', '20000'], { cwd: root, env: { ...process.env, KILN_SCENE_RELEASE_INPUTS: '1' } });
+}
+if (import.meta.main) process.exitCode = runReleaseInputGate();
diff --git a/scenes/scripts/tests/browser-options.test.ts b/scenes/scripts/tests/browser-options.test.ts
new file mode 100644
index 00000000..29c3e4a2
--- /dev/null
+++ b/scenes/scripts/tests/browser-options.test.ts
@@ -0,0 +1,16 @@
+import { expect, test } from 'bun:test';
+import { sceneBrowserOptions } from '../browser-options.mjs';
+
+test('scene browser defaults stay headless; explicit options and host GPU flags are preserved', () => {
+ expect(sceneBrowserOptions({}, {})).toEqual({ headless: true, args: [] });
+ const env = { KILN_SCENE_HEADED: '1', KILN_SCENE_CHROME_ARGS: '["--ozone-platform=x11","--enable-features=Vulkan"]' };
+ expect(sceneBrowserOptions({}, env)).toEqual({ headless: false, args: ['--ozone-platform=x11', '--enable-features=Vulkan'] });
+ expect(sceneBrowserOptions({ headless: true, args: ['--window-size=1280,720'] }, env)).toEqual({ headless: true, args: ['--ozone-platform=x11', '--enable-features=Vulkan', '--window-size=1280,720'] });
+});
+
+test('bad browser configuration fails before launching a browser or creating its profile', () => {
+ for (const KILN_SCENE_HEADED of ['yes', '', 'true']) expect(() => sceneBrowserOptions({}, { KILN_SCENE_HEADED })).toThrow(/KILN_SCENE_HEADED/);
+ for (const KILN_SCENE_CHROME_ARGS of ['--flag', '{}', '[1]', '["https://example.com"]', '["--flag\\u0000"]']) {
+ expect(() => sceneBrowserOptions({}, { KILN_SCENE_CHROME_ARGS })).toThrow(/KILN_SCENE_CHROME_ARGS/);
+ }
+});
diff --git a/scenes/scripts/tests/browser-startup.test.ts b/scenes/scripts/tests/browser-startup.test.ts
new file mode 100644
index 00000000..416cac69
--- /dev/null
+++ b/scenes/scripts/tests/browser-startup.test.ts
@@ -0,0 +1,40 @@
+import { expect, test } from 'bun:test';
+import { closeExtraStartupPages } from '../browser-startup';
+
+// Headed Chrome exits when its last window closes, unlike headless Chrome.
+function headedBrowser(startupTabs: number) {
+ let connected = true;
+ const open = new Set<{ close(): Promise<void> }>();
+ const newPage = async () => {
+ if (!connected) throw new Error('Target.createTarget failed: browser window closed');
+ const page = { async close() { open.delete(page); if (!open.size) connected = false; } };
+ open.add(page);
+ return page;
+ };
+ return {
+ async start() { return Promise.all(Array.from({ length: startupTabs }, () => newPage())); },
+ browser: {
+ pages: async () => [...open],
+ newPage,
+ async close() { for (const page of [...open]) await page.close(); connected = false; },
+ },
+ isConnected: () => connected,
+ };
+}
+
+test.each([1, 3])('fresh capture pages survive startup cleanup with %i initial tab(s)', async startupTabs => {
+ const owned = headedBrowser(startupTabs);
+ const initial = await owned.start();
+ await closeExtraStartupPages(owned.browser);
+ // Reproduce the actual runner lifetime: every capture opens and closes its own page.
+ for (let capture = 0; capture < 3; capture++) {
+ const page = await owned.browser.newPage();
+ expect(initial).not.toContain(page);
+ await page.close();
+ expect(owned.isConnected()).toBe(true);
+ }
+ expect(await owned.browser.pages()).toEqual([initial[0]!]);
+ await owned.browser.close();
+ expect(owned.isConnected()).toBe(false);
+ expect(await owned.browser.pages()).toEqual([]);
+});
diff --git a/scenes/scripts/tests/checks.test.ts b/scenes/scripts/tests/checks.test.ts
index 32d71c7a..1b82a78a 100644
--- a/scenes/scripts/tests/checks.test.ts
+++ b/scenes/scripts/tests/checks.test.ts
@@ -1,43 +1,77 @@
import { describe, expect, test } from 'bun:test';
-import { validatePins, type PinSnapshot, APPROVED_PINS } from '../check-pins';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { collectPinSnapshot, validatePins, type PinSnapshot, APPROVED_PINS } from '../check-pins';
import { findHygieneHits, DENYLIST } from '../check-bundle-hygiene';
import { isAllowedLicense } from '../check-licenses';
function fixture(): PinSnapshot {
- const peers = { react: '19.3.0', 'react-dom': '19.3.0', three: '0.186.0', '@react-three/fiber': '9.8.1' };
+ const peers = { react: '19.3.0', 'react-dom': '19.3.0', three: '0.186.1', '@react-three/fiber': '9.8.1' };
return {
manifests: [
{ path: 'package.json', json: { private: true, packageManager: '[email protected]', devDependencies: { ...APPROVED_PINS } } },
{ path: 'packages/scene-kit/package.json', json: { name: '@kiln-scenes/scene-kit', private: true, peerDependencies: peers, devDependencies: peers } },
],
lockfiles: ['bun.lock'],
- lock: { packages: { three: ['[email protected]', '', {}, 'sha512-fixture'], '@types/three': ['@types/[email protected]', '', {}, 'sha512-types-fixture'] } },
+ lock: { packages: { three: ['[email protected]', '', {}, 'sha512-fixture'], '@types/three': ['@types/[email protected]', '', {}, 'sha512-types-fixture'] } },
site: { dependencies: peers, devDependencies: { '@types/react': '^19.3.0', '@types/react-dom': '^19.3.0', '@types/three': '0.186.0', typescript: '6.0.3' } },
- engine: { dependencies: { three: '0.186.0' } },
- renderService: { dependencies: { three: '0.186.0' } },
- toolchain: { bun: '1.4.2', node: '22.23.2', npm: '12.0.2' },
- siteToolchain: { bun: '1.4.2', node: '22.23.2', npm: '12.0.2' },
- siteViteVersions: ['8.3.0'],
- installedThree: [{ path: 'node_modules/three', version: '0.186.0' }],
+ engine: { dependencies: { three: '0.186.1' } },
+ renderService: { dependencies: { three: '0.186.1' } },
+ toolchain: { bun: '1.4.2', node: '22.23.3', npm: '12.2.0' },
+ siteToolchain: { bun: '1.4.2', node: '22.23.3', npm: '12.2.0' },
+ siteViteVersions: ['8.3.2'],
+ installedThree: [{ path: 'node_modules/three', version: '0.186.1' }],
};
}
describe('U-20 pin fixture repositories', () => {
+ test('collects pins from a relocated integrated checkout', async () => {
+ const repo = await mkdtemp(join(tmpdir(), 'kiln pins checkout '));
+ const root = join(repo, 'scenes');
+ const f = fixture();
+ async function write(path: string, value: unknown) {
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, JSON.stringify(value));
+ }
+ try {
+ await Promise.all([
+ ...f.manifests.map(m => write(join(root, m.path), m.json)),
+ write(join(root, 'bun.lock'), f.lock),
+ write(join(root, 'toolchain.json'), f.toolchain),
+ write(join(root, 'node_modules/three/package.json'), { version: '0.186.1' }),
+ write(join(repo, 'site/package.json'), f.site),
+ write(join(repo, 'site/bun.lock'), { packages: { vite: ['[email protected]'] } }),
+ write(join(repo, 'package.json'), f.engine),
+ write(join(repo, 'render-service/package.json'), f.renderService),
+ write(join(repo, 'toolchain.json'), f.siteToolchain),
+ ]);
+ const snapshot = collectPinSnapshot(root);
+ expect(validatePins(snapshot)).toEqual([]);
+ expect(snapshot.site).toEqual(f.site);
+ expect(snapshot.engine).toEqual(f.engine);
+ expect(snapshot.renderService).toEqual(f.renderService);
+ await write(join(repo, 'package.json'), { dependencies: { three: '0.186.2' } });
+ expect(validatePins(collectPinSnapshot(root)).join('\n')).toContain('engine three');
+ } finally {
+ await rm(repo, { recursive: true, force: true });
+ }
+ });
test('accepts exact pins and the website React types exception', () => expect(validatePins(fixture())).toEqual([]));
test('rejects a different three in a package', () => {
- const f = fixture(); f.manifests[1]!.json.devDependencies!.three = '0.186.1';
- expect(validatePins(f).join('\n')).toContain('three must be 0.186.0');
+ const f = fixture(); f.manifests[1]!.json.devDependencies!.three = '0.186.2';
+ expect(validatePins(f).join('\n')).toContain('three must be 0.186.1');
});
test('rejects a range outside the two website types exceptions', () => {
const f = fixture(); f.manifests[0]!.json.devDependencies!.react = '^19.3.0';
expect(validatePins(f).join('\n')).toContain('react must be 19.3.0');
});
test('detects a website mismatch', () => {
- const f = fixture(); f.site.dependencies!.three = '0.186.1';
+ const f = fixture(); f.site.dependencies!.three = '0.186.2';
expect(validatePins(f).join('\n')).toContain('website three');
});
test('detects a second lockfile resolution even with an exact direct pin', () => {
- const f = fixture(); f.lock.packages['nested/three'] = ['[email protected]', '', {}, 'sha512-other'];
+ const f = fixture(); f.lock.packages['nested/three'] = ['[email protected]', '', {}, 'sha512-other'];
expect(validatePins(f).join('\n')).toContain('exactly one three resolution');
});
test('rejects a second lockfile and an unapproved direct package', () => {
@@ -48,8 +82,8 @@ describe('U-20 pin fixture repositories', () => {
});
test('rejects missing TS6 alias, two physical three copies, and a wrong engine pin', () => {
const f = fixture(); delete f.manifests[0]!.json.devDependencies!['typescript-6'];
- f.installedThree.push({ path: 'packages/scene-kit/node_modules/three', version: '0.186.0' });
- f.engine.dependencies!.three = '^0.186.0';
+ f.installedThree.push({ path: 'packages/scene-kit/node_modules/three', version: '0.186.1' });
+ f.engine.dependencies!.three = '^0.186.1';
const result = validatePins(f).join('\n');
expect(result).toContain('typescript-6'); expect(result).toContain('physical three'); expect(result).toContain('engine three');
});
diff --git a/scenes/scripts/tests/farm-count-gates.test.ts b/scenes/scripts/tests/farm-count-gates.test.ts
index 739125b3..07d629a8 100644
--- a/scenes/scripts/tests/farm-count-gates.test.ts
+++ b/scenes/scripts/tests/farm-count-gates.test.ts
@@ -49,7 +49,20 @@ function optimization() {
frozen: { placements: 555, nodes: 4191 }, frameGraph: { hiddenRoots: 575, dynamicRoots: 29 } } };
}
const pilot = () => ({ ...counts(), assetTexturePool: { uniqueBefore: 98, uniqueAfter: 29 } });
-function b07(raw = optimization()) { return compareFarmOptimizationCounts({ release: 'r33', counts: raw, pilot: pilot(), pilotRepeat: pilot(), rewrite: counts() }); }
+const rewrite = () => ({ ...counts(), textures: 41 });
+function b07(raw = optimization()) { return compareFarmOptimizationCounts({ release: 'r33', counts: raw, pilot: pilot(), pilotRepeat: pilot(), rewrite: rewrite() }); }
+
+test('D68 renderer texture goldens name prewarm and cached-shadow provenance independently of pilot view allocation', () => {
+ const current = compareFarmOptimizationCounts({ release: 'r34', counts: optimization(), pilot: pilot(), pilotRepeat: { ...pilot(), textures: 35 }, rewrite: { ...counts(), textures: 41 } });
+ expect(current.pass).toBe(true);
+ expect(current.textureGolden).toMatchObject({ decision: 'D-68', profile: 'cached-shadows', expected: 41 });
+ expect(current.pilotTextureObservations).toEqual({ first: 29, repeat: 35, gatedAsEquality: false });
+ expect(compareFarmOptimizationCounts({ release: 'r34', counts: optimization(), pilot: pilot(), pilotRepeat: pilot(), rewrite: { ...counts(), textures: 39 } }).pass).toBe(false);
+ const prewarm = compareFarmOptimizationCounts({ release: 'r34', counts: optimization(), pilot: pilot(), pilotRepeat: pilot(), rewrite: { ...counts(), textures: 39 }, textureProfile: 'prewarmed' });
+ expect(prewarm.pass).toBe(true);
+ expect(prewarm.textureGolden).toMatchObject({ profile: 'prewarmed', expected: 39 });
+ expect(compareFarmOptimizationCounts({ release: 'r34', counts: optimization(), pilot: pilot(), pilotRepeat: pilot(), rewrite: { ...counts(), textures: 42 } }).pass).toBe(false);
+});
test('B-07 checks independently measured optimization fields and both pilot texture samples', () => {
const result = b07();
@@ -62,7 +75,7 @@ test('B-07 checks independently measured optimization fields and both pilot text
expect(b07(raw).pass).toBe(false);
const missing = optimization(); delete (missing.optimization as any).frozen;
expect(b07(missing).pass).toBe(false);
- expect(compareFarmOptimizationCounts({ release: 'r33', counts: optimization(), pilot: pilot(), pilotRepeat: { ...pilot(), textures: 30 }, rewrite: counts() }).pass).toBe(false);
+ expect(compareFarmOptimizationCounts({ release: 'r33', counts: optimization(), pilot: pilot(), pilotRepeat: { ...pilot(), textures: NaN }, rewrite: rewrite() }).pass).toBe(false);
});
test('B-07 distinguishes recorded historical counts from current sealed goldens and unsafe instances', () => {
@@ -84,13 +97,13 @@ const colliderFixture = () => ({ colliders: 3, dynamic: 2, staticTriangles: 90,
test('B-07 collider portion equals the frozen fixture in count, kind, order and triangles', () => {
const live = { ...colliderFixture(), keys: colliderFixture().keys.map(key => ({ ...key, key: `port ${key.key}` })) };
expect(compareColliderCounts(live, colliderFixture()).every(check => check.pass)).toBe(true);
- const result = compareFarmOptimizationCounts({ release: 'r33', counts: optimization(), pilot: pilot(), pilotRepeat: pilot(), rewrite: counts(), colliders: { actual: live, fixture: colliderFixture() } });
+ const result = compareFarmOptimizationCounts({ release: 'r33', counts: optimization(), pilot: pilot(), pilotRepeat: pilot(), rewrite: rewrite(), colliders: { actual: live, fixture: colliderFixture() } });
expect(result.pass).toBe(true); expect(result.pending).toEqual([]); expect(result.scope).toBe('Optimization statistics and collider counts');
const reordered = { ...colliderFixture(), keys: [...colliderFixture().keys].reverse() };
expect(compareColliderCounts(reordered, colliderFixture()).find(check => check.name.startsWith('colliders.keys'))!.pass).toBe(false);
expect(compareColliderCounts({ ...colliderFixture(), staticTriangles: 91 }, colliderFixture()).some(check => !check.pass)).toBe(true);
expect(compareColliderCounts(null, colliderFixture()).every(check => !check.pass)).toBe(true);
- expect(compareFarmOptimizationCounts({ release: 'r33', counts: optimization(), pilot: pilot(), pilotRepeat: pilot(), rewrite: counts(), colliders: { actual: { ...colliderFixture(), doors: 2 }, fixture: colliderFixture() } }).pass).toBe(false);
+ expect(compareFarmOptimizationCounts({ release: 'r33', counts: optimization(), pilot: pilot(), pilotRepeat: pilot(), rewrite: rewrite(), colliders: { actual: { ...colliderFixture(), doors: 2 }, fixture: colliderFixture() } }).pass).toBe(false);
});
test('X-02 names its fixture kind and the coverage summary requires play fixtures on both backends', () => {
diff --git a/scenes/scripts/tests/farm-paired-parity.test.ts b/scenes/scripts/tests/farm-paired-parity.test.ts
new file mode 100644
index 00000000..5d729146
--- /dev/null
+++ b/scenes/scripts/tests/farm-paired-parity.test.ts
@@ -0,0 +1,43 @@
+import { expect, test } from 'bun:test';
+import { acceptedBuildEvidence, captureSamePhasePair, pairedFarmCoverage, pairedFarmVerdict } from '../capture-farm-paired';
+
+test('D68 flags only a new pilot failure that the accepted build does not share', () => {
+ for (const accepted of [false, true]) for (const candidate of [false, true]) {
+ expect(pairedFarmVerdict({ pass: accepted }, { pass: candidate })).toEqual({ pass: candidate || !accepted, regression: accepted && !candidate });
+ }
+ expect(() => pairedFarmVerdict({ pass: undefined } as any, { pass: false })).toThrow();
+});
+
+test('both captures use the same finite pilot phase and the same untouched pilot pair', async () => {
+ const image = () => ({ width: 1280, height: 720, data: new Uint8Array(1280 * 720 * 4).fill(255) });
+ const first = image(), repeat = image();
+ const calls: unknown[] = [];
+ const capture = async (side: string, phase: number) => { calls.push({ side, phase }); return { png: image(), stats: { side } }; };
+ const result = await captureSamePhasePair({ pilot: { first, repeat, phase: 12.345 }, capture });
+ expect(calls).toEqual([{ side: 'accepted', phase: 12.345 }, { side: 'candidate', phase: 12.345 }]);
+ expect(result).toMatchObject({ phase: 12.345, verdict: { pass: true, regression: false } });
+ expect(result.accepted.metric.scope).toBe('b06-d18');
+ expect(result.candidate.metric.scope).toBe('b06-d18');
+ await expect(captureSamePhasePair({ pilot: { first, repeat, phase: NaN }, capture })).rejects.toThrow('phase');
+ await expect(captureSamePhasePair({ pilot: { first, repeat, phase: 0 }, capture: async () => { throw new Error('capture failed'); } })).rejects.toThrow('capture failed');
+});
+
+test('release qualification needs every named and play view on both backends, without duplicate substitution', () => {
+ const views = ['hero', 'play-yard'];
+ const rows = views.flatMap(view => ['webgpu', 'webgl2'].map(backend => ({ view, backend, status: 'pass' })));
+ expect(pairedFarmCoverage(views, rows, true)).toMatchObject({ releaseQualified: true, expected: 4, checked: 4 });
+ expect(pairedFarmCoverage(views, rows.slice(0, 3), true)).toMatchObject({ releaseQualified: false, missing: ['play-yard/webgl2'] });
+ expect(pairedFarmCoverage(views, [...rows, rows[0]], true)).toMatchObject({ releaseQualified: false });
+ expect(pairedFarmCoverage(views, rows.map((row, i) => i ? row : { ...row, status: 'error' }), true)).toMatchObject({ releaseQualified: false });
+});
+
+test('all passing pairs without exact accepted-build evidence remain a diagnostic reconstruction', () => {
+ const rows = ['webgpu', 'webgl2'].map(backend => ({ view: 'hero', backend, status: 'pass' }));
+ expect(pairedFarmCoverage(['hero'], rows)).toMatchObject({ releaseQualified: false, acceptedBuildVerified: false });
+ expect(acceptedBuildEvidence(undefined, 'a'.repeat(64))).toMatchObject({ verified: false, status: 'unknown' });
+ const receipt = { schema: 'kiln.farm-accepted-build/1', ownerAccepted: true, decision: 'Explicit owner decision for fixture build', buildSha256: 'a'.repeat(64) };
+ expect(acceptedBuildEvidence(receipt, receipt.buildSha256)).toMatchObject({ verified: true, status: 'recorded' });
+ expect(() => acceptedBuildEvidence(receipt, 'b'.repeat(64))).toThrow('exact build');
+ expect(() => acceptedBuildEvidence({ ...receipt, ownerAccepted: false }, receipt.buildSha256)).toThrow();
+ expect(() => acceptedBuildEvidence({ ...receipt, decision: '' }, receipt.buildSha256)).toThrow();
+});
diff --git a/scenes/scripts/tests/farm-pilot-server.test.ts b/scenes/scripts/tests/farm-pilot-server.test.ts
new file mode 100644
index 00000000..cca0b7d9
--- /dev/null
+++ b/scenes/scripts/tests/farm-pilot-server.test.ts
@@ -0,0 +1,32 @@
+import { expect, test } from 'bun:test';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { serveSealedPilot } from '../capture-farm-parity';
+
+test('sealed pilot advances past Bun busy-port diagnostics without probing or changing the pilot server', async () => {
+ const workspace = await mkdtemp(join(tmpdir(), 'kiln-pilot-busy-'));
+ const root = join(workspace, '.tmp/pilot-r34/scene');
+ await mkdir(root, { recursive: true });
+ // The unchanged pilot logs error.message, which Bun spells without an EADDRINUSE code.
+ await writeFile(join(root, 'serve.mjs'), `const port=Number(process.argv[2]); if(port===4400){console.error('Failed to start server. Is port 4400 in use?');process.exit(1);} console.log('Farm review: http://127.0.0.1:'+port+'/');setInterval(()=>{},1000);`);
+ let hosted: Awaited<ReturnType<typeof serveSealedPilot>> | undefined;
+ try {
+ hosted = await serveSealedPilot(workspace, 'r34');
+ expect(hosted.port).toBe(4401);
+ expect(hosted.log).toHaveLength(2);
+ expect(hosted.log[0]?.exit).toBe(1);
+ await hosted.close();
+ expect(hosted.closed).toBe(true);
+ await hosted.close();
+ } finally { await hosted?.close(); await rm(workspace, { recursive: true, force: true }); }
+});
+
+test('sealed pilot treats an integrity failure as an error, never as a busy port', async () => {
+ const workspace = await mkdtemp(join(tmpdir(), 'kiln-pilot-invalid-'));
+ const root = join(workspace, '.tmp/pilot-r34/scene');
+ await mkdir(root, { recursive: true });
+ await writeFile(join(root, 'serve.mjs'), `console.error('Scene content differs from delivery: index.html');process.exit(1);`);
+ try { await expect(serveSealedPilot(workspace, 'r34')).rejects.toThrow('Scene content differs'); }
+ finally { await rm(workspace, { recursive: true, force: true }); }
+});
diff --git a/scenes/scripts/tests/farm-qualification.test.ts b/scenes/scripts/tests/farm-qualification.test.ts
new file mode 100644
index 00000000..d92db9c5
--- /dev/null
+++ b/scenes/scripts/tests/farm-qualification.test.ts
@@ -0,0 +1,45 @@
+import { expect, test } from 'bun:test';
+import * as drawParity from '../capture-farm-draw-parity';
+import * as x02 from '../farm-x02-baseline';
+import { sceneBrowserOptions } from '../browser-options.mjs';
+
+const request = { tiers: ['economy', 'high'], views: ['hero', 'dest-tractor'], backend: 'webgpu' };
+const complete = () => request.tiers.flatMap(tier => request.views.map(view => ({ tier, view, backend: request.backend, pass: true })));
+
+test('Farm draw parity exits successfully only for complete passing requested cells', () => {
+ expect(drawParity.farmDrawParityVerdict(request, complete())).toMatchObject({ pass: true, exitCode: 0, expected: 4, checked: 4 });
+ expect(drawParity.farmDrawParityVerdict(request, complete().slice(1))).toMatchObject({ pass: false, exitCode: 1, missing: ['economy/hero/webgpu'] });
+ expect(drawParity.farmDrawParityVerdict(request, [...complete(), complete()[0]!])).toMatchObject({ pass: false, exitCode: 1 });
+ expect(drawParity.farmDrawParityVerdict(request, complete().map(row => ({ ...row, backend: 'webgl2' })))).toMatchObject({ pass: false, exitCode: 1 });
+ expect(drawParity.farmDrawParityVerdict({ ...request, views: [] }, [])).toMatchObject({ pass: false, exitCode: 1 });
+});
+
+test('Farm draw parity rejects failed, errored and browser-error rows even if other cells pass', () => {
+ for (const patch of [{ pass: false }, { error: 'capture failed' }, { messages: { before: [], repeat: [], after: ['pageerror: failure'] } }]) {
+ const rows = complete(); rows[0] = { ...rows[0]!, ...patch };
+ expect(drawParity.farmDrawParityVerdict(request, rows)).toMatchObject({ pass: false, exitCode: 1, failed: ['economy/hero/webgpu'] });
+ }
+ const rows = complete().map(row => ({ ...row, messages: { before: ['warn: THREE.Clock deprecation'], repeat: [], after: [] } }));
+ expect(drawParity.farmDrawParityVerdict(request, rows)).toMatchObject({ pass: true, exitCode: 0 });
+});
+
+test('Farm X02 records the same resolved headless mode passed to browser launch', () => {
+ const headed = sceneBrowserOptions({}, { KILN_SCENE_HEADED: '1', KILN_SCENE_CHROME_ARGS: '["--ozone-platform=x11"]' });
+ expect(x02.farmX02BrowserProvenance('Chrome/150.0', headed)).toEqual({ browser: 'headed Chrome/150.0', browserLaunch: { headless: false } });
+ const headless = sceneBrowserOptions({}, {});
+ expect(x02.farmX02BrowserProvenance('Chrome/150.0', headless)).toEqual({ browser: 'headless Chrome/150.0', browserLaunch: { headless: true } });
+});
+
+test('Farm parity can format retained error rows after JSON turns nonfinite metrics into null', () => {
+ const failed = { tier: 'economy', view: 'hero', backend: 'webgpu', pass: false, b06: false, error: 'capture failed',
+ globalMean: NaN, noiseGlobalMean: Infinity, passingTiles: 0, afterVsBefore: {}, repeatVsBefore: {} };
+ const retained = JSON.parse(JSON.stringify(failed));
+ expect(retained.globalMean).toBeNull();
+ for (const row of [retained, failed, { ...retained, globalMean: undefined, noiseGlobalMean: undefined }]) {
+ expect(drawParity.farmDrawParityMarkdownRow(row)).toBe('| webgpu | economy | hero | **NO** | NO | 0/144 | unavailable | unavailable | unavailable / unavailable | unavailable / unavailable | unavailable | - | - | - |');
+ expect(drawParity.farmDrawParityVerdict({ tiers: ['economy'], views: ['hero'], backend: 'webgpu' }, [row])).toMatchObject({ pass: false, exitCode: 1 });
+ }
+ const passed = { ...retained, backend: 'webgl2', pass: true, b06: true, error: undefined, globalMean: 0.0002, noiseGlobalMean: 0,
+ passingTiles: 144, afterVsBefore: { over32: 2, differing: 4, max: 34 }, repeatVsBefore: { over32: 0, differing: 0 } };
+ expect(drawParity.farmDrawParityMarkdownRow(passed)).toContain('| yes | yes | 144/144 | 2.00e-4 | 0.00e+0 | 2 / 0 | 4 / 0 | 34 |');
+});
diff --git a/scenes/scripts/tests/foundry-builder.test.ts b/scenes/scripts/tests/foundry-builder.test.ts
new file mode 100644
index 00000000..c2ce8661
--- /dev/null
+++ b/scenes/scripts/tests/foundry-builder.test.ts
@@ -0,0 +1,73 @@
+import { expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { resolve } from 'node:path';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import * as builder from '../../packages/foundry-floor/tests/tools/rebuild-code';
+
+const packageRoot = resolve(import.meta.dir, '../../packages/foundry-floor');
+mkdirSync(resolve(packageRoot, 'dist'), { recursive: true });
+
+test('Foundry code rebuild keeps its default and accepts a separate owned output directory', () => {
+ const input = resolve(packageRoot, 'dist/revision2-code/standalone');
+ expect(builder.codeRebuildDirectory('/sealed/input')).toBe(resolve(packageRoot, 'dist/revision2-code'));
+ expect(builder.codeRebuildDirectory(input, 'packages/foundry-floor/dist/alignment-ui2')).toBe(resolve(packageRoot, 'dist/alignment-ui2'));
+ for (const output of [packageRoot, resolve(packageRoot, 'dist'), resolve(packageRoot, '../farm/dist/new'), resolve(packageRoot, 'src')]) {
+ expect(() => builder.codeRebuildDirectory(input, output)).toThrow(/owned output/);
+ }
+});
+
+test('Foundry refuses overlapping input and output before reading or replacing the sealed input', async () => {
+ const root = mkdtempSync(resolve(packageRoot, 'dist/builder-output-test-'));
+ const output = resolve(root, 'candidate'), input = resolve(output, 'standalone');
+ mkdirSync(input, { recursive: true });
+ const sentinel = resolve(input, 'retained.txt'); writeFileSync(sentinel, 'sealed input');
+ try {
+ await expect(builder.rebuildCode(input, { outputDir: output })).rejects.toThrow(/overlap/);
+ expect(readFileSync(sentinel, 'utf8')).toBe('sealed input');
+ expect(() => builder.codeRebuildDirectory(root, output)).toThrow(/overlap/);
+ const alias = resolve(root, 'input-alias'); symlinkSync(input, alias, 'junction');
+ expect(() => builder.codeRebuildDirectory(alias, output)).toThrow(/overlap/);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+});
+
+test('Foundry rejects a symlinked output that escapes its package dist directory', () => {
+ const root = mkdtempSync(resolve(packageRoot, 'dist/builder-output-test-'));
+ const alias = resolve(root, 'source-alias'); symlinkSync(resolve(packageRoot, 'src'), alias, 'junction');
+ try { expect(() => builder.codeRebuildDirectory('/sealed/input', resolve(alias, 'candidate'))).toThrow(/owned output/); }
+ finally { rmSync(root, { recursive: true, force: true }); }
+});
+
+test('Foundry output preparation preserves a separately built test sibling and the original public input', async () => {
+ const root = mkdtempSync(resolve(packageRoot, 'dist/builder-output-test-'));
+ const original = resolve(root, 'original'), output = resolve(root, 'new');
+ for (const dir of [original, resolve(output, 'standalone'), resolve(output, 'receipt'), resolve(output, 'test')]) mkdirSync(dir, { recursive: true });
+ writeFileSync(resolve(original, 'retained.txt'), 'original public');
+ writeFileSync(resolve(output, 'test/retained.txt'), 'qualified test');
+ writeFileSync(resolve(output, 'standalone/stale.txt'), 'old public');
+ writeFileSync(resolve(output, 'receipt/bundle-public.json'), 'old receipt');
+ try {
+ expect(await builder.prepareCodeRebuildDirectory(original, output)).toBe(output);
+ expect(readFileSync(resolve(original, 'retained.txt'), 'utf8')).toBe('original public');
+ expect(readFileSync(resolve(output, 'test/retained.txt'), 'utf8')).toBe('qualified test');
+ expect(() => readFileSync(resolve(output, 'standalone/stale.txt'))).toThrow();
+ expect(() => readFileSync(resolve(output, 'receipt/bundle-public.json'))).toThrow();
+ } finally { rmSync(root, { recursive: true, force: true }); }
+});
+
+test('Foundry CLI accepts only an explicit optional output directory and one sealed input', () => {
+ expect(builder.codeRebuildArguments(['original', '--out-dir', 'packages/foundry-floor/dist/alignment-ui2'])).toEqual({ sealed: 'original', outputDir: 'packages/foundry-floor/dist/alignment-ui2' });
+ expect(builder.codeRebuildArguments([])).toEqual({});
+ for (const args of [['--out-dir'], ['--out-dir', '--quiet'], ['one', 'two'], ['--unknown'], ['--out-dir', 'one', '--out-dir', 'two']]) {
+ expect(() => builder.codeRebuildArguments(args)).toThrow(/Usage/);
+ }
+});
+
+// A release build runs outside the unit suite's browser/runtime aliases. Importing
+// its receipt helpers must not load React Three Fiber's CommonJS renderer.
+test('Foundry code-only release builder imports in an ordinary Bun process', () => {
+ const result = spawnSync(process.execPath, ['-e', "await import('./packages/foundry-floor/tests/tools/rebuild-code.ts')"], {
+ cwd: resolve(import.meta.dir, '../..'), encoding: 'utf8', timeout: 15_000,
+ });
+ expect(result.error).toBeUndefined();
+ expect({ status: result.status, stderr: result.stderr }).toEqual({ status: 0, stderr: '' });
+});
diff --git a/scenes/scripts/tests/gpu-work.test.ts b/scenes/scripts/tests/gpu-work.test.ts
new file mode 100644
index 00000000..f3cd780a
--- /dev/null
+++ b/scenes/scripts/tests/gpu-work.test.ts
@@ -0,0 +1,53 @@
+import { expect, test } from 'bun:test';
+import { gpuWorkSummary, tabletPairVerdict } from '../gpu-work';
+
+test('GPU work averages paired busy/clock samples, with explicit MHz conversion and sources', () => {
+ const mali = gpuWorkSummary([{ gpuBusyPercent: 20, gpuClockKHz: 1_000_000 }, { gpuBusyPercent: 80, gpuClockKHz: 500_000 }]);
+ expect(mali).toMatchObject({ samples: 2, clockMHzMean: 750, busyClockMHzMean: 300, sources: ['mali-sysfs-kHz'] });
+ // Multiplying the means would incorrectly yield 375.
+ expect(gpuWorkSummary([{ gpu: { 'utilization.gpu': 50, 'clocks.gr': 1700 } }])).toMatchObject({ samples: 1, clockMHzMean: 1700, busyClockMHzMean: 850, sources: ['nvidia-smi-MHz'] });
+});
+
+test('missing, zero-clock and invalid samples never become zero GPU work or get cross-paired', () => {
+ expect(gpuWorkSummary([{ gpuBusyPercent: 20 }, { gpuClockKHz: 1000000 }, { gpuBusyPercent: 0, gpuClockKHz: 0 }, { gpuBusyPercent: 101, gpuClockKHz: 1000000 }, null])).toMatchObject({ samples: 0, omitted: 5, clockMHzMean: null, busyClockMHzMean: null });
+ expect(gpuWorkSummary([{ gpuBusyPercent: 0, gpuClockKHz: 500000 }]).busyClockMHzMean).toBe(0);
+});
+
+const pairs = () => [1, 2, 3].flatMap(pair => (['A', 'B'] as const).map(side => ({ pair, side, valid: true, seconds: 60,
+ gpuWork: gpuWorkSummary(Array.from({ length: 30 }, () => ({ gpuBusyPercent: side === 'A' ? 20 : 20.6, gpuClockKHz: 500000 }))),
+ metrics: { p95: 20, withinOne: side === 'A' ? .95 : .94, over50: 0, over100: 0, gpuBusyClockMHz: side === 'A' ? 100 : 103 } })));
+test('D16 retains exact margins, requires all three pairs to meet both margins, and keeps the p95 and hitch gates', () => {
+ expect(tabletPairVerdict(pairs()).pass).toBe(true);
+ const worse = pairs(); for (const r of worse.filter(r => r.side === 'B')) { r.metrics.withinOne = .939; r.metrics.gpuBusyClockMHz = 103.1; r.gpuWork.busyClockMHzMean = 103.1; }
+ expect(tabletPairVerdict(worse)).toMatchObject({ pass: false, refreshRegressions: 3, gpuWorkRegressions: 3 });
+ worse[1]!.metrics.withinOne = .95; worse[1]!.metrics.gpuBusyClockMHz = 100; worse[1]!.gpuWork.busyClockMHzMean = 100;
+ expect(tabletPairVerdict(worse).pass).toBe(false);
+ for (const r of worse.filter(r => r.side === 'B')) { r.metrics.withinOne = .95; r.metrics.gpuBusyClockMHz = 100; r.gpuWork.busyClockMHzMean = 100; }
+ expect(tabletPairVerdict(worse).pass).toBe(true);
+ worse[1]!.metrics.p95 = 33.4;
+ expect(tabletPairVerdict(worse).pass).toBe(false);
+ worse[1]!.metrics.p95 = 20; worse[1]!.metrics.over50 = 3;
+ expect(tabletPairVerdict(worse).pass).toBe(false);
+});
+test('D16 missing, invalid, short or duplicate evidence stays unqualified', () => {
+ expect(tabletPairVerdict(pairs().slice(0, 4)).pass).toBeNull();
+ const short = pairs(); short[1]!.seconds = 10;
+ expect(tabletPairVerdict(short).pass).toBeNull();
+ const invalid = pairs(); invalid[1]!.valid = false;
+ expect(tabletPairVerdict(invalid).pass).toBeNull();
+ expect(tabletPairVerdict([...pairs(), pairs()[0]!]).pass).toBeNull();
+ const missing = pairs(); missing[1]!.gpuWork.busyClockMHzMean = NaN;
+ expect(tabletPairVerdict(missing).pass).toBeNull();
+});
+
+test('D16 requires actual Mali sample provenance and at least 90 percent of the 2-second sampling window', () => {
+ const sparse = pairs();
+ sparse[1]!.gpuWork = gpuWorkSummary([{ gpuBusyPercent: 20, gpuClockKHz: 500000 }, ...Array(29).fill(null)]);
+ expect(tabletPairVerdict(sparse).pass).toBeNull();
+ sparse[1]!.gpuWork = gpuWorkSummary(Array(26).fill({ gpuBusyPercent: 20, gpuClockKHz: 500000 }));
+ expect(tabletPairVerdict(sparse).pass).toBeNull();
+ sparse[1]!.gpuWork = gpuWorkSummary(Array(27).fill({ gpuBusyPercent: 20, gpuClockKHz: 500000 }));
+ expect(tabletPairVerdict(sparse).pass).toBe(true);
+ sparse[1]!.gpuWork = gpuWorkSummary(Array(30).fill({ gpu: { 'utilization.gpu': 20, 'clocks.gr': 500 } }));
+ expect(tabletPairVerdict(sparse).pass).toBeNull();
+});
diff --git a/scenes/scripts/tests/parity-images.test.ts b/scenes/scripts/tests/parity-images.test.ts
index 43072bf5..f76c112e 100644
--- a/scenes/scripts/tests/parity-images.test.ts
+++ b/scenes/scripts/tests/parity-images.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from 'bun:test';
-import { compareParityImages } from '../parity-images';
+import { compareLuminanceImages, compareParityImages } from '../parity-images';
function solid(value: number, width = 16, height = 9) {
const data = new Uint8Array(width * height * 4);
@@ -7,27 +7,27 @@ function solid(value: number, width = 16, height = 9) {
return { width, height, data };
}
test('linear luminance metric uses sRGB decoding and exact 16 by 9 tiles', () => {
- const black = solid(0), gray = solid(128), result = compareParityImages(black, black, gray);
+ const black = solid(0), gray = solid(128), result = compareLuminanceImages(black, black, gray);
expect(result.globalMean).toBeCloseTo(((128 / 255 + .055) / 1.055) ** 2.4, 12);
expect(result.tiles).toHaveLength(144); expect(result.tiles.every(tile => tile.noise === 0 && tile.threshold === .02)).toBe(true);
expect(result.passingTiles).toBe(0); expect(result.pass).toBe(false);
- const identical = compareParityImages(gray, gray, gray);
+ const identical = compareLuminanceImages(gray, gray, gray);
expect(identical.globalMean).toBe(0); expect(identical.passingTiles).toBe(144); expect(identical.pass).toBe(true);
});
test('four failing tiles pass the 97 percent rule while five fail, without relaxing the global mean', () => {
const black = solid(0), changed = solid(0);
for (let p = 0; p < 4; p++) for (let channel = 0; channel < 3; channel++) changed.data[p * 4 + channel] = 46;
- const four = compareParityImages(black, black, changed);
+ const four = compareLuminanceImages(black, black, changed);
expect(four.passingTiles).toBe(140); expect(four.globalMean).toBeLessThan(.02); expect(four.pass).toBe(true);
for (let channel = 0; channel < 3; channel++) changed.data[4 * 4 + channel] = 46;
- const five = compareParityImages(black, black, changed);
+ const five = compareLuminanceImages(black, black, changed);
expect(five.passingTiles).toBe(139); expect(five.pass).toBe(false);
- expect(compareParityImages(solid(0), solid(255), solid(46)).pass).toBe(false);
+ expect(compareLuminanceImages(solid(0), solid(255), solid(46)).pass).toBe(false);
});
test('each noise floor is local and the diff image retains absolute luminance differences', () => {
const a = solid(0), b = solid(0), rewrite = solid(0);
for (let c = 0; c < 3; c++) { b.data[c] = 20; rewrite.data[c] = 39; rewrite.data[4 + c] = 39; }
- const result = compareParityImages(a, b, rewrite);
+ const result = compareLuminanceImages(a, b, rewrite);
expect(result.tiles[0]!.threshold).toBeCloseTo(result.tiles[0]!.noise * 3, 12);
expect(result.tiles[0]!.pass).toBe(true); expect(result.tiles[1]!.pass).toBe(false);
expect(result.diff.data[3]).toBe(255); expect(result.diff.data[0]).toBeGreaterThan(0);
@@ -35,7 +35,51 @@ test('each noise floor is local and the diff image retains absolute luminance di
});
test('invalid dimensions and non-opaque inputs fail rather than producing misleading scores', () => {
const opaque = solid(0), transparent = solid(0); transparent.data[3] = 0;
- expect(() => compareParityImages(opaque, solid(0, 32, 9), opaque)).toThrow(/dimensions/);
- expect(() => compareParityImages(opaque, opaque, transparent)).toThrow(/opaque/);
- expect(() => compareParityImages(solid(0, 1, 1), solid(0, 1, 1), solid(0, 1, 1))).toThrow(/16.*9/);
+ expect(() => compareLuminanceImages(opaque, solid(0, 32, 9), opaque)).toThrow(/dimensions/);
+ expect(() => compareLuminanceImages(opaque, opaque, transparent)).toThrow(/opaque/);
+ expect(() => compareLuminanceImages(solid(0, 1, 1), solid(0, 1, 1), solid(0, 1, 1))).toThrow(/16.*9/);
+});
+
+test('D18 catches thin changes hidden by tile means and allows exactly 100 pixels beyond repeat noise', () => {
+ const original = solid(0, 1280, 720), repeat = solid(0, 1280, 720), changed = solid(0, 1280, 720);
+ // Spread changes through one row; their tile means stay well below the luminance limit.
+ for (let p = 0; p < 121; p++) changed.data[p * 4] = 33;
+ for (let p = 0; p < 20; p++) repeat.data[p * 4 + 2] = 33;
+ const over = compareParityImages(original, repeat, changed);
+ expect(over.luminancePass).toBe(true);
+ expect(over.lines).toEqual({ over32: 121, noise: 20, budget: 100, pass: false });
+ expect(over.pass).toBe(false);
+ changed.data[120 * 4] = 32;
+ const boundary = compareParityImages(original, repeat, changed);
+ expect(boundary.lines.over32).toBe(120);
+ expect(boundary.pass).toBe(true);
+});
+
+test('D18 configurable budget is an explicit finite nonnegative integer, and never replaces the luminance gate', () => {
+ const original = solid(0), changed = solid(0);
+ changed.data[0] = 33;
+ expect(compareParityImages(original, original, changed, { over32Budget: 0 }).pass).toBe(false);
+ expect(compareParityImages(original, original, changed, { over32Budget: 1 }).pass).toBe(true);
+ expect(compareParityImages(original, solid(255), solid(46), { over32Budget: 1000 }).pass).toBe(false);
+ for (const over32Budget of [-1, .5, NaN, Infinity]) {
+ expect(() => compareParityImages(original, original, original, { over32Budget })).toThrow(/budget/i);
+ }
+});
+
+test('a crop cannot silently inherit the adopted full-view thin-line budget', () => {
+ const crop = solid(0, 640, 252);
+ expect(() => { compareParityImages(crop, crop, crop); }).toThrow(/explicit.*budget|full.*view/i);
+ expect(compareParityImages(crop, crop, crop, { over32Budget: 5 })).toMatchObject({ scope: 'custom-budget', lines: { budget: 5 }, pass: true });
+ const full = solid(0, 1280, 720);
+ expect(compareParityImages(full, full, full)).toMatchObject({ scope: 'b06-d18', lines: { budget: 100 }, pass: true });
+});
+
+test('luminance-only crop diagnostics retain their historical tile gate without claiming D18', async () => {
+ const { compareLuminanceImages } = await import('../parity-images');
+ const crop = solid(0, 640, 252), changed = solid(0, 640, 252);
+ for (let p = 0; p < 101; p++) changed.data[p * 4] = 33;
+ const result = compareLuminanceImages(crop, crop, changed);
+ expect(result).toMatchObject({ scope: 'luminance-only', pass: true, luminancePass: true });
+ expect('lines' in result).toBe(false);
+ expect(compareParityImages(crop, crop, changed, { over32Budget: 100 }).pass).toBe(false);
});
diff --git a/scenes/scripts/tests/portable-runner.test.ts b/scenes/scripts/tests/portable-runner.test.ts
new file mode 100644
index 00000000..dd63049d
--- /dev/null
+++ b/scenes/scripts/tests/portable-runner.test.ts
@@ -0,0 +1,18 @@
+import { expect, spyOn, test } from 'bun:test';
+
+test('the portable gate selects script contracts without selecting historical author-input suites', async () => {
+ const previousExitCode = process.exitCode;
+ const spawn = spyOn(Bun, 'spawnSync').mockReturnValue({ exitCode: 0 } as ReturnType<typeof Bun.spawnSync>);
+ try {
+ await import('../test-portable');
+ expect(spawn).toHaveBeenCalledTimes(1);
+ const [command] = spawn.mock.calls[0]!;
+ expect(command).toContain('./scripts/tests/static-server.test.ts');
+ expect(command).toContain('./scripts/tests/checks.test.ts');
+ expect(command).toContain('./packages/scene-kit/tests/ui/browser-launch.test.ts');
+ expect(command).not.toContain('./packages/foundry-floor/tests/unit/ff3-pack.test.ts');
+ expect(command).not.toContain('./packages/farm/tests/unit/hand-clearance.test.ts');
+ expect(command).not.toContain('./packages/foundry-floor/tests/unit/glb-world.test.ts');
+ expect(command).not.toContain('./packages/golden-gate/tests/unit/vehicle-models.test.ts');
+ } finally { spawn.mockRestore(); process.exitCode = previousExitCode; }
+});
diff --git a/scenes/scripts/tests/qualify-farm-static.test.ts b/scenes/scripts/tests/qualify-farm-static.test.ts
index e56c9c61..0111c5ce 100644
--- a/scenes/scripts/tests/qualify-farm-static.test.ts
+++ b/scenes/scripts/tests/qualify-farm-static.test.ts
@@ -14,6 +14,18 @@ test('qualification recomputes fixed thresholds and does not trust a pass label'
const failed = metric(); failed.globalMean = .03;
expect(() => validateMetric(failed)).toThrow();
});
+test('historical r33 qualification refuses a receipt using the newer D18 scope', () => {
+ expect(() => validateMetric({ ...metric(), scope: 'b06-d18', luminancePass: true, lines: { over32: 0, noise: 0, budget: 100, pass: true } })).toThrow(/historical|D18/);
+});
+test('historical PNG replay preserves only the original luminance fields', async () => {
+ const { compareHistoricalStaticImages } = await import('../qualify-farm-static');
+ const data = new Uint8Array(1280 * 720 * 4); for (let i = 3; i < data.length; i += 4) data[i] = 255;
+ const original = { width: 1280, height: 720, data }, changed = { ...original, data: data.slice() };
+ for (let i = 0; i < 101; i++) changed.data[i * 4] = 33;
+ const measured = compareHistoricalStaticImages(original, original, changed);
+ expect(measured.pass).toBe(true); expect('scope' in measured).toBe(false); expect('lines' in measured).toBe(false); expect('luminancePass' in measured).toBe(false);
+ expect(() => validateMetric(measured)).not.toThrow();
+});
test('qualification replaces only window cases and selects the latest attempt even if it failed', () => {
const views = ['hero', 'house-window-out'];
const base = views.flatMap(view => ['webgpu', 'webgl2'].map(backend => ({ view, backend, attempt: 1, status: view === 'hero' ? 'pass' : 'fail' })));
diff --git a/scenes/scripts/tests/release-inputs.test.ts b/scenes/scripts/tests/release-inputs.test.ts
new file mode 100644
index 00000000..d490643e
--- /dev/null
+++ b/scenes/scripts/tests/release-inputs.test.ts
@@ -0,0 +1,82 @@
+import { afterEach, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
+import { stageFiles } from '../../packages/scene-kit/src/staging';
+import { findSceneFixture, RELEASE_SCENES, releasedAssetRoot, verifyReleasedSceneInputs, type ReleasePins } from '../release-inputs';
+import { runReleaseInputGate } from '../test-release-inputs';
+
+const roots: string[] = [], sha = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex');
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
+function fixture() {
+ const root = mkdtempSync(resolve(tmpdir(), 'kiln release inputs ')); roots.push(root);
+ const source = resolve(root, 'source.glb'); writeFileSync(source, 'synthetic asset bytes');
+ const pins = {} as ReleasePins;
+ for (const scene of RELEASE_SCENES) {
+ const out = releasedAssetRoot(root, scene);
+ stageFiles({ id: scene, release: 'test-release', three: '0.186.1', out,
+ models: [{ id: 'example', to: 'models/example.glb' }], data: {}, files: [{ from: source, to: 'models/example.glb' }] });
+ pins[scene] = { id: scene, release: 'test-release', three: '0.186.1',
+ packJsonSha256: sha(readFileSync(resolve(out, 'pack.json'))), sha256sumsSha256: sha(readFileSync(resolve(out, 'SHA256SUMS'))) };
+ }
+ return { root, pins, source };
+}
+
+test('released inputs require every scene and the exact externally pinned pack, sums and members', () => {
+ const { root, pins } = fixture();
+ expect(verifyReleasedSceneInputs({ root, pins }).map(r => [r.scene, r.release, r.models, r.files])).toEqual(RELEASE_SCENES.map(s => [s, 'test-release', 1, 1]));
+ const assets = releasedAssetRoot(root, 'foundry-floor'), model = resolve(assets, 'models/example.glb');
+ const original = readFileSync(model); writeFileSync(model, 'changed');
+ expect(() => verifyReleasedSceneInputs({ root, pins })).toThrow('models/example.glb');
+ writeFileSync(model, original); rmSync(model);
+ expect(() => verifyReleasedSceneInputs({ root, pins })).toThrow('models/example.glb');
+ writeFileSync(model, original);
+ const pack = resolve(assets, 'pack.json'), saved = readFileSync(pack);
+ writeFileSync(pack, Buffer.concat([saved, Buffer.from('\n')]));
+ expect(() => verifyReleasedSceneInputs({ root, pins })).toThrow('pack.json pin');
+ writeFileSync(pack, saved); writeFileSync(resolve(assets, 'SHA256SUMS'), 'changed');
+ expect(() => verifyReleasedSceneInputs({ root, pins })).toThrow('SHA256SUMS pin');
+ rmSync(releasedAssetRoot(root, 'farm'), { recursive: true });
+ expect(() => verifyReleasedSceneInputs({ root, pins })).toThrow('Restore');
+});
+
+test('a manifest and member edited together cannot replace the pinned release, and unexpected asset files fail', () => {
+ const { root, pins } = fixture(), assets = releasedAssetRoot(root, 'golden-gate');
+ writeFileSync(resolve(assets, 'extra.glb'), 'unlisted');
+ expect(() => verifyReleasedSceneInputs({ root, pins })).toThrow('extra.glb');
+ rmSync(resolve(assets, 'extra.glb'));
+ const pack = JSON.parse(readFileSync(resolve(assets, 'pack.json'), 'utf8'));
+ writeFileSync(resolve(assets, 'models/example.glb'), 'replacement');
+ pack.files[0].bytes = 11; pack.files[0].sha256 = sha(Buffer.from('replacement'));
+ writeFileSync(resolve(assets, 'pack.json'), JSON.stringify(pack));
+ expect(() => verifyReleasedSceneInputs({ root, pins })).toThrow('pack.json pin');
+});
+
+test('Foundry fixtures prefer restored release bytes; required mode never falls back to staged or author inputs', () => {
+ const { root, source } = fixture(), path = 'models/example.glb', bytes = readFileSync(source);
+ const staged = resolve(root, 'packages/foundry-floor/staged/revision2', path);
+ mkdirSync(resolve(staged, '..'), { recursive: true }); writeFileSync(staged, bytes);
+ const input = { scene: 'foundry-floor' as const, path, sha256: sha(bytes), bytes: bytes.length };
+ const options = { root, fallback: [staged], required: true };
+ expect(findSceneFixture(input, options)).toBe(resolve(releasedAssetRoot(root, 'foundry-floor'), path));
+ rmSync(releasedAssetRoot(root, 'foundry-floor'), { recursive: true });
+ expect(() => findSceneFixture(input, options)).toThrow('Required released fixture');
+ expect(findSceneFixture(input, { ...options, required: false })).toBe(staged);
+ writeFileSync(staged, 'other revision');
+ expect(findSceneFixture(input, { ...options, required: false })).toBeUndefined();
+ expect(() => findSceneFixture({ ...input, path: '../escape.glb' }, options)).toThrow();
+});
+
+test('the release gate refuses absent inputs before tests and runs its selected suites in required-input mode', () => {
+ const { root, pins } = fixture(); let runs = 0;
+ const run: Parameters<typeof runReleaseInputGate>[0]['run'] = (command, options) => {
+ runs++; expect(command).toContain('./packages/foundry-floor/tests/unit/glb-world.test.ts');
+ expect(command).toContain('./packages/golden-gate/tests/unit/vehicle-models.test.ts');
+ expect(options.env.KILN_SCENE_RELEASE_INPUTS).toBe('1'); expect(options.cwd).toBe(root);
+ return 7;
+ };
+ expect(runReleaseInputGate({ root, pins, run })).toBe(7); expect(runs).toBe(1);
+ rmSync(releasedAssetRoot(root, 'farm'), { recursive: true });
+ expect(() => runReleaseInputGate({ root, pins, run })).toThrow('Restore'); expect(runs).toBe(1);
+});
diff --git a/scenes/scripts/tests/static-server.test.ts b/scenes/scripts/tests/static-server.test.ts
index ac1f80bc..df4ee820 100644
--- a/scenes/scripts/tests/static-server.test.ts
+++ b/scenes/scripts/tests/static-server.test.ts
@@ -3,10 +3,37 @@ import { spawnSync } from 'node:child_process';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { relative, resolve, sep } from 'node:path';
import { pathToFileURL } from 'node:url';
-import { isServerEntry } from '../static-server.mjs';
+import { isServerEntry, startStaticServer } from '../static-server.mjs';
const root = resolve(import.meta.dir, '../..');
+test('WebP GET, HEAD and byte ranges use image/webp with exact bytes and nosniff', async () => {
+ await mkdir(resolve(root, '.tmp'), { recursive: true });
+ const dir = await mkdtemp(resolve(root, '.tmp', 'webp-server-'));
+ const bytes = Buffer.from('RIFF1234WEBPfixture');
+ await writeFile(resolve(dir, 'image.webp'), bytes);
+ let server: Awaited<ReturnType<typeof startStaticServer>> | undefined;
+ try {
+ server = await startStaticServer({ root: dir, port: 0 });
+ for (const method of ['GET', 'HEAD']) {
+ const response = await fetch(`${server.url}/image.webp`, { method });
+ expect(response.status).toBe(200);
+ expect(response.headers.get('content-type')).toBe('image/webp');
+ expect(response.headers.get('content-length')).toBe(String(bytes.length));
+ expect(response.headers.get('x-content-type-options')).toBe('nosniff');
+ expect(Buffer.from(await response.arrayBuffer())).toEqual(method === 'GET' ? bytes : Buffer.alloc(0));
+ }
+ const partial = await fetch(`${server.url}/image.webp`, { headers: { Range: 'bytes=8-11' } });
+ expect(partial.status).toBe(206); expect(partial.headers.get('content-type')).toBe('image/webp');
+ expect(partial.headers.get('content-range')).toBe(`bytes 8-11/${bytes.length}`);
+ expect(await partial.text()).toBe('WEBP');
+ const invalid = await fetch(`${server.url}/image.webp`, { headers: { Range: 'bytes=999-' } });
+ expect(invalid.status).toBe(416); await invalid.arrayBuffer();
+ const forbidden = await fetch(`${server.url}/%5coutside.webp`);
+ expect(forbidden.status).toBe(403); await forbidden.arrayBuffer();
+ } finally { try { await server?.close(); } finally { await rm(dir, { recursive: true, force: true }); } }
+});
+
// FARM-005: the hub kit bundles scripts/static-server.mjs into runner/look-farm.mjs (through scene-kit's serveOwned). Inside a
// bundle the module's import.meta.url is the bundle's own, so the file's CLI guard must not start a server there.
describe('static server CLI guard (FARM-005)', () => {
diff --git a/scenes/scripts/tests/timing-ab.test.ts b/scenes/scripts/tests/timing-ab.test.ts
index 832a7ac2..d8ee98d1 100644
--- a/scenes/scripts/tests/timing-ab.test.ts
+++ b/scenes/scripts/tests/timing-ab.test.ts
@@ -1,6 +1,9 @@
import { expect, test } from 'bun:test';
+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { cellKind, cellUrl, cpuPercent, d41Verdict, displayRate, frameStats, gpuBusyMedian, hitchCounts, HUB_RULE, interleaveOrder, parseBattery, parseCell, parseLoadavg, parseNvidiaSmi, parseProcStat,
- parseThermalStatus, parseTop, parseWho, PC_RULE, percentile, planRuns, quietVerdict, refreshShare, summarizeCell, tabletCool, type RunMetrics } from '../timing-ab';
+ parseThermalStatus, parseTop, parseWho, PC_RULE, TABLET_RULE, percentile, planRuns, quietVerdict, refreshShare, summarizeBlock, summarizeCell, tabletCool, type RunMetrics } from '../timing-ab';
test('percentile uses the pilot rule (ceil(n q)-th smallest) and frame stats keep count, fps and sampled time', () => {
const values = [10, 1, 9, 2, 8, 3, 7, 4, 6, 5];
@@ -90,15 +93,34 @@ Tasks: 300 total, 1 running, 299 sleeping, 0 stopped, 0 zombie
});
test('quiet verdicts: the hub pilot rule and this PC rule', () => {
- const calm = { cpu: [1, 1.5, .8, 2, 1, 1, 1, 1], gpu: [0, 0, 1, 0, 0, 0, 0, 0] };
+ const calm = { cpu: [1, 1.5, .8, 2, 1, 1, 1, 1], gpu: [0, 0, 1, 0, 0, 0, 0, 0], screenLocked: false };
expect(quietVerdict(calm, HUB_RULE).quiet).toBe(true);
expect(quietVerdict({ ...calm, gpu: [0, 0, 4, 0, 0, 0, 0, 0] }, HUB_RULE).reasons).toEqual(['GPU max 4 % > 3 %']);
expect(quietVerdict({ ...calm, cpu: [1, 1, 1, 13, 1, 1, 1, 1] }, HUB_RULE).reasons[0]).toMatch(/CPU max 13/);
expect(quietVerdict({ ...calm, screenLocked: true }, HUB_RULE).quiet).toBe(false);
- expect(quietVerdict({ cpu: [1, 1], gpu: [] }, HUB_RULE).reasons).toEqual(['2 of 8 CPU samples']);
- const busyPc = { cpu: [35, 40, 38, 36, 37, 39, 41, 36], gpu: [22, 25, 24, 23, 22, 21, 20, 25] };
+ expect(quietVerdict({ cpu: [1, 1], gpu: [], screenLocked: false }, HUB_RULE).reasons).toEqual(['2 of 8 CPU samples', '0 of 8 readable GPU samples in [0, 100]']);
+ const busyPc = { cpu: [35, 40, 38, 36, 37, 39, 41, 36], gpu: [22, 25, 24, 23, 22, 21, 20, 25], screenLocked: false };
expect(quietVerdict(busyPc, PC_RULE).reasons).toEqual(['CPU mean 37.75 % >= 20 %', 'GPU max 25 % > 9.999 %']);
- expect(quietVerdict({ cpu: [10, 12, 15, 11, 9, 14, 13, 12], gpu: [5, 5, 5, 5, 5, 5, 5, 9] }, PC_RULE).quiet).toBe(true);
+ expect(quietVerdict({ cpu: [10, 12, 15, 11, 9, 14, 13, 12], gpu: [5, 5, 5, 5, 5, 5, 5, 9], screenLocked: false }, PC_RULE).quiet).toBe(true);
+});
+
+test('a quiet proof requires a complete readable bounded GPU window on every host policy', () => {
+ for (const rule of [HUB_RULE, PC_RULE, TABLET_RULE]) {
+ const cpu = Array(rule.samples).fill(1), calm = Array(rule.samples).fill(0);
+ for (const bad of [null, NaN, Infinity, -1, 101]) {
+ const gpu = [...calm]; gpu[3] = bad;
+ const result = quietVerdict({ cpu, gpu, screenLocked: false }, rule);
+ expect(result.quiet).toBe(false);
+ expect(result.reasons.some(reason => reason.includes('GPU samples'))).toBe(true);
+ // Extra valid samples must not conceal a bad reading in the observed window.
+ expect(quietVerdict({ cpu, gpu: [...gpu, 0], screenLocked: false }, rule).quiet).toBe(false);
+ }
+ expect(quietVerdict({ cpu, gpu: calm.slice(1), screenLocked: false }, rule).quiet).toBe(false);
+ expect(quietVerdict({ cpu, gpu: Array(rule.samples).fill(null), screenLocked: false }, rule)).toMatchObject({ quiet: false, gpuMax: null });
+ expect(quietVerdict({ cpu, gpu: calm, screenLocked: false }, rule).quiet).toBe(true);
+ expect(quietVerdict({ cpu, gpu: [...calm.slice(1), rule.gpuMaxAtMost], screenLocked: false }, rule).quiet).toBe(true);
+ expect(quietVerdict({ cpu, gpu: [...calm.slice(1), rule.gpuMaxAtMost + .01], screenLocked: false }, rule).quiet).toBe(false);
+ }
});
test('tablet readings and the cool rule (thermal none or light, battery at most 35 C)', () => {
@@ -142,3 +164,24 @@ test('GPU busy during a run is the median of nvidia-smi or Mali gpu_busy samples
expect(gpuBusyMedian([{ gpuBusyPercent: 31 }, { batteryC: 25, gpuBusyPercent: 29 }, { gpuBusyPercent: null }])).toBe(29);
expect(gpuBusyMedian([])).toBeNull();
});
+
+test('persisted timing summary derives GPU units and tablet acceptance from raw samples, not cached scalar claims', async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'kiln-timing-summary-'));
+ try {
+ await mkdir(join(directory, 'runs'));
+ await writeFile(join(directory, 'block.json'), JSON.stringify({ device: 'tablet', block: 'fixture' }));
+ const record = (pair: number, side: 'A' | 'B') => ({ pair, side, valid: true, seconds: 60,
+ cell: { scene: 'farm', tier: 'minimal', name: 'hero', kind: 'view' },
+ metrics: { p50: 16, p95: 17, withinOne: .99, withinTwo: 1, over50: 0, over100: 0, gpuClockMHz: 999, gpuBusyClockMHz: 999 },
+ loadDuring: Array.from({ length: 30 }, () => ({ gpuBusyPercent: 20, gpuClockKHz: 500000 })) });
+ for (const pair of [1, 2, 3]) for (const side of ['A', 'B'] as const) await writeFile(join(directory, 'runs', `${pair}-${side}.json`), JSON.stringify(record(pair, side)));
+ const qualified = await summarizeBlock(directory), cell = qualified.cells[0]!;
+ expect(cell.A.gpuClockMHz?.median).toBe(500);
+ expect(cell.B.gpuBusyClockMHz?.median).toBe(100);
+ expect(cell.tabletAdoption?.pass).toBe(true);
+ expect(await readFile(join(directory, 'summary.md'), 'utf8')).toContain('Busy × MHz');
+ const missing = record(1, 'B'); missing.loadDuring = [];
+ await writeFile(join(directory, 'runs', '1-B.json'), JSON.stringify(missing));
+ expect((await summarizeBlock(directory)).cells[0]!.tabletAdoption?.pass).toBeNull();
+ } finally { await rm(directory, { recursive: true, force: true }); }
+});
diff --git a/scenes/scripts/tests/timing-evidence.test.ts b/scenes/scripts/tests/timing-evidence.test.ts
new file mode 100644
index 00000000..c1ba2e1c
--- /dev/null
+++ b/scenes/scripts/tests/timing-evidence.test.ts
@@ -0,0 +1,189 @@
+import { expect, test } from 'bun:test';
+import { acquireTimingResources, cleanupTimingResources, installTimingEvidence, sampleWithLoad, timingCollectionVerdict } from '../timing-evidence';
+import { HUB_RULE, measureTimingRun, parseScreenLocker, PC_RULE, quietVerdict, TABLET_RULE } from '../timing-ab';
+
+test('sampling failure still stops the load poller, and simultaneous cleanup failure is preserved', async () => {
+ let stops = 0;
+ const failed = new Error('page evaluation failed');
+ await expect(sampleWithLoad(async () => { throw failed; }, async () => { stops++; return []; })).rejects.toBe(failed);
+ expect(stops).toBe(1);
+ try {
+ await sampleWithLoad(async () => { throw failed; }, async () => { throw new Error('poller stop failed'); });
+ throw new Error('Expected both failures');
+ } catch (error) {
+ expect(error).toBeInstanceOf(AggregateError);
+ expect((error as AggregateError).errors.map(e => e.message)).toEqual(['page evaluation failed', 'poller stop failed']);
+ }
+ expect(await sampleWithLoad(async () => 42, async () => ['sample'])).toEqual({ end: 42, loadDuring: ['sample'] });
+});
+
+test('the measurement keeps its original failure when its owned page also fails to close', async () => {
+ let evaluations = 0;
+ const page = { on() {}, async bringToFront() {}, async setViewport() {}, async evaluateOnNewDocument() {}, async goto() {}, async waitForFunction() {},
+ async evaluate() { return evaluations++ === 0 ? [8.3, 8.3] : { error: 'scene start failed' }; }, async close() { throw new Error('page close failed'); } };
+ const cleanup: Awaited<ReturnType<typeof cleanupTimingResources>> = [];
+ try {
+ await measureTimingRun({ newPage: async () => page } as any, { side: 'A', base: 'http://127.0.0.1:4400' } as any,
+ { scene: 'farm', tier: 'high', name: 'hero' }, { device: 'local', seconds: 60, warmupMs: 0, width: 1920, height: 1080, backend: 'webgpu', extra: {}, adb: null, loadEveryMs: 5000, browserPid: null, cleanup });
+ throw new Error('Expected both failures');
+ } catch (error) {
+ expect(error).toBeInstanceOf(AggregateError);
+ expect((error as AggregateError).errors.map(e => e.message)).toEqual(['Scene failed: "scene start failed"', 'STOP: Measurement page cleanup failed: page close failed']);
+ }
+ expect(cleanup).toEqual([{ name: 'measurement-page', ok: false, error: 'page close failed' }]);
+});
+
+test('cleanup records failures while continuing to release other owned resources', async () => {
+ const order: string[] = [];
+ const result = await cleanupTimingResources([
+ { name: 'browser', async close() { order.push('browser'); throw new Error('browser close failed'); } },
+ { name: 'profile', async close() { order.push('profile'); } },
+ { name: 'server', async close() { order.push('server'); throw new Error('server close failed'); } },
+ ]);
+ expect(order).toEqual(['browser', 'profile', 'server']);
+ expect(result).toEqual([{ name: 'browser', ok: false, error: 'browser close failed' }, { name: 'profile', ok: true }, { name: 'server', ok: false, error: 'server close failed' }]);
+});
+
+test('partial startup owns and cleans the first server when the second startup fails', async () => {
+ const owned: { name: string; close(): Promise<void> }[] = [];
+ let closed = false;
+ try {
+ await expect(acquireTimingResources(owned, [async () => ({ name: 'A', async close() { closed = true; } }),
+ async () => { throw new Error('B cannot listen'); }])).rejects.toThrow('B cannot listen');
+ } finally { await cleanupTimingResources(owned); }
+ expect(closed).toBe(true);
+});
+
+test('a server cleanup timeout is a failure, not a successful close', async () => {
+ const resource = { name: 'server', timeoutMs: 1, close: () => new Promise<void>(() => {}) };
+ const closing = cleanupTimingResources([resource]);
+ const outcome = await Promise.race([closing, new Promise(resolve => setTimeout(() => resolve('test watchdog'), 30))]);
+ expect(outcome).toEqual([{ name: 'server', ok: false, error: 'Cleanup timed out after 1 ms' }]);
+});
+
+test('unrecognized locker output remains unknown', () => {
+ expect(parseScreenLocker('(true,)\n')).toBe(true);
+ expect(parseScreenLocker('(false,)\n')).toBe(false);
+ for (const value of [null, '', 'permission denied', '(not-a-boolean,)']) expect(parseScreenLocker(value)).toBeNull();
+});
+
+function pageFixture() {
+ const handlers = new Map<string, (() => void)[]>();
+ let at = 0, focused = true;
+ const canvas = { width: 1920, height: 1080 };
+ class Context {
+ canvas = canvas;
+ configured: unknown;
+ configure(descriptor: { device: unknown }) { this.configured = descriptor.device; }
+ }
+ const nativeCalls: any[] = [];
+ const gpu = {
+ async requestAdapter(options?: { powerPreference?: string }) {
+ nativeCalls.push({ operation: 'adapter', receiver: this, options });
+ const info = { vendor: options?.powerPreference === 'high-performance' ? 'nvidia' : 'other', architecture: 'fixture', device: '', description: '' };
+ return { info, async requestDevice(descriptor?: unknown) {
+ nativeCalls.push({ operation: 'device', receiver: this, descriptor });
+ return { adapterInfo: info };
+ } };
+ },
+ };
+ const listen = (name: string, handler: () => void) => handlers.set(name, [...(handlers.get(name) ?? []), handler]);
+ const scope: any = { document: { visibilityState: 'visible', hasFocus: () => focused, addEventListener: listen,
+ querySelectorAll: () => [canvas] }, addEventListener: listen, performance: { now: () => ++at }, navigator: { gpu }, GPUCanvasContext: Context };
+ return { scope, canvas, Context, nativeCalls, event(name: string, value: boolean | string) {
+ if (name === 'visibilitychange') scope.document.visibilityState = value; else focused = value as boolean;
+ for (const handler of handlers.get(name) ?? []) handler();
+ } };
+}
+
+test('hidden and blur intervals invalidate the sample even after visibility and focus return', () => {
+ const page = pageFixture(); installTimingEvidence(page.scope);
+ const evidence = page.scope.__timingEvidence;
+ page.event('visibilitychange', 'hidden'); page.event('blur', false);
+ page.event('visibilitychange', 'visible'); page.event('focus', true);
+ evidence.begin();
+ expect(evidence.finish()).toMatchObject({ visibility: { hidden: false }, focus: { lost: false } });
+ evidence.begin();
+ page.event('visibilitychange', 'hidden'); page.event('blur', false);
+ page.event('visibilitychange', 'visible'); page.event('focus', true);
+ expect(evidence.finish()).toMatchObject({ visibility: { initial: 'visible', final: 'visible', hidden: true }, focus: { initial: true, final: true, lost: true } });
+ expect(evidence.finish().visibility.changes.map((e: any) => e.state)).toEqual(['hidden', 'visible']);
+ expect(evidence.finish().focus.changes.map((e: any) => e.focused)).toEqual([false, true]);
+ evidence.begin();
+ expect(evidence.finish()).toMatchObject({ visibility: { hidden: false }, focus: { lost: false } });
+ page.event('visibilitychange', 'hidden'); page.event('blur', false); evidence.begin();
+ page.event('visibilitychange', 'visible'); page.event('focus', true);
+ expect(evidence.finish()).toMatchObject({ visibility: { initial: 'hidden', hidden: true }, focus: { initial: false, lost: true } });
+});
+
+test('GPU evidence follows the exact scene canvas device, not an unrelated default adapter probe', async () => {
+ const page = pageFixture(); installTimingEvidence(page.scope);
+ const gpu = page.scope.navigator.gpu;
+ const rendererOptions = { powerPreference: 'high-performance', featureLevel: 'compatibility', xrCompatible: false };
+ const rendererAdapter = await gpu.requestAdapter(rendererOptions);
+ const descriptor = { requiredFeatures: ['timestamp-query'], requiredLimits: { maxBindGroups: 4 } };
+ const rendererDevice = await rendererAdapter.requestDevice(descriptor);
+ const context = new page.Context(); context.configure({ device: rendererDevice });
+ const unrelated = await gpu.requestAdapter(); await unrelated.requestDevice();
+ const observed = page.scope.__timingEvidence.gpu();
+ expect(observed).toMatchObject({ status: 'bound', adapter: { vendor: 'nvidia' }, binding: 'scene-canvas.configure' });
+ expect(observed.canvasBindings).toHaveLength(1);
+ const device = observed.deviceRequests.find((d: any) => d.id === observed.canvasBindings[0].deviceId);
+ expect(device.requestAdapterOptions).toEqual(rendererOptions);
+ expect(device.requestDeviceOptions).toEqual(descriptor);
+ expect(page.nativeCalls[0]).toEqual({ operation: 'adapter', receiver: gpu, options: rendererOptions });
+ expect(page.nativeCalls[1]).toEqual({ operation: 'device', receiver: rendererAdapter, descriptor });
+ expect(context.configured).toBe(rendererDevice);
+});
+
+test('a device request without a scene-canvas binding stays unqualified', async () => {
+ const page = pageFixture(); installTimingEvidence(page.scope);
+ await (await page.scope.navigator.gpu.requestAdapter({ powerPreference: 'high-performance' })).requestDevice();
+ expect(page.scope.__timingEvidence.gpu()).toMatchObject({ status: 'unbound', adapter: null });
+ new page.Context().configure({ device: {} });
+ expect(page.scope.__timingEvidence.gpu()).toMatchObject({ status: 'unbound', adapter: null });
+});
+
+test('host quiet cannot certify an unknown screen-lock probe; tablet sampling does not invent a host probe', () => {
+ const calm = { cpu: Array(8).fill(1), gpu: Array(8).fill(0) };
+ for (const rule of [HUB_RULE, PC_RULE]) {
+ expect(quietVerdict({ ...calm, screenLocked: null }, rule).quiet).toBe(false);
+ expect(quietVerdict(calm, rule).quiet).toBe(false);
+ expect(quietVerdict({ ...calm, screenLocked: false }, rule).quiet).toBe(true);
+ }
+ expect(quietVerdict(calm, TABLET_RULE).quiet).toBe(true);
+});
+
+test('collection verdict rejects missing, duplicate, invalid, failed, unprimed or unclean runs', () => {
+ const complete = { expected: ['A', 'B'], runs: [{ label: 'A', valid: true }, { label: 'B', valid: true }], expectedPrimes: 2,
+ primes: [{ ok: true }, { ok: true }], cleanup: [{ ok: true }], stopped: null };
+ expect(timingCollectionVerdict(complete).pass).toBe(true);
+ for (const override of [{ runs: complete.runs.slice(1) }, { runs: [complete.runs[0]!, complete.runs[0]!] },
+ { runs: [...complete.runs, { label: 'C', valid: true }] }, { runs: [complete.runs[0]!, { label: 'B', valid: false }] },
+ { runs: [complete.runs[0]!, { label: 'B', valid: true, error: 'failed to save' }] }, { primes: [{ ok: true }] },
+ { primes: [{ ok: true }, { ok: false }] }, { cleanup: [{ ok: false }] }, { stopped: 'not quiet' }]) {
+ expect(timingCollectionVerdict({ ...complete, ...override }).pass).toBe(false);
+ }
+});
+
+test('serialized installer works without module closures and reports blocked instrumentation without altering native calls', async () => {
+ const page = pageFixture();
+ const native = page.scope.navigator.gpu.requestAdapter;
+ Object.defineProperty(page.scope.navigator.gpu, 'requestAdapter', { value: native, writable: false, configurable: false });
+ new Function('scope', `(${installTimingEvidence.toString()})(scope)`)(page.scope);
+ const adapter = await page.scope.navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
+ expect(adapter.info.vendor).toBe('nvidia');
+ expect(page.nativeCalls).toHaveLength(1);
+ const evidence = page.scope.__timingEvidence.gpu();
+ expect(evidence.status).toBe('unbound');
+ expect(evidence.errors.length).toBeGreaterThan(0);
+});
+
+test('native device rejection is preserved and cannot produce bound hardware evidence', async () => {
+ const page = pageFixture(), failure = new Error('device rejected');
+ page.scope.navigator.gpu.requestAdapter = async () => ({ info: { vendor: 'nvidia' }, requestDevice: async () => { throw failure; } });
+ installTimingEvidence(page.scope);
+ const adapter = await page.scope.navigator.gpu.requestAdapter();
+ await expect(adapter.requestDevice()).rejects.toBe(failure);
+ expect(page.scope.__timingEvidence.gpu()).toMatchObject({ status: 'unbound', adapter: null, deviceRequests: [] });
+});
diff --git a/scenes/scripts/tests/timing-kit.test.ts b/scenes/scripts/tests/timing-kit.test.ts
new file mode 100644
index 00000000..f43b1dd2
--- /dev/null
+++ b/scenes/scripts/tests/timing-kit.test.ts
@@ -0,0 +1,30 @@
+import { expect, test } from 'bun:test';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+
+test('the generated timing kit reads its Node pin from the workspace toolchain', async () => {
+ const workspace = resolve(import.meta.dir, '../..');
+ await mkdir(resolve(workspace, '.tmp'), { recursive: true });
+ // Keep the fixture inside the checkout for the generator's read-only Git provenance.
+ const fixture = await mkdtemp(resolve(workspace, '.tmp/timing-kit-test-'));
+ try {
+ await mkdir(resolve(fixture, 'scripts'), { recursive: true });
+ await writeFile(resolve(fixture, 'scripts/make-timing-kit.ts'), await readFile(resolve(workspace, 'scripts/make-timing-kit.ts')));
+ await writeFile(resolve(fixture, 'scripts/timing-ab.ts'), 'export const fixtureRunner = true;\n');
+ const node = '22.99.7'; // Deliberately different from every checked-in pin.
+ await writeFile(resolve(fixture, 'toolchain.json'), JSON.stringify({ bun: '1.4.2', node, npm: '12.2.0' }));
+ for (const label of ['before', 'after']) {
+ const out = resolve(fixture, 'packages/farm/dist', label, 'test'); await mkdir(out, { recursive: true });
+ await writeFile(resolve(out, 'index.html'), '<!doctype html><title>Fixture</title>');
+ await writeFile(resolve(out, 'build.json'), JSON.stringify({ mode: 'test', scene: 'farm', release: 'fixture', packSha256: 'same-pack', chunks: [], source: 'fixture' }));
+ }
+ const child = Bun.spawn([process.execPath, 'scripts/make-timing-kit.ts', '--a', 'before', '--b', 'after', '--scenes', 'farm', '--out', 'out'], { cwd: fixture, stdout: 'pipe', stderr: 'pipe' });
+ const [code, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]);
+ expect({ code, error: code ? stderr || stdout : '' }).toEqual({ code: 0, error: '' });
+ const manifest = JSON.parse(await readFile(resolve(fixture, 'out/MANIFEST.json'), 'utf8'));
+ const readme = await readFile(resolve(fixture, 'out/README.txt'), 'utf8');
+ expect(manifest.runner.nodePin).toBe(node);
+ expect(readme).toContain(`Node ${node} is the pin`);
+ expect(readme).toContain(`/node-versions/v${node}/installation/node.exe`);
+ } finally { await rm(fixture, { recursive: true, force: true }); }
+});
diff --git a/scenes/scripts/timing-ab.ts b/scenes/scripts/timing-ab.ts
index 2e5ca795..6a364b54 100644
--- a/scenes/scripts/timing-ab.ts
+++ b/scenes/scripts/timing-ab.ts
@@ -15,6 +15,8 @@
// node runner/timing-ab.mjs summary --dir results/<block>
// node runner/timing-ab.mjs transient [--device tablet] WebGPU TRANSIENT_ATTACHMENT support (read-only)
// node runner/timing-ab.mjs verify
+import { gpuWorkSummary, tabletPairVerdict } from './gpu-work';
+import { acquireTimingResources, cleanupTimingResources, installTimingEvidence, sampleWithLoad, timingCollectionVerdict, timingError } from './timing-evidence';
import { execFile } from 'node:child_process';
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
@@ -133,21 +135,25 @@ export function parseTop(text: string, limit = 8) {
.map(f => ({ pid: Number(f[0]), user: f[1]!, cpuPercent: Number(f[cpu]), memPercent: Number(f[mem]), command: f.slice(command).join(' ') })).slice(0, limit);
}
/** The sealed pilot's hub preflight rule (8 samples of 2 s; CPU mean < 5 %, CPU max < 12 %, NVIDIA GPU <= 3 %, no screen locker). */
-export const HUB_RULE = { samples: 8, intervalSeconds: 2, cpuMeanBelow: 5, cpuMaxBelow: 12, gpuMaxAtMost: 3, source: 'sealed pilot ops/run-hub-performance.py preflight (hub-2026-09-30 tools/common.py)' } as const;
-/** This PC (plan default): CPU < 20 % and GPU < 10 %, judged on the same 8 x 2 s window. */
-export const PC_RULE = { samples: 8, intervalSeconds: 2, cpuMeanBelow: 20, cpuMaxBelow: 100, gpuMaxAtMost: 9.999, source: 'plan default for this PC: CPU < 20 %, GPU < 10 %' } as const;
+export const HUB_RULE = { samples: 8, intervalSeconds: 2, cpuMeanBelow: 5, cpuMaxBelow: 12, gpuMaxAtMost: 3, requireUnlocked: true, source: 'sealed pilot ops/run-hub-performance.py preflight (hub-2026-09-30 tools/common.py)' } as const;
+/** This PC (plan default): CPU < 20 % and GPU < 10 %, judged on the same 8 x 2 s window.
+ * An unavailable GPU counter (including a PC without NVIDIA telemetry) is unqualified, never assumed idle. */
+export const PC_RULE = { samples: 8, intervalSeconds: 2, cpuMeanBelow: 20, cpuMaxBelow: 100, gpuMaxAtMost: 9.999, requireUnlocked: true, source: 'plan default for this PC: CPU < 20 %, GPU < 10 %' } as const;
/** The pilot's tablet preflight (farm-pilot ops/tablet-observe.py): CPU mean < 8 %, CPU max < 12 %, Mali GPU busy <= 3 %. */
export const TABLET_RULE = { samples: 8, intervalSeconds: 2, cpuMeanBelow: 8, cpuMaxBelow: 12, gpuMaxAtMost: 3, source: 'farm-pilot ops/tablet-observe.py (golden-gate tests/tools/tablet-check.ts)' } as const;
-export type QuietRule = { samples: number; intervalSeconds: number; cpuMeanBelow: number; cpuMaxBelow: number; gpuMaxAtMost: number; source: string };
+export type QuietRule = { samples: number; intervalSeconds: number; cpuMeanBelow: number; cpuMaxBelow: number; gpuMaxAtMost: number; requireUnlocked?: boolean; source: string };
export function quietVerdict(window: { cpu: readonly number[]; gpu: readonly (number | null)[]; screenLocked?: boolean | null }, rule: QuietRule) {
- const cpu = window.cpu.filter(Number.isFinite), gpu = window.gpu.filter((v): v is number => typeof v === 'number' && Number.isFinite(v));
+ const cpu = window.cpu.filter(Number.isFinite), gpu = window.gpu.filter((v): v is number => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 100);
const cpuMean = cpu.length ? cpu.reduce((s, v) => s + v, 0) / cpu.length : null, cpuMax = cpu.length ? Math.max(...cpu) : null, gpuMax = gpu.length ? Math.max(...gpu) : null;
const reasons: string[] = [];
if (cpu.length < rule.samples) reasons.push(`${cpu.length} of ${rule.samples} CPU samples`);
+ if (gpu.length < rule.samples) reasons.push(`${gpu.length} of ${rule.samples} readable GPU samples in [0, 100]`);
+ if (gpu.length !== window.gpu.length) reasons.push(`${window.gpu.length - gpu.length} GPU samples unavailable or outside [0, 100]`);
if (cpuMean !== null && cpuMean >= rule.cpuMeanBelow) reasons.push(`CPU mean ${cpuMean.toFixed(2)} % >= ${rule.cpuMeanBelow} %`);
if (cpuMax !== null && cpuMax >= rule.cpuMaxBelow) reasons.push(`CPU max ${cpuMax.toFixed(2)} % >= ${rule.cpuMaxBelow} %`);
if (gpuMax !== null && gpuMax > rule.gpuMaxAtMost) reasons.push(`GPU max ${gpuMax} % > ${rule.gpuMaxAtMost} %`);
if (window.screenLocked) reasons.push('screen locker active');
+ else if (rule.requireUnlocked && window.screenLocked !== false) reasons.push('screen locker status unknown');
return { quiet: reasons.length === 0, cpuMean, cpuMax, gpuMax, reasons, rule };
}
// Tablet readings (dumpsys battery and thermalservice; the Mali sysfs nodes used by golden-gate tablet-check.ts).
@@ -174,9 +180,9 @@ export function tabletCool(state: { thermalStatus: number | null; batteryC: numb
export interface RunMetrics { p50: number | null; p95: number | null; p99: number | null; max: number | null; fps: number | null; withinOne: number | null; withinTwo: number | null;
over50: number; over100: number; longestMs: number | null; cpuRenderP50: number | null; cpuRenderP95: number | null; drawsMedian: number | null; trianglesMedian: number | null;
/** Median GPU busy % over the load samples taken during the sample (hub: nvidia-smi utilization.gpu; tablet: Mali gpu_busy). At a locked refresh it shows a cost difference the frame interval cannot. */
- gpuBusy?: number | null }
+ gpuBusy?: number | null; gpuClockMHz?: number | null; gpuBusyClockMHz?: number | null }
export interface RunSummaryInput { side: Side; pair: number; valid: boolean; metrics: RunMetrics }
-const METRIC_KEYS = ['p50', 'p95', 'p99', 'max', 'fps', 'withinOne', 'withinTwo', 'over50', 'over100', 'longestMs', 'cpuRenderP50', 'cpuRenderP95', 'drawsMedian', 'trianglesMedian', 'gpuBusy'] as const;
+const METRIC_KEYS = ['p50', 'p95', 'p99', 'max', 'fps', 'withinOne', 'withinTwo', 'over50', 'over100', 'longestMs', 'cpuRenderP50', 'cpuRenderP95', 'drawsMedian', 'trianglesMedian', 'gpuBusy', 'gpuClockMHz', 'gpuBusyClockMHz'] as const;
/** GPU busy % from load samples taken during a run: nvidia-smi rows (hub, this PC) or Mali gpu_busy readings (tablet). */
export function gpuBusyMedian(samples: readonly unknown[]): number | null {
const values = samples.map(s => { const x = s as { gpu?: Record<string, unknown> | null; gpuBusyPercent?: number | null }; return x.gpu ? x.gpu['utilization.gpu'] : x.gpuBusyPercent; })
@@ -207,7 +213,7 @@ export function summarizeCell(runs: readonly RunSummaryInput[]) {
return [k, values.length ? { medianDelta: median(values), bLower: values.filter(v => v < 0).length, bHigher: values.filter(v => v > 0).length, equal: values.filter(v => v === 0).length } : null];
}));
const ratio = (k: typeof METRIC_KEYS[number]) => { const ra = a[k]?.median, rb = b[k]?.median; return typeof ra === 'number' && typeof rb === 'number' && ra !== 0 ? rb / ra : null; };
- return { A: a, B: b, pairs: paired.length, paired, deltas, ratios: { p50: ratio('p50'), p95: ratio('p95'), cpuRenderP50: ratio('cpuRenderP50'), gpuBusy: ratio('gpuBusy') } };
+ return { A: a, B: b, pairs: paired.length, paired, deltas, ratios: { p50: ratio('p50'), p95: ratio('p95'), cpuRenderP50: ratio('cpuRenderP50'), gpuBusy: ratio('gpuBusy'), gpuClockMHz: ratio('gpuClockMHz'), gpuBusyClockMHz: ratio('gpuBusyClockMHz') } };
}
// ---------------------------------------------------------------- scenes: views, workloads and the page setup per scene
@@ -296,6 +302,10 @@ async function writeJson(path: string, value: unknown) { await mkdir(dirname(pat
// ---------------------------------------------------------------- host load (hub, this PC) and tablet state
const GPU_FIELDS = ['utilization.gpu', 'temperature.gpu', 'clocks.gr', 'memory.used', 'pstate'] as const;
+export const parseScreenLocker = (text: string | null): boolean | null => {
+ const match = text?.trim().match(/^\(\s*(true|false)\s*,?\s*\)$/);
+ return match ? match[1] === 'true' : null;
+};
async function gpuRow() { const out = await run('nvidia-smi', [`--query-gpu=${GPU_FIELDS.join(',')}`, '--format=csv,noheader,nounits'], 8000); return out ? parseNvidiaSmi(out, GPU_FIELDS)[0] ?? null : null; }
async function cpuCounters() {
if (process.platform === 'linux') return parseProcStat(await readFile('/proc/stat', 'utf8'));
@@ -328,7 +338,7 @@ async function hostState() {
governor: linux ? await read('/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor') : null, who: linux ? parseWho(await run('who', []) ?? '') : null,
loginctlSessions: linux ? parseWho(await run('loginctl', ['list-sessions', '--no-legend']) ?? '') : null,
top: linux ? parseTop(await run('top', ['-b', '-n', '1', '-o', '%CPU', '-w', '200']) ?? '') : null,
- screenLockerActive: locker === null ? null : /true/.test(locker), gpu: await gpuRow() };
+ screenLockerActive: parseScreenLocker(locker), gpu: await gpuRow() };
}
/** The quiet window: `samples` readings `intervalSeconds` apart of whole-machine CPU and NVIDIA GPU, with the busiest processes over it. */
async function quietWindow(rule: QuietRule) {
@@ -363,7 +373,7 @@ async function tabletQuietWindow(adb: Adb) {
}
/** Samples load every `everyMs` while a run samples frames; stopped by the returned function. */
function startLoadSampler(device: 'local' | 'tablet', adb: Adb | null, everyMs: number) {
- const samples: unknown[] = []; let stopped = false, previous: { total: number; idle: number } | null = null, tick = 0;
+ const samples: unknown[] = []; let stopped = false, previous: { total: number; idle: number } | null = null, tick = 0, failure: { error: unknown } | undefined;
const loop = (async () => {
if (device === 'local') previous = await cpuCounters();
while (!stopped) {
@@ -374,8 +384,8 @@ function startLoadSampler(device: 'local' | 'tablet', adb: Adb | null, everyMs:
else { const g = (await adb.shell('cat /sys/kernel/gpu/gpu_busy /sys/kernel/gpu/gpu_clock 2>/dev/null').catch(() => '')).trim().split(/\s+/); samples.push({ at: now(), gpuBusyPercent: g[0] ? parseFloat(g[0]) : null, gpuClockKHz: g[1] ? Number(g[1]) : null }); }
} else { const current = await cpuCounters(); samples.push({ at: now(), cpuPercent: round(cpuPercent(previous!, current)), gpu: await gpuRow() }); previous = current; }
}
- })();
- return async () => { stopped = true; await loop; return samples; };
+ })().catch(error => { failure = { error }; });
+ return async () => { stopped = true; await loop; if (failure) throw failure.error; return samples; };
}
// ---------------------------------------------------------------- page measurement
@@ -417,22 +427,23 @@ async function serve(side: Side, root: string, ports: [number, number], taken: S
if (taken.has(port)) continue;
try { const s = await startStaticServer({ root, port }); taken.add(port);
// Chrome keeps connections alive (on the tablet through adb reverse), so they are cut before the server closes.
- const close = () => Promise.race([(s.server.closeAllConnections?.(), s.close()), sleep(5000)]) as Promise<void>;
+ const close = async () => { s.server.closeAllConnections?.(); await s.close(); };
return { side, label: build?.label ?? root, root, base: s.url, port, build: build && { label: build.label, scene: build.scene, mode: build.mode, release: build.release, chunks: build.chunks?.map((c: { name: string }) => c.name), source: build.source }, close };
} catch (error) { if ((error as { code?: string }).code !== 'EADDRINUSE') throw error; }
}
throw new Error(`No free port in ${ports[0]}-${ports[1]}`);
}
-interface MeasureOptions { device: 'local' | 'tablet'; seconds: number; warmupMs: number; width: number; height: number; backend: 'webgpu'; extra: Record<string, string>; adb: Adb | null; loadEveryMs: number; browserPid: number | null }
-async function measure(browser: Browser, served: Served, cell: Cell, o: MeasureOptions) {
+interface MeasureOptions { device: 'local' | 'tablet'; seconds: number; warmupMs: number; width: number; height: number; backend: 'webgpu'; extra: Record<string, string>; adb: Adb | null; loadEveryMs: number; browserPid: number | null; cleanup: Awaited<ReturnType<typeof cleanupTimingResources>> }
+export async function measureTimingRun(browser: Browser, served: Served, cell: Cell, o: MeasureOptions) {
const page = await browser.newPage(), messages: { type: string; text: string }[] = [];
+ let failure: { error: unknown } | undefined;
page.on('console', m => { if ((m.type() === 'error' || m.type() === 'warn') && messages.length < 100) messages.push({ type: m.type(), text: m.text().slice(0, 400) }); });
page.on('pageerror', e => { if (messages.length < 100) messages.push({ type: 'pageerror', text: String(e).slice(0, 400) }); });
try {
await page.bringToFront().catch(() => undefined);
if (o.device === 'local') await page.setViewport({ width: o.width, height: o.height, deviceScaleFactor: 1 });
- await page.evaluateOnNewDocument(installRecorder); await page.evaluateOnNewDocument(installCss, PAGE_CSS);
+ await page.evaluateOnNewDocument(installRecorder); await page.evaluateOnNewDocument(installTimingEvidence); await page.evaluateOnNewDocument(installCss, PAGE_CSS);
const display = await measureDisplay(page);
const url = cellUrl(served.base, cell, o.extra), started = Date.now();
await page.goto(url, { waitUntil: 'load', timeout: 180_000 });
@@ -441,10 +452,11 @@ async function measure(browser: Browser, served: Served, cell: Cell, o: MeasureO
const w = window as any, api = w.__kilnScene, host = w.__kilnHarness.snapshot(); // eslint-disable-line @typescript-eslint/no-explicit-any
if (w.__ab.error) return { error: w.__ab.error };
api.feedFrameTimes([]); // the governor is held at the tier's level 0 (as perf.ts and perf-core.ts X-05)
- return { error: null, errors: host.errors, readyAt: w.__ab.readyAt, backend: document.querySelector('.ks-root')?.getAttribute('data-kiln-backend') ?? null, tier: api.tierState(), msaaPolicy: api.invoke('msaaPolicy') ?? null };
+ return { error: null, errors: host.errors, readyAt: w.__ab.readyAt, backend: document.querySelector('.ks-root')?.getAttribute('data-kiln-backend') ?? null, tier: api.tierState(), msaaPolicy: api.invoke('msaaPolicy') ?? null, gpu: w.__timingEvidence.gpu() };
});
if (setup.error) throw new Error(`Scene failed: ${JSON.stringify(setup.error)}`);
if (setup.backend !== o.backend) throw new Error(`${served.side} runs ${setup.backend}, not ${o.backend}`);
+ if (setup.gpu.status !== 'bound') throw new Error(`STOP: Renderer GPU device provenance is unbound: ${JSON.stringify(setup.gpu)}`);
if (setup.tier?.tier !== cell.tier || setup.tier.level !== 0) throw new Error(`${served.side} tier is ${setup.tier?.tier} level ${setup.tier?.level}, not ${cell.tier} level 0`);
// The page holds a screen wake lock (run-farm-tablet.ts openTab), so the tablet panel stays on through the sample.
const wakeLock = await page.evaluate(async () => { try { (window as any).__abWakeLock = await (navigator as any).wakeLock.request('screen'); return 'held'; } catch (error) { return String(error); } }); // eslint-disable-line @typescript-eslint/no-explicit-any
@@ -453,35 +465,50 @@ async function measure(browser: Browser, served: Served, cell: Cell, o: MeasureO
if (o.warmupMs) await sleep(o.warmupMs);
const before = await scene.state(page), clock0 = await page.evaluate(() => (window as any).__kilnScene.motionPolicy().time as number); // eslint-disable-line @typescript-eslint/no-explicit-any
const ticks = await procTicks(), t0 = Date.now();
- await page.evaluate(() => { const w = window as any, rec = w.__ab; w.__kilnScene.beginMeasurement(); rec.intervals = []; rec.draws = []; rec.triangles = []; rec.last = null; rec.recording = true; }); // eslint-disable-line @typescript-eslint/no-explicit-any
+ await page.evaluate(() => { const w = window as any, rec = w.__ab; const observed = w.__timingEvidence.begin();
+ if (observed.visibility.initial !== 'visible' || !observed.focus.initial) throw new Error('STOP: Measurement page is not visible and focused');
+ w.__kilnScene.beginMeasurement(); rec.intervals = []; rec.draws = []; rec.triangles = []; rec.last = null; rec.recording = true; }); // eslint-disable-line @typescript-eslint/no-explicit-any
const stopLoad = startLoadSampler(o.device, o.adb, o.loadEveryMs);
- await sleep(o.seconds * 1000);
- const end = await page.evaluate(() => {
+ const { end, loadDuring: during } = await sampleWithLoad(async () => {
+ await sleep(o.seconds * 1000);
+ return page.evaluate(() => {
const w = window as any, api = w.__kilnScene, rec = w.__ab, host = w.__kilnHarness.snapshot(); // eslint-disable-line @typescript-eslint/no-explicit-any
rec.recording = false; api.recordFrames(false); const s = api.stats();
const canvas = document.querySelector('.ks-root canvas') as HTMLCanvasElement | null;
return { intervals: rec.intervals as number[], draws: rec.draws as number[], triangles: rec.triangles as number[], cpu: api.cpuRenderTimes() as number[], tier: api.tierState(), clock: api.motionPolicy().time as number,
- errors: host.errors, visibility: document.visibilityState, longTasks: s.longTasks ?? null, pipelines: s.pipelines ?? null, msaaPolicy: api.invoke('msaaPolicy') ?? null,
+ errors: host.errors, visibility: document.visibilityState, foreground: w.__timingEvidence.finish(), gpu: w.__timingEvidence.gpu(), longTasks: s.longTasks ?? null, pipelines: s.pipelines ?? null, msaaPolicy: api.invoke('msaaPolicy') ?? null,
canvas: canvas ? { buffer: [canvas.width, canvas.height], css: [canvas.clientWidth, canvas.clientHeight], dpr: devicePixelRatio } : null };
- });
- const during = await stopLoad(), seconds = (Date.now() - t0) / 1000;
+ });
+ }, stopLoad);
+ const seconds = (Date.now() - t0) / 1000;
const after = await scene.state(page);
const external = process.platform === 'linux' && o.device === 'local' ? externalBusiest(ticks, await procTicks(), seconds, [process.pid, ...(o.browserPid ? [o.browserPid] : [])]) : null;
- const env = await page.evaluate(async () => { const a = await (navigator as any).gpu?.requestAdapter?.().catch(() => null), i = a?.info; return { userAgent: navigator.userAgent, adapter: i ? { vendor: i.vendor, architecture: i.architecture, device: i.device, description: i.description } : null, inner: [innerWidth, innerHeight], dpr: devicePixelRatio }; }); // eslint-disable-line @typescript-eslint/no-explicit-any
+ const env = await page.evaluate(() => ({ userAgent: navigator.userAgent, inner: [innerWidth, innerHeight], dpr: devicePixelRatio }));
const stats = frameStats(end.intervals), cpu = frameStats(end.cpu), share = refreshShare(end.intervals, display.periodMs ?? NaN), hitches = hitchCounts(end.intervals);
const checks = { backend: setup.backend, tierHeldAtLevel0: end.tier?.tier === cell.tier && end.tier?.level === 0, clockAdvanced: end.clock > clock0, engaged: scene.engaged(kind, cell.name, before),
movedForWorkload: kind === 'view' ? null : JSON.stringify(before.pose) !== JSON.stringify(after.pose), noErrors: end.errors.length === 0, pageVisible: end.visibility === 'visible',
+ visibilityMaintained: !end.foreground.visibility.hidden, focusMaintained: !end.foreground.focus.lost,
+ rendererDeviceBound: end.gpu.status === 'bound', adapterIdentified: !!(end.gpu.adapter?.vendor || end.gpu.adapter?.device || end.gpu.adapter?.description),
coverage: round(stats.sampledMs / (o.seconds * 1000), 3), displayMeasured: !!display.periodMs,
refreshMismatch: !!display.periodMs && stats.p50 !== null && stats.p50 < .75 * display.periodMs };
- const valid = checks.tierHeldAtLevel0 && checks.clockAdvanced && checks.engaged && checks.movedForWorkload !== false && checks.noErrors && checks.pageVisible && (checks.coverage ?? 0) >= .9 && checks.displayMeasured && !checks.refreshMismatch;
+ const valid = checks.tierHeldAtLevel0 && checks.clockAdvanced && checks.engaged && checks.movedForWorkload !== false && checks.noErrors && checks.pageVisible && checks.visibilityMaintained && checks.focusMaintained && checks.rendererDeviceBound && checks.adapterIdentified && (checks.coverage ?? 0) >= .9 && checks.displayMeasured && !checks.refreshMismatch;
+ const gpuWork = gpuWorkSummary(during);
const metrics: RunMetrics = { p50: stats.p50, p95: stats.p95, p99: stats.p99, max: stats.max, fps: stats.fps, withinOne: share.withinOne, withinTwo: share.withinTwo, over50: hitches.over50, over100: hitches.over100,
- longestMs: hitches.longestMs, cpuRenderP50: cpu.p50, cpuRenderP95: cpu.p95, drawsMedian: median(end.draws), trianglesMedian: median(end.triangles), gpuBusy: gpuBusyMedian(during) };
+ longestMs: hitches.longestMs, cpuRenderP50: cpu.p50, cpuRenderP95: cpu.p95, drawsMedian: median(end.draws), trianglesMedian: median(end.triangles), gpuBusy: gpuBusyMedian(during), gpuClockMHz: gpuWork.clockMHzMean, gpuBusyClockMHz: gpuWork.busyClockMHzMean };
return { valid, checks, url, readyMs: round(setup.readyAt, 1), wakeLock, display, frames: stats, refresh: share, hitches, d41: d41Verdict(hitches, { row: o.device === 'tablet' ? 'tablet' : 'desktop', seconds: o.seconds }),
cpuRenderMs: { ...cpu, sampledMs: undefined }, draws: { median: median(end.draws), min: end.draws.length ? Math.min(...end.draws) : null, max: end.draws.length ? Math.max(...end.draws) : null, samples: end.draws.length },
- triangles: { median: median(end.triangles), samples: end.triangles.length }, metrics, msaaPolicy: { atStart: setup.msaaPolicy, atEnd: end.msaaPolicy }, tier: { start: setup.tier && { tier: setup.tier.tier, level: setup.tier.level, device: setup.tier.device }, end: end.tier && { tier: end.tier.tier, level: end.tier.level } },
- workload: { kind, before, after }, canvas: end.canvas, longTasks: end.longTasks, pipelines: end.pipelines, environment: env, loadDuring: during, externalBusiest: external, messages, sampleWallSeconds: round(seconds, 2), startedToSampleMs: t0 - started,
+ triangles: { median: median(end.triangles), samples: end.triangles.length }, metrics, gpuWork, msaaPolicy: { atStart: setup.msaaPolicy, atEnd: end.msaaPolicy }, tier: { start: setup.tier && { tier: setup.tier.tier, level: setup.tier.level, device: setup.tier.device }, end: end.tier && { tier: end.tier.tier, level: end.tier.level } },
+ workload: { kind, before, after }, canvas: end.canvas, longTasks: end.longTasks, pipelines: end.pipelines, environment: { ...env, adapter: end.gpu.adapter, gpu: end.gpu }, foreground: end.foreground, cleanup: o.cleanup, loadDuring: during, externalBusiest: external, messages, sampleWallSeconds: round(seconds, 2), startedToSampleMs: t0 - started,
frameIntervalsMs: end.intervals.map(v => round(v)), cpuRenderTimesMs: end.cpu.map(v => round(v)) };
- } finally { await page.close().catch(() => undefined); }
+ } catch (error) { failure = { error }; throw error; }
+ finally {
+ const closed = await cleanupTimingResources([{ name: 'measurement-page', close: () => page.close() }]); o.cleanup.push(...closed);
+ if (closed.some(result => !result.ok)) {
+ const error = new Error(`STOP: Measurement page cleanup failed: ${closed.map(result => result.error).filter(Boolean).join('; ')}`);
+ if (failure) throw new AggregateError([failure.error, error], 'STOP: Measurement and page cleanup both failed');
+ throw error;
+ }
+ }
}
// ---------------------------------------------------------------- the A/B block
@@ -547,11 +574,15 @@ async function abBlock() {
// Two builds, two owned loopback ports (4400-4499: the device kit's range, so adb reverse maps the same numbers on the tablet).
const taken = new Set<number>(), ports = (option('--ports', '4400-4489')!.split('-').map(Number)) as [number, number];
const served = {} as Record<SceneId, { A: Served; B: Served }>;
- for (const scene of [...new Set(cells.map(c => c.scene))]) served[scene] = { A: await serve('A', resolve(rootA, scene), ports, taken), B: await serve('B', resolve(rootB, scene), ports, taken) };
- record.builds = Object.fromEntries(Object.entries(served).map(([scene, s]) => [scene, { A: { root: s.A.root, port: s.A.port, build: s.A.build }, B: { root: s.B.root, port: s.B.port, build: s.B.build } }]));
+ const ownedServers: Served[] = [];
let browser: Browser | null = null, profile: string | null = null, browserPid: number | null = null; const adb = device === 'tablet' ? adbFor() : null;
let stopped: string | null = null;
try {
+ for (const scene of [...new Set(cells.map(c => c.scene))]) {
+ const [A, B] = await acquireTimingResources(ownedServers, [() => serve('A', resolve(rootA, scene), ports, taken), () => serve('B', resolve(rootB, scene), ports, taken)]);
+ served[scene] = { A: A!, B: B! };
+ }
+ record.builds = Object.fromEntries(Object.entries(served).map(([scene, s]) => [scene, { A: { root: s.A.root, port: s.A.port, build: s.A.build }, B: { root: s.B.root, port: s.B.port, build: s.B.build } }]));
if (device === 'local') {
record.preflight = flag('--no-preflight') ? { skipped: 'Not evidence: --no-preflight' } : await preflight(hostRule(), Number(option('--wait-quiet', '10')));
await save();
@@ -580,7 +611,7 @@ async function abBlock() {
await save();
// One discarded load per side warms the HTTP and shader caches equally before the first measured run.
if (primeSeconds > 0) {
- const primes = [];
+ const primes: Record<string, unknown>[] = []; record.primes = primes;
for (const cell of cells) for (const side of ['A', 'B'] as const) {
let session: TabletSession | null = null; const prime: Record<string, unknown> = { cell: cellId(cell), side };
try {
@@ -589,8 +620,11 @@ async function abBlock() {
try { if (device === 'local') await page.setViewport({ width, height, deviceScaleFactor: 1 }); await page.evaluateOnNewDocument(installRecorder); await page.evaluateOnNewDocument(installCss, PAGE_CSS);
await page.goto(cellUrl(served[cell.scene][side].base, cell, query[side]), { waitUntil: 'load', timeout: 180_000 });
await page.waitForFunction(() => (window as any).__ab.readyAt !== null || (window as any).__ab.error, { timeout: 180_000, polling: 200 }); await sleep(primeSeconds * 1000); // eslint-disable-line @typescript-eslint/no-explicit-any
- prime.ok = true; } finally { await page.close().catch(() => undefined); }
- } catch (error) { prime.ok = false; prime.error = String(error).slice(0, 300); }
+ prime.ok = true; } finally {
+ const closed = await cleanupTimingResources([{ name: 'prime-page', close: () => page.close() }]); prime.cleanup = closed;
+ if (closed.some(result => !result.ok)) throw new Error(`STOP: Prime page cleanup failed: ${closed.map(result => result.error).filter(Boolean).join('; ')}`);
+ }
+ } catch (error) { prime.ok = false; prime.error = timingError(error).slice(0, 1000); if (/STOP:/.test(String(error))) stopped ??= timingError(error); }
finally { if (device === 'tablet') { const r = await tabletRelease(adb!, session); prime.mappingsEmpty = r.empty ?? null; if (r.problems.length) stopped ??= `mapping cleanup after prime: ${r.problems.join('; ')}`; } }
primes.push(prime); console.log(JSON.stringify({ event: 'prime', ...prime }));
if (stopped) throw new Error(`STOP: ${stopped}`);
@@ -600,7 +634,8 @@ async function abBlock() {
for (const planned of plan) {
const cell = planned.cell, side = planned.side, label = `${cellId(cell)}-pair${planned.pair}-${side}`;
let session: TabletSession | null = null, cool: unknown = null;
- const entry: Record<string, unknown> = { label, cell: cellId(cell), pair: planned.pair, position: planned.position, side };
+ const cleanup: Awaited<ReturnType<typeof cleanupTimingResources>> = [];
+ const entry: Record<string, unknown> = { label, cell: cellId(cell), pair: planned.pair, position: planned.position, side, cleanup };
try {
if (device === 'tablet') {
const c = await waitCool(adb!, Number(option('--cool-wait', '10'))); cool = c;
@@ -608,7 +643,7 @@ async function abBlock() {
session = await tabletConnect(adb!, [served[cell.scene][side].port]);
}
const loadBefore = device === 'local' ? { at: now(), cpuPercent: null, gpu: await gpuRow(), loadavg: process.platform === 'linux' ? parseLoadavg(await readFile('/proc/loadavg', 'utf8')) : null } : await tabletReading(adb!);
- const result = await measure(session?.browser ?? browser!, served[cell.scene][side], cell, { device, seconds, warmupMs, width, height, backend: 'webgpu', extra: query[side], adb, loadEveryMs: device === 'tablet' ? 2_000 : 5_000, browserPid });
+ const result = await measureTimingRun(session?.browser ?? browser!, served[cell.scene][side], cell, { device, seconds, warmupMs, width, height, backend: 'webgpu', extra: query[side], adb, loadEveryMs: device === 'tablet' ? 2_000 : 5_000, browserPid, cleanup });
const loadAfter = device === 'local' ? { at: now(), gpu: await gpuRow(), loadavg: process.platform === 'linux' ? parseLoadavg(await readFile('/proc/loadavg', 'utf8')) : null } : await tabletReading(adb!);
const fileRecord = { schema: 'kiln.timing-ab-run/1', block, device, cell: { ...cell, kind: cellKind(cell) }, side, label: served[cell.scene][side].label, pair: planned.pair, position: planned.position, seconds, warmupSeconds: warmupMs / 1000,
build: served[cell.scene][side].build, query: query[side], startedAt: now(), loadBefore, loadAfter, coolBefore: cool, ...result };
@@ -617,7 +652,7 @@ async function abBlock() {
console.log(JSON.stringify({ event: 'run', ...entry }));
if (device === 'tablet') { const t = tabletCool(loadAfter as { thermalStatus: number | null; batteryC: number | null }); if (!t.cool) { stopped = `tablet warmed during ${label}: ${t.reasons.join('; ')}`; } }
} catch (error) {
- entry.error = String((error as Error)?.message ?? error).slice(0, 1000); console.log(JSON.stringify({ event: 'run-failed', ...entry }));
+ entry.error = timingError(error).slice(0, 2000); console.log(JSON.stringify({ event: 'run-failed', ...entry }));
if (/STOP:/.test(String(error))) stopped ??= String(error);
} finally {
if (device === 'tablet') { const r = await tabletRelease(adb!, session); entry.mappingsAfter = r.mappings; entry.mappingsEmpty = r.empty ?? null; if (r.problems.length) { stopped ??= `mapping cleanup: ${r.problems.join('; ')}`; } }
@@ -627,14 +662,22 @@ async function abBlock() {
}
} catch (error) { stopped ??= String((error as Error)?.message ?? error); console.error(String((error as Error)?.stack ?? error)); }
finally {
- if (browser) await browser.close().catch(() => undefined);
- if (profile) await rm(profile, { recursive: true, force: true }).catch(() => undefined);
- for (const s of Object.values(served)) { await s.A.close().catch(() => undefined); await s.B.close().catch(() => undefined); }
+ const cleanup = await cleanupTimingResources([
+ ...(browser ? [{ name: 'browser', close: () => browser!.close() }] : []),
+ ...(profile ? [{ name: 'browser-profile', close: () => rm(profile!, { recursive: true, force: true }) }] : []),
+ ...ownedServers.map(server => ({ name: `server-${server.side}-${server.port}`, close: server.close, timeoutMs: 5000 })),
+ ]);
+ record.cleanup = cleanup;
+ if (cleanup.some(result => !result.ok)) stopped ??= `Cleanup failed: ${cleanup.filter(result => !result.ok).map(result => `${result.name}: ${result.error}`).join('; ')}`;
if (device === 'tablet' && adb) { record.deviceAfter = await deviceState(adb).catch(e => String(e)); record.mappingsAtEnd = await listMappings(adb).catch(e => String(e)); }
+ record.collection = timingCollectionVerdict({ expected: plan.map(p => `${cellId(p.cell)}-pair${p.pair}-${p.side}`),
+ runs: record.runs as Parameters<typeof timingCollectionVerdict>[0]['runs'], expectedPrimes: primeSeconds > 0 ? cells.length * 2 : 0,
+ primes: (record.primes ?? []) as { ok?: boolean }[], cleanup, stopped });
record.finishedAt = now(); record.stopped = stopped; await save();
}
const summary = await summarizeBlock(out);
- console.log(JSON.stringify({ event: 'block', block, out, stopped, cells: summary.cells.map(c => ({ cell: c.cell, A: c.A.valid, B: c.B.valid, p95: [c.A.p95?.median, c.B.p95?.median] })) }));
+ console.log(JSON.stringify({ event: 'block', block, out, stopped, collection: record.collection, cells: summary.cells.map(c => ({ cell: c.cell, A: c.A.valid, B: c.B.valid, p95: [c.A.p95?.median, c.B.p95?.median] })) }));
+ // Collector exit zero is not acceptance: the persisted collection verdict and D41/D16 must be reviewed.
if (stopped) process.exitCode = 2;
}
@@ -649,20 +692,26 @@ export async function summarizeBlock(dir: string) {
const ids = [...new Set(runs.map(r => `${r.cell.scene}-${r.cell.tier}-${r.cell.name}`))];
const cells = ids.map(id => {
const list = runs.filter(r => `${r.cell.scene}-${r.cell.tier}-${r.cell.name}` === id);
- const s = summarizeCell(list.map(r => ({ side: r.side, pair: r.pair, valid: r.valid, metrics: { ...r.metrics, gpuBusy: r.metrics.gpuBusy ?? gpuBusyMedian(r.loadDuring ?? []) } })));
+ const normalized = list.map(r => {
+ const work = gpuWorkSummary(r.loadDuring ?? []);
+ return { side: r.side, pair: r.pair, valid: r.valid, seconds: r.seconds, gpuWork: work, metrics: { ...r.metrics,
+ gpuBusy: r.metrics.gpuBusy ?? gpuBusyMedian(r.loadDuring ?? []),
+ gpuClockMHz: work.clockMHzMean, gpuBusyClockMHz: work.busyClockMHzMean } };
+ });
+ const s = summarizeCell(normalized);
const sideFacts = (side: Side) => { const l = list.filter(r => r.side === side); return { label: l[0]?.build?.label ?? null, chunks: l[0]?.build?.chunks ?? null, msaa: [...new Set(l.map(r => JSON.stringify(r.msaaPolicy?.atEnd ?? null)))], periodMs: median(l.map(r => r.display?.periodMs).filter(Number.isFinite)),
d41: l.map(r => r.d41?.pass ?? null), invalid: l.filter(r => !r.valid).map(r => ({ pair: r.pair, checks: r.checks })) }; };
- return { cell: id, scene: list[0].cell.scene, tier: list[0].cell.tier, name: list[0].cell.name, kind: list[0].cell.kind, seconds: [...new Set(list.map(r => r.seconds))], facts: { A: sideFacts('A'), B: sideFacts('B') }, ...s };
+ return { tabletAdoption: block.device === 'tablet' ? tabletPairVerdict(normalized) : null, cell: id, scene: list[0].cell.scene, tier: list[0].cell.tier, name: list[0].cell.name, kind: list[0].cell.kind, seconds: [...new Set(list.map(r => r.seconds))], facts: { A: sideFacts('A'), B: sideFacts('B') }, ...s };
});
- const out = { schema: 'kiln.timing-ab-summary/1', block: block.block ?? null, device: block.device ?? null, generatedAt: now(), runs: runs.length, stopped: block.stopped ?? null,
- method: 'Per run: rAF frame intervals over the sample after a warm-up, governor held at the tier level 0. Per side: median (min-max) over valid runs. Paired: B - A within each interleaved pair (both runs valid), median over pairs, and how many pairs B was lower or higher. Refresh shares (OD-7): interval < 1.5 and < 2.5 measured display periods. D-41: 0 over 100 ms, 0 over 50 ms, longest <= 50 ms per 60 s run (tablet: at most 2 over 50 ms, 0 over 100 ms); judged only on runs of at least 60 s.',
+ const out = { schema: 'kiln.timing-ab-summary/1', block: block.block ?? null, device: block.device ?? null, generatedAt: now(), runs: runs.length, stopped: block.stopped ?? null, collection: block.collection ?? null,
+ method: 'Per run: rAF frame intervals over the sample after a warm-up, governor held at the tier level 0. Per side: median (min-max) over valid runs. Paired: B - A within each interleaved pair (both runs valid), median over pairs, and how many pairs B was lower or higher. Refresh shares (OD-7): interval < 1.5 and < 2.5 measured display periods. D-41: 0 over 100 ms, 0 over 50 ms, longest <= 50 ms per 60 s run (tablet: at most 2 over 50 ms, 0 over 100 ms); judged only on runs of at least 60 s. GPU clock is MHz (Mali sysfs kHz / 1000; NVIDIA clocks.gr MHz). GPU activity is the mean of same-sample busy fraction × MHz, not product of means or energy. D16 requires three valid tablet pairs; missing evidence is unqualified.',
cells };
await writeJson(resolve(dir, 'summary.json'), out);
const md = [`# Timing A/B ${out.block ?? dir} (${out.device ?? '?'})`, '', out.method, '', `Runs: ${runs.length}.${out.stopped ? ` **Stopped: ${out.stopped}**` : ''}`, '',
- '| Cell | Side (label) | Valid | p50 ms | p95 ms | Within 1 refresh | Within 2 | >50 ms | >100 ms | Longest ms | CPU render p50 ms | GPU busy % | Draws | Period ms |', '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|'];
+ '| Cell | Side (label) | Valid | p50 ms | p95 ms | Within 1 refresh | Within 2 | >50 ms | >100 ms | Longest ms | CPU render p50 ms | GPU busy % | GPU MHz | Busy × MHz | Draws | Period ms |', '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|'];
for (const c of cells) for (const side of ['A', 'B'] as const) {
const x = c[side], f = c.facts[side];
- md.push(`| ${c.cell} | ${side} (${f.label}) | ${x.valid}/${x.runs} | ${ms(x.p50?.median)} (${ms(x.p50?.min)}-${ms(x.p50?.max)}) | ${ms(x.p95?.median)} (${ms(x.p95?.min)}-${ms(x.p95?.max)}) | ${pct(x.withinOne?.median)} | ${pct(x.withinTwo?.median)} | ${x.over50 ? `${x.over50.median} (max ${x.over50.max})` : '-'} | ${x.over100 ? `${x.over100.median} (max ${x.over100.max})` : '-'} | ${ms(x.longestMs?.max, 1)} | ${ms(x.cpuRenderP50?.median)} | ${x.gpuBusy ? `${ms(x.gpuBusy.median, 1)} (${ms(x.gpuBusy.min, 0)}-${ms(x.gpuBusy.max, 0)})` : '-'} | ${x.drawsMedian?.median ?? '-'} | ${ms(f.periodMs, 3)} |`);
+ md.push(`| ${c.cell} | ${side} (${f.label}) | ${x.valid}/${x.runs} | ${ms(x.p50?.median)} (${ms(x.p50?.min)}-${ms(x.p50?.max)}) | ${ms(x.p95?.median)} (${ms(x.p95?.min)}-${ms(x.p95?.max)}) | ${pct(x.withinOne?.median)} | ${pct(x.withinTwo?.median)} | ${x.over50 ? `${x.over50.median} (max ${x.over50.max})` : '-'} | ${x.over100 ? `${x.over100.median} (max ${x.over100.max})` : '-'} | ${ms(x.longestMs?.max, 1)} | ${ms(x.cpuRenderP50?.median)} | ${x.gpuBusy ? `${ms(x.gpuBusy.median, 1)} (${ms(x.gpuBusy.min, 0)}-${ms(x.gpuBusy.max, 0)})` : '-'} | ${ms(x.gpuClockMHz?.median, 1)} | ${ms(x.gpuBusyClockMHz?.median, 1)} | ${x.drawsMedian?.median ?? '-'} | ${ms(f.periodMs, 3)} |`);
}
md.push('', '| Cell | Pairs | Δp50 ms (B-A, median; B lower/higher) | Δp95 ms | Δ within 1 | Δ CPU render p50 ms | Δ GPU busy pt | p95 ratio B/A |', '|---|---|---|---|---|---|---|---|');
for (const c of cells) {
@@ -670,6 +719,7 @@ export async function summarizeBlock(dir: string) {
const cellText = (k: string, f: (v: number | null) => string) => d[k] ? `${f(d[k]!.medianDelta)} (${d[k]!.bLower}/${d[k]!.bHigher})` : '-';
md.push(`| ${c.cell} | ${c.pairs} | ${cellText('p50', v => ms(v, 3))} | ${cellText('p95', v => ms(v, 3))} | ${cellText('withinOne', v => typeof v === 'number' ? `${(100 * v).toFixed(2)} pt` : '-')} | ${cellText('cpuRenderP50', v => ms(v, 3))} | ${cellText('gpuBusy', v => ms(v, 1))} | ${typeof c.ratios.p95 === 'number' ? c.ratios.p95.toFixed(3) : '-'} |`);
}
+ for (const c of cells) if (c.tabletAdoption) md.push('', `D16 ${c.cell}: ${c.tabletAdoption.pass === null ? 'unqualified' : c.tabletAdoption.pass ? 'pass' : 'fail'}; refresh regressions ${c.tabletAdoption.refreshRegressions}/3; GPU-work regressions ${c.tabletAdoption.gpuWorkRegressions}/3. ${c.tabletAdoption.reasons.join('; ')}`);
await writeFile(resolve(dir, 'summary.md'), md.join('\n') + '\n');
return out;
}
diff --git a/scenes/scripts/timing-evidence.ts b/scenes/scripts/timing-evidence.ts
new file mode 100644
index 00000000..b494e678
--- /dev/null
+++ b/scenes/scripts/timing-evidence.ts
@@ -0,0 +1,143 @@
+/** Sampling and teardown policies shared by the timing runner and its offline regression tests. */
+export async function sampleWithLoad<T>(sample: () => Promise<T>, stopLoad: () => Promise<unknown[]>) {
+ const result = { end: undefined as T, loadDuring: [] as unknown[] };
+ let failure: { error: unknown } | undefined;
+ try { result.end = await sample(); return result; }
+ catch (error) { failure = { error }; throw error; }
+ finally {
+ try { result.loadDuring = await stopLoad(); }
+ catch (error) {
+ if (failure) throw new AggregateError([failure.error, error], 'Timing sample and load-poller cleanup both failed');
+ throw error;
+ }
+ }
+}
+
+export function timingError(error: unknown): string {
+ return error instanceof AggregateError ? `${error.message}: ${error.errors.map(timingError).join('; ')}` : error instanceof Error ? error.message : String(error);
+}
+
+export async function acquireTimingResources<T>(owned: T[], starts: (() => Promise<T>)[]) {
+ const added: T[] = [];
+ for (const start of starts) { const resource = await start(); owned.push(resource); added.push(resource); }
+ return added;
+}
+
+export async function cleanupTimingResources(resources: { name: string; close(): Promise<void>; timeoutMs?: number }[]) {
+ const results: { name: string; ok: boolean; error?: string }[] = [];
+ for (const resource of resources) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ if (resource.timeoutMs !== undefined) await Promise.race([resource.close(), new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(() => reject(new Error(`Cleanup timed out after ${resource.timeoutMs} ms`)), resource.timeoutMs);
+ })]);
+ else await resource.close();
+ results.push({ name: resource.name, ok: true });
+ }
+ catch (error) { results.push({ name: resource.name, ok: false, error: timingError(error) }); }
+ finally { if (timer !== undefined) clearTimeout(timer); }
+ }
+ return results;
+}
+
+/** Collection validity only; D41, D16 and campaign acceptance remain separate evidence. */
+export function timingCollectionVerdict(o: { expected: readonly string[]; runs: { label: string; valid?: boolean; error?: unknown }[]; expectedPrimes: number; primes: { ok?: boolean }[]; cleanup: { ok: boolean }[]; stopped: unknown }) {
+ const counts = new Map<string, number>(); for (const run of o.runs) counts.set(run.label, (counts.get(run.label) ?? 0) + 1);
+ const missing = o.expected.filter(label => !counts.has(label));
+ const duplicates = [...counts].filter(([, count]) => count > 1).map(([label]) => label);
+ const unexpected = [...counts.keys()].filter(label => !o.expected.includes(label));
+ const validRuns = o.runs.filter(run => run.valid === true && run.error === undefined).length;
+ const primesOk = o.primes.length === o.expectedPrimes && o.primes.every(prime => prime.ok === true), cleanupOk = o.cleanup.every(row => row.ok === true);
+ const pass = !o.stopped && missing.length === 0 && duplicates.length === 0 && unexpected.length === 0 && o.runs.length === o.expected.length && validRuns === o.expected.length && primesOk && cleanupOk;
+ return { pass, expectedRuns: o.expected.length, recordedRuns: o.runs.length, validRuns, missing, duplicates, unexpected, primesOk, cleanupOk,
+ scope: 'Collection validity only; inspect D41, D16, display rate and campaign acceptance separately.' };
+}
+
+/** Self-contained: Puppeteer serializes this function into the page before scene scripts execute. */
+export function installTimingEvidence(scope: any = globalThis) {
+ if (scope.__timingEvidence) return;
+ let active = false, started = 0;
+ const visibility = { initial: '', final: '', hidden: false, changes: [] as { state: string; atMs: number }[], omitted: 0 };
+ const focus = { initial: false, final: false, lost: false, changes: [] as { focused: boolean; atMs: number }[], omitted: 0 };
+ const errors: string[] = [], adapterRequests: any[] = [], deviceRequests: any[] = [];
+ const adapters = new WeakMap<object, any>(), devices = new WeakMap<object, any>(), bindings = new Map<object, number | null>();
+ const info = (value: any) => value ? { vendor: value.vendor ?? '', architecture: value.architecture ?? '', device: value.device ?? '', description: value.description ?? '' } : null;
+ const copy = (value: any) => value === undefined ? null : JSON.parse(JSON.stringify(value));
+ const failed = (error: unknown) => { if (errors.length < 16) errors.push(String(error)); };
+ scope.document.addEventListener('visibilitychange', () => {
+ if (!active) return;
+ const state = scope.document.visibilityState; visibility.hidden ||= state !== 'visible';
+ if (visibility.changes.length < 64) visibility.changes.push({ state, atMs: scope.performance.now() - started }); else visibility.omitted++;
+ });
+ for (const name of ['blur', 'focus']) scope.addEventListener(name, () => {
+ if (!active) return;
+ const focused = scope.document.hasFocus(); focus.lost ||= !focused;
+ if (focus.changes.length < 64) focus.changes.push({ focused, atMs: scope.performance.now() - started }); else focus.omitted++;
+ });
+ // Observe the native call chain without requesting any extra adapter/device or changing its options.
+ try {
+ const gpu = scope.navigator.gpu;
+ if (!gpu) throw new Error('WebGPU is unavailable');
+ const requestAdapter = gpu.requestAdapter;
+ Object.defineProperty(gpu, 'requestAdapter', { configurable: true, writable: true, value: async function(this: any, ...args: any[]) {
+ const adapter = await requestAdapter.apply(this, args);
+ if (!adapter) return adapter;
+ try {
+ if (adapterRequests.length >= 16) throw new Error('Adapter observation limit exceeded');
+ const row = { id: adapterRequests.length + 1, options: copy(args[0]), info: info(adapter.info) };
+ adapterRequests.push(row);
+ const seen = adapters.has(adapter); adapters.set(adapter, row);
+ if (!seen) {
+ const requestDevice = adapter.requestDevice;
+ Object.defineProperty(adapter, 'requestDevice', { configurable: true, writable: true, value: async function(this: any, ...deviceArgs: any[]) {
+ const device = await requestDevice.apply(this, deviceArgs);
+ try {
+ if (deviceRequests.length >= 16) throw new Error('Device observation limit exceeded');
+ const origin = adapters.get(this);
+ const observed = { id: deviceRequests.length + 1, adapterId: origin?.id ?? null,
+ requestAdapterOptions: origin?.options ?? null, requestDeviceOptions: copy(deviceArgs[0]),
+ adapterInfo: origin?.info ?? null, deviceAdapterInfo: info(device.adapterInfo) };
+ deviceRequests.push(observed); devices.set(device, observed);
+ } catch (error) { failed(error); }
+ return device;
+ } });
+ }
+ } catch (error) { failed(error); }
+ return adapter;
+ } });
+ const prototype = scope.GPUCanvasContext?.prototype, configure = prototype?.configure;
+ if (typeof configure !== 'function') throw new Error('GPUCanvasContext.configure is unavailable');
+ Object.defineProperty(prototype, 'configure', { ...Object.getOwnPropertyDescriptor(prototype, 'configure'), value: function(this: any, ...args: any[]) {
+ const result = configure.apply(this, args);
+ try {
+ if (!bindings.has(this.canvas) && bindings.size >= 16) throw new Error('Canvas observation limit exceeded');
+ bindings.set(this.canvas, devices.get(args[0]?.device)?.id ?? null);
+ } catch (error) { failed(error); }
+ return result;
+ } });
+ } catch (error) { failed(error); }
+ scope.__timingEvidence = {
+ begin() {
+ started = scope.performance.now(); active = true;
+ Object.assign(visibility, { initial: scope.document.visibilityState, final: scope.document.visibilityState, hidden: scope.document.visibilityState !== 'visible', changes: [], omitted: 0 });
+ const focused = scope.document.hasFocus();
+ Object.assign(focus, { initial: focused, final: focused, lost: !focused, changes: [], omitted: 0 });
+ return { visibility, focus };
+ },
+ finish() {
+ if (active) {
+ visibility.final = scope.document.visibilityState; visibility.hidden ||= visibility.final !== 'visible';
+ focus.final = scope.document.hasFocus(); focus.lost ||= !focus.final; active = false;
+ }
+ return { visibility, focus };
+ },
+ gpu() {
+ const canvasBindings = Array.from(scope.document.querySelectorAll('.ks-root canvas') as Iterable<any>, (canvas, index) => ({ canvas: index, deviceId: bindings.get(canvas) ?? null }));
+ const ids = new Set(canvasBindings.map(row => row.deviceId));
+ const bound = errors.length === 0 && canvasBindings.length > 0 && ids.size === 1 && !ids.has(null);
+ const device = bound ? deviceRequests.find(row => row.id === canvasBindings[0]!.deviceId) : null;
+ return { status: bound ? 'bound' : 'unbound', binding: 'scene-canvas.configure', adapter: device?.deviceAdapterInfo ?? device?.adapterInfo ?? null,
+ adapterRequests, deviceRequests, canvasBindings, errors };
+ },
+ };
+}
diff --git a/scenes/scripts/toolchain-run.ps1 b/scenes/scripts/toolchain-run.ps1
index d6a243e9..abbb6ba0 100644
--- a/scenes/scripts/toolchain-run.ps1
+++ b/scenes/scripts/toolchain-run.ps1
@@ -2,10 +2,28 @@
param([Parameter(ValueFromRemainingArguments = $true)][string[]] $TaskArguments)
$ErrorActionPreference = 'Stop'
$workspace = Split-Path -Parent $PSScriptRoot
-$nodeInstall = 'C:/Users/Mattm/AppData/Roaming/fnm/node-versions/v22.23.2/installation'
+$toolchain = Get-Content -LiteralPath (Join-Path $workspace 'toolchain.json') -Raw | ConvertFrom-Json
+if ([string]$toolchain.node -notmatch '^\d+\.\d+\.\d+$') {
+ throw 'toolchain.json must pin a stable Node release.'
+}
+$nodeInstall = $null
+if ($env:APPDATA) {
+ $candidate = Join-Path $env:APPDATA "fnm/node-versions/v$($toolchain.node)/installation"
+ if (Test-Path -LiteralPath (Join-Path $candidate 'node.exe') -PathType Leaf) {
+ $nodeInstall = $candidate
+ }
+}
$previousPath = $env:PATH
try {
- $env:PATH = "$workspace/node_modules/.bin;$nodeInstall;$previousPath"
+ # Prefer the pinned per-user fnm install when present; otherwise keep PATH's Node.
+ $entries = @((Join-Path $workspace 'node_modules/.bin'))
+ if ($nodeInstall) { $entries += $nodeInstall }
+ $entries += $previousPath
+ $env:PATH = $entries -join [System.IO.Path]::PathSeparator
+ $nodeVersion = (& node --version | Out-String).Trim()
+ if ($LASTEXITCODE -ne 0 -or $nodeVersion -ne "v$($toolchain.node)") {
+ throw "Node $($toolchain.node) is required; selected $nodeVersion. Install the pinned version with fnm or select it on PATH."
+ }
$env:npm_config_cache = "$workspace/.tmp/npm-cache"
$env:BUN_INSTALL_CACHE_DIR = "$workspace/.tmp/bun-cache"
$env:TEMP = "$workspace/.tmp"
diff --git a/scenes/toolchain.json b/scenes/toolchain.json
index 4dffda87..93c67d40 100644
--- a/scenes/toolchain.json
+++ b/scenes/toolchain.json
@@ -1,5 +1,5 @@
{
"bun": "1.4.2",
- "node": "22.23.2",
- "npm": "12.0.2"
+ "node": "22.23.3",
+ "npm": "12.2.0"
}
diff --git a/scenes/types/node-runtime.d.ts b/scenes/types/node-runtime.d.ts
index b18c11a6..ba34ee9f 100644
--- a/scenes/types/node-runtime.d.ts
+++ b/scenes/types/node-runtime.d.ts
@@ -1,9 +1,17 @@
// Small declarations for the Node-only staging/build surface; no extra installed type package.
+declare namespace NodeJS {
+ type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd';
+ interface ProcessEnv { [key: string]: string | undefined }
+}
+declare module 'node:module' {
+ export function createRequire(filename: string | URL): { (id: string): unknown; resolve(id: string): string };
+}
declare module 'node:crypto' {
interface Hash { update(data: Uint8Array | string): Hash; digest(encoding: 'hex'): string }
export function createHash(algorithm: string): Hash;
}
declare module 'node:fs' {
+ export const constants: { F_OK: number; X_OK: number };
interface Dirent { name: string; isDirectory(): boolean; isSymbolicLink(): boolean; isFile(): boolean }
interface Stats { size: number; isDirectory(): boolean; isSymbolicLink(): boolean; isFile(): boolean }
export function readFileSync(path: string | URL): Uint8Array;
@@ -22,6 +30,8 @@ declare module 'node:fs' {
export function rmSync(path: string | URL, options?: { recursive?: boolean; force?: boolean }): void;
}
declare module 'node:path' {
+ export const posix: { join(...paths: string[]): string };
+ export const win32: { join(...paths: string[]): string };
export const sep: string;
export function resolve(...paths: string[]): string;
export function join(...paths: string[]): string;
@@ -41,6 +51,7 @@ declare module 'node:assert/strict' {
export default assert;
}
declare module 'node:fs/promises' {
+ export function access(path: string | URL, mode?: number): Promise<void>;
export function mkdir(path: string | URL, options?: { recursive?: boolean }): Promise<string | undefined>;
export function mkdtemp(prefix: string): Promise<string>;
export function readFile(path: string | URL): Promise<Uint8Array>;
@@ -49,7 +60,7 @@ declare module 'node:fs/promises' {
export function readdir(path: string | URL): Promise<string[]>;
export function realpath(path: string | URL): Promise<string>;
export function stat(path: string | URL): Promise<{ size: number; isFile(): boolean; isDirectory(): boolean }>;
- export function rm(path: string | URL, options?: { recursive?: boolean; force?: boolean }): Promise<void>;
+ export function rm(path: string | URL, options?: { recursive?: boolean; force?: boolean; maxRetries?: number; retryDelay?: number }): Promise<void>;
}
declare module 'node:http' {
interface Server {
@@ -77,7 +88,7 @@ declare module 'node:child_process' {
}): ChildProcess;
}
-declare const process: { cwd(): string; pid: number; execPath: string; env: Record<string, string | undefined>; argv: string[]; exitCode?: number; platform: string; version: string; exit(code?: number): never };
+declare const process: { cwd(): string; pid: number; execPath: string; env: NodeJS.ProcessEnv; argv: string[]; exitCode?: number; platform: NodeJS.Platform; version: string; exit(code?: number): never };
declare module 'node:os' {
interface CpuInfo { model: string; times: { user: number; nice: number; sys: number; idle: number; irq: number } }
export function cpus(): CpuInfo[];
diff --git a/scripts/check-toolchain.test.mjs b/scripts/check-toolchain.test.mjs
index 7666354d..32e781eb 100644
--- a/scripts/check-toolchain.test.mjs
+++ b/scripts/check-toolchain.test.mjs
@@ -95,7 +95,7 @@ test('the staged copy of this repository passes, so every rule below can fail',
try {
const { status, out } = run(root);
expect(status, out).toBe(0);
- expect(out.trim()).toBe('Toolchain metadata: Bun 1.4.2, Node 22.23.2, npm 12.0.2');
+ expect(out.trim()).toBe('Toolchain metadata: Bun 1.4.2, Node 22.23.3, npm 12.2.0');
} finally {
await rm(root, { recursive: true, force: true });
}
@@ -106,7 +106,7 @@ test('maintainer pins do not become consumer Bun or npm requirements', async ()
'package.json',
(text) => {
const pkg = JSON.parse(text);
- pkg.engines.npm = '12.0.2';
+ pkg.engines.npm = '12.2.0';
return JSON.stringify(pkg);
},
'engines must contain only the end-user Node range',
@@ -126,7 +126,7 @@ test('a stale consumer floor is named independently of maintainer pins', async (
'package.json',
(text) => {
const pkg = JSON.parse(text);
- pkg.engines.node = '22.23.2';
+ pkg.engines.node = '22.23.3';
return JSON.stringify(pkg);
},
'engines.node must match the runtime compatibility contract',
@@ -147,7 +147,7 @@ test('prose that tells a contributor to install the wrong Bun is named', async (
test('three drifting in the site manifest is named, with the manifest', async () => {
await rejects(
'site/package.json',
- (text) => text.replace('"three": "0.186.0"', '"three": "0.185.1"'),
+ (text) => text.replace('"three": "0.186.1"', '"three": "0.185.1"'),
'site/package.json=0.185.1',
);
});
@@ -155,7 +155,7 @@ test('three drifting in the site manifest is named, with the manifest', async ()
test('three drifting in the render service is named, with the manifest', async () => {
await rejects(
'render-service/package.json',
- (text) => text.replace('"three": "0.186.0"', '"three": "0.187.0"'),
+ (text) => text.replace('"three": "0.186.1"', '"three": "0.187.0"'),
'render-service/package.json=0.187.0',
);
});
diff --git a/scripts/qualify-full-optimizer.mjs b/scripts/qualify-full-optimizer.mjs
new file mode 100644
index 00000000..eb529b73
--- /dev/null
+++ b/scripts/qualify-full-optimizer.mjs
@@ -0,0 +1,386 @@
+/** Offline full-mode corpus gate. Run with Bun; never modifies source assets. */
+import { createHash } from 'node:crypto';
+import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
+import { dirname, join, relative, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import * as THREE from 'three';
+import { unpartition } from '@gltf-transform/functions';
+import { createGltfIO, MSFT_LOD } from '../src/gltf-io.ts';
+import { findRigidBoundaries } from '../src/rigid-merge.ts';
+import { optimizeGlbBytes, renderGLBInProcess } from '../src/render.ts';
+import { runtimeBuildIdentity } from './build-runtime.mjs';
+
+const hash = (value) => createHash('sha256').update(value).digest('hex');
+const rounded = (values) => Array.from(values, (value) => Math.round(value * 1e10) / 1e10);
+const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+/** The released terrain uses gltfpack/meshopt, while the core optimizer has no
+ * injected decoder. Exercise a decoded in-memory derivative and identify it in
+ * the receipt; this does not imply direct compressed-input support in the engine.
+ */
+export async function prepareCorpusInput(bytes) {
+ const io = createGltfIO();
+ const json = (await io.binaryToJSON(bytes)).json;
+ const compressed = ['EXT_meshopt_compression', 'KHR_meshopt_compression'];
+ if (!json.extensionsUsed?.some((name) => compressed.includes(name))) return bytes;
+ const { MeshoptDecoder } = await import('three/examples/jsm/libs/meshopt_decoder.module.js');
+ await MeshoptDecoder.ready;
+ io.registerDependencies({ 'meshopt.decoder': MeshoptDecoder });
+ const document = await io.readBinary(bytes);
+ for (const extension of document.getRoot().listExtensionsUsed())
+ if (compressed.includes(extension.extensionName)) extension.dispose();
+ await document.transform(unpartition());
+ return io.writeBinary(document);
+}
+
+function pathsOf(doc) {
+ const paths = new Map();
+ const visit = (node, path) => {
+ if (paths.has(node)) return;
+ paths.set(node, path);
+ node.listChildren().forEach((child, index) => {
+ visit(child, `${path}/${index}:${child.getName()}`);
+ });
+ };
+ doc
+ .getRoot()
+ .listScenes()
+ .forEach((scene, si) => {
+ scene.listChildren().forEach((node, ni) => {
+ visit(node, `scene:${si}/${ni}:${node.getName()}`);
+ });
+ });
+ // Lower LOD levels are deliberately off-scene, but must still be checked.
+ for (const node of doc.getRoot().listNodes()) {
+ if (paths.has(node) || node.getParentNode()) continue;
+ visit(node, `off:${paths.size}:${node.getName()}`);
+ }
+ return paths;
+}
+
+function materialEvidence(material) {
+ if (!material) return null;
+ const slots = ['BaseColor', 'MetallicRoughness', 'Normal', 'Occlusion', 'Emissive'];
+ return {
+ name: material.getName(),
+ extras: material.getExtras(),
+ baseColor: material.getBaseColorFactor(),
+ metallic: material.getMetallicFactor(),
+ roughness: material.getRoughnessFactor(),
+ emissive: material.getEmissiveFactor(),
+ normalScale: material.getNormalScale(),
+ occlusionStrength: material.getOcclusionStrength(),
+ alphaMode: material.getAlphaMode(),
+ alphaCutoff: material.getAlphaCutoff(),
+ doubleSided: material.getDoubleSided(),
+ extensions: material
+ .listExtensions()
+ .map((extension) => extension.extensionName)
+ .sort(),
+ textures: slots.map((slot) => {
+ const texture = material[`get${slot}Texture`]();
+ const info = material[`get${slot}TextureInfo`]();
+ if (!texture) return null;
+ const transform = info.getExtension('KHR_texture_transform');
+ return {
+ bytes: hash(texture.getImage() ?? new Uint8Array()),
+ mime: texture.getMimeType(),
+ texCoord: info.getTexCoord(),
+ mag: info.getMagFilter(),
+ min: info.getMinFilter(),
+ s: info.getWrapS(),
+ t: info.getWrapT(),
+ transform: transform
+ ? [
+ transform.getOffset(),
+ transform.getScale(),
+ transform.getRotation(),
+ transform.getTexCoord(),
+ ]
+ : null,
+ };
+ }),
+ };
+}
+
+/** Aggregate world-space evidence, independent of merged topology and vertex indexing.
+ * Includes off-scene LODs, named hierarchy, animation channels and material bindings.
+ * This is a structural regression gate, not a pixel or destination-appearance test.
+ */
+export function optimizerEvidence(doc) {
+ const root = doc.getRoot();
+ const paths = pathsOf(doc);
+ const boundaries = findRigidBoundaries(doc, new Set());
+ const geometry = {};
+ const materials = new Set();
+ for (const node of root.listNodes()) {
+ let anchor = node;
+ while (!boundaries.has(anchor) && anchor.getParentNode()) anchor = anchor.getParentNode();
+ const group = `${paths.get(anchor)}:${boundaries.has(node) ? 'own' : 'descendants'}`;
+ const world = new THREE.Matrix4().fromArray(node.getWorldMatrix());
+ const normalMatrix = new THREE.Matrix3().getNormalMatrix(world);
+ const linear = new THREE.Matrix3().setFromMatrix4(world);
+ const facing = Math.sign(world.determinant());
+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
+ const position = primitive.getAttribute('POSITION');
+ if (!position) throw new Error(`No POSITION: ${paths.get(node)}`);
+ const material = JSON.stringify(materialEvidence(primitive.getMaterial()));
+ materials.add(material);
+ const semantics = primitive.listSemantics().sort();
+ const key = `${group}|${hash(material)}|${primitive.getMode()}|${semantics.join(',')}`;
+ geometry[key] ??= {
+ elements: 0,
+ low: [Infinity, Infinity, Infinity],
+ high: [-Infinity, -Infinity, -Infinity],
+ moments: [],
+ absolute: [],
+ face: [0, 0, 0, 0, 0, 0],
+ faceAbsolute: [0, 0, 0, 0, 0, 0],
+ };
+ const record = geometry[key];
+ const indices = primitive.getIndices();
+ const count = indices?.getCount() ?? position.getCount();
+ const at = (i) => indices?.getScalar(i) ?? i;
+ const point = (i) =>
+ new THREE.Vector3().fromArray(position.getElement(i, [])).applyMatrix4(world);
+ for (let i = 0; i < count; i++) {
+ const index = at(i);
+ const p = point(index);
+ [p.x, p.y, p.z].forEach((value, axis) => {
+ record.low[axis] = Math.min(record.low[axis], value);
+ record.high[axis] = Math.max(record.high[axis], value);
+ });
+ const values = [];
+ for (const semantic of semantics) {
+ const value = primitive.getAttribute(semantic).getElement(index, []);
+ if (semantic === 'POSITION') p.toArray(value);
+ if (semantic === 'NORMAL')
+ new THREE.Vector3()
+ .fromArray(value)
+ .applyMatrix3(normalMatrix)
+ .normalize()
+ .toArray(value);
+ if (semantic === 'TANGENT')
+ new THREE.Vector3().fromArray(value).applyMatrix3(linear).normalize().toArray(value);
+ values.push(...value);
+ }
+ for (const [vi, value] of values.entries()) {
+ if (!Number.isFinite(value)) throw new Error(`Non-finite attribute: ${paths.get(node)}`);
+ // First, second and third moments catch same-bounds edits and attribute changes.
+ for (let power = 1; power <= 3; power++) {
+ const mi = vi * 3 + power - 1;
+ const term = value ** power;
+ record.moments[mi] = (record.moments[mi] ?? 0) + term;
+ record.absolute[mi] = (record.absolute[mi] ?? 0) + Math.abs(term);
+ }
+ }
+ }
+ record.elements += count;
+ if (primitive.getMode() === 4) {
+ for (let i = 0; i + 2 < count; i += 3) {
+ const [a, b, c] = [point(at(i)), point(at(i + 1)), point(at(i + 2))];
+ const face = b.clone().sub(a).cross(c.clone().sub(a)).multiplyScalar(facing);
+ const area = face.length() / 2;
+ const center = a.clone().add(b).add(c).divideScalar(3);
+ const normal = primitive.getAttribute('NORMAL');
+ // Weight orientation by area: zero-area pole triangles can gain a tiny
+ // signed cross product after Float32 baking without changing a surface.
+ const agreement =
+ normal && area > 0
+ ? area *
+ face
+ .clone()
+ .normalize()
+ .dot(
+ new THREE.Vector3()
+ .fromArray(normal.getElement(at(i), []))
+ .applyMatrix3(normalMatrix)
+ .normalize(),
+ )
+ : 0;
+ const values = [
+ area,
+ area * center.x,
+ area * center.y,
+ area * center.z,
+ (facing * a.dot(b.clone().cross(c))) / 6,
+ agreement,
+ ];
+ values.forEach((value, j) => {
+ record.face[j] += value;
+ record.faceAbsolute[j] += Math.abs(value);
+ });
+ }
+ }
+ }
+ }
+ return {
+ nodes: [...paths]
+ .map(([node, path]) => ({
+ path,
+ matrix: rounded(node.getMatrix()),
+ extras: node.getExtras(),
+ weights: node.getWeights(),
+ extensions: node
+ .listExtensions()
+ .map((extension) => extension.extensionName)
+ .sort(),
+ lod:
+ node
+ .getExtension(MSFT_LOD)
+ ?.listLevels()
+ .map((level) => paths.get(level) ?? `material:${level.getName()}`) ?? [],
+ visibility: node.getExtension('KHR_node_visibility')?.getVisible() ?? true,
+ skin: node.getSkin()
+ ? {
+ joints: node
+ .getSkin()
+ .listJoints()
+ .map((joint) => paths.get(joint)),
+ inverseBindMatrices: rounded(
+ node.getSkin().getInverseBindMatrices()?.getArray() ?? [],
+ ),
+ }
+ : null,
+ }))
+ .sort((a, b) => a.path.localeCompare(b.path)),
+ animations: root.listAnimations().map((animation) => ({
+ name: animation.getName(),
+ channels: animation.listChannels().map((channel) => ({
+ target: paths.get(channel.getTargetNode()),
+ path: channel.getTargetPath(),
+ interpolation: channel.getSampler().getInterpolation(),
+ input: rounded(channel.getSampler().getInput().getArray()),
+ output: rounded(channel.getSampler().getOutput().getArray()),
+ })),
+ })),
+ materials: [...materials].sort(),
+ geometry,
+ };
+}
+
+export function compareOptimizerEvidence(before, after) {
+ const issues = [];
+ for (const field of ['nodes', 'animations', 'materials'])
+ if (JSON.stringify(before[field]) !== JSON.stringify(after[field])) issues.push(field);
+ const keys = Object.keys(before.geometry).sort();
+ if (JSON.stringify(keys) !== JSON.stringify(Object.keys(after.geometry).sort()))
+ issues.push('geometry.groups');
+ for (const key of keys) {
+ const a = before.geometry[key];
+ const b = after.geometry[key];
+ if (!b) continue;
+ if (a.elements !== b.elements) issues.push(`geometry.elements:${key}`);
+ for (const field of ['low', 'high', 'moments', 'face']) {
+ const scale =
+ field === 'moments'
+ ? a.absolute
+ : field === 'face'
+ ? a.faceAbsolute
+ : a.high.map((v, i) => Math.max(Math.abs(v), Math.abs(a.low[i]), v - a.low[i]));
+ if (
+ a[field].length !== b[field].length ||
+ a[field].some(
+ (v, i) =>
+ !Number.isFinite(b[field][i]) ||
+ Math.abs(v - b[field][i]) > 1e-5 * Math.max(1, scale[i]),
+ )
+ )
+ issues.push(`geometry.${field}:${key}`);
+ }
+ }
+ return issues;
+}
+
+async function filesUnder(directory, suffix) {
+ const output = [];
+ for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) =>
+ a.name.localeCompare(b.name),
+ )) {
+ const path = join(directory, entry.name);
+ if (entry.isDirectory()) output.push(...(await filesUnder(path, suffix)));
+ else if (entry.isFile() && entry.name.endsWith(suffix)) output.push(path);
+ }
+ return output;
+}
+
+async function main() {
+ const args = process.argv.slice(2);
+ const value = (flag, fallback) => (args.includes(flag) ? args[args.indexOf(flag) + 1] : fallback);
+ const troy = value('--troy', null);
+ const output = resolve(value('--out', 'tmp/full-optimizer-corpus/results.json'));
+ const inputs = [
+ ...(await filesUnder(join(repo, 'examples'), '.kiln.js')),
+ ...(await filesUnder(join(repo, 'scenes/.cache/site-inputs'), '.glb')),
+ ...(troy ? await filesUnder(resolve(troy), 'asset.glb') : []),
+ ].filter((file) => file.includes(value('--filter', '')));
+ const limit = Number(value('--limit', '0'));
+ if (limit > 0) inputs.splice(limit);
+ if (!inputs.length) throw new Error('No corpus inputs found');
+ const io = createGltfIO();
+ const results = [];
+ const identity = await runtimeBuildIdentity(repo);
+ await mkdir(dirname(output), { recursive: true });
+ for (const file of inputs) {
+ const result = { file: relative(repo, file) };
+ try {
+ const source = await readFile(file);
+ result.sourceSha256 = hash(source);
+ const original = file.endsWith('.kiln.js')
+ ? (await renderGLBInProcess(source.toString(), { optimize: 'off', instance: 'off' })).glb
+ : source;
+ const prepared = await prepareCorpusInput(original);
+ result.inputPreparation = prepared === original ? 'none' : 'meshopt-decoded-derivative';
+ result.preparedInputSha256 = hash(prepared);
+ const baseline = await optimizeGlbBytes(prepared, { mode: 'palette', instance: 'off' });
+ const full = await optimizeGlbBytes(prepared, { mode: 'full', instance: 'off' });
+ const repeat = await optimizeGlbBytes(prepared, { mode: 'full', instance: 'off' });
+ if (!baseline || !full || !repeat)
+ throw new Error('An optimization pass returned no artifact');
+ const changes = compareOptimizerEvidence(
+ optimizerEvidence(await io.readBinary(baseline.bytes)),
+ optimizerEvidence(await io.readBinary(full.bytes)),
+ );
+ Object.assign(result, {
+ bytesBefore: original.length,
+ bytesAfter: full.bytes.length,
+ artifactSha256: hash(full.bytes),
+ deterministic: hash(full.bytes) === hash(repeat.bytes),
+ changes,
+ validationErrors: full.gltfValidation.issues.numErrors,
+ summary: full.summary,
+ warnings: full.warnings,
+ });
+ if (changes.length || !result.deterministic || result.validationErrors)
+ result.error = 'Corpus invariant failed';
+ } catch (error) {
+ result.error = error instanceof Error ? error.message : String(error);
+ }
+ results.push(result);
+ console.log(
+ `${result.error ? 'FAIL' : 'PASS'} ${result.file}${result.error ? `: ${result.error}` : ''}`,
+ );
+ await writeFile(
+ output,
+ `${JSON.stringify({ schemaVersion: 1, identity, scope: 'Palette versus full: world geometry aggregates, hierarchy, animation, LOD, material bindings, deterministic bytes and Khronos errors. No saved asset mutation or GPU/appearance acceptance.', troyIncluded: Boolean(troy), expectedInputs: inputs.length, completed: results.length, failures: results.filter((row) => row.error).length, results }, null, 2)}\n`,
+ );
+ }
+ const finalIdentity = await runtimeBuildIdentity(repo);
+ const stable = finalIdentity.identity === identity.identity;
+ const report = JSON.parse(await readFile(output, 'utf8'));
+ Object.assign(report, {
+ finalIdentity,
+ sourceStable: stable,
+ gateSha256: hash(await readFile(fileURLToPath(import.meta.url))),
+ });
+ await writeFile(output, `${JSON.stringify(report, null, 2)}\n`);
+ if (!stable) {
+ console.error(
+ 'Runtime source/dependencies changed during qualification; rerun on a stable tree.',
+ );
+ process.exitCode = 1;
+ }
+ if (results.some((result) => result.error)) process.exitCode = 1;
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main();
diff --git a/scripts/qualify-full-optimizer.test.mjs b/scripts/qualify-full-optimizer.test.mjs
new file mode 100644
index 00000000..db013a7f
--- /dev/null
+++ b/scripts/qualify-full-optimizer.test.mjs
@@ -0,0 +1,121 @@
+import { describe, expect, test } from 'bun:test';
+import { Document } from '@gltf-transform/core';
+import { createGltfIO, MSFT_LOD, MSFTLod } from '../src/gltf-io';
+import { optimizeGlbBytes } from '../src/render';
+import { compareOptimizerEvidence, optimizerEvidence } from './qualify-full-optimizer.mjs';
+
+function fixture() {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const mat = doc.createMaterial('paint');
+ const scene = doc.createScene();
+ const pivot = doc.createNode('Joint_Door');
+ scene.addChild(pivot);
+ const parts = [0, 1].map((index) => {
+ const position = doc
+ .createAccessor()
+ .setBuffer(buffer)
+ .setType('VEC3')
+ .setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]));
+ const mesh = doc
+ .createMesh()
+ .addPrimitive(doc.createPrimitive().setMaterial(mat).setAttribute('POSITION', position));
+ const node = doc
+ .createNode(`Part_${index}`)
+ .setTranslation([index * 2, 0, 0])
+ .setMesh(mesh);
+ pivot.addChild(node);
+ return node;
+ });
+ return { doc, pivot, parts };
+}
+
+describe('full optimizer corpus evidence', () => {
+ test('accepts intentional topology changes while preserving world geometry and named pivots', async () => {
+ const { doc } = fixture();
+ const io = createGltfIO();
+ const result = await optimizeGlbBytes(await io.writeBinary(doc), {
+ mode: 'full',
+ instance: 'off',
+ });
+ expect(result.summary.drawsAfter).toBe(1);
+ expect(
+ compareOptimizerEvidence(
+ optimizerEvidence(doc),
+ optimizerEvidence(await io.readBinary(result.bytes)),
+ ),
+ ).toEqual([]);
+ });
+
+ test('detects a same-bounds geometry change, material change and named transform change', () => {
+ const { doc, parts, pivot } = fixture();
+ const before = optimizerEvidence(doc);
+ const pos = parts[0].getMesh().listPrimitives()[0].getAttribute('POSITION');
+ pos.setElement(1, [0.5, 0, 0]);
+ expect(
+ compareOptimizerEvidence(before, optimizerEvidence(doc)).some((item) =>
+ item.startsWith('geometry'),
+ ),
+ ).toBe(true);
+ pos.setElement(1, [1, 0, 0]);
+ doc.getRoot().listMaterials()[0].setRoughnessFactor(0.25);
+ expect(compareOptimizerEvidence(before, optimizerEvidence(doc))).toContain('materials');
+ doc.getRoot().listMaterials()[0].setRoughnessFactor(1);
+ pivot.setTranslation([1, 0, 0]);
+ expect(compareOptimizerEvidence(before, optimizerEvidence(doc))).toContain('nodes');
+ });
+
+ test('checks off-scene LOD geometry and references with the engine IO', async () => {
+ const { doc, parts } = fixture();
+ const low = parts[1];
+ low.getParentNode().removeChild(low);
+ parts[0].setExtension(MSFT_LOD, doc.createExtension(MSFTLod).createLod().addLevel(low));
+ const io = createGltfIO();
+ const reloaded = await io.readBinary(await io.writeBinary(doc));
+ const before = optimizerEvidence(reloaded);
+ expect(compareOptimizerEvidence(optimizerEvidence(doc), before)).toEqual([]);
+ const lod = reloaded
+ .getRoot()
+ .listNodes()
+ .find((node) => node.getName() === 'Part_0')
+ .getExtension(MSFT_LOD);
+ lod
+ .listLevels()[0]
+ .getMesh()
+ .listPrimitives()[0]
+ .getAttribute('POSITION')
+ .setElement(1, [0.25, 0, 0]);
+ expect(
+ compareOptimizerEvidence(before, optimizerEvidence(reloaded)).some((item) =>
+ item.startsWith('geometry'),
+ ),
+ ).toBe(true);
+ });
+
+ test('detects flipped visible winding even when vertex moments and bounds are unchanged', () => {
+ const { doc, parts } = fixture();
+ const buffer = doc.getRoot().listBuffers()[0];
+ for (const node of parts) {
+ const normal = doc
+ .createAccessor()
+ .setBuffer(buffer)
+ .setType('VEC3')
+ .setArray(new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]));
+ node.getMesh().listPrimitives()[0].setAttribute('NORMAL', normal);
+ }
+ const before = optimizerEvidence(doc);
+ parts[0]
+ .getMesh()
+ .listPrimitives()[0]
+ .setIndices(
+ doc
+ .createAccessor()
+ .setBuffer(buffer)
+ .setType('SCALAR')
+ .setArray(new Uint16Array([0, 2, 1])),
+ );
+ const changes = compareOptimizerEvidence(before, optimizerEvidence(doc));
+ expect(changes).toHaveLength(1);
+ expect(changes[0]).toStartWith('geometry.face:');
+ });
+});
diff --git a/scripts/reliability.test.mjs b/scripts/reliability.test.mjs
index a760c03e..246af62b 100644
--- a/scripts/reliability.test.mjs
+++ b/scripts/reliability.test.mjs
@@ -22,8 +22,8 @@ describe('repository reliability contracts', () => {
expect(pkg.engines).toEqual({ node: '^20.15.0 || >=22.2.0' });
expect(await readJson('toolchain.json')).toEqual({
bun: '1.4.2',
- node: '22.23.2',
- npm: '12.0.2',
+ node: '22.23.3',
+ npm: '12.2.0',
});
});
@@ -36,7 +36,7 @@ describe('repository reliability contracts', () => {
expect(pkg.scripts['check:toolchain']).toBe('bun scripts/check-toolchain.mjs');
expect(result.status, result.stderr || result.stdout).toBe(0);
- expect(result.stdout.trim()).toBe('Toolchain metadata: Bun 1.4.2, Node 22.23.2, npm 12.0.2');
+ expect(result.stdout.trim()).toBe('Toolchain metadata: Bun 1.4.2, Node 22.23.3, npm 12.2.0');
});
test('coverage is measured, ratcheted, and retained by CI', async () => {
diff --git a/site/DEPLOYMENT.md b/site/DEPLOYMENT.md
index 1660fee2..8ff8bd79 100644
--- a/site/DEPLOYMENT.md
+++ b/site/DEPLOYMENT.md
@@ -1,10 +1,63 @@
# Cloudflare deployment
+**Release direction, 3 October:** Owner confirmed the farmer fix, could not reproduce
+the water jump locally, and authorized commit, main integration and deployment after
+settling the focused performance findings. See the [release disposition](../docs/reviews/2026-10-03-release-disposition.md).
+The upload inventory now contains 486 entries with zero problems. Deploy only after
+required CI checks and a clean-main build pass. Historical performance failures remain
+recorded; no 108-minute audit or npm publication is required.
+
The production site is a direct upload to the `kilnstudio` Cloudflare Pages project,
whose production branch is `production`. The code is maintained on GitHub `main`.
GitHub Actions validates the engine and website; it does not deploy the site.
Package publication is separate and remains deferred to v1.0.
+## Current hub status (3 October 2026)
+
+The migration is complete: `kilnstudio.tools` is served by this Pages project.
+Public build-info and authenticated Pages records identify production commit
+`b1ac6ee`, deployment `33c716c7-16e5-46c6-93bf-f2260f0082be`, with packs enabled.
+The optimized Farm is live. Golden Gate g9 and Foundry ff3-review2 remain the sealed
+production inputs. Local candidate delivery pins are prepared and staged through the normal verified
+archive path. Read `src/data/scene-inputs.json` and `src/data/scene-packs.json` for
+the exact current IDs and hashes; production remains unchanged.
+
+Existing OAuth can read the Pages project and `kiln-assets` R2 bucket. The hub has
+no permanent Wrangler binary or PowerShell on PATH; read-only access was verified
+with this exact-version invocation:
+
+```sh
+npm exec --yes [email protected] -- wrangler whoami
+```
+
+The portable Node wrapper implements artifact-manifest verification immediately
+before upload. Its offline fixture tests and dirty-checkout refusal are qualified;
+no production upload was used as a test. Authentication has been verified. Use
+browser OAuth separately if access expires; never record token contents.
+
+The [alignment plan](../docs/plans/2026-10-02-core-scenes-site-alignment.md) and
+[backlog](../docs/backlog.md) track the current candidate and remaining work. Local
+core/scene/site changes are uncommitted. Preserve the exact artifact hash on every
+static, download, scene-control, viewer, keyboard and accessibility receipt.
+Changed runtime bytes require matching new evidence; prior checks do not imply
+owner acceptance, physical-device qualification or a clean production release.
+
+Historical candidate receipts remain under `.cache/alignment-preliminary/`,
+`.cache/alignment-before-migration/`, `.cache/alignment-release-docs/` and subsequent
+alignment directories. The code1 artifact `f0e49fbc…` passed its recorded static,
+download, lifecycle, viewer and accessibility checks; later UI integration found
+focus, menu stacking and page-layout fixes. Its receipts retain that earlier
+scope. See the maintained backlog for the final candidate disposition rather than
+relabeling an old artifact as current.
+
+Before release, inspect the actual `dist/build-info.json` and
+`dist/artifact-files.json`, verify all three scene releases/chunks and all three
+upload manifests, and require the final candidate's qualification receipts.
+The upload-set command validates without uploading. The deploy dry run must
+refuse an uncommitted checkout. The initial alignment checkpoints preceded release authorization; record the actual final commit/deployment in release receipts.
+
+## Build and deploy contract
+
Use the versions in `toolchain.json`. From the repository root:
```sh
@@ -32,20 +85,83 @@ independently verifies each model, data file and runtime chunk.
The authoritative R2 upload sets are `mirror-manifest.json`, `upload-manifest.json`
and `scene-inputs.json`. Preserve existing versioned objects; verify each upload
against its declared SHA-256 and check the public download URLs before deployment.
+From `site/`, `node scripts/upload-set.mjs` validates and summarizes all three
+manifests, including scene archives, without uploading. Duplicate paths or
+inconsistent bases fail the check; extracted GLBs must still name a pinned mirror
+archive.
After authorization, merge through the required main-branch checks and build again
from clean `main`. Review the result, then use:
-```powershell
-pwsh -File site/scripts/deploy.ps1 -DryRun
-pwsh -File site/scripts/deploy.ps1
+```sh
+node site/scripts/deploy.mjs --dry-run
+node site/scripts/deploy.mjs
```
-The script rejects a dirty checkout, a build from another commit, a build made with
-packs disabled, and Pages file-limit violations. Wrangler must already be installed
-and authenticated. It does not create credentials or change DNS.
+Run these commands from the repository root. `--site DIR` selects another site
+directory; `--project-name NAME` defaults to `kilnstudio`. The PowerShell entrypoint
+remains a thin compatibility wrapper for `-Site`, `-ProjectName`, `-Wrangler` and
+`-DryRun`. The former `-AllowPacksOff` bypass now fails explicitly: production
+requires `KILN_SITE_PACKS=1`.
+
+The script rejects a dirty checkout (including untracked files anywhere in the
+repository), a build from another commit, a build recorded as dirty, and disabled
+packs. It verifies the artifact-manifest digest in `build-info.json`, its file count
+and byte total, every file's size and SHA-256, and exact directory membership.
+Only `build-info.json` and `artifact-files.json` are excluded from the manifest,
+matching the build's receipt format; both still count toward the 20,000-file and
+25 MiB per-file limits. Missing, additional or altered files, symlinks, unsafe
+manifest paths and duplicate entries fail the preflight.
+
+This is a static-site deployment boundary: `site/functions`, `dist/functions`,
+`dist/_worker.js` (file or directory) and `dist/_routes.json` are refused, even if
+ignored by Git or listed in a receipt. Wrangler would otherwise compile Functions
+outside the verified output or rebundle worker imports. A future server-side
+deployment needs its own reviewed artifact contract.
+
+Dry run performs these checks offline and does not invoke npm or Wrangler, log in,
+or upload. A deployment uses the exact `[email protected]` npm package, invoking
+npm's JavaScript through Node without a command shell. npm may prepare that version
+in its cache. An optional `--wrangler EXECUTABLE` must report exactly `4.147.0`;
+Windows `.cmd` and `.bat` wrappers are unsupported, so use the default Node/npm
+invocation there. Existing Cloudflare authentication is required. After Wrangler
+preparation, the script repeats all file and Git checks and rejects changed
+receipts before uploading to branch `production` with the full HEAD commit.
+Upload output is streamed with stdin closed, so Wrangler cannot prompt to create a
+missing project or start interactive authentication. The selected project and branch
+remain explicit. The script never invokes login, creates a project, uploads R2
+objects or changes DNS.
+
+## Rollback after an authorized release
+
+Retain deployment `33c716c7-16e5-46c6-93bf-f2260f0082be` in `kilnstudio` as the
+recorded rollback target for this candidate: production commit `b1ac6ee`, Farm
+`r36-local-review`, Golden Gate `g9` and Foundry `ff3-review2`. The 3 October
+08:08:58 UTC public readback still matches artifact manifest
+`5ecbbe7673348989a85ef2beb2613e5f27f92c9449cec67690f0791288ab7d15`
+(2,727 inventoried files / 200,950,082 bytes). Preserve that build-info, manifest
+and readback receipt with the new deployment's records; this readback does not
+independently qualify every public file.
+
+Perform a rollback only when authorized. Immediately beforehand, verify that the
+target still exists in the correct project and is a successful production
+deployment. Cloudflare excludes preview deployments from rollback targets. In the
+Pages project's **Deployments** list, open the target's actions menu, select
+**Rollback to this deployment**, and confirm the exact target. This is the
+[documented Cloudflare Pages rollback procedure](https://developers.cloudflare.com/pages/configuration/rollbacks/);
+the local deploy wrapper does not implement rollback.
+
+Afterward, verify the production deployment ID and public `build-info.json`, the
+artifact-manifest digest, restored scene runtime/pack hashes, mapped downloads
+and gallery/scene entry, controls and exit flows over HTTPS. Record the result and
+both deployment IDs. Keep all old and new versioned R2 objects unchanged: restoring
+Pages does not require deleting the new `g9-code3` or `ff3-review2-code3` objects.
+No rollback, upload or deployment has been performed during this preparation.
+
+## Historical initial migration
-For the initial migration, first create the Pages project, deploy and verify its
+The following migration procedure is historical; do not repeat it for a routine
+release. For the initial migration, first create the Pages project, deploy and verify its
`pages.dev` address, then associate `kilnstudio.tools` as a custom domain and replace
its GitHub Pages DNS records with the Pages target. Preserve `assets`, `app`, `mcp`
and other unrelated services. Retire GitHub Pages only after the new apex is verified.
diff --git a/site/README.md b/site/README.md
index d81f8b5e..27ca6dde 100644
--- a/site/README.md
+++ b/site/README.md
@@ -1,12 +1,46 @@
# Kiln website
-## v0.9 Cloudflare rollout, 2026-10-01
+## Current delivery and alignment, 2026-10-03
+
+The site runs on Cloudflare Pages direct upload: project `kilnstudio`, production
+branch `production`, domain `kilnstudio.tools`. Public assets use the `kiln-assets`
+R2 bucket. GitHub checks validate source; they do not deploy it. Public build-info
+and the authenticated deployment list agree on production commit `b1ac6ee`, clean
+with packs enabled, deployment `33c716c7-16e5-46c6-93bf-f2260f0082be`. Source main
+is `ac8456c`; those are different checkpoints.
+
+The [alignment plan](../docs/plans/2026-10-02-core-scenes-site-alignment.md) and
+[backlog](../docs/backlog.md) govern upcoming core, assets, scenes and site work.
+Troy is deferred. The portable Node deployment wrapper is implemented and tested,
+including final artifact-hash verification; existing OAuth has been verified on the
+Linux hub. Follow [DEPLOYMENT.md](DEPLOYMENT.md) for the contract. No deployment was
+made by this alignment work.
+
+The local launch candidate and exact runtime archives are rebuilt as fixes are
+qualified. Use the backlog for current controls, accessibility and performance
+results and remaining release boundaries; earlier artifacts retain their
+own evidence. The site records its exact served bytes in `build-info.json` and
+`artifact-files.json`. A successful local build is not production approval.
+
+Current asset catalogs distinguish revision acceptance: Farm's 23 exact asset picks
+are owner-accepted; the six Vehicles r4 children remain candidates even though
+their earlier r2 parents were accepted. Foundry has 62 models (55 candidates and
+seven accepted) with internally consistent source/download pins. The large #131
+optimization changed scene runtime code, not those model files. Review status does
+not imply a newly discovered defect. See the alignment plan's complete asset inventory.
+
+All checkpoint sections below are historical. Their authorization, preview labels,
+local candidates and test counts describe those dates; they do not override the
+current plan, manifests or a new release's acceptance requirements.
+
+## Historical v0.9 Cloudflare rollout, 2026-10-01
The owner authorized integration to main and site deployment. Current inputs are Farm
r36-local-review, Golden Gate g9 and Foundry ff3-review2. The engine, site and maintained
scene sources now share this repository. Follow [DEPLOYMENT.md](DEPLOYMENT.md) for a
clean build, pinned assets, exact-commit deployment and live verification. Package
-publication remains deferred to v1.0. Foundry retains its in-production preview status.
+publication remained deferred to v1.0. The Foundry preview label in this checkpoint
+was subsequently removed; consult current site data for presentation status.
The records below are historical checkpoints. Their old no-deploy boundaries and
revision numbers do not override the current release authorization or manifests.
@@ -168,9 +202,9 @@ establish the FF3 candidate's quality or the owner's acceptance.
## Toolchain
-Use the repository's pinned maintainer tools: Bun 1.4.2, Node 22.23.2 and npm 12.0.2. Put that Node installation first on `PATH` before running build/check commands; the site media pipeline uses Node, native Sharp and an installed Chrome or Chromium.
+Use the repository's pinned maintainer tools: Bun 1.4.2, Node 22.23.3 and npm 12.2.0, as recorded in `../toolchain.json` and `../scenes/toolchain.json`. Put that Node installation first on `PATH` before running build/check commands; the site media pipeline uses Node, native Sharp and an installed Chrome or Chromium.
-Runtime dependencies are exact pins. The owner-required `@types/react` and `@types/react-dom` literals remain `^19.3.0`, with exact resolutions in `bun.lock`. Astro 7.3.5 and React 19.3.0 are used with `@astrojs/react` 7.0.0. Site TypeScript is 6.0.3 because `@astrojs/check` 0.9.10 declares TypeScript 5/6 support, excluding 7. Site Three.js is 0.186.0, matching the unchanged engine/render-service manifests and their repository gate. The sealed Farm's original scene uses 0.186.1; it is not loaded or ported into this website. The separately delivered R3F scene also pins 0.186.0, as agreed by the owner, and the site build refuses to bundle a second copy of Three.js, React, React DOM or `@react-three/fiber`.
+Runtime dependencies are exact pins. The owner-required `@types/react` and `@types/react-dom` literals remain `^19.3.0`, with exact resolutions in `bun.lock`. Astro 7.3.5 and React 19.3.0 are used with `@astrojs/react` 7.0.0. Site TypeScript is 6.0.3 because `@astrojs/check` 0.9.10 declares TypeScript 5/6 support, excluding 7. The site, engine, render service and maintained scene packages pin Three.js 0.186.1; the site and scene packages pin `@types/three` 0.186.0 and `@react-three/fiber` 9.8.1. The site builds Farm from maintained scene source and serves the separately sealed Golden Gate and Foundry public bundles. Each sealed runtime retains its own producer identity; historical builds are not relabeled by current manifest pins. The site build refuses to bundle a second copy of Three.js, React, React DOM or `@react-three/fiber`.
## Data preparation
@@ -213,7 +247,7 @@ bun scripts/rig-posters.mjs vehicles --service http://127.0.0.1:8123 --mirror /p
`stage-vehicles.mjs` refuses a vehicle unless everything that vouches for it agrees: the delivered export, the scene pack's copy and the hash its licence text states; the saved revision's sealed files, its parent chain and a creation time inside the run credited with it; the binary chunk of the delivered file and of the saved export; every tier's triangles, bounds, materials and parts in both forms; wheels that stop being drawn where the last tier starts; each tier inside its brief's body-triangle budget; and three.js's own loader drawing exactly the top tier and the wheels the catalog reports. Sizes and triangle counts are read from the GLBs, and the descriptions are the authors' own briefs. The editable ZIP is the saved revision built with fixed timestamps (the revision's UTC creation time), so the same inputs give the same bytes; the pack ZIP is the six GLBs and licence texts under a `delivery.json` inventory. A repeated run leaves `mirror-manifest.json`, `commons-build.json` and `packs/vehicles.json` unchanged. Nothing is uploaded. The vehicles share the Farm pack's licence (CC0-1.0, authored content only; owner decision D-35). The owner approved all six at every tier, including the corrected transit bus on 30 September 2026; the catalog records that approval against its exact revision. The Vehicles r2 catalogue now includes the g7 licence restage while preserving those accepted model identities. `vehicle-runs.mjs` records each run's requested model and effort from its receipt and invocation; no effort is independently confirmed.
-### Foundry Floor pack (in production)
+### Foundry Floor pack (historical delivery record)
The Foundry Floor pack (62 interior and campus models, release FF3) is staged from the sealed Foundry Floor scene pack. It includes 31 interior models, 12 campus structures, six road vehicles, eight plants and five freight vehicles. Run `node scripts/scene-pack.mjs` first, then
diff --git a/site/bun.lock b/site/bun.lock
index 7505c676..5e4a0371 100644
--- a/site/bun.lock
+++ b/site/bun.lock
@@ -17,7 +17,7 @@
"react": "19.3.0",
"react-dom": "19.3.0",
"tailwindcss": "4.3.3",
- "three": "0.186.0",
+ "three": "0.186.1",
},
"devDependencies": {
"@astrojs/check": "0.9.10",
@@ -31,14 +31,18 @@
"fontverter": "2.0.0",
"html-validate": "11.16.1",
"lighthouse": "13.5.0",
- "parse5": "8.0.0",
+ "parse5": "8.0.1",
"puppeteer-core": "25.12.0",
"sharp": "0.35.5",
"subset-font": "2.9.0",
"typescript": "6.0.3",
+ "vite": "8.3.2",
},
},
},
+ "overrides": {
+ "vite": "8.3.2",
+ },
"packages": {
"@astrojs/astro2tsx": ["@astrojs/[email protected]", "", { "dependencies": { "@emnapi/core": "1.11.3", "@napi-rs/wasm-runtime": "1.2.4" } }, "sha512-Uj/M9zbrhu5cIZEvWAGTbQJRKSxXWJ/E59BZwt7F+chrKhbfttW+9rkS/l+1QxoJP1KU3UnpM62M7yszfAI0WA=="],
@@ -298,7 +302,7 @@
"@oslojs/encoding": ["@oslojs/[email protected]", "", {}, "sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ=="],
- "@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-Nm4s/jB+4FpFsPhWGEC4h7rzksesmtnMXomo6rCMcg/b8zLQuOziRgkCS1fxDCXOlJB/6Q8oABOZ/OP6RIPj9A=="],
+ "@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw=="],
"@paulirish/trace_engine": ["@paulirish/[email protected]", "", { "dependencies": { "legacy-javascript": "latest", "third-party-web": "latest" } }, "sha512-Qsm6F5C8xf6ZzQXbQc2+wcpe6sggfs/gvc/ytqSurdvYg3kyW0ECHCqE0CWBKZpqgjVfPNX9c7SCS3r2nEIRGg=="],
@@ -308,35 +312,35 @@
"@react-three/fiber": ["@react-three/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.17.8", "@types/webxr": "*", "base64-js": "^1.5.1", "buffer": "^6.0.3", "its-fine": "^2.1.1", "react-use-measure": "^2.1.7", "scheduler": "^0.28.0", "suspend-react": "^0.1.3", "use-sync-external-store": "^1.4.0", "zustand": "^5.0.3" }, "peerDependencies": { "expo": ">=43.0", "expo-asset": ">=8.4", "expo-file-system": ">=11.0", "expo-gl": ">=11.0", "react": ">=19 <19.4", "react-dom": ">=19 <19.4", "react-native": ">=0.78", "three": ">=0.156" }, "optionalPeers": ["expo", "expo-asset", "expo-file-system", "expo-gl", "react-dom", "react-native"] }, "sha512-GbNP4r6F/gpclFKkLGHzXcuwFWAzLyKsmrQGcDuwK3wQnwLH6F1TfGtEYjHy8OQoGsajwT19B9jtVLLjjfH09w=="],
- "@rolldown/binding-android-arm-eabi": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-EypzgnYCwyVY4NDHKzGmNJT5b+XaQEBniHxsMdeIQLB/tcCzZnhqrzHpZFbX9iaxx+5RiB8caATBtfvZP7zVxQ=="],
+ "@rolldown/binding-android-arm-eabi": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A=="],
- "@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-l17HE9EweWaqJZhuUuNBN/FzM62xw+DECVnJyvMsxn8vJFAGLy5QfLDoYAcronkAN8VxKZHezDpulHDPx95vFw=="],
+ "@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg=="],
- "@rolldown/binding-darwin-arm64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-8ED8ELFvHXc6OCETIn4gXObPiaR6bckM/ipXtbzlPVDRMBfEGjCKgO90F9YtfdpDatVx/ZQw7aZ1vUMf/+T3Mw=="],
+ "@rolldown/binding-darwin-arm64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w=="],
- "@rolldown/binding-darwin-x64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-/WPripjtiAIZ2tWY7ddijORT0Ujg87wxWW/qcoFVCKAWVDPhtY0xr7Dj0M3GyNGz60jGwTElhro/mkF9dT7dDQ=="],
+ "@rolldown/binding-darwin-x64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA=="],
- "@rolldown/binding-freebsd-x64": ["@rolldown/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-14DI4NcqpvbICxSnGLx3PmtDaWqRP/KGSGb6C+JLLVPeZRl6dKdHba3pGsqT3vpdTqhEYIPG0MMQ8c0xYqoJxA=="],
+ "@rolldown/binding-freebsd-x64": ["@rolldown/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ=="],
- "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-bxrWIRvHWQvbJwi+VIie/kDJmQxcNE6xxWwZdqF/ExVAigtHkv54WTLQPb+QsZdnFy18fg7JPfWGL0RH6vwIlQ=="],
+ "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g=="],
- "@rolldown/binding-linux-arm64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-toOY2BChBZyuxU7OYX6Tn389di4IzAqPTycVcci0O7FSfBqzRB3RZn+K5Is6ANf4tmgRd/K1yZTsNTXbkXsnLg=="],
+ "@rolldown/binding-linux-arm64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw=="],
- "@rolldown/binding-linux-arm64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-lAIXTH/aiLRLxsTgQvfhjo4K1ydWIp00+V0voOr9beb/9ZmkUFrSIb03dXNFRgMNvkE6oGsF10ioQ6UsI+vS5Q=="],
+ "@rolldown/binding-linux-arm64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw=="],
- "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-kdnwS28Pkenp/mZMRwjXXXwxQ7pIsm+bF919LUK93BOyhcLsrVKdP2p9fxpiPNPAbNuch8ypQt0pm2P2LYCAGg=="],
+ "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ=="],
- "@rolldown/binding-linux-s390x-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-516OdsyLdr5E65paF3yBF55t8mfm9+gmtCsK3xI7XKXIT7EfRlHhxL8K/NR6Hu8BWSgF5+1w74lTL0+nxcc8Qw=="],
+ "@rolldown/binding-linux-s390x-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw=="],
- "@rolldown/binding-linux-x64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-r8/z8n7GFaYRln3xmP1Cxy0HH/HLM0uBUPkEuSVEfKGDA89M0FsZRZJRSwe/tJjRx+fpH/gjorfhB8tmEbSFLA=="],
+ "@rolldown/binding-linux-x64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw=="],
- "@rolldown/binding-linux-x64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-pAsE8iiDxUg1xBqdhrTfg45AVDVpirjz00sblEYClGNNcMnDb+e8beQgqIAw6LvauX/APvgxUnwrgun/YYGBhw=="],
+ "@rolldown/binding-linux-x64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g=="],
- "@rolldown/binding-openharmony-arm64": ["@rolldown/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-lTcIYmmnQQA8Or/2DatS6oSqcdLHvendjS+zLu+FwgToynWMRSmQdpM65fTANJgIS4mjbMOo5KT2lnT9SAb96w=="],
+ "@rolldown/binding-openharmony-arm64": ["@rolldown/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA=="],
- "@rolldown/binding-win32-arm64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-e3Gu3WxbNk/UqQhxqU7YIYO+9ZBvWNz3U+h/qRFosscMFzdRPbXYSaSWgSnklv2fz1TgzBTcti2z35c/7irsHw=="],
+ "@rolldown/binding-win32-arm64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew=="],
- "@rolldown/binding-win32-x64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-W/jg5qoRSqjsEv0+dZi4e687mcHqmVuU0P4fK6qS/xjetW2Gmc1W8j//z5nAeNcC8Ttm0hV46IjcYeuVwYhuiw=="],
+ "@rolldown/binding-win32-x64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ=="],
"@rolldown/pluginutils": ["@rolldown/[email protected]", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
@@ -626,7 +630,7 @@
"enquirer": ["[email protected]", "", { "dependencies": { "ansi-colors": "^4.1.1", "strip-ansi": "^6.0.1" } }, "sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ=="],
- "entities": ["[email protected]", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],
+ "entities": ["[email protected]", "", {}, "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA=="],
"es-module-lexer": ["[email protected]", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="],
@@ -1004,7 +1008,7 @@
"parse-latin": ["[email protected]", "", { "dependencies": { "@types/nlcst": "^2.0.0", "@types/unist": "^3.0.0", "nlcst-to-string": "^4.0.0", "unist-util-modify-children": "^4.0.0", "unist-util-visit-children": "^3.0.0", "vfile": "^6.0.0" } }, "sha512-mhHgobPPua5kZ98EF4HWiH167JWBfl4pvAIXXdbaVohtK7a6YBOy56kvhCqduqyo/f3yrHFWmqmiMg/BkBkYYQ=="],
- "parse5": ["[email protected]", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-9m4m5GSgXjL4AjumKzq1Fgfp3Z8rsvjRNbnkVwfu2ImRqE5D0LnY2QfDen18FSY9C573YU5XxSapdHZTZ2WolA=="],
+ "parse5": ["[email protected]", "", { "dependencies": { "entities": "^8.0.0" } }, "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw=="],
"path-browserify": ["[email protected]", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="],
@@ -1098,7 +1102,7 @@
"robots-parser": ["[email protected]", "", {}, "sha512-s+pyvQeIKIZ0dx5iJiQk1tPLJAWln39+MI5jtM8wnyws+G5azk+dMnMX0qfbqNetKKNgcWWOdi0sfm+FbQbgdQ=="],
- "rolldown": ["[email protected]", "", { "dependencies": { "@oxc-project/types": "=0.148.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.7", "@rolldown/binding-android-arm64": "1.2.7", "@rolldown/binding-darwin-arm64": "1.2.7", "@rolldown/binding-darwin-x64": "1.2.7", "@rolldown/binding-freebsd-x64": "1.2.7", "@rolldown/binding-linux-arm-gnueabihf": "1.2.7", "@rolldown/binding-linux-arm64-gnu": "1.2.7", "@rolldown/binding-linux-arm64-musl": "1.2.7", "@rolldown/binding-linux-ppc64-gnu": "1.2.7", "@rolldown/binding-linux-s390x-gnu": "1.2.7", "@rolldown/binding-linux-x64-gnu": "1.2.7", "@rolldown/binding-linux-x64-musl": "1.2.7", "@rolldown/binding-openharmony-arm64": "1.2.7", "@rolldown/binding-win32-arm64-msvc": "1.2.7", "@rolldown/binding-win32-x64-msvc": "1.2.7" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-g0EtLvBjTUB7jhyV0S/TCup3v/XSVl45vUIGbOGU4QPiyjTenCe4mKuFvW9fEgYmS2Fo42AUssRmNuMziXdrig=="],
+ "rolldown": ["[email protected]", "", { "dependencies": { "@oxc-project/types": "=0.152.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.12", "@rolldown/binding-android-arm64": "1.2.12", "@rolldown/binding-darwin-arm64": "1.2.12", "@rolldown/binding-darwin-x64": "1.2.12", "@rolldown/binding-freebsd-x64": "1.2.12", "@rolldown/binding-linux-arm-gnueabihf": "1.2.12", "@rolldown/binding-linux-arm64-gnu": "1.2.12", "@rolldown/binding-linux-arm64-musl": "1.2.12", "@rolldown/binding-linux-ppc64-gnu": "1.2.12", "@rolldown/binding-linux-s390x-gnu": "1.2.12", "@rolldown/binding-linux-x64-gnu": "1.2.12", "@rolldown/binding-linux-x64-musl": "1.2.12", "@rolldown/binding-openharmony-arm64": "1.2.12", "@rolldown/binding-win32-arm64-msvc": "1.2.12", "@rolldown/binding-win32-x64-msvc": "1.2.12" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ=="],
"satteri": ["[email protected]", "", { "dependencies": { "@types/estree-jsx": "^1.0.5", "@types/hast": "^3.0.5", "@types/mdast": "^4.0.4", "@types/unist": "^3.0.3" }, "optionalDependencies": { "@bruits/satteri-darwin-arm64": "0.10.5", "@bruits/satteri-darwin-x64": "0.10.5", "@bruits/satteri-linux-arm64-gnu": "0.10.5", "@bruits/satteri-linux-arm64-musl": "0.10.5", "@bruits/satteri-linux-x64-gnu": "0.10.5", "@bruits/satteri-linux-x64-musl": "0.10.5", "@bruits/satteri-wasm32-wasi": "0.10.5", "@bruits/satteri-win32-arm64-msvc": "0.10.5", "@bruits/satteri-win32-x64-msvc": "0.10.5" } }, "sha512-Ao1LKpAEa9Wdg0otgbVKViZHEq9ebdXe4DMrp3s9vQAU0HNIuHnFEuMuOcm0ZIXyV0Yzxj91NvhLpvXZJO/5ZQ=="],
@@ -1158,7 +1162,7 @@
"third-party-web": ["[email protected]", "", {}, "sha512-p+PfyL5U0ediGzvwPzMSdD9MnC8rHW6nWJJVLIQvqN7RsSqfaZ+7n4c9GILqH36EYR0eXB9CzAeCRnKFr/9uJg=="],
- "three": ["[email protected]", "", {}, "sha512-cr/fIM2ddMSVbYVgkfD4jLJv7Fh/8ZTjvo+7gQeSVGUZHxpx9FDwoL5iC7hUz/LiRA8wMbqfnb90xKfm1/HHkQ=="],
+ "three": ["[email protected]", "", {}, "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA=="],
"three-mesh-bvh": ["[email protected]", "", { "peerDependencies": { "three": ">= 0.159.0" } }, "sha512-4G5lBaF+g2auKX3P0yqx+MJC6oVt6sB5k+CchS6Ob0qvH0YIhuUk1eYr7ktsIpY+albCqE80/FVQGV190PmiAg=="],
@@ -1250,7 +1254,7 @@
"vfile-message": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
- "vite": ["[email protected]", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.6", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ=="],
+ "vite": ["[email protected]", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.11", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-SQr1x6W5vVSbROg7vsyXIaxK9b0G7zsT68acdWWRmnBUsgDieLCRG+Rep9WdZgcposvv/GSnr4GUUBqB3vXq6w=="],
"vitefu": ["[email protected]", "", { "peerDependencies": { "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["vite"] }, "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg=="],
@@ -1444,6 +1448,10 @@
"csso/css-tree/mdn-data": ["[email protected]", "", {}, "sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g=="],
+ "hast-util-from-html/parse5/entities": ["[email protected]", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],
+
+ "hast-util-raw/parse5/entities": ["[email protected]", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],
+
"lighthouse/yargs/cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
"lighthouse/yargs/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
diff --git a/site/package.json b/site/package.json
index 42317a57..21a0044d 100644
--- a/site/package.json
+++ b/site/package.json
@@ -2,7 +2,7 @@
"name": "kiln-site",
"private": true,
"type": "module",
- "description": "Kiln 0.9: the tool, source docs and revision-bound Commons assets.",
+ "description": "Kiln: the tool, source docs and revision-bound Commons assets.",
"scripts": {
"assets": "bun scripts/build-assets.mjs",
"dev": "astro dev",
@@ -20,7 +20,7 @@
"@react-three/fiber": "9.8.1",
"react": "19.3.0",
"react-dom": "19.3.0",
- "three": "0.186.0",
+ "three": "0.186.1",
"@fontsource-variable/archivo": "5.3.0",
"@fontsource/ibm-plex-mono": "5.3.0",
"tailwindcss": "4.3.3",
@@ -39,10 +39,14 @@
"fontverter": "2.0.0",
"html-validate": "11.16.1",
"lighthouse": "13.5.0",
- "parse5": "8.0.0",
+ "parse5": "8.0.1",
"puppeteer-core": "25.12.0",
"sharp": "0.35.5",
"subset-font": "2.9.0",
- "typescript": "6.0.3"
+ "typescript": "6.0.3",
+ "vite": "8.3.2"
+ },
+ "overrides": {
+ "vite": "8.3.2"
}
}
diff --git a/site/scripts/deploy.mjs b/site/scripts/deploy.mjs
new file mode 100644
index 00000000..e11b1df4
--- /dev/null
+++ b/site/scripts/deploy.mjs
@@ -0,0 +1,188 @@
+/** Upload a reviewed, sealed site build after release authorization. No build, login, R2 upload or DNS changes. */
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { lstat, readFile, readdir, realpath } from 'node:fs/promises';
+import { basename, dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+export const WRANGLER_VERSION = '4.147.0';
+const SITE = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const RECEIPTS = new Set(['build-info.json', 'artifact-files.json']);
+const MAX_FILES = 20_000;
+const MAX_FILE_BYTES = 25 * 1024 * 1024;
+const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');
+const isDigest = (value) => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value);
+const isCount = (value) => Number.isSafeInteger(value) && value >= 0;
+
+export function execute(file, args, { cwd, inherit = false } = {}, exec = execFileSync) {
+ return exec(file, args, {
+ cwd, shell: false, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024,
+ stdio: inherit ? ['ignore', 'inherit', 'inherit'] : ['ignore', 'pipe', 'pipe'],
+ }) ?? '';
+}
+
+function manifestPath(value) {
+ return typeof value === 'string' && !/[\\:\x00-\x1f\x7f]/.test(value) &&
+ value.split('/').every(part => part !== '' && part !== '.' && part !== '..') && !RECEIPTS.has(value);
+}
+
+/** Inspect all entries, including the two receipts: symlinks and special files never reach Wrangler. */
+async function outputFiles(dist) {
+ const files = new Map();
+ async function walk(path, name) {
+ const stat = await lstat(path);
+ if (stat.isSymbolicLink()) throw new Error(`Symlink in deployment output: ${name || 'dist'}`);
+ if (stat.isDirectory()) {
+ for (const child of await readdir(path)) await walk(join(path, child), name ? `${name}/${child}` : child);
+ } else if (stat.isFile() && name) {
+ if (stat.size > MAX_FILE_BYTES) throw new Error(`${name} exceeds the Pages 25 MiB file limit.`);
+ files.set(name, { path, bytes: stat.size });
+ if (files.size > MAX_FILES) throw new Error('Deployment exceeds the Pages 20,000-file limit.');
+ } else throw new Error(`Unsupported deployment entry: ${name || 'dist'}`);
+ }
+ await walk(dist, '');
+ return files;
+}
+
+async function outputBytes(files, name) {
+ const file = files.get(name);
+ if (!file) throw new Error(`Missing deployment file: ${name}`);
+ const stat = await lstat(file.path);
+ if (stat.isSymbolicLink()) throw new Error(`Symlink in deployment output: ${name}`);
+ if (!stat.isFile() || stat.size !== file.bytes) throw new Error(`Deployment file changed during preflight: ${name}`);
+ return readFile(file.path);
+}
+
+async function assertStaticDeployment(site, dist) {
+ // Pages otherwise compiles cwd/functions outside the artifact manifest, or
+ // bundles _worker.js (including its imports) after our byte verification.
+ for (const [directory, name] of [[site, 'functions'], [dist, 'functions'], [dist, '_worker.js'], [dist, '_routes.json']]) {
+ try {
+ await lstat(join(directory, name));
+ } catch (error) {
+ if (error.code === 'ENOENT') continue;
+ throw error;
+ }
+ throw new Error(`Static deployment refuses ${directory === site ? 'site' : 'dist'}/${name}. Worker/Functions inputs require a separately reviewed deployment workflow.`);
+ }
+}
+
+/** Verify the existing build-info/artifact-files format without changing the output or contacting Cloudflare. */
+export async function preflight({ site = SITE, run = execute } = {}) {
+ site = resolve(site);
+ const dist = join(site, 'dist');
+ await assertStaticDeployment(site, dist);
+ const files = await outputFiles(dist);
+ if (!files.has('index.html')) throw new Error('Missing dist/index.html. Build and review the production site first.');
+ const infoBytes = await outputBytes(files, 'build-info.json');
+ const info = JSON.parse(infoBytes.toString('utf8'));
+ if (info.treeClean !== true) throw new Error('The build was not made from a clean tree. Rebuild and review a clean commit.');
+ if (info.kilnSitePacks !== '1') throw new Error('Production deployment requires KILN_SITE_PACKS=1; reduced builds cannot be deployed by this script.');
+ if (typeof info.commit !== 'string' || !/^[0-9a-f]{7,64}$/.test(info.commit)) throw new Error('The build has no valid Git commit identity.');
+ const artifacts = info.artifacts;
+ if (!artifacts || artifacts.manifest !== 'artifact-files.json' || !isDigest(artifacts.sha256) ||
+ !isCount(artifacts.files) || !isCount(artifacts.bytes)) throw new Error('Invalid artifact manifest receipt in build-info.json.');
+ const manifestBytes = await outputBytes(files, artifacts.manifest);
+ if (digest(manifestBytes) !== artifacts.sha256) throw new Error('Artifact manifest digest mismatch. Rebuild and review before deploying.');
+ const manifest = JSON.parse(manifestBytes.toString('utf8'));
+ if (!Array.isArray(manifest)) throw new Error('Artifact manifest must be a file list.');
+ if (manifest.length + RECEIPTS.size > MAX_FILES) throw new Error('Deployment exceeds the Pages 20,000-file limit including receipts.');
+ const expected = new Set();
+ let artifactBytes = 0;
+ for (const file of manifest) {
+ if (!file || !manifestPath(file.path)) throw new Error('Invalid artifact manifest path; paths must be relative and cannot name the excluded receipts.');
+ if (expected.has(file.path)) throw new Error(`Duplicate artifact manifest path: ${file.path}`);
+ if (!isCount(file.bytes) || !isDigest(file.sha256)) throw new Error(`Invalid artifact manifest size or digest: ${file.path}`);
+ if (file.bytes > MAX_FILE_BYTES) throw new Error(`${file.path} exceeds the Pages 25 MiB file limit.`);
+ expected.add(file.path);
+ artifactBytes += file.bytes;
+ }
+ if (!Number.isSafeInteger(artifactBytes) || manifest.length !== artifacts.files || artifactBytes !== artifacts.bytes)
+ throw new Error('Artifact manifest count or byte total mismatch.');
+ for (const name of files.keys()) if (!RECEIPTS.has(name) && !expected.has(name)) throw new Error(`Unexpected deployment file absent from the manifest: ${name}`);
+ for (const file of manifest) {
+ const bytes = await outputBytes(files, file.path);
+ if (bytes.length !== file.bytes || digest(bytes) !== file.sha256) throw new Error(`Artifact size or hash mismatch: ${file.path}`);
+ }
+
+ // No pathspec: source changes anywhere in the checkout invalidate the reviewed build.
+ const git = async (...args) => String(await run('git', ['-C', site, ...args], { cwd: site })).trim();
+ const head = await git('rev-parse', '--verify', 'HEAD');
+ if (!/^[0-9a-f]{40,64}$/.test(head)) throw new Error('Cannot resolve the checkout HEAD.');
+ const builtCommit = await git('rev-parse', '--verify', `${info.commit}^{commit}`);
+ if (builtCommit !== head) throw new Error(`Build commit ${info.commit} differs from checkout HEAD ${head}. Rebuild and review this commit.`);
+ if (await git('status', '--porcelain', '--untracked-files=all')) throw new Error('The checkout has uncommitted or untracked changes. Commit, rebuild and review before deployment.');
+ return {
+ site, dist, head, info, files: files.size, bytes: [...files.values()].reduce((sum, file) => sum + file.bytes, 0),
+ buildInfoSha256: digest(infoBytes), artifactManifestSha256: artifacts.sha256,
+ };
+}
+
+/** Node executes npm's JavaScript directly, including on Windows; no .cmd shell or command interpolation. */
+export async function resolveNpmCli({ execPath = process.execPath, env = process.env, platform = process.platform } = {}) {
+ const nodePaths = [execPath];
+ try { nodePaths.push(await realpath(execPath)); } catch { /* The executable-directory candidates remain useful. */ }
+ const directories = [...nodePaths.map(dirname), ...(env.PATH ?? env.Path ?? '').split(platform === 'win32' ? ';' : ':').filter(Boolean)];
+ const candidates = [env.npm_execpath, ...directories.flatMap(directory => [join(directory, 'node_modules/npm/bin/npm-cli.js'), join(directory, 'npm')])];
+ for (const candidate of candidates) {
+ if (!candidate) continue;
+ try {
+ const path = await realpath(candidate);
+ if (basename(path) === 'npm-cli.js' && (await lstat(path)).isFile()) return path;
+ } catch { /* Try the next standard npm location. */ }
+ }
+ throw new Error('Cannot find npm-cli.js. Install the maintained Node/npm toolchain, or supply --wrangler with the exact pinned executable.');
+}
+
+/** Run the full preflight even in dry-run mode. Only an authorized non-dry run can prepare Wrangler and upload. */
+export async function deploy({ site = SITE, projectName = 'kilnstudio', wrangler, dryRun = false, npmCli, run = execute, log = console.log } = {}) {
+ if (typeof projectName !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(projectName)) throw new Error('Invalid Pages project name.');
+ if (wrangler && /\.(?:cmd|bat)$/i.test(wrangler)) throw new Error('Use the default pinned npm invocation instead of a Wrangler .cmd/.bat shell wrapper.');
+ const initial = await preflight({ site, run });
+ const argumentsFor = (checked) => ['pages', 'deploy', checked.dist, '--project-name', projectName, '--branch', 'production', '--commit-hash', checked.head, '--commit-dirty=false'];
+ log(`Verified ${initial.files} files (${initial.bytes} bytes), commit ${initial.head}, packs=1; ${projectName}/production.`);
+ if (dryRun) {
+ log(`Dry run: no upload, package preparation or login. Wrangler ${WRANGLER_VERSION} is required for deployment.`);
+ return { deployed: false, preflight: initial };
+ }
+ const command = wrangler
+ ? { file: wrangler, prefix: [] }
+ : { file: process.execPath, prefix: [npmCli ?? await resolveNpmCli(), 'exec', '--yes', `--package=wrangler@${WRANGLER_VERSION}`, '--', 'wrangler'] };
+ const versionText = String(await run(command.file, [...command.prefix, '--version'], { cwd: initial.site }));
+ const version = versionText.match(/^\s*(?:wrangler\s+)?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?)\s*$/m)?.[1];
+ if (version !== WRANGLER_VERSION) throw new Error(`Deployment requires Wrangler ${WRANGLER_VERSION}; the executable did not report that exact version.`);
+ // npm preparation can take time. Recheck all bytes and Git state afterwards, immediately before upload.
+ const checked = await preflight({ site: initial.site, run });
+ if (checked.head !== initial.head || checked.buildInfoSha256 !== initial.buildInfoSha256 || checked.artifactManifestSha256 !== initial.artifactManifestSha256)
+ throw new Error('Deployment receipts or HEAD changed while preparing Wrangler. Review the build again.');
+ await run(command.file, [...command.prefix, ...argumentsFor(checked)], { cwd: checked.site, inherit: true });
+ return { deployed: true, preflight: checked };
+}
+
+export function parseArgs(args) {
+ const options = {};
+ const values = { '--site': 'site', '--project-name': 'projectName', '--wrangler': 'wrangler' };
+ for (let index = 0; index < args.length; index++) {
+ const arg = args[index];
+ if (arg === '--dry-run') options.dryRun = true;
+ else if (arg === '--help') options.help = true;
+ else if (arg === '--allow-packs-off') throw new Error('The packs-off bypass is retired. Production requires KILN_SITE_PACKS=1.');
+ else if (Object.hasOwn(values, arg)) {
+ const value = args[++index];
+ if (!value || value.startsWith('--')) throw new Error(`Missing value for ${arg}.`);
+ options[values[arg]] = value;
+ } else throw new Error(`Unknown deployment option: ${arg}`);
+ }
+ return options;
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ try {
+ const options = parseArgs(process.argv.slice(2));
+ if (options.help) console.log('Usage: node site/scripts/deploy.mjs [--site DIR] [--project-name NAME] [--wrangler EXECUTABLE] [--dry-run]\nRun only after release authorization. Dry run performs offline checks; deployment uses Wrangler 4.147.0.');
+ else await deploy(options);
+ } catch (error) {
+ console.error(`Deployment refused: ${error.message}`);
+ process.exitCode = 1;
+ }
+}
diff --git a/site/scripts/deploy.ps1 b/site/scripts/deploy.ps1
index cf68a8cd..a6d051d2 100644
--- a/site/scripts/deploy.ps1
+++ b/site/scripts/deploy.ps1
@@ -1,38 +1,10 @@
<#
.SYNOPSIS
- Deploy the reviewed local build of the Kiln site (site/dist) to Cloudflare Pages by direct upload. Run after release authorization.
-
+ Compatibility entrypoint for the portable, receipt-verifying Pages deploy script.
.DESCRIPTION
- Hosting decision S-4 (site-build/DECISIONS.md): the site is a direct upload of the build that was reviewed on this PC,
- so the deployed bytes are the reviewed bytes. This script checks that dist/ is that build, prints what it is about to
- upload, and runs
-
- wrangler pages deploy <dist> --project-name <name> --branch production --commit-hash <HEAD> --commit-dirty=false
-
- It refuses when dist/index.html is missing, when dist/build-info.json (written by the build's last step,
- site/scripts/build-info.mjs) is missing or names another commit, when the build was made from a tree with
- uncommitted changes, or when the site checkout has uncommitted or untracked changes now. It uses the wrangler that
- is installed and installs nothing. It never logs in, creates a project, uploads to R2 or changes DNS: those are the
- owner's one-time steps in site/DEPLOYMENT.md.
-
-.PARAMETER Site
- The site directory (defaults to this repository's site directory).
-
-.PARAMETER ProjectName
- The Cloudflare Pages project, created once by the owner with `production` as its production branch.
-
-.PARAMETER Wrangler
- wrangler to run. Defaults to `wrangler` on PATH, then Bun's global bin (~/.bun/bin/wrangler.exe).
-
-.PARAMETER AllowPacksOff
- Deploy a build made with KILN_SITE_PACKS=0 (the pre-upload build without Commons downloads). Without this switch
- only a launch-mode build (KILN_SITE_PACKS=1) is deployed.
-
-.PARAMETER DryRun
- Run every check, print the command, then exit without deploying.
-
-.EXAMPLE
- pwsh -NoProfile -File site/scripts/deploy.ps1 -DryRun
+ Run after release authorization. Node owns all checks and the exact Wrangler pin.
+ -DryRun performs the complete offline preflight without package preparation or upload.
+ -AllowPacksOff is retained only to report its removal: production requires packs=1.
#>
[CmdletBinding()]
param(
@@ -45,69 +17,9 @@ param(
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
-
-$Site = (Resolve-Path -LiteralPath $Site).Path
-$dist = Join-Path $Site 'dist'
-if (-not (Test-Path -LiteralPath (Join-Path $dist 'index.html'))) {
- throw "No production build at $dist (index.html is missing). Build the site first; this script does not build."
-}
-
-# wrangler: -Wrangler, else PATH, else Bun's global bin. Only its version is read here.
-if (-not $Wrangler) {
- $onPath = Get-Command wrangler -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
- $Wrangler = if ($onPath) { $onPath.Source } else { Join-Path $HOME '.bun\bin\wrangler.exe' }
-}
-if (-not (Test-Path -LiteralPath $Wrangler)) {
- throw "wrangler was not found (tried $Wrangler). Install it yourself or pass -Wrangler; this script installs nothing."
-}
-$wranglerVersion = ((& $Wrangler --version 2>$null) | Where-Object { $_ -match '\d+\.\d+' } | Select-Object -First 1)
-if (-not $wranglerVersion) { throw "$Wrangler --version printed no version." }
-
-# The checkout: clean, including untracked files (an untracked source file could have been built into dist/).
-$head = (& git -C $Site rev-parse HEAD).Trim()
-$short = (& git -C $Site rev-parse --short HEAD).Trim()
-$status = @(& git -C $Site status --porcelain)
-if ($status.Count) {
- throw "The site checkout has uncommitted or untracked changes ($($status.Count) entries; first: $($status[0].Trim())). Commit or remove them, rebuild, review, then deploy."
-}
-
-# The build: made from this commit, from a clean tree.
-$infoFile = Join-Path $dist 'build-info.json'
-if (-not (Test-Path -LiteralPath $infoFile)) {
- throw "dist/ has no build-info.json, so it cannot be tied to a commit. Rebuild with the site's build script."
-}
-$info = Get-Content -LiteralPath $infoFile -Raw | ConvertFrom-Json
-if ($info.commit -ne $short) {
- throw "dist/ was built from commit $($info.commit), but the checkout is at $short. Rebuild and review this commit first."
-}
-if ($info.treeClean -ne $true) {
- throw "dist/ was built from a tree with uncommitted changes (build-info.json treeClean: $($info.treeClean)). Rebuild from the clean commit."
-}
-if ($info.kilnSitePacks -ne '1' -and -not $AllowPacksOff) {
- throw "dist/ was built with KILN_SITE_PACKS=$($info.kilnSitePacks), not the launch mode (1). Pass -AllowPacksOff to deploy it anyway."
-}
-
-$files = @(Get-ChildItem -LiteralPath $dist -Recurse -File)
-$bytes = ($files | Measure-Object -Property Length -Sum).Sum
-$largest = $files | Sort-Object Length -Descending | Select-Object -First 1
-
-# Pages' direct-upload limits, as the installed wrangler enforces them: 20,000 files and 25 MiB per file.
-if ($files.Count -gt 20000) { throw "dist/ has $($files.Count) files; a Pages deployment takes at most 20,000." }
-if ($largest.Length -gt 25MB) { throw "$($largest.FullName) is $($largest.Length) bytes; Pages takes files up to 25 MiB." }
-
-Write-Host "wrangler: $Wrangler ($($wranglerVersion.Trim()))"
-Write-Host "dist: $dist"
-Write-Host ("files: {0:N0} files, {1:N0} bytes; largest {2} ({3:N0} bytes)" -f $files.Count, $bytes, $largest.FullName.Substring($dist.Length + 1), $largest.Length)
-Write-Host "build: commit $($info.commit), KILN_SITE_PACKS=$($info.kilnSitePacks), docs $($info.docs.commit), skills $($info.skills.commit), built $($info.builtAt)"
-Write-Host "project: $ProjectName (branch production)"
-
-$arguments = @('pages', 'deploy', $dist, '--project-name', $ProjectName, '--branch', 'production', '--commit-hash', $head, '--commit-dirty=false')
-$command = "`"$Wrangler`" $($arguments -join ' ')"
-if ($DryRun) {
- Write-Host "Dry run, not deployed: $command"
- return
-}
-
-Write-Host "Deploying: $command"
-& $Wrangler @arguments
+$arguments = @((Join-Path $PSScriptRoot 'deploy.mjs'), '--site', $Site, '--project-name', $ProjectName)
+if ($Wrangler) { $arguments += @('--wrangler', $Wrangler) }
+if ($AllowPacksOff) { $arguments += '--allow-packs-off' }
+if ($DryRun) { $arguments += '--dry-run' }
+& node @arguments
exit $LASTEXITCODE
diff --git a/site/scripts/deploy.test.ts b/site/scripts/deploy.test.ts
new file mode 100644
index 00000000..1b463c87
--- /dev/null
+++ b/site/scripts/deploy.test.ts
@@ -0,0 +1,235 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { mkdtemp, mkdir, readFile, rm, symlink, truncate, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { deploy, execute, parseArgs, preflight, resolveNpmCli, WRANGLER_VERSION } from './deploy.mjs';
+
+const roots: string[] = [];
+const hash = (value: string | Buffer) => createHash('sha256').update(value).digest('hex');
+const head = 'a1234567890abcdef1234567890abcdef12345678';
+const otherHead = 'b1234567890abcdef1234567890abcdef12345678';
+const quiet = () => {};
+type Command = { file: string; args: string[]; options?: { cwd?: string; inherit?: boolean } };
+afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); });
+
+async function fixture() {
+ const root = await mkdtemp(join(tmpdir(), 'kiln-deploy-')); roots.push(root);
+ const site = join(root, 'site with spaces');
+ const dist = join(site, 'dist'); await mkdir(join(dist, 'nested'), { recursive: true });
+ const files = [{ path: 'index.html', text: '<p>Reviewed</p>' }, { path: 'nested/model.glb', text: 'model bytes' }];
+ for (const file of files) await writeFile(join(dist, file.path), file.text);
+ const manifest = files.map(({ path, text }) => ({ path, bytes: Buffer.byteLength(text), sha256: hash(text) }));
+ const info: any = { commit: head.slice(0, 7), treeClean: true, kilnSitePacks: '1', builtAt: '2026-10-03T00:00:00.000Z' };
+ async function seal() {
+ const bytes = `${JSON.stringify(manifest)}\n`;
+ info.artifacts = { manifest: 'artifact-files.json', files: manifest.length, bytes: manifest.reduce((n, f) => n + f.bytes, 0), sha256: hash(bytes) };
+ await writeFile(join(dist, 'artifact-files.json'), bytes);
+ await writeFile(join(dist, 'build-info.json'), JSON.stringify(info));
+ }
+ await seal();
+ const calls: Command[] = [];
+ let status = '';
+ let currentHead = head;
+ let version = WRANGLER_VERSION;
+ let onVersion: (() => Promise<void>) | undefined;
+ const run = async (file: string, args: string[], options?: Command['options']) => {
+ calls.push({ file, args, options });
+ if (file === 'git') {
+ if (args.includes('status')) return status;
+ if (args.at(-1) === 'HEAD') return currentHead;
+ if (args.at(-1) === `${info.commit}^{commit}`) return info.commit === otherHead.slice(0, 7) ? otherHead : head;
+ throw new Error(`Unexpected git command: ${args}`);
+ }
+ if (args.at(-1) === '--version') { await onVersion?.(); return `${version}\n`; }
+ if (args.includes('deploy')) return '';
+ throw new Error(`Unexpected command: ${file} ${args}`);
+ };
+ return { root, site, dist, files, manifest, info, seal, calls, run, setStatus: (value: string) => { status = value; }, setHead: (value: string) => { currentHead = value; }, setVersion: (value: string) => { version = value; }, onVersion: (fn: () => Promise<void>) => { onVersion = fn; } };
+}
+
+describe('deployment preflight', () => {
+ test.each(['functions-directory', 'functions-symlink', 'worker-file', 'worker-directory', 'asset-functions', 'worker-routes'])('rejects dynamic or ignored worker inputs for the static deployment: %s', async (kind) => {
+ const f = await fixture();
+ if (kind === 'functions-directory') { await mkdir(join(f.site, 'functions')); await writeFile(join(f.site, 'functions/index.js'), 'export function onRequest() {}'); }
+ if (kind === 'functions-symlink') { const target = join(f.root, 'external-functions'); await mkdir(target); await symlink(target, join(f.site, 'functions'), 'junction'); }
+ if (kind === 'worker-directory') await mkdir(join(f.dist, '_worker.js'));
+ if (kind === 'asset-functions') await mkdir(join(f.dist, 'functions'));
+ if (kind === 'worker-file' || kind === 'worker-routes') {
+ const path = kind === 'worker-file' ? '_worker.js' : '_routes.json';
+ const text = kind === 'worker-file' ? 'export default {};' : '{}';
+ await writeFile(join(f.dist, path), text);
+ f.manifest.push({ path, bytes: Buffer.byteLength(text), sha256: hash(text) });
+ await f.seal();
+ }
+ await expect(deploy({ site: f.site, dryRun: true, run: f.run, log: quiet })).rejects.toThrow(/static.*deployment|deployment.*static/i);
+ expect(f.calls.every(call => call.file === 'git')).toBe(true);
+ });
+
+ test('verifies the receipt, every artifact and full checkout identity without network on dry run', async () => {
+ const f = await fixture();
+ const result = await deploy({ site: f.site, dryRun: true, run: f.run, log: quiet });
+ expect(result.deployed).toBe(false);
+ expect(result.preflight.files).toBe(4); // Both excluded receipts still count towards Pages limits.
+ expect(result.preflight.head).toBe(head);
+ expect(f.calls.every(call => call.file === 'git')).toBe(true);
+ expect(f.calls.some(call => call.args.includes('--untracked-files=all'))).toBe(true);
+ });
+
+ test.each(['tampered', 'missing', 'extra'])('rejects %s output', async (kind) => {
+ const f = await fixture();
+ if (kind === 'tampered') await writeFile(join(f.dist, 'nested/model.glb'), 'wrong bytes');
+ if (kind === 'missing') await rm(join(f.dist, 'nested/model.glb'));
+ if (kind === 'extra') await writeFile(join(f.dist, 'unexpected.txt'), 'extra');
+ await expect(preflight({ site: f.site, run: f.run })).rejects.toThrow(/mismatch|missing|unexpected/i);
+ });
+
+ test('rejects an altered manifest even if every listed member would verify', async () => {
+ const f = await fixture();
+ await writeFile(join(f.dist, 'artifact-files.json'), `${JSON.stringify(f.manifest)} `);
+ await expect(preflight({ site: f.site, run: f.run })).rejects.toThrow(/manifest.*digest/i);
+ });
+
+ test.each(['../escape', '/escape', 'C:/escape', 'nested\\escape', 'nested//escape', './index.html', 'build-info.json', 'artifact-files.json'])('rejects unsafe or excluded manifest path %s', async (path) => {
+ const f = await fixture(); f.manifest[0].path = path; await f.seal();
+ await expect(preflight({ site: f.site, run: f.run })).rejects.toThrow(/manifest.*path/i);
+ });
+
+ test.each(['file', 'directory', 'receipt', 'root'])('rejects a symlink at the %s boundary', async (kind) => {
+ const f = await fixture();
+ const target = kind === 'file' ? join(f.dist, 'nested/model.glb') : kind === 'directory' ? join(f.dist, 'nested') : kind === 'receipt' ? join(f.dist, 'build-info.json') : f.dist;
+ const replacement = join(f.root, 'linked-target');
+ if (kind === 'directory' || kind === 'root') await mkdir(replacement);
+ else await writeFile(replacement, await readFile(target));
+ await rm(target, { recursive: true });
+ await symlink(replacement, target, kind === 'directory' || kind === 'root' ? 'junction' : 'file');
+ await expect(preflight({ site: f.site, run: f.run })).rejects.toThrow(/symlink/i);
+ });
+
+ test.each(['duplicate', 'count', 'bytes', 'negative', 'digest', 'missing-index', 'manifest-name'])('rejects malformed receipt or manifest: %s', async (kind) => {
+ const f = await fixture();
+ if (kind === 'duplicate') f.manifest.push({ ...f.manifest[0] });
+ if (kind === 'negative') f.manifest[0].bytes = -1;
+ if (kind === 'digest') f.manifest[0].sha256 = 'bad';
+ if (kind === 'missing-index') { f.manifest.shift(); await rm(join(f.dist, 'index.html')); }
+ await f.seal();
+ if (kind === 'count') f.info.artifacts.files++;
+ if (kind === 'bytes') f.info.artifacts.bytes++;
+ if (kind === 'manifest-name') f.info.artifacts.manifest = '../other.json';
+ await writeFile(join(f.dist, 'build-info.json'), JSON.stringify(f.info));
+ await expect(preflight({ site: f.site, run: f.run })).rejects.toThrow();
+ });
+
+ test.each(['dirty-checkout', 'dirty-build', 'wrong-commit', 'packs-off'])('rejects %s', async (kind) => {
+ const f = await fixture();
+ if (kind === 'dirty-checkout') f.setStatus('?? engine-untracked.ts\n');
+ if (kind === 'dirty-build') f.info.treeClean = false;
+ if (kind === 'wrong-commit') f.info.commit = otherHead.slice(0, 7);
+ if (kind === 'packs-off') f.info.kilnSitePacks = '0';
+ await f.seal();
+ await expect(deploy({ site: f.site, dryRun: true, run: f.run, log: quiet })).rejects.toThrow();
+ expect(f.calls.every(call => call.file === 'git')).toBe(true);
+ });
+
+ test('counts the two receipts in the 20,000-file limit', async () => {
+ const f = await fixture();
+ while (f.manifest.length < 19999) f.manifest.push({ path: `file-${f.manifest.length}`, bytes: 0, sha256: hash('') });
+ await f.seal();
+ await expect(preflight({ site: f.site, run: f.run })).rejects.toThrow(/20,000/);
+ });
+
+ test('rejects files larger than 25 MiB before reading their contents', async () => {
+ const f = await fixture(); await truncate(join(f.dist, 'nested/model.glb'), 25 * 1024 * 1024 + 1);
+ await expect(preflight({ site: f.site, run: f.run })).rejects.toThrow(/25 MiB/);
+ });
+});
+
+describe('deployment command', () => {
+ test('streams upload output without a shell or interactive input', () => {
+ let received: any;
+ execute('node', ['npm-cli.js', 'exec'], { cwd: '/fixture/site', inherit: true }, (file: any, args: any, options: any) => { received = { file, args, options }; return ''; });
+ expect(received.options.stdio).toEqual(['ignore', 'inherit', 'inherit']);
+ expect(received.options.shell).toBe(false);
+ });
+
+ test('Node CLI dry run refuses ignored Functions and untracked files outside site in a real Git tree', async () => {
+ const f = await fixture();
+ const git = (...args: string[]) => execFileSync('git', ['-C', f.root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ git('init');
+ await writeFile(join(f.root, '.gitignore'), 'site with spaces/dist/\n');
+ git('add', '.gitignore');
+ git('-c', 'user.name=Deployment Fixture', '-c', '[email protected]', '-c', 'commit.gpgsign=false', '-c', `core.hooksPath=${join(f.root, 'no-hooks')}`, 'commit', '-m', 'Fixture');
+ f.info.commit = git('rev-parse', '--short', 'HEAD'); await f.seal();
+ const args = [fileURLToPath(new URL('./deploy.mjs', import.meta.url)), '--site', f.site, '--dry-run'];
+ const clean = spawnSync('node', args, { encoding: 'utf8' });
+ expect(clean.status).toBe(0);
+ expect(clean.stdout).toContain('Dry run: no upload');
+ await writeFile(join(f.root, '.git/info/exclude'), 'site with spaces/functions/\n');
+ await mkdir(join(f.site, 'functions')); await writeFile(join(f.site, 'functions/index.js'), 'export function onRequest() {}');
+ expect(git('status', '--porcelain', '--untracked-files=all')).toBe('');
+ const outsideArtifacts = spawnSync('node', args, { encoding: 'utf8' });
+ expect(outsideArtifacts.status).toBe(1);
+ expect(outsideArtifacts.stderr).toContain('Static deployment refuses site/functions');
+ await rm(join(f.site, 'functions'), { recursive: true });
+ await writeFile(join(f.root, 'engine-new.ts'), '// Untracked engine source');
+ const dirty = spawnSync('node', args, { encoding: 'utf8' });
+ expect(dirty.status).toBe(1);
+ expect(dirty.stderr).toContain('uncommitted or untracked');
+ });
+
+ test('pins Wrangler through Node/npm arguments and sends exact HEAD to Pages', async () => {
+ const f = await fixture(); const npmCli = join(f.root, 'npm cli.js');
+ await deploy({ site: f.site, npmCli, run: f.run, log: quiet });
+ const commands = f.calls.filter(call => call.file !== 'git');
+ expect(commands).toHaveLength(2);
+ expect(commands[0].file).toBe(process.execPath);
+ expect(commands[0].args).toEqual([npmCli, 'exec', '--yes', `--package=wrangler@${WRANGLER_VERSION}`, '--', 'wrangler', '--version']);
+ expect(commands[1].args).toEqual([npmCli, 'exec', '--yes', `--package=wrangler@${WRANGLER_VERSION}`, '--', 'wrangler', 'pages', 'deploy', f.dist, '--project-name', 'kilnstudio', '--branch', 'production', '--commit-hash', head, '--commit-dirty=false']);
+ expect(commands[1].options?.inherit).toBe(true);
+ expect(f.calls.at(-2)?.file).toBe('git');
+ });
+
+ test.each(['tamper', 'reseal', 'dirty', 'head', 'functions'])('rechecks immediately after Wrangler preparation: %s', async (kind) => {
+ const f = await fixture();
+ f.onVersion(async () => {
+ if (kind === 'tamper') await writeFile(join(f.dist, 'index.html'), 'changed');
+ if (kind === 'reseal') { f.info.builtAt = 'changed'; await f.seal(); }
+ if (kind === 'dirty') f.setStatus(' M src/change.ts\n');
+ if (kind === 'head') f.setHead(otherHead);
+ if (kind === 'functions') await mkdir(join(f.site, 'functions'));
+ });
+ await expect(deploy({ site: f.site, npmCli: '/test/npm-cli.js', run: f.run, log: quiet })).rejects.toThrow();
+ expect(f.calls.some(call => call.args.includes('deploy'))).toBe(false);
+ });
+
+ test('an explicit Wrangler executable must match the exact pin', async () => {
+ const f = await fixture(); f.setVersion('4.146.0');
+ await expect(deploy({ site: f.site, wrangler: '/test/wrangler', run: f.run, log: quiet })).rejects.toThrow(/4\.147\.0/);
+ expect(f.calls.some(call => call.args.includes('deploy'))).toBe(false);
+ });
+
+ test('propagates an upload failure instead of reporting a deployment', async () => {
+ const f = await fixture();
+ const run = async (file: string, args: string[], options?: Command['options']) => {
+ if (args.includes('deploy')) throw new Error('Upload failed');
+ return f.run(file, args, options);
+ };
+ await expect(deploy({ site: f.site, npmCli: '/test/npm-cli.js', run, log: quiet })).rejects.toThrow('Upload failed');
+ });
+
+ test('uses npm CLI JavaScript on Windows without a command shell', async () => {
+ const f = await fixture(); const nodeDir = join(f.root, 'node');
+ const cli = join(nodeDir, 'node_modules/npm/bin/npm-cli.js');
+ await mkdir(join(nodeDir, 'node_modules/npm/bin'), { recursive: true }); await writeFile(cli, '// fixture');
+ expect(await resolveNpmCli({ execPath: join(nodeDir, 'node.exe'), env: {}, platform: 'win32' })).toBe(cli);
+ });
+
+ test('accepts portable flags and refuses the old production bypass or unknown options', () => {
+ expect(parseArgs(['--site', '/test/site', '--project-name', 'kilnstudio', '--dry-run'])).toEqual({ site: '/test/site', projectName: 'kilnstudio', dryRun: true });
+ expect(() => parseArgs(['--allow-packs-off'])).toThrow(/packs/i);
+ expect(() => parseArgs(['--site'])).toThrow(/value/i);
+ expect(() => parseArgs(['--unsafe'])).toThrow(/unknown/i);
+ });
+});
diff --git a/site/scripts/initial-runtime.mjs b/site/scripts/initial-runtime.mjs
index a50ccc60..a57ac8ed 100644
--- a/site/scripts/initial-runtime.mjs
+++ b/site/scripts/initial-runtime.mjs
@@ -22,7 +22,9 @@ function importsOf(file, code) {
}
/** Verify FF3's explicit initial campus closure against every delivered chunk and its actual import statements. */
export async function measureInitialLoad({receipt,chunks,code,packRelease=receipt.release}) {
- if(receipt.mode!=='public' || !['ff3','ff3-review2'].includes(receipt.release) || !Array.isArray(receipt.chunks) || !Array.isArray(receipt.initialChunks))throw new Error('Expected a public FF3 initial-load receipt');
+ // code1 through code5 are explicit metadata-only delivery namespaces, not appearance acceptance.
+ // Each receipt must still name the delivered manifest and prove every chunk below.
+ if(receipt.mode!=='public' || !['ff3','ff3-review2','ff3-review2-code1','ff3-review2-code2','ff3-review2-code3','ff3-review2-code4','ff3-review2-code5'].includes(receipt.release) || !Array.isArray(receipt.chunks) || !Array.isArray(receipt.initialChunks))throw new Error('Expected a public FF3 initial-load receipt');
if(receipt.release!==packRelease)throw new Error('Initial-load receipt names a different scene pack release');
const records=receipt.chunks.map(record=>({...record,file:fileOf(record.name)}));
if(new Set(records.map(c=>c.file)).size!==records.length || !same(records.map(c=>c.file),chunks.map(c=>c.file)))throw new Error('Initial-load chunk inventory differs from delivered files');
diff --git a/site/scripts/initial-runtime.test.ts b/site/scripts/initial-runtime.test.ts
index a355910e..fc68468e 100644
--- a/site/scripts/initial-runtime.test.ts
+++ b/site/scripts/initial-runtime.test.ts
@@ -25,6 +25,18 @@ test('the registered-floor review release keeps the same verified initial closur
await expect(measureInitialLoad({receipt:next,chunks,code,packRelease:'ff3'})).rejects.toThrow(/release/);
await expect(measureInitialLoad({receipt:{...next,release:'ff3-unreviewed'},chunks,code,packRelease:'ff3-unreviewed'})).rejects.toThrow(/receipt/);
});
+test.each(['ff3-review2-code1','ff3-review2-code2','ff3-review2-code3','ff3-review2-code4','ff3-review2-code5'])('the explicit %s delivery label retains pack equality, hashes and initial closure checks', async release=>{
+ const next={...receipt(),release};
+ const result=await measureInitialLoad({receipt:next,chunks,code,packRelease:next.release});
+ expect(result.files).toEqual(['camera-part.js','exterior-part.js','index-root.js']);
+ expect(result.bytes).toBe(next.initialCode.bytes);
+ await expect(measureInitialLoad({receipt:next,chunks,code,packRelease:'ff3-review2'})).rejects.toThrow(/release/);
+ await expect(measureInitialLoad({receipt:{...next,release:'ff3-review2-code6'},chunks,code,packRelease:'ff3-review2-code6'})).rejects.toThrow(/receipt/);
+ const forged=structuredClone(next);forged.chunks[0]!.sha256='0'.repeat(64);
+ await expect(measureInitialLoad({receipt:forged,chunks,code,packRelease:next.release})).rejects.toThrow(/pin/);
+ const omitted={...next,initialChunks:next.initialChunks.filter(name=>!name.includes('camera'))};
+ await expect(measureInitialLoad({receipt:omitted,chunks,code,packRelease:next.release})).rejects.toThrow(/closure/);
+});
test('missing chunks, forged hashes, omitted static dependencies and non-dynamic interiors fail closed',async()=>{
const missing=receipt();missing.chunks.pop();await expect(measureInitialLoad({receipt:missing,chunks,code})).rejects.toThrow(/chunk inventory/);
const hash=receipt();hash.chunks[0]!.sha256='0'.repeat(64);await expect(measureInitialLoad({receipt:hash,chunks,code})).rejects.toThrow(/pin/);
diff --git a/site/scripts/scene-console.mjs b/site/scripts/scene-console.mjs
new file mode 100644
index 00000000..3d153b03
--- /dev/null
+++ b/site/scripts/scene-console.mjs
@@ -0,0 +1,26 @@
+// Known lines remain in the report. Unknown messages and incomplete evidence fail closed.
+const KNOWN_WARNINGS = [/^THREE\.Clock: This module has been deprecated/];
+const UNSUPPORTED_BLUETOOTH = "Error with Permissions-Policy header: Unrecognized feature: 'bluetooth'.";
+
+function unsupportedBluetooth(entry, environment) {
+ // Chrome documents Linux Bluetooth support behind an experimental flag:
+ // https://developer.chrome.com/docs/capabilities/bluetooth
+ // features() enumerates supported policy features; allowedFeatures() would only
+ // show what this document's policy permits and cannot prove lack of support.
+ if (entry.type !== 'warn' || entry.text !== UNSUPPORTED_BLUETOOTH
+ || !/^Chrome\/\d+\./.test(environment?.browser ?? '')
+ || !/^Linux\b/.test(environment?.platform ?? '')
+ || environment?.secureContext !== true || environment?.bluetoothApiPresent !== false
+ || !Array.isArray(environment?.supportedPolicyFeatures)
+ || environment.supportedPolicyFeatures.includes('bluetooth')
+ || typeof environment?.permissionsPolicy !== 'string') return false;
+ const directives = environment.permissionsPolicy.split(',').map((value) => value.trim())
+ .filter((value) => /^bluetooth(?:\s|=|$)/.test(value));
+ return directives.length === 1 && /^bluetooth\s*=\s*\(\s*\)$/.test(directives[0]);
+}
+
+export function classifyExploreConsole(entries, environment) {
+ const flagged = entries.filter((entry) => entry.scenario === 'explore' && ['error', 'warn', 'warning'].includes(entry.type));
+ const isKnown = (entry) => KNOWN_WARNINGS.some((pattern) => pattern.test(entry.text)) || unsupportedBluetooth(entry, environment);
+ return { known: flagged.filter(isKnown), unexpected: flagged.filter((entry) => !isKnown(entry)) };
+}
diff --git a/site/scripts/scene-console.test.ts b/site/scripts/scene-console.test.ts
new file mode 100644
index 00000000..84edd28c
--- /dev/null
+++ b/site/scripts/scene-console.test.ts
@@ -0,0 +1,62 @@
+import { expect, test } from 'bun:test';
+import { classifyExploreConsole } from './scene-console.mjs';
+
+const text = "Error with Permissions-Policy header: Unrecognized feature: 'bluetooth'.";
+const warning = { scenario: 'explore', type: 'warn', text };
+const observed = {
+ browser: 'Chrome/150.0.7871.128',
+ platform: 'Linux x86_64',
+ secureContext: true,
+ bluetoothApiPresent: false,
+ supportedPolicyFeatures: ['camera', 'geolocation', 'fullscreen'],
+ permissionsPolicy: 'camera=(), microphone=(), bluetooth=(), geolocation=()',
+};
+
+test('retains the exact unsupported Bluetooth warning as known only with observed browser and deny-header evidence', () => {
+ const entries = [warning];
+ const result = classifyExploreConsole(entries, observed);
+ expect(result).toEqual({ known: [warning], unexpected: [] });
+ expect(result.known[0]).toBe(warning);
+ expect(entries).toEqual([warning]);
+});
+
+test('missing or contradictory browser support evidence never excuses a policy warning', () => {
+ for (const environment of [
+ undefined,
+ {},
+ { ...observed, browser: undefined },
+ { ...observed, browser: 'Firefox/150.0' },
+ { ...observed, platform: undefined },
+ { ...observed, platform: 'Win32' },
+ { ...observed, secureContext: false },
+ { ...observed, secureContext: undefined },
+ { ...observed, bluetoothApiPresent: true },
+ { ...observed, bluetoothApiPresent: undefined },
+ { ...observed, supportedPolicyFeatures: null },
+ { ...observed, supportedPolicyFeatures: undefined },
+ { ...observed, supportedPolicyFeatures: ['camera', 'bluetooth'] },
+ ]) expect(classifyExploreConsole([warning], environment)).toEqual({ known: [], unexpected: [warning] });
+});
+
+test('the served header must declare exactly one empty Bluetooth allowlist', () => {
+ for (const permissionsPolicy of [undefined, null, '', 'camera=()', 'bluetooth=*', 'bluetooth=(self)', 'bluetooth', 'bluetooth=(), bluetooth=*', 'bluetooth=(), bluetooth=()', 'not-bluetooth=()']) {
+ expect(classifyExploreConsole([warning], { ...observed, permissionsPolicy })).toEqual({ known: [], unexpected: [warning] });
+ }
+});
+
+test('only the exact Puppeteer warn message is classified, never errors or other warnings', () => {
+ for (const entry of [
+ { ...warning, type: 'error' },
+ { ...warning, type: 'warning' },
+ { ...warning, text: text.replace('bluetooth', 'camera') },
+ { ...warning, text: `${text} Other failure` },
+ { ...warning, text: 'Unknown policy error' },
+ ]) expect(classifyExploreConsole([entry], observed)).toEqual({ known: [], unexpected: [entry] });
+});
+
+test('existing upstream Clock reporting and unexpected Explore failures remain intact', () => {
+ const clock = { scenario: 'explore', type: 'warn', text: 'THREE.Clock: This module has been deprecated. Please use THREE.Timer instead.' };
+ const error = { scenario: 'explore', type: 'error', text: 'Scene failed' };
+ const injected = { scenario: 'pack-unavailable', type: 'error', text: 'Intentional failed request' };
+ expect(classifyExploreConsole([clock, error, injected], observed)).toEqual({ known: [clock], unexpected: [error] });
+});
diff --git a/site/scripts/scene-controls-observer.test.ts b/site/scripts/scene-controls-observer.test.ts
new file mode 100644
index 00000000..08bd985a
--- /dev/null
+++ b/site/scripts/scene-controls-observer.test.ts
@@ -0,0 +1,64 @@
+import { expect, test } from 'bun:test';
+import { installControlObserver } from './verify-scene-controls.mjs';
+
+function fixture() {
+ const devtools = new EventTarget();
+ const root = { getAttribute: () => 'webgpu', querySelectorAll: () => [{}] };
+ const actor = { matrixWorld: { elements: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 3, 4, 1] } };
+ const attributes = new Float32Array([1, 2, 3, 0, 99, 99, 99, 0]);
+ const freight = { name: 'traffic-truck-tractor-lod0', visible: true, geometry: { instanceCount: 1, attributes: { iA: { array: attributes } } } };
+ const state: any = { scene: null, camera: actor, gl: { domElement: { isConnected: true, closest: () => root } } };
+ const scene = { isScene: true, __r3f: { root: { getState: () => state } }, getObjectByName: (name: string) => name === 'farmer-yard-0' ? actor : null, traverse: (visit: any) => visit(freight) };
+ state.scene = scene;
+ const scope: any = { EventTarget, __THREE_DEVTOOLS__: devtools, document: { visibilityState: 'visible' }, __timingEvidence: { gpu: () => ({ status: 'bound' }) } };
+ return { scope, state, scene, actor, attributes, freight, observe: (detail: unknown) => devtools.dispatchEvent(new CustomEvent('observe', { detail })) };
+}
+
+test('serialized observer uses the mounted renderer root and copies only active named transforms/buffers without updates', () => {
+ const f = fixture(), prior = f.scope.__THREE_DEVTOOLS__;
+ const serialized = new Function(`return (${installControlObserver.toString()})`)();
+ serialized(f.scope);
+ f.observe({ isScene: true }); // Reflection/temporary scenes do not become a root.
+ f.observe(f.scene);
+ const result = f.scope.__siteControlSnapshot();
+ expect(f.scope.__THREE_DEVTOOLS__).toBe(prior);
+ expect(result.farmer).toEqual({ subject: 'farmer-yard-0', position: [2, 3, 4] });
+ expect(result.freight).toEqual([{ name: 'traffic-truck-tractor-lod0', positions: [[1, 2, 3, 0]] }]);
+ expect(result.gpu.status).toBe('bound');
+ result.freight[0].positions[0][0] = 100;
+ result.farmer.position[0] = 100;
+ expect(f.attributes[0]).toBe(1);
+ expect(f.actor.matrixWorld.elements[12]).toBe(2);
+});
+
+test('observer fails closed for absent, disconnected or ambiguous renderer roots', () => {
+ const f = fixture(); installControlObserver(f.scope);
+ expect(() => f.scope.__siteControlSnapshot()).toThrow(/observed 0/);
+ f.observe(f.scene); f.state.gl.domElement.isConnected = false;
+ expect(() => f.scope.__siteControlSnapshot()).toThrow(/observed 0/);
+ f.state.gl.domElement.isConnected = true;
+ const second = fixture(); f.observe(second.scene);
+ expect(() => f.scope.__siteControlSnapshot()).toThrow(/observed 2/);
+});
+
+test('invisible freight and inactive capacity never count as visible movement evidence', () => {
+ const f = fixture(); installControlObserver(f.scope); f.observe(f.scene);
+ f.freight.visible = false;
+ expect(f.scope.__siteControlSnapshot().freight).toEqual([]);
+ f.freight.visible = true; f.freight.geometry.instanceCount = 0;
+ expect(f.scope.__siteControlSnapshot().freight).toEqual([]);
+});
+
+test('camera projection and canvas size evidence is copied without changing the live camera', () => {
+ const f = fixture();
+ f.state.camera.fov = 50;
+ f.state.gl.domElement.clientWidth = 390;
+ f.state.gl.domElement.clientHeight = 791;
+ installControlObserver(f.scope); f.observe(f.scene);
+ const result = f.scope.__siteControlSnapshot();
+ expect(result.camera.fov).toBe(50);
+ expect(result.camera.forward).toEqual([-0, -0, -1]);
+ expect(result.canvas).toEqual({ width: 390, height: 791 });
+ result.camera.forward[2] = 7;
+ expect(f.actor.matrixWorld.elements[10]).toBe(1);
+});
diff --git a/site/scripts/scene-controls-proof.mjs b/site/scripts/scene-controls-proof.mjs
new file mode 100644
index 00000000..18c72dd7
--- /dev/null
+++ b/site/scripts/scene-controls-proof.mjs
@@ -0,0 +1,85 @@
+import assert from 'node:assert/strict';
+
+const position = value => Array.isArray(value) && value.length >= 3 && value.every(Number.isFinite);
+const freightKind = name => /^traffic-truck-tractor-lod\d$/.test(name) ? 'tractor' : /^traffic-trailer-(dryvan|flatbed|tanker)-lod\d$/.test(name) ? 'trailer' : null;
+
+export function assertPositionMotion(before, after, minimum = 0.05) {
+ assert.ok(before?.subject && before.subject === after?.subject, 'Movement must observe the same subject');
+ assert.ok(position(before.position) && position(after.position), 'Movement requires finite observed positions');
+ const metres = Math.hypot(after.position[0] - before.position[0], after.position[2] - before.position[2]);
+ assert.ok(metres > minimum, `No meaningful horizontal movement: ${metres} m`);
+ return metres;
+}
+
+export function assertPanelObservation(panel) {
+ assert.ok(panel?.rect && panel.root && panel.hitWithin, 'Panel must receive touches above the scene');
+ for (const rect of [panel.rect, panel.root]) {
+ assert.ok(['left', 'top', 'right', 'bottom'].every(key => Number.isFinite(rect[key])), 'Panel bounds missing');
+ assert.ok(rect.right > rect.left && rect.bottom > rect.top, 'Panel must have an area');
+ }
+ assert.ok(panel.rect.left >= panel.root.left - 1 && panel.rect.right <= panel.root.right + 1 && panel.rect.top >= panel.root.top - 1 && panel.rect.bottom <= panel.root.bottom + 1, 'Panel is clipped outside the scene');
+ assert.ok(['scrollHeight', 'clientHeight', 'scrollBefore', 'scrollAfter'].every(key => Number.isFinite(panel[key])) && panel.clientHeight > 0, 'Panel scroll observations missing');
+ if (panel.scrollHeight > panel.clientHeight + 2) assert.ok(panel.scrollAfter > panel.scrollBefore + 1, 'Overflowing panel did not scroll under real touch');
+}
+
+export function assertControlBackend(requested, observed, headed) {
+ assert.equal(headed, true, 'Live control qualification requires a headed browser');
+ assert.ok(['webgpu', 'webgl2'].includes(requested), 'Explicit backend required');
+ assert.equal(observed?.backend, requested, 'Rendered backend differs from requested backend');
+ let identity;
+ if (requested === 'webgpu') {
+ assert.equal(observed.gpu?.status, 'bound', 'Actual canvas device must be bound to its adapter');
+ assert.deepEqual(observed.gpu.errors, []);
+ identity = Object.values(observed.gpu.adapter ?? {}).filter(value => typeof value === 'string').join(' ').trim();
+ } else identity = observed.glRenderer;
+ assert.ok(typeof identity === 'string' && identity.trim(), 'Renderer hardware identity missing');
+ assert.doesNotMatch(identity, /swiftshader|llvmpipe|lavapipe|software|microsoft basic render/i, 'Software renderer cannot qualify live hardware controls');
+}
+
+/** Visible instance-buffer changes only; no individual vehicle identity or fifth-wheel alignment claim. */
+export function movingFreightKinds(before, after) {
+ const moved = new Set();
+ for (const row of after ?? []) {
+ const kind = freightKind(row.name);
+ if (!kind) continue;
+ const previous = before?.find(candidate => candidate.name === row.name);
+ if (row.positions?.some((value, index) => position(value) && position(previous?.positions?.[index]) && Math.hypot(value[0] - previous.positions[index][0], value[2] - previous.positions[index][2]) > 0.05)) moved.add(kind);
+ }
+ return ['tractor', 'trailer'].filter(kind => moved.has(kind));
+}
+
+export function visibleFreightKinds(rows) {
+ const kinds = new Set((rows ?? []).filter(row => row.positions?.some(position)).map(row => freightKind(row.name)));
+ return ['tractor', 'trailer'].filter(kind => kinds.has(kind));
+}
+
+/** Public FF campus gestures, derived from its sealed The split preset and road span.
+ * Pixel deltas follow the pinned OrbitControls defaults. Readback, not the plan,
+ * establishes that a real browser gesture reached the requested camera pose.
+ */
+export function freightScanPlan(canvas, camera) {
+ assert.ok(canvas && Number.isFinite(canvas.width) && Number.isFinite(canvas.height) && canvas.width > 80 && canvas.height > 80, 'Freight scan requires measured canvas dimensions');
+ assert.ok(position(camera?.position) && position(camera.forward) && camera.fov === 50, 'Freight scan requires The split camera and projection');
+ const target = [-2400, 35, 0], offset = camera.position.map((value, index) => value - target[index]);
+ const radius = Math.hypot(...offset);
+ assert.ok(Math.abs(camera.position[0] + 3917.012466228799) < 2 && Math.abs(camera.position[1] - 142.57870284779813) < 2 && Math.abs(camera.position[2]) < 2, 'The split public view was not applied');
+ assert.ok(Math.hypot(...camera.forward.map((value, index) => value + offset[index] / radius)) < 0.002, 'The split camera points away from its target');
+ const distance = 500, halfFov = Math.tan(camera.fov * Math.PI / 360), stepMetres = 160;
+ assert.ok(stepMetres < 2 * distance * halfFov * canvas.width / canvas.height, 'Canvas is too narrow for the bounded freight sweep');
+ const pixels = (metres, at) => metres * canvas.height / (2 * at * halfFov);
+ // Raise the orbit before panning: the sweep crosses 70m front fins and the
+ // public rig keeps six metres clear of grounded solids on every input frame.
+ const polar = Math.acos(offset[1] / radius) - Math.PI / 50;
+ return { rotatePixels: canvas.height / 4, rotateYPixels: canvas.height / 100, panWestPixels: pixels(-1800, radius),
+ wheelDelta: -100 * Math.log(distance / radius) / Math.log(0.95), scanPanPixels: pixels(stepMetres, distance),
+ startPosition: [-4200, target[1] + Math.cos(polar) * distance, -Math.sin(polar) * distance],
+ forward: [0, -Math.cos(polar), Math.sin(polar)], stepMetres, maxPositions: 55 };
+}
+
+export function assertFreightScanCamera(camera, plan, step) {
+ assert.ok(Number.isInteger(step) && step >= 0 && step < plan.maxPositions, 'Freight scan step exceeds its bound');
+ assert.ok(position(camera?.position) && position(camera.forward) && camera.fov === 50, 'Freight scan camera evidence missing');
+ const expected = plan.startPosition.map((value, index) => value + (index === 0 ? step * plan.stepMetres : 0));
+ assert.ok(Math.hypot(...camera.position.map((value, index) => value - expected[index])) < 4, `Public freight gesture missed corridor step ${step}: ${camera.position}`);
+ assert.ok(Math.hypot(...camera.forward.map((value, index) => value - plan.forward[index])) < 0.004, 'Public freight gesture changed the viewing direction');
+}
diff --git a/site/scripts/scene-controls-proof.test.ts b/site/scripts/scene-controls-proof.test.ts
new file mode 100644
index 00000000..9656e877
--- /dev/null
+++ b/site/scripts/scene-controls-proof.test.ts
@@ -0,0 +1,88 @@
+import { expect, test } from 'bun:test';
+import { assertControlBackend, assertPanelObservation, assertPositionMotion, movingFreightKinds, freightScanPlan, visibleFreightKinds, assertFreightScanCamera } from './scene-controls-proof.mjs';
+
+test('movement evidence requires finite positions of the same observed subject and meaningful horizontal travel', () => {
+ const before = { subject: 'farmer-yard-0', position: [0, 1, 0] };
+ expect(() => assertPositionMotion(before, { ...before, position: [0.3, 1, 0] })).not.toThrow();
+ for (const after of [before, null, { ...before, position: [0, 2, 0] }, { ...before, position: [NaN, 1, 0] }, { subject: 'camera', position: [3, 1, 0] }]) {
+ expect(() => assertPositionMotion(before, after)).toThrow();
+ }
+});
+
+test('panel evidence rejects clipped, obscured, unscrollable-overflow and missing observations', () => {
+ const panel = { rect: { left: 12, top: 70, right: 372, bottom: 600 }, root: { left: 0, top: 0, right: 390, bottom: 650 }, hitWithin: true, scrollHeight: 800, clientHeight: 530, scrollBefore: 0, scrollAfter: 80 };
+ expect(() => assertPanelObservation(panel)).not.toThrow();
+ for (const value of [null, { ...panel, hitWithin: false }, { ...panel, scrollAfter: 0 }, { ...panel, rect: { ...panel.rect, right: 420 } }, { ...panel, clientHeight: NaN }]) {
+ expect(() => assertPanelObservation(value)).toThrow();
+ }
+});
+
+test('control qualification needs headed actual backend and the bound renderer hardware, not a separate adapter probe', () => {
+ const observed = { backend: 'webgpu', gpu: { status: 'bound', adapter: { description: 'NVIDIA RTX' }, errors: [] } };
+ expect(() => assertControlBackend('webgpu', observed, true)).not.toThrow();
+ for (const value of [null, { ...observed, backend: 'webgl2' }, { ...observed, gpu: { status: 'unbound', adapter: observed.gpu.adapter, errors: [] } }, { ...observed, gpu: { ...observed.gpu, adapter: { description: 'SwiftShader' } } }, { ...observed, gpu: { ...observed.gpu, adapter: {} } }]) {
+ expect(() => assertControlBackend('webgpu', value, true)).toThrow();
+ }
+ expect(() => assertControlBackend('webgpu', observed, false)).toThrow();
+ expect(() => assertControlBackend('webgl2', { backend: 'webgl2', glRenderer: 'ANGLE (NVIDIA)' }, true)).not.toThrow();
+ expect(() => assertControlBackend('webgl2', { backend: 'webgl2', glRenderer: 'llvmpipe' }, true)).toThrow();
+});
+
+test('freight proof distinguishes advancing tractor and trailer buffers from static or unrelated traffic', () => {
+ const row = (name: string, x: number) => ({ name, positions: [[x, 0, 1, 0]] });
+ const before = [row('traffic-truck-tractor-lod0', 1), row('traffic-trailer-dryvan-lod0', 2), row('traffic-sedan-lod0', 3)];
+ const after = [row('traffic-truck-tractor-lod0', 2), row('traffic-trailer-dryvan-lod0', 3), row('traffic-sedan-lod0', 4)];
+ expect(movingFreightKinds(before, after)).toEqual(['tractor', 'trailer']);
+ expect(movingFreightKinds(before, before)).toEqual([]);
+ expect(movingFreightKinds(before, [after[0]])).toEqual(['tractor']);
+ expect(movingFreightKinds(before, [row('traffic-trailer-dryvan-lod1', 3)])).toEqual([]);
+ expect(movingFreightKinds(before, [row('traffic-truck-tractor-lod0', NaN)])).toEqual([]);
+});
+
+const splitCamera = { subject: 'camera', position: [-3917.012466228799, 142.57870284779813, 0], fov: 50,
+ forward: [0.9974949866040544, -0.0707372016677029, 0] };
+
+test('public freight sweep covers the sealed road with overlapping views and scales real gestures with canvas height', () => {
+ const plan = freightScanPlan({ width: 390, height: 791 }, splitCamera);
+ expect(plan.rotatePixels).toBeCloseTo(791 / 4, 8);
+ expect(plan.rotateYPixels).toBeCloseTo(791 / 100, 8);
+ expect(plan.panWestPixels).toBeCloseTo(-1003.848136120502, 8);
+ expect(plan.wheelDelta).toBeCloseTo(-2168.7011295566035, 8);
+ expect(plan.startPosition[0]).toBe(-4200);
+ // The road sweep passes narrow 70m grounded front fins; six metres of clearance
+ // must not change the camera on intermediate pointermove frames.
+ expect(plan.startPosition[1]).toBeGreaterThan(76);
+ expect(plan.startPosition[1]).toBeCloseTo(35 + 500 * Math.cos(1.5 - Math.PI / 50), 8);
+ expect(plan.startPosition[2]).toBeCloseTo(-500 * Math.sin(1.5 - Math.PI / 50), 8);
+ expect(plan.maxPositions).toBe(55);
+ expect(plan.startPosition[0] + (plan.maxPositions - 1) * plan.stepMetres).toBeGreaterThanOrEqual(4300);
+ // Projected road width is wider than the stride, so the fixed camera sweep has no gaps.
+ expect(plan.stepMetres).toBeLessThan(2 * 500 * Math.tan(25 * Math.PI / 180) * 390 / 791);
+ const resized = freightScanPlan({ width: 780, height: 1582 }, splitCamera);
+ expect(resized.rotatePixels).toBe(plan.rotatePixels * 2);
+ expect(resized.rotateYPixels).toBe(plan.rotateYPixels * 2);
+ expect(resized.panWestPixels).toBe(plan.panWestPixels * 2);
+ expect(resized.scanPanPixels).toBe(plan.scanPanPixels * 2);
+ expect(resized.wheelDelta).toBe(plan.wheelDelta);
+ for (const [canvas, camera] of [
+ [{ width: 0, height: 791 }, splitCamera], [{ width: 390, height: NaN }, splitCamera],
+ [{ width: 100, height: 791 }, splitCamera], [{ width: 390, height: 791 }, { ...splitCamera, fov: 40 }],
+ [{ width: 390, height: 791 }, { ...splitCamera, position: [-4460, 45, -250] }],
+ [{ width: 390, height: 791 }, { ...splitCamera, forward: [-1, 0, 0] }],
+ ]) expect(() => freightScanPlan(canvas, camera)).toThrow();
+});
+
+test('freight scan needs both finite visible kinds and camera readback matching the requested corridor step', () => {
+ const row = (name: string, positions: number[][]) => ({ name, positions });
+ const tractor = row('traffic-truck-tractor-lod2', [[0, 1, 2, 0]]);
+ const trailer = row('traffic-trailer-dryvan-lod2', [[2, 1, 2, 0]]);
+ expect(visibleFreightKinds([tractor, trailer])).toEqual(['tractor', 'trailer']);
+ expect(visibleFreightKinds([tractor, tractor])).toEqual(['tractor']);
+ expect(visibleFreightKinds([row('traffic-sedan-lod0', [[1, 2, 3, 0]]), row('traffic-trailer-tanker-lod1', [[NaN, 0, 0, 0]])])).toEqual([]);
+ const plan = freightScanPlan({ width: 390, height: 791 }, splitCamera);
+ const observed = { subject: 'camera', position: [...plan.startPosition], forward: [0, -Math.cos(1.5 - Math.PI / 50), Math.sin(1.5 - Math.PI / 50)], fov: 50 };
+ expect(() => assertFreightScanCamera(observed, plan, 0)).not.toThrow();
+ expect(() => assertFreightScanCamera({ ...observed, position: [observed.position[0] + plan.stepMetres, ...observed.position.slice(1)] }, plan, 1)).not.toThrow();
+ expect(() => assertFreightScanCamera(observed, plan, 1)).toThrow();
+ expect(() => assertFreightScanCamera({ ...observed, forward: [1, 0, 0] }, plan, 0)).toThrow();
+});
diff --git a/site/scripts/scene-delivery-binding.mjs b/site/scripts/scene-delivery-binding.mjs
new file mode 100644
index 00000000..ded2e3c0
--- /dev/null
+++ b/site/scripts/scene-delivery-binding.mjs
@@ -0,0 +1,47 @@
+import { parse } from 'parse5';
+import { compareRuntimeRecord } from './scene-pack.mjs';
+
+const ORIGIN = 'https://kilnstudio.tools';
+const elements = (html, tag) => {
+ const found = [];
+ const walk = node => { if (node.tagName === tag) found.push(Object.fromEntries((node.attrs ?? []).map(a => [a.name, a.value]))); for (const child of node.childNodes ?? []) walk(child); };
+ walk(parse(html)); return found;
+};
+const requireEqual = (actual, expected, message) => { if (actual !== expected) throw new Error(`${message}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`); };
+
+/**
+ * Self-consistent runtime hashes alone can describe the wrong delivery. Bind the selected catalog
+ * to the emitted shell and, for frame scenes, the actual entry script and asset-base metadata.
+ * Payload hashes, producer evidence and budgets remain separate verification steps.
+ */
+export function verifySceneDeliveryBinding({ id, record, runtime, shellHtml, frameHtml }) {
+ if (!['farm', 'golden-gate', 'foundry-floor'].includes(id)) throw new Error(`Unknown scene binding: ${id}`);
+ requireEqual(record?.id, id, 'Catalog scene id');
+ requireEqual(runtime?.schema, 'kiln.scene-runtime/1', 'Runtime schema');
+ requireEqual(runtime?.id, id, 'Runtime scene id');
+ const kind = id === 'farm' ? 'module' : 'frame';
+ requireEqual(runtime.kind, kind, 'Runtime kind');
+ if (!/^[A-Za-z0-9_-]+\.js$/.test(runtime.file)) throw new Error('Invalid runtime entry file');
+ if (kind === 'frame') {
+ const differences = compareRuntimeRecord(record.runtime, runtime);
+ if (differences.length) throw new Error(`Served catalog runtime differs: ${differences.join('; ')}`);
+ }
+ const root = `/scene-runtime/${id}/`, entry = `${root}${runtime.file}`, url = kind === 'frame' ? `${root}frame.html` : entry;
+ requireEqual(runtime.url, url, 'Runtime URL');
+ const shells = elements(shellHtml, 'scene-shell');
+ requireEqual(shells.length, 1, 'Exactly one emitted scene shell');
+ const shell = shells[0];
+ for (const [key, value] of Object.entries({ 'data-scene': id, 'data-kind': kind, 'data-runtime-url': url, 'data-asset-base': record.base })) requireEqual(shell[key], value, `Scene shell ${key}`);
+ if (kind === 'frame') {
+ requireEqual(runtime.chunk, entry, 'Runtime chunk URL');
+ if (typeof frameHtml !== 'string') throw new Error('Frame HTML is required');
+ const bases = elements(frameHtml, 'meta').filter(e => e.name === 'kiln-asset-base');
+ requireEqual(bases.length, 1, 'Exactly one frame asset base');
+ requireEqual(bases[0].content, record.base, 'Frame asset base');
+ const scripts = elements(frameHtml, 'script').filter(e => e.type === 'module');
+ requireEqual(scripts.length, 1, 'Exactly one frame module');
+ if (!scripts[0].src) throw new Error('Frame entry module needs src');
+ requireEqual(new URL(scripts[0].src, new URL(url, ORIGIN)).href, new URL(entry, ORIGIN).href, 'Frame module entry');
+ }
+ return { id, kind, runtimeUrl: url, assetBase: record.base, entry };
+}
diff --git a/site/scripts/scene-delivery-binding.test.ts b/site/scripts/scene-delivery-binding.test.ts
new file mode 100644
index 00000000..019cd6c4
--- /dev/null
+++ b/site/scripts/scene-delivery-binding.test.ts
@@ -0,0 +1,51 @@
+import { expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { gzipSync } from 'node:zlib';
+import { verifySceneDeliveryBinding } from './scene-delivery-binding.mjs';
+import { verifyRuntimePayload } from './served-runtime.mjs';
+
+function fixture() {
+ const id = 'golden-gate', file = 'index-current.js', base = '/scene-packs/golden-gate/g9-code5/';
+ const pin = { kind: 'frame', file, bytes: 42, gzipBytes: 33, gzipMethod: 'bun-zlib', sha256: 'a'.repeat(64), modulesSha256: 'b'.repeat(64) };
+ const record = { id, release: 'g9-code5', base, runtime: pin };
+ const runtime = { schema: 'kiln.scene-runtime/1', id, ...pin, url: `/scene-runtime/${id}/frame.html`, chunk: `/scene-runtime/${id}/${file}` };
+ const shellHtml = `<scene-shell data-scene="${id}" data-kind="frame" data-runtime-url="${runtime.url}" data-asset-base="${base}"></scene-shell>`;
+ const frameHtml = `<meta name="kiln-asset-base" content="${base}"><script type="module" src="./${file}"></script>`;
+ return { id, record, runtime, shellHtml, frameHtml };
+}
+test('binds the catalog, scene shell, frame pack metadata and actual module reference', () => {
+ expect(verifySceneDeliveryBinding(fixture())).toMatchObject({ id: 'golden-gate' });
+});
+test('rejects a self-consistent stale payload that still passes its own byte checks', async () => {
+ const f = fixture(), bytes = Buffer.from('export const stale = true'), digest = createHash('sha256').update(bytes).digest('hex');
+ f.runtime.file = 'index-old.js'; f.runtime.bytes = bytes.length; f.runtime.gzipBytes = gzipSync(bytes).length; f.runtime.sha256 = digest;
+ const served = { ...f.runtime, kind: 'module' };
+ expect(await verifyRuntimePayload(served, async () => bytes)).toMatchObject({ bytes: bytes.length });
+ expect(() => verifySceneDeliveryBinding(f)).toThrow(/catalog runtime/);
+});
+test.each(['sha256', 'modulesSha256', 'bytes', 'gzipBytes', 'chunks', 'initialLoad'])('rejects catalog %s drift even if runtime.json is internally consistent', field => {
+ const f = fixture(); (f.runtime as any)[field] = field.includes('Bytes') || field === 'bytes' ? 1 : 'changed';
+ expect(() => verifySceneDeliveryBinding(f)).toThrow(/catalog runtime/);
+});
+test.each([
+ ['stale frame asset base', (f: ReturnType<typeof fixture>) => { f.frameHtml = f.frameHtml.replaceAll('g9-code5', 'g9-code3'); }],
+ ['wrong frame entry', (f: ReturnType<typeof fixture>) => { f.frameHtml = f.frameHtml.replace('index-current.js', 'index-old.js'); }],
+ ['extra frame module', (f: ReturnType<typeof fixture>) => { f.frameHtml += '<script type="module" src="./extra.js"></script>'; }],
+ ['duplicate frame pack metadata', (f: ReturnType<typeof fixture>) => { f.frameHtml += '<meta name="kiln-asset-base" content="/other/">'; }],
+ ['external frame entry', (f: ReturnType<typeof fixture>) => { f.frameHtml = f.frameHtml.replace('./index-current.js', 'https://elsewhere.test/index-current.js'); }],
+ ['stale shell asset base', (f: ReturnType<typeof fixture>) => { f.shellHtml = f.shellHtml.replaceAll('g9-code5', 'g9-code3'); }],
+ ['wrong shell runtime URL', (f: ReturnType<typeof fixture>) => { f.shellHtml = f.shellHtml.replace('/frame.html', '/old.html'); }],
+ ['wrong shell scene', (f: ReturnType<typeof fixture>) => { f.shellHtml = f.shellHtml.replace('data-scene="golden-gate"', 'data-scene="farm"'); }],
+ ['duplicate shell', (f: ReturnType<typeof fixture>) => { f.shellHtml += f.shellHtml; }],
+ ['wrong runtime id', (f: ReturnType<typeof fixture>) => { f.runtime.id = 'foundry-floor'; }],
+ ['wrong runtime entry URL', (f: ReturnType<typeof fixture>) => { f.runtime.chunk = '/scene-runtime/golden-gate/index-other.js'; }],
+] as const)('rejects %s', (_name, mutate) => {
+ const f = fixture(); mutate(f); expect(() => verifySceneDeliveryBinding(f)).toThrow();
+});
+test('Farm module mode binds the actual shell to its exact emitted entry and selected pack', () => {
+ const runtime = { schema: 'kiln.scene-runtime/1', id: 'farm', kind: 'module', file: 'farm-current.js', url: '/scene-runtime/farm/farm-current.js' };
+ const record = { id: 'farm', base: '/scene-packs/farm/r36-local-review/' };
+ const shellHtml = `<scene-shell data-scene="farm" data-kind="module" data-runtime-url="${runtime.url}" data-asset-base="${record.base}"></scene-shell>`;
+ expect(verifySceneDeliveryBinding({ id: 'farm', record, runtime, shellHtml })).toMatchObject({ id: 'farm' });
+ expect(() => verifySceneDeliveryBinding({ id: 'farm', record, runtime, shellHtml: shellHtml.replace('farm-current.js', 'farm-old.js') })).toThrow();
+});
diff --git a/site/scripts/scene-pack.test.ts b/site/scripts/scene-pack.test.ts
index 7a1afd0d..77e01bf3 100644
--- a/site/scripts/scene-pack.test.ts
+++ b/site/scripts/scene-pack.test.ts
@@ -3,7 +3,6 @@ import { existsSync } from 'node:fs';
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
-import pkg from '../package.json';
import scenePacks from '../src/data/scene-packs.json';
import { farmScene, foundryFloorScene, goldenGateScene } from '../src/data/scenes';
import { hashBytes } from './mirror-core.mjs';
@@ -284,7 +283,8 @@ describe('scene pack catalog record', () => {
expect(record.base).toBe(`/scene-packs/farm/${record.release}/`);
expect(record.source).toBe('.cache/site-inputs/farm/standalone');
expect(record).toMatchObject({ sealedFiles: 34, sealedBytes: 7_133_727, packJsonSha256: '5d046aa2c04637436d7e3918db690f4f25f6684a58ae7a78d333dec9df428f48' });
- expect(record.three).toBe(pkg.dependencies.three);
+ // The sealed asset pack keeps its original producer version when current runtime code advances.
+ expect(record.three).toBe('0.186.0');
expect(record.totalFiles).toBe(record.sealedFiles + 3);
expect(record.totalBytes).toBeGreaterThan(record.sealedBytes);
for (const digest of [record.packJsonSha256, record.sha256sumsSha256, record.noticesSha256]) expect(digest).toMatch(/^[0-9a-f]{64}$/);
@@ -294,37 +294,37 @@ describe('scene pack catalog record', () => {
expect(() => stagedPackDirectory({ base: '/../escape/' }, '/site')).toThrow('Unexpected');
});
- test('the Golden Gate record is the g9 local review with the final six vehicles, inside its ceiling', () => {
+ test('the Golden Gate code5 delivery retains the g9 asset payload inside its runtime ceiling', () => {
const record = scenePacks['golden-gate'];
- expect(record.release).toBe('g9');
- expect(record.base).toBe('/scene-packs/golden-gate/g9/');
- // Preserved g9 carries the new six-vehicle delivery with the qualified water opening and controls.
- expect(record).toMatchObject({ sealedFiles: 103, sealedBytes: 12_186_327, packJsonSha256: 'c2a1d83fce6caf07a7b3e87070ccb8a983dd68e0c7f98eee3f1ba5255ce059cb', sha256sumsSha256: '75ce79fc746eafd27d7b597396489294a821fef5d88a05981b6bb9572159a58a' });
+ expect(record.release).toBe('g9-code5');
+ expect(record.base).toBe('/scene-packs/golden-gate/g9-code5/');
+ // Only the delivery release changes the asset manifest; every sealed g9 payload digest remains.
+ expect(record).toMatchObject({ sealedFiles: 103, sealedBytes: 12_186_327, packJsonSha256: '748536356d9639c65c76bc18f1e865c3426f5ee49904239efcb9b9c24c8a1524', sha256sumsSha256: '75ce79fc746eafd27d7b597396489294a821fef5d88a05981b6bb9572159a58a' });
expect(record.source).toBe('.cache/site-inputs/golden-gate/standalone');
- expect(record.three).toBe(pkg.dependencies.three);
+ expect(record.three).toBe('0.186.0');
expect(record.totalFiles).toBe(record.sealedFiles + 3);
for (const digest of [record.packJsonSha256, record.sha256sumsSha256, record.noticesSha256, record.runtime.sha256, record.runtime.modulesSha256]) expect(digest).toMatch(/^[0-9a-f]{64}$/);
- expect(record.runtime).toMatchObject({ kind: 'frame', file: 'index-BDTQ3svb.js', bytes: 1_724_619, gzipBytes: 518_716 });
+ expect(record.runtime).toMatchObject({ kind: 'frame', file: 'index-DhpWxFro.js', bytes: 1_708_928, gzipBytes: 512_680 });
expect(checkCeiling('golden-gate', record.runtime).within).toBe(true);
expect(record.runtime.bytes).toBeLessThanOrEqual(CEILINGS['golden-gate'].bytes);
expect(goldenGateScene.assetBase).toBe(record.base);
- expect(stagedPackDirectory(record, '/site')).toBe(resolve('/site', 'public', 'scene-packs', 'golden-gate', 'g9'));
+ expect(stagedPackDirectory(record, '/site')).toBe(resolve('/site', 'public', 'scene-packs', 'golden-gate', 'g9-code5'));
});
- test('the Foundry Floor record is ff3-review2 with a verified initial closure inside its ceiling', () => {
+ test('the Foundry Floor code5 delivery retains the review2 payload with a verified initial closure inside its ceiling', () => {
const record = scenePacks['foundry-floor'];
- expect(record.release).toBe('ff3-review2');
- expect(record.base).toBe('/scene-packs/foundry-floor/ff3-review2/');
+ expect(record.release).toBe('ff3-review2-code5');
+ expect(record.base).toBe('/scene-packs/foundry-floor/ff3-review2-code5/');
expect(record.source).toBe('.cache/site-inputs/foundry-floor/standalone');
- expect(record.three).toBe(pkg.dependencies.three);
+ expect(record.three).toBe('0.186.0');
expect(record.totalFiles).toBe(record.sealedFiles + 3);
// Final frozen FF3 intake verifies 85 sealed files and every initial/deferred chunk.
- expect(record).toMatchObject({ sealedFiles: 85, sealedBytes: 11_519_818, packJsonSha256: '6ce49d05791bf42d21f3628237a5cf005ce9f2fa15938f0c321430d781c2c5d4' });
+ expect(record).toMatchObject({ sealedFiles: 85, sealedBytes: 11_519_818, packJsonSha256: '822be1171621273dfdf857fe6ca320ed41d16e03c49fc49860c13e7092be4836' });
for (const digest of [record.packJsonSha256, record.sha256sumsSha256, record.noticesSha256, record.runtime.sha256, record.runtime.modulesSha256]) expect(digest).toMatch(/^[0-9a-f]{64}$/);
- expect(record.runtime).toMatchObject({ kind: 'frame', file: 'index-Y86dU6mu.js', bytes: 1_705_082, gzipBytes: 517_258, initialLoad: { bytes: 1_527_808, gzipBytes: 446_414 } });
+ expect(record.runtime).toMatchObject({ kind: 'frame', file: 'index-BpDIz-38.js', bytes: 1_710_132, gzipBytes: 519_928, initialLoad: { bytes: 1_532_295, gzipBytes: 448_748 } });
expect(checkCeiling('foundry-floor', record.runtime).within).toBe(true);
expect(foundryFloorScene.assetBase).toBe(record.base);
- expect(stagedPackDirectory(record, '/site')).toBe(resolve('/site', 'public', 'scene-packs', 'foundry-floor', 'ff3-review2'));
+ expect(stagedPackDirectory(record, '/site')).toBe(resolve('/site', 'public', 'scene-packs', 'foundry-floor', 'ff3-review2-code5'));
});
test.each(['farm', 'golden-gate', 'foundry-floor'])('the %s scene page stays out of search results whatever its availability says', async (id) => {
diff --git a/site/scripts/scene-producer.mjs b/site/scripts/scene-producer.mjs
new file mode 100644
index 00000000..128ecb92
--- /dev/null
+++ b/site/scripts/scene-producer.mjs
@@ -0,0 +1,73 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { SCENE_DEDUPE, packageRoots, posix } from './scene-source.mjs';
+
+export const PRODUCER_SCHEMA = 'kiln.scene-producer/1';
+const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
+const version = (value, name) => {
+ if (typeof value !== 'string' || !VERSION.test(value)) throw new Error(`Invalid producer ${name} version`);
+ return value;
+};
+const rootsFor = (modules) => {
+ if (!Array.isArray(modules) || modules.some((id) => typeof id !== 'string')) throw new Error('Invalid producer modules');
+ const roots = packageRoots(modules);
+ for (const [name, copies] of roots) if (copies.size > 1) throw new Error(`Producer has multiple ${name} roots`);
+ return roots;
+};
+
+/** A sealed Bun store path is historical evidence; an unversioned path says nothing about a version. */
+function pathVersion(root, name) {
+ if (!root) return null;
+ const prefix = `${name.replace('/', '+')}@`;
+ const store = /\/node_modules\/\.bun\/([^/]+)\/node_modules\//.exec(posix(root))?.[1];
+ if (!store?.startsWith(prefix)) return null;
+ // Bun's optional peer-context suffix is not part of the package version.
+ const candidate = store.slice(prefix.length).replace(/\+[0-9a-f]+$/, '');
+ return version(candidate, name);
+}
+
+function checkedChunks(chunks) {
+ if (!Array.isArray(chunks) || chunks.length === 0) throw new Error('Producer receipt has no chunks');
+ const seen = new Set();
+ return chunks.map((chunk) => {
+ if (!chunk || typeof chunk.file !== 'string' || !/^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+\.js$/.test(chunk.file)
+ || seen.has(chunk.file) || !Number.isSafeInteger(chunk.bytes) || chunk.bytes < 0 || !/^[a-f0-9]{64}$/.test(chunk.sha256)) throw new Error('Invalid producer chunk');
+ seen.add(chunk.file);
+ return { file: chunk.file, bytes: chunk.bytes, sha256: chunk.sha256 };
+ }).sort((a, b) => a.file.localeCompare(b.file, 'en'));
+}
+
+/** Verify a producer receipt against the bytes being staged; never consult this machine's packages. */
+export function producerEvidence({ modules, producer, chunks }) {
+ const roots = rootsFor(modules);
+ const inferred = Object.fromEntries([...roots].map(([name, copies]) => [name, pathVersion([...copies][0], name)]));
+ if (producer === undefined) return { source: 'module-paths', dependencies: inferred, build: { vite: null, pluginReact: null } };
+ if (!producer || producer.schema !== PRODUCER_SCHEMA) throw new Error('Unknown scene producer schema');
+ const dependencies = {};
+ for (const name of SCENE_DEDUPE) {
+ const value = producer.dependencies?.[name];
+ if (roots.get(name).size === 0) {
+ if (value !== null) throw new Error(`Producer lists absent ${name}`);
+ dependencies[name] = null;
+ continue;
+ }
+ dependencies[name] = version(value, name);
+ if (inferred[name] && inferred[name] !== value) throw new Error(`Producer ${name} version contradicts module paths`);
+ }
+ const build = { vite: version(producer.build?.vite, 'vite'), pluginReact: version(producer.build?.pluginReact, 'pluginReact') };
+ if (JSON.stringify(checkedChunks(producer.chunks)) !== JSON.stringify(checkedChunks(chunks))) throw new Error('Producer chunks do not match the runtime');
+ return { source: 'producer-receipt', dependencies, build };
+}
+
+/** Used only while producing a new build: read the package roots that actually contributed modules. */
+export function createProducerReceipt({ modules, chunks, build }) {
+ const dependencies = Object.fromEntries([...rootsFor(modules)].map(([name, roots]) => {
+ if (roots.size === 0) return [name, null];
+ const metadata = JSON.parse(readFileSync(join([...roots][0], 'package.json'), 'utf8'));
+ if (metadata.name !== name) throw new Error(`Producer package metadata does not name ${name}`);
+ return [name, version(metadata.version, name)];
+ }));
+ const producer = { schema: PRODUCER_SCHEMA, dependencies, build: { vite: build.vite, pluginReact: build.pluginReact }, chunks: checkedChunks(chunks) };
+ producerEvidence({ modules, producer, chunks });
+ return producer;
+}
diff --git a/site/scripts/scene-producer.test.ts b/site/scripts/scene-producer.test.ts
new file mode 100644
index 00000000..13d44904
--- /dev/null
+++ b/site/scripts/scene-producer.test.ts
@@ -0,0 +1,52 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createProducerReceipt, producerEvidence } from './scene-producer.mjs';
+
+const directories: string[] = [];
+afterEach(async () => { for (const path of directories.splice(0)) await rm(path, { recursive: true, force: true }); });
+const modules = ['C:/old/scenes/node_modules/.bun/[email protected]/node_modules/three/build/three.core.js'];
+const chunks = [{ file: 'assets/index-x.js', bytes: 24, sha256: 'a'.repeat(64) }];
+const receipt = () => ({ schema: 'kiln.scene-producer/1', dependencies: { three: '0.186.0', react: null, 'react-dom': null, '@react-three/fiber': null } as Record<string, string | null>, build: { vite: '8.3.2', pluginReact: '6.0.3' }, chunks: structuredClone(chunks) });
+
+describe('scene producer evidence', () => {
+ test('historical modules identify the bundled version without borrowing installed tool versions', () => {
+ expect(producerEvidence({ modules, chunks })).toEqual({ source: 'module-paths', dependencies: { three: '0.186.0', react: null, 'react-dom': null, '@react-three/fiber': null }, build: { vite: null, pluginReact: null } });
+ expect(producerEvidence({ modules: ['/old/node_modules/three/build/three.core.js'], chunks }).dependencies.three).toBeNull();
+ });
+
+ test('a complete receipt binds exact chunks and carries producer tool versions', () => {
+ expect(producerEvidence({ modules, chunks, producer: receipt() })).toMatchObject({ source: 'producer-receipt', dependencies: { three: '0.186.0' }, build: { vite: '8.3.2', pluginReact: '6.0.3' } });
+ });
+
+ test('rejects contradictory or invalid dependency versions instead of trusting a false receipt', () => {
+ for (const version of ['0.186.1', '^0.186.0', null, '/home/private']) {
+ const producer = receipt(); producer.dependencies.three = version;
+ expect(() => producerEvidence({ modules, chunks, producer })).toThrow();
+ }
+ const producer = receipt(); producer.dependencies.react = '19.3.0';
+ expect(() => producerEvidence({ modules, chunks, producer })).toThrow('react');
+ const invalid = receipt(); invalid.build.vite = '^8.3.2';
+ expect(() => producerEvidence({ modules, chunks, producer: invalid })).toThrow('vite');
+ expect(() => producerEvidence({ modules, chunks, producer: { ...receipt(), schema: 'unknown' } })).toThrow('schema');
+ });
+
+ test('rejects changed, missing, extra, duplicated and unsafe chunks', () => {
+ const cases = [[], [...chunks, chunks[0]], [{ ...chunks[0], file: '../index-x.js' }], [{ ...chunks[0], bytes: 25 }], [{ ...chunks[0], sha256: 'b'.repeat(64) }], [...chunks, { ...chunks[0], file: 'assets/extra.js' }]];
+ for (const recorded of cases) expect(() => producerEvidence({ modules, chunks, producer: { ...receipt(), chunks: recorded } })).toThrow('chunk');
+ });
+
+ test('current producers read versions at the actual bundled module roots', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'kiln-producer-')); directories.push(root);
+ const packageRoot = join(root, 'node_modules/three');
+ await mkdir(packageRoot, { recursive: true });
+ await writeFile(join(packageRoot, 'package.json'), JSON.stringify({ name: 'three', version: '0.186.1' }));
+ const currentModules = [join(packageRoot, 'build/three.core.js')];
+ const produced = createProducerReceipt({ modules: currentModules, chunks, build: { vite: '8.3.2', pluginReact: '6.0.3' } });
+ expect(produced.dependencies.three).toBe('0.186.1');
+ expect(producerEvidence({ modules: currentModules, chunks, producer: produced }).dependencies.three).toBe('0.186.1');
+ await writeFile(join(packageRoot, 'package.json'), JSON.stringify({ name: 'other', version: '0.186.1' }));
+ expect(() => createProducerReceipt({ modules: currentModules, chunks, build: produced.build })).toThrow('three');
+ });
+});
diff --git a/site/scripts/scene-runtime.mjs b/site/scripts/scene-runtime.mjs
index 37a8ea1a..f152d3ef 100644
--- a/site/scripts/scene-runtime.mjs
+++ b/site/scripts/scene-runtime.mjs
@@ -2,11 +2,13 @@ import { spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import { copyFile, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { createRequire } from 'node:module';
import { dirname, join, resolve } from 'node:path';
import { gzipSync } from 'node:zlib';
import { fileURLToPath } from 'node:url';
import { measureInitialLoad, verifyInitialLoad } from './initial-runtime.mjs';
import { installFrameReporter } from '../src/scenes/frame-reporter.mjs';
+import { createProducerReceipt, producerEvidence } from './scene-producer.mjs';
import { RUNTIME_DIRECTORY, SCENE_DEDUPE, SCENE_PACKAGES, duplicatePackages, exportAliases, packageRoots, posix, resolveScenesDir, threeFacade } from './scene-source.mjs';
const SITE = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -121,6 +123,7 @@ export async function buildRuntime({ id = 'farm', scenesDir, outDir, alias = tru
const file = files[0];
const bytes = await readFile(join(outDir, file));
const gzip = gzipMeasure(bytes);
+ const producer = createProducerReceipt({ modules, chunks: [{ file, bytes: bytes.length, sha256: sha256(bytes) }], build: { vite: toolVersion('vite'), pluginReact: toolVersion('@vitejs/plugin-react') } });
return {
id,
file,
@@ -131,6 +134,7 @@ export async function buildRuntime({ id = 'farm', scenesDir, outDir, alias = tru
modules: [...new Set(modules)].sort(),
copies: packageCopies(modules),
facade: modules.some((moduleId) => posix(moduleId).endsWith('/packages/scene-kit/src/renderer/three-runtime.ts')),
+ producer: producerEvidence({ modules, producer, chunks: producer.chunks }),
};
}
@@ -146,17 +150,25 @@ export function checkCeiling(id, measurement) {
};
}
-const toolVersion = (name, site = SITE) => {
- try {
- return JSON.parse(readFileSync(resolve(site, 'node_modules', name, 'package.json'), 'utf8')).version;
- } catch {
- return null;
+const require = createRequire(import.meta.url);
+const toolVersion = (name) => {
+ let directory = dirname(require.resolve(name));
+ while (true) {
+ const path = join(directory, 'package.json');
+ if (existsSync(path)) {
+ const metadata = JSON.parse(readFileSync(path, 'utf8'));
+ if (metadata.name === name) return metadata.version;
+ }
+ const parent = dirname(directory);
+ if (parent === directory) throw new Error(`Cannot identify the ${name} producer version`);
+ directory = parent;
}
};
/** The public build record stored beside the staged runtime. It carries no local paths. */
-export function runtimeManifest(id, measurement, { kind = 'module', site = SITE } = {}) {
+export function runtimeManifest(id, measurement, { kind = 'module' } = {}) {
const fit = checkCeiling(id, measurement);
+ const producer = measurement.producer ?? producerEvidence({ modules: measurement.modules ?? [] });
return {
schema: RUNTIME_SCHEMA,
id,
@@ -170,8 +182,8 @@ export function runtimeManifest(id, measurement, { kind = 'module', site = SITE
...(measurement.chunks ? { chunks: measurement.chunks } : {}),
...(measurement.initialLoad ? { initialLoad: measurement.initialLoad } : {}),
ceiling: { ...fit.ceiling, decision: 'D-15', ...(measurement.initialLoad ? { scope: 'Initial campus static closure; interior deferred until Enter the fab' } : {}), withinCeiling: fit.within, percent: fit.percent },
- three: { version: toolVersion('three', site), facade: measurement.facade, copies: Object.fromEntries(Object.entries(measurement.copies).map(([name, roots]) => [name, roots.map((root) => root.replace(/^.*\/node_modules\//, 'node_modules/'))])) },
- build: { vite: toolVersion('vite', site), pluginReact: toolVersion('@vitejs/plugin-react', site), dedupe: [...SCENE_DEDUPE] },
+ three: { version: producer.dependencies.three, facade: measurement.facade, copies: Object.fromEntries(Object.entries(measurement.copies).map(([name, roots]) => [name, roots.map((root) => root.replace(/^.*\/node_modules\//, 'node_modules/'))])) },
+ build: { ...producer.build, dedupe: [...SCENE_DEDUPE], dependencies: producer.dependencies, evidence: producer.source },
};
}
@@ -255,12 +267,14 @@ export async function measureFrameRuntime({ id, source }) {
}
const entry = chunks.find((chunk) => chunk.file === entries[0]);
const modulesBytes = await readFile(join(source, 'bundle-modules.json'));
- const modules = JSON.parse(modulesBytes.toString('utf8')).modules;
+ const moduleReceipt = JSON.parse(modulesBytes.toString('utf8'));
+ const modules = moduleReceipt.modules;
if (!Array.isArray(modules)) throw new Error('bundle-modules.json lists no modules');
const duplicates = duplicatePackages(modules);
if (duplicates.length) {
throw new Error(`The ${id} build carries more than one copy of ${duplicates.map(({ name, copies }) => `${name} (${copies.join(', ')})`).join('; ')}`);
}
+ const producer = producerEvidence({ modules, producer: moduleReceipt.producer, chunks: chunks.map((chunk) => ({ ...chunk, file: `assets/${chunk.file}` })) });
let initialLoad;
if (existsSync(join(source, 'bundle-public.json'))) {
if (id !== 'foundry-floor') throw new Error('Initial campus receipts are specific to Foundry Floor');
@@ -280,6 +294,7 @@ export async function measureFrameRuntime({ id, source }) {
sha256: entry.sha256,
...(chunks.length > 1 ? { chunks } : {}),
modules,
+ producer,
copies: packageCopies(modules),
facade: modules.some((moduleId) => posix(moduleId).endsWith('/packages/scene-kit/src/renderer/three-runtime.ts')),
};
diff --git a/site/scripts/scene-runtime.test.ts b/site/scripts/scene-runtime.test.ts
index 6071e695..ecfbf50c 100644
--- a/site/scripts/scene-runtime.test.ts
+++ b/site/scripts/scene-runtime.test.ts
@@ -148,6 +148,28 @@ describe('a standalone runtime staged as built', () => {
expect(record.modulesSha256).toBe(hashBytes(await readFile(join(source, 'bundle-modules.json'))));
});
+ test('validates new producer receipts before staging a runtime independently of the asset pack version', async () => {
+ const root = await temp();
+ const modules = [FACADE, '/producer/node_modules/.bun/[email protected]/node_modules/three/build/three.core.js'];
+ const source = await standalone(root, { modules });
+ const chunk = await readFile(join(source, 'assets/index-abc123.js'));
+ const producer = { schema: 'kiln.scene-producer/1', dependencies: { three: '0.186.1', react: null, 'react-dom': null, '@react-three/fiber': null }, build: { vite: '8.3.2', pluginReact: '6.0.3' }, chunks: [{ file: 'assets/index-abc123.js', bytes: chunk.length, sha256: hashBytes(chunk) }] };
+ // Asset provenance remains the sealed pack's version; a code-only rebuild may advance the renderer.
+ await json(join(source, 'assets/pack.json'), { three: '0.186.0', release: 'g9' });
+ await json(join(source, 'bundle-modules.json'), { modules, producer });
+ const measurement = await measureFrameRuntime({ id: 'golden-gate', source });
+ const manifest = await stageFrameRuntime({ id: 'golden-gate', source, measurement, packBase: '/scene-packs/golden-gate/g9/', site: join(root, 'site') });
+ expect(manifest.three.version).toBe('0.186.1');
+ expect(manifest.build).toMatchObject({ vite: '8.3.2', pluginReact: '6.0.3', evidence: 'producer-receipt' });
+ expect(JSON.stringify(manifest)).not.toContain('/producer/');
+ await writeFile(join(source, 'assets/index-abc123.js'), 'changed');
+ await expect(measureFrameRuntime({ id: 'golden-gate', source })).rejects.toThrow('Producer chunks');
+ await writeFile(join(source, 'assets/index-abc123.js'), chunk);
+ producer.dependencies.three = '0.186.0';
+ await json(join(source, 'bundle-modules.json'), { modules, producer });
+ await expect(measureFrameRuntime({ id: 'golden-gate', source })).rejects.toThrow('contradicts');
+ });
+
test('refuses a second entry, a second three, a missing facade and a bundle over its ceiling', async () => {
const two = await standalone(await temp());
await writeFile(join(two, 'assets', 'index-other.js'), 'x');
@@ -213,6 +235,22 @@ describe('a standalone runtime staged as built', () => {
});
describe('a runtime manifest', () => {
+ test('archived runtime metadata describes its producer, even beside newer installed dependencies', async () => {
+ const root = await temp();
+ const source = await standalone(root);
+ const site = join(root, 'site');
+ await json(join(site, 'node_modules/three/package.json'), { version: '9.9.9' });
+ await json(join(site, 'node_modules/vite/package.json'), { version: '99.0.0' });
+ await json(join(site, 'node_modules/@vitejs/plugin-react/package.json'), { version: '99.0.0' });
+ const { measurement } = await measureFrameRuntime({ id: 'golden-gate', source });
+ const manifest = runtimeManifest('golden-gate', measurement, { kind: 'frame', site });
+ expect(manifest.three.version).toBe('0.186.0');
+ expect(manifest.build).toMatchObject({ vite: null, pluginReact: null, evidence: 'module-paths' });
+ const unknown = await standalone(await temp(), { modules: [FACADE, '/old/node_modules/three/build/three.core.js'] });
+ const unversioned = await measureFrameRuntime({ id: 'golden-gate', source: unknown });
+ expect(runtimeManifest('golden-gate', unversioned.measurement, { kind: 'frame', site }).three.version).toBeNull();
+ });
+
test('records the measurement, the ceiling it was held to and the three it carries', () => {
const measurement = { file: 'farm-abc.js', bytes: 1_582_844, gzipBytes: 462_811, gzipMethod: 'bun-zlib', sha256: 'a'.repeat(64), facade: true, copies: { three: ['C:/scenes/node_modules/.bun/[email protected]/node_modules/three'], react: [], 'react-dom': [], '@react-three/fiber': [] } };
const manifest = runtimeManifest('farm', measurement, { site: SITE });
diff --git a/site/scripts/scene-viewport.mjs b/site/scripts/scene-viewport.mjs
new file mode 100644
index 00000000..46151751
--- /dev/null
+++ b/site/scripts/scene-viewport.mjs
@@ -0,0 +1,33 @@
+/** The scene mount's minimum room, from browser measurements. */
+export function sceneHasRoom(measured) {
+ const { documentClientWidth, overlayClientWidth, overlay, mount } = measured;
+ if (!overlay || !mount) return false;
+ const values = [documentClientWidth, overlayClientWidth, overlay.left, overlay.right, overlay.width, mount.left, mount.right, mount.width, mount.height];
+ if (!values.every(Number.isFinite) || documentClientWidth <= 0 || overlayClientWidth <= 0) return false;
+ // A native browser scrollbar occupies part of innerWidth; an overlay scrollbar
+ // can further reduce its client width. Neither represents a narrow scene.
+ return Math.abs(overlay.left) <= 1 && Math.abs(overlay.right - documentClientWidth) <= 1
+ && Math.abs(overlay.width - documentClientWidth) <= 1
+ && overlayClientWidth <= overlay.width + 1
+ && Math.abs(mount.width - overlayClientWidth) <= 1
+ && mount.left >= overlay.left - 1 && mount.right <= overlay.right + 1
+ && mount.height >= 200;
+}
+
+/** Runs in the browser before page scripts so late control reveals remain visible. */
+export function observeSceneLayoutShifts(scope = window) {
+ scope.__shifts = [];
+ new scope.PerformanceObserver((list) => {
+ const rect = (value) => value ? { x: value.x, y: value.y, width: value.width, height: value.height } : null;
+ for (const entry of list.getEntries()) scope.__shifts.push({
+ value: entry.value, hadRecentInput: entry.hadRecentInput, time: entry.startTime,
+ fonts: scope.document.fonts.status,
+ exploreHidden: scope.document.querySelector('scene-shell [data-explore]')?.hidden ?? null,
+ sources: (entry.sources ?? []).map((source) => ({
+ tag: source.node?.tagName ?? null, id: source.node?.id ?? null,
+ classes: typeof source.node?.className === 'string' ? source.node.className : null,
+ previous: rect(source.previousRect), current: rect(source.currentRect),
+ })),
+ });
+ }).observe({ type: 'layout-shift', buffered: true });
+}
diff --git a/site/scripts/scene-viewport.test.ts b/site/scripts/scene-viewport.test.ts
new file mode 100644
index 00000000..932c06d1
--- /dev/null
+++ b/site/scripts/scene-viewport.test.ts
@@ -0,0 +1,71 @@
+import { expect, test } from 'bun:test';
+import { observeSceneLayoutShifts, sceneHasRoom } from './scene-viewport.mjs';
+
+const measured = {
+ viewportWidth: 390,
+ documentClientWidth: 375,
+ overlay: { left: 0, right: 375, width: 375 },
+ overlayClientWidth: 375,
+ mount: { left: 0, right: 375, width: 375, height: 851 },
+};
+
+test('a scene fills the layout viewport when the browser reserves a scrollbar', () => {
+ expect(sceneHasRoom(measured)).toBe(true);
+});
+
+test('a scrollbar inside the overlay reduces the available mount width', () => {
+ expect(sceneHasRoom({ ...measured, overlayClientWidth: 360, mount: { ...measured.mount, right: 360, width: 360 } })).toBe(true);
+});
+
+test('a viewport without scrollbar reservation still needs a full-width overlay and mount', () => {
+ expect(sceneHasRoom({ ...measured, viewportWidth: 375 })).toBe(true);
+});
+
+test('a genuinely narrow overlay or mount fails, even without horizontal overflow', () => {
+ expect(sceneHasRoom({ ...measured, viewportWidth: 375, overlay: { left: 0, right: 360, width: 360 } })).toBe(false);
+ expect(sceneHasRoom({ ...measured, viewportWidth: 375, mount: { ...measured.mount, right: 360, width: 360 } })).toBe(false);
+});
+
+test('shifted or oversized overlay and mount rectangles are not full viewport coverage', () => {
+ expect(sceneHasRoom({ ...measured, viewportWidth: 375, overlay: { left: 15, right: 390, width: 375 } })).toBe(false);
+ expect(sceneHasRoom({ ...measured, viewportWidth: 375, overlay: { left: 0, right: 390, width: 390 } })).toBe(false);
+ expect(sceneHasRoom({ ...measured, viewportWidth: 375, mount: { ...measured.mount, left: 15, right: 390 } })).toBe(false);
+});
+
+test('the existing 200px minimum height and 1px width tolerance remain', () => {
+ expect(sceneHasRoom({ ...measured, mount: { ...measured.mount, height: 199 } })).toBe(false);
+ expect(sceneHasRoom({ ...measured, mount: { ...measured.mount, width: 374.5, right: 374.5, height: 200 } })).toBe(true);
+});
+
+test('absent, zero or nonfinite measurements fail closed', () => {
+ for (const change of [
+ { mount: null }, { overlay: null }, { overlayClientWidth: 0 },
+ { documentClientWidth: Number.NaN }, { overlayClientWidth: Infinity },
+ { mount: { ...measured.mount, height: Infinity } },
+ ]) expect(sceneHasRoom({ ...measured, viewportWidth: 375, ...change })).toBe(false);
+});
+
+test('layout-shift receipts retain source rectangles and timing without retaining live DOM nodes', () => {
+ let notify!: (list: { getEntries: () => any[] }) => void;
+ let observed: unknown;
+ const scope = {
+ __shifts: [] as any[],
+ document: { fonts: { status: 'loaded' }, querySelector: () => ({ hidden: false }) },
+ PerformanceObserver: class {
+ constructor(callback: typeof notify) { notify = callback; }
+ observe(options: unknown) { observed = options; }
+ },
+ };
+ observeSceneLayoutShifts(scope);
+ const previousRect = { x: 33, y: 577.609375, width: 687, height: 322.390625 };
+ const currentRect = { x: 33, y: 649.609375, width: 687, height: 250.390625 };
+ const node = { tagName: 'DIV', id: '', className: 'grid gap-px bg-rule' };
+ notify({ getEntries: () => [{ value: 0.026113501549358126, hadRecentInput: false, startTime: 52.9, sources: [{ node, previousRect, currentRect }] }] });
+ expect(observed).toEqual({ type: 'layout-shift', buffered: true });
+ expect(scope.__shifts[0]).toEqual({
+ value: 0.026113501549358126, hadRecentInput: false, time: 52.9, fonts: 'loaded', exploreHidden: false,
+ sources: [{ tag: 'DIV', id: '', classes: 'grid gap-px bg-rule', previous: previousRect, current: currentRect }],
+ });
+ expect(scope.__shifts[0].sources[0].previous).not.toBe(previousRect);
+ expect(JSON.stringify(scope.__shifts)).not.toContain('tagName');
+});
diff --git a/site/scripts/upload-set.mjs b/site/scripts/upload-set.mjs
index f7274a6d..ebeb5e14 100644
--- a/site/scripts/upload-set.mjs
+++ b/site/scripts/upload-set.mjs
@@ -5,7 +5,8 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
/**
* The files that have to be on the asset host before KILN_SITE_PACKS can be 1: every pinned file in
* `src/data/mirror-manifest.json` plus the exact GLBs extracted from the sealed Farm archive in
- * `src/data/upload-manifest.json`. Nothing here uploads anything; this reads the two checked-in manifests and
+ * `src/data/upload-manifest.json`, and the pinned runtime archives in `src/data/scene-inputs.json`.
+ * Nothing here uploads anything; this reads the three checked-in manifests and
* prints what the owner would upload and what to check afterwards, so the list is never a number remembered from an
* earlier report.
*
@@ -15,13 +16,22 @@ const SITE = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const SHA256 = /^[0-9a-f]{64}$/;
const groupOf = (path) => path.split('/').slice(0, 2).join('/');
+const validBase = (value) => {
+ if (typeof value !== 'string' || !value.endsWith('/')) return false;
+ try {
+ const url = new URL(value);
+ return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash;
+ } catch { return false; }
+};
-export function summarizeUploadSet(mirror, upload) {
+export function summarizeUploadSet(mirror, upload, sceneInputs = { base: mirror.base, files: [] }) {
const problems = [];
const groups = new Map();
const seen = new Map();
const mirrorPaths = new Set((mirror.files ?? []).map((record) => record.path));
const count = (source, records, base) => {
+ if (!validBase(base)) problems.push(`${source}: base must be an absolute HTTP(S) URL ending in /`);
+ else if (base !== mirror.base) problems.push(`${source}: base does not match mirror-manifest base`);
for (const record of records ?? []) {
if (typeof record?.path !== 'string' || !record.path || record.path.startsWith('/') || record.path.includes('..')) {
problems.push(`${source}: a record has no usable path (${JSON.stringify(record)?.slice(0, 80)})`);
@@ -41,6 +51,7 @@ export function summarizeUploadSet(mirror, upload) {
};
count('mirror-manifest', mirror.files, mirror.base);
count('upload-manifest', upload.files, upload.base);
+ count('scene-inputs', sceneInputs.files, sceneInputs.base);
// An extracted GLB is a member of an archive that is itself in the mirror; one that names another archive would be unverifiable.
for (const record of upload.files ?? []) {
if (!mirrorPaths.has(record.archive)) problems.push(`${record.path}: its archive ${record.archive} is not a pinned mirror file`);
@@ -50,13 +61,13 @@ export function summarizeUploadSet(mirror, upload) {
total.files += entry.files;
total.bytes += entry.bytes;
}
- return { mirrorFiles: mirror.files?.length ?? 0, extractedFiles: upload.files?.length ?? 0, groups: [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([group, entry]) => ({ group, ...entry })), total, problems };
+ return { mirrorFiles: mirror.files?.length ?? 0, extractedFiles: upload.files?.length ?? 0, sceneInputFiles: sceneInputs.files?.length ?? 0, groups: [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([group, entry]) => ({ group, ...entry })), total, problems };
}
async function main() {
const readJson = async (name) => JSON.parse(await readFile(join(SITE, 'src/data', name), 'utf8'));
- const summary = summarizeUploadSet(await readJson('mirror-manifest.json'), await readJson('upload-manifest.json'));
- console.log(`Upload set: ${summary.mirrorFiles} pinned mirror files and ${summary.extractedFiles} extracted Farm GLBs; ${summary.total.files} files, ${summary.total.bytes.toLocaleString('en-US')} bytes. Nothing is uploaded by this script.`);
+ const summary = summarizeUploadSet(await readJson('mirror-manifest.json'), await readJson('upload-manifest.json'), await readJson('scene-inputs.json'));
+ console.log(`Upload set: ${summary.mirrorFiles} pinned mirror files, ${summary.extractedFiles} extracted Farm GLBs and ${summary.sceneInputFiles} scene input archives; ${summary.total.files} files, ${summary.total.bytes.toLocaleString('en-US')} bytes. Nothing is uploaded by this script.`);
for (const { group, files, bytes } of summary.groups) console.log(` ${group.padEnd(40)} ${String(files).padStart(4)} files ${String(bytes).padStart(13)} bytes`);
console.log(`Problems: ${summary.problems.length}`);
for (const problem of summary.problems) console.log(` ${problem}`);
diff --git a/site/scripts/upload-set.test.ts b/site/scripts/upload-set.test.ts
index fb9d53e7..918727cc 100644
--- a/site/scripts/upload-set.test.ts
+++ b/site/scripts/upload-set.test.ts
@@ -16,6 +16,14 @@ const upload = {
base,
files: [{ path: 'packs/farm/r1/models/a.glb', url: `${base}packs/farm/r1/models/a.glb`, bytes: 40, sha256: sha('d'), archive: 'packs/farm/r1/farm.zip', member: 'models/a.glb' }],
};
+const sceneInputs = {
+ base,
+ files: [
+ { path: 'scene-inputs/release1/farm.zip', bytes: 60, sha256: sha('e') },
+ { path: 'scene-inputs/release2/golden-gate.zip', bytes: 70, sha256: sha('f') },
+ { path: 'scene-inputs/release2/foundry-floor.zip', bytes: 80, sha256: sha('a') },
+ ],
+};
describe('the R2 upload set', () => {
test('counts the pinned mirror files and the extracted GLBs, by group', () => {
@@ -31,6 +39,46 @@ describe('the R2 upload set', () => {
]);
});
+ test('includes all three scene archives in the required upload totals and groups', () => {
+ const summary = summarizeUploadSet(mirror, upload, sceneInputs);
+ expect(summary.problems).toEqual([]);
+ expect(summary.sceneInputFiles).toBe(3);
+ expect(summary.total).toEqual({ files: 7, bytes: 400 });
+ expect(summary.groups.slice(-2)).toEqual([
+ { group: 'scene-inputs/release1', files: 1, bytes: 60 },
+ { group: 'scene-inputs/release2', files: 2, bytes: 150 },
+ ]);
+ });
+
+ test('validates scene pins and reports duplicate paths across or within manifests', () => {
+ const result = summarizeUploadSet(mirror, upload, { base, files: [
+ { ...sceneInputs.files[0], bytes: -1, sha256: 'invalid', url: 'https://elsewhere.test/farm.zip' },
+ sceneInputs.files[0],
+ mirror.files[0],
+ upload.files[0],
+ { path: '../outside', bytes: 1, sha256: sha('a') },
+ ] });
+ const text = result.problems.join('\n');
+ expect(text).toContain('scene-inputs/release1/farm.zip: bytes is not a whole number');
+ expect(text).toContain('scene-inputs/release1/farm.zip: sha256 is not 64 hex characters');
+ expect(text).toContain(`scene-inputs/release1/farm.zip: url is not ${base}scene-inputs/release1/farm.zip`);
+ expect(text).toContain('listed in scene-inputs and scene-inputs');
+ expect(text).toContain('listed in mirror-manifest and scene-inputs');
+ expect(text).toContain('listed in upload-manifest and scene-inputs');
+ expect(text).toContain('scene-inputs: a record has no usable path');
+ });
+
+ test('requires valid matching upload bases and keeps extracted archive provenance in the mirror manifest', () => {
+ for (const invalid of ['', 'relative/', 'file:///tmp/', 'https://assets.example.test', 'https://name:[email protected]/', 'https://assets.example.test/?query']) {
+ const result = summarizeUploadSet(mirror, upload, { ...sceneInputs, base: invalid });
+ expect(result.problems.join('\n')).toContain('scene-inputs: base must be an absolute HTTP(S) URL ending in /');
+ }
+ expect(summarizeUploadSet(mirror, upload, { ...sceneInputs, base: 'https://other.example.test/' }).problems)
+ .toContain('scene-inputs: base does not match mirror-manifest base');
+ const unpinned = summarizeUploadSet(mirror, { ...upload, files: [{ ...upload.files[0], archive: sceneInputs.files[0]!.path }] }, sceneInputs);
+ expect(unpinned.problems.join('\n')).toContain('its archive scene-inputs/release1/farm.zip is not a pinned mirror file');
+ });
+
test('reports a bad hash, a bad size, a duplicated path, a foreign url and an archive that is not pinned', () => {
const bad = summarizeUploadSet(
{ base, files: [...mirror.files, { path: 'media/farm/a.avif', bytes: -1, sha256: 'xyz' }] },
@@ -51,9 +99,12 @@ describe('the R2 upload set', () => {
test('the checked-in manifests are consistent: valid records, no duplicate path, every extracted file inside a pinned archive', () => {
const read = (name: string) => JSON.parse(readFileSync(new URL(`../src/data/${name}`, import.meta.url), 'utf8'));
- const summary = summarizeUploadSet(read('mirror-manifest.json'), read('upload-manifest.json'));
+ const inputs = read('scene-inputs.json');
+ const summary = summarizeUploadSet(read('mirror-manifest.json'), read('upload-manifest.json'), inputs);
expect(summary.problems).toEqual([]);
expect(summary.mirrorFiles).toBeGreaterThan(0);
expect(summary.extractedFiles).toBeGreaterThan(0);
+ expect(summary.sceneInputFiles).toBe(inputs.files.length);
+ expect(summary.total.files).toBe(summary.mirrorFiles + summary.extractedFiles + summary.sceneInputFiles);
});
});
diff --git a/site/scripts/verify-foundry-flow.mjs b/site/scripts/verify-foundry-flow.mjs
index 91022e52..7cb203dd 100644
--- a/site/scripts/verify-foundry-flow.mjs
+++ b/site/scripts/verify-foundry-flow.mjs
@@ -1,20 +1,42 @@
+import { sceneBrowserOptions } from '../../scenes/scripts/browser-options.mjs';
import assert from 'node:assert/strict';
import { readFile, mkdir, writeFile } from 'node:fs/promises';
import { join, resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
import puppeteer from 'puppeteer-core';
import { chromeExecutable } from './build-site-media.mjs';
import { hashBytes } from './mirror-core.mjs';
-const [base, destination='.cache/round-4/ff3-site-flow']=process.argv.slice(2);
-if(!base)throw new Error('Usage: bun scripts/verify-foundry-flow.mjs <site-url> [report-directory]');
+
+export function flowBackendPlan(autoSmoke = false) {
+ return autoSmoke
+ ? { qualification: 'auto-smoke', backends: ['auto'] }
+ : { qualification: 'webgpu-and-webgl2', backends: ['webgpu', 'webgl2'] };
+}
+
+export function assertRenderedBackend(requested, rendered) {
+ assert.ok(['auto', 'webgpu', 'webgl2'].includes(requested), 'Unknown requested backend');
+ assert.ok(['webgpu', 'webgl2'].includes(rendered), `No recognized rendered backend: ${rendered}`);
+ if (requested !== 'auto') {
+ assert.equal(rendered, requested, `Required ${requested} backend; rendered ${rendered}`);
+ }
+}
+
+export async function main(argv = process.argv.slice(2)) {
+const unknown = argv.filter(arg => arg.startsWith('--') && arg !== '--auto-smoke');
+if (unknown.length) throw new Error(`Unknown Foundry flow option: ${unknown.join(', ')}`);
+const positional = argv.filter(arg => arg !== '--auto-smoke');
+const [base, destination='.cache/round-4/ff3-site-flow']=positional;
+if(!base || positional.length > 2)throw new Error('Usage: bun scripts/verify-foundry-flow.mjs <site-url> [report-directory] [--auto-smoke]');
+const plan = flowBackendPlan(argv.includes('--auto-smoke'));
const out=resolve(destination);await mkdir(out,{recursive:true});
const runtime=JSON.parse(await readFile('dist/scene-runtime/foundry-floor/runtime.json','utf8'));
assert.ok(runtime.initialLoad,'The full FF3 runtime with verified initial closure is required');
-const report={runtimeSha256:runtime.sha256,initialLoad:runtime.initialLoad,checks:[],scenarios:[],errors:[]};
-const browser=await puppeteer.launch({executablePath:chromeExecutable(),headless:true,pipe:true,args:['--no-sandbox'],defaultViewport:{width:1440,height:900}});
+const report={qualification:plan.qualification,runtimeSha256:runtime.sha256,initialLoad:runtime.initialLoad,checks:[],scenarios:[],errors:[]};
+const browser=await puppeteer.launch({executablePath:chromeExecutable(),headless:sceneBrowserOptions().headless,pipe:true,args:['--no-sandbox', ...sceneBrowserOptions().args],defaultViewport:{width:1440,height:900}});
report.browser=await browser.version();
async function clickText(frame,text){const handles=await frame.$$('button');for(const handle of handles)if(await handle.evaluate((button,label)=>button.textContent.trim()===label,text)){await handle.click();return;}throw new Error(`No visible control ${text}`);}
try{
- for(const backend of ['auto','webgl2']){
+ for(const backend of plan.backends){
const page=await browser.newPage(),received=new Map(),pending=[];const observed=[];
// Each backend qualification verifies response bytes, so it must fetch bodies rather than reuse 304s.
await page.setCacheEnabled(false);
@@ -31,6 +53,8 @@ try{
await page.click('[data-explore]');
await page.waitForFunction(()=>document.querySelector('scene-shell')?.dataset.sceneState==='ready',{timeout:60000});
const iframe=await page.$('[data-mount] iframe');const frame=await iframe.contentFrame();assert.ok(frame);
+ const campusBackend=await frame.$eval('.ks-root',root=>root.getAttribute('data-kiln-backend'));
+ assertRenderedBackend(backend,campusBackend);
await page.waitForNetworkIdle({idleTime:500,timeout:30000});await Promise.all(pending);
assert.deepEqual([...received.keys()].sort(),[...runtime.initialLoad.files].sort(),'Only initial campus code loads before entry');
await clickText(frame,'Arrival');
@@ -40,17 +64,20 @@ try{
await page.waitForNetworkIdle({idleTime:500,timeout:30000});await Promise.all(pending);
assert.deepEqual([...received.keys()].sort(),runtime.chunks.map(chunk=>chunk.file).sort(),'Entering fetches all deferred interior code with exact hashes');
const status=await frame.evaluate(()=>({backend:document.querySelector('.ks-root')?.getAttribute('data-kiln-backend'),hud:document.querySelector('.ff-hud')?.textContent,canvases:document.querySelectorAll('canvas').length}));
- assert.equal(status.canvases,1);assert.match(status.hud,/Wafer|wafer|lot|Lot/);if(backend==='webgl2')assert.equal(status.backend,'webgl2');
+ assert.equal(status.canvases,1);assert.match(status.hud,/Wafer|wafer|lot|Lot/);assertRenderedBackend(backend,status.backend);
await page.screenshot({path:join(out,`${backend}-interior.png`)});
await clickText(frame,'Exit to campus');
await frame.waitForFunction(()=>Boolean(document.querySelector('.fc-hud')),{timeout:30000});
await page.click('[data-exit]');
await page.waitForFunction(()=>document.querySelector('scene-shell')?.dataset.sceneState==='idle',{timeout:10000});
assert.equal(await page.$eval('[data-explore]',button=>button===document.activeElement),true);
- report.scenarios.push({backend,renderedBackend:status.backend,chunks:[...received.values()],interiorHud:status.hud,entryAndReturn:true});
+ report.scenarios.push({backend,campusBackend,renderedBackend:status.backend,chunks:[...received.values()],interiorHud:status.hud,entryAndReturn:true});
await page.close();
}
- report.checks.push('No scene code before Explore; exact initial closure only before Enter; all deferred chunks after Enter; real interior HUD/canvas; return to campus, exit and focus restore on both backends.');
+ report.checks.push(`No scene code before Explore; exact initial closure only before Enter; all deferred chunks after Enter; real interior HUD/canvas; return to campus, exit and focus restore. ${plan.qualification === 'auto-smoke' ? 'Automatic-backend smoke only; not both-backend release qualification.' : 'Required WebGPU and WebGL2 backends verified in campus and interior.'}`);
assert.equal(report.errors.length,0,JSON.stringify(report.errors));
}finally{await browser.close();await writeFile(join(out,'flow.json'),JSON.stringify(report,null,2));}
-console.log(JSON.stringify({scenarios:report.scenarios.length,errors:report.errors.length,checks:report.checks}));
+console.log(JSON.stringify({qualification:report.qualification,scenarios:report.scenarios.length,errors:report.errors.length,checks:report.checks}));
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) await main();
diff --git a/site/scripts/verify-foundry-flow.test.ts b/site/scripts/verify-foundry-flow.test.ts
new file mode 100644
index 00000000..e0c21504
--- /dev/null
+++ b/site/scripts/verify-foundry-flow.test.ts
@@ -0,0 +1,26 @@
+import { expect, test } from 'bun:test';
+import { assertRenderedBackend, flowBackendPlan } from './verify-foundry-flow.mjs';
+
+test('release Foundry flow requires WebGPU and WebGL2 as distinct actual backends', () => {
+ expect(flowBackendPlan()).toEqual({
+ qualification: 'webgpu-and-webgl2',
+ backends: ['webgpu', 'webgl2'],
+ });
+ expect(() => assertRenderedBackend('webgpu', 'webgl2')).toThrow(/webgpu/i);
+ expect(() => assertRenderedBackend('webgl2', 'webgpu')).toThrow(/webgl2/i);
+ expect(() => assertRenderedBackend('webgpu', 'webgpu')).not.toThrow();
+ expect(() => assertRenderedBackend('webgl2', 'webgl2')).not.toThrow();
+});
+
+test('an explicit auto smoke plan reports one observed backend without claiming release qualification', () => {
+ expect(flowBackendPlan(true)).toEqual({ qualification: 'auto-smoke', backends: ['auto'] });
+ expect(() => assertRenderedBackend('auto', 'webgl2')).not.toThrow();
+ expect(() => assertRenderedBackend('auto', 'webgpu')).not.toThrow();
+ for (const actual of [null, undefined, 'unknown']) {
+ expect(() => assertRenderedBackend('auto', actual)).toThrow(/backend/i);
+ }
+});
+
+test('unknown requested backends cannot silently become smoke qualification', () => {
+ expect(() => assertRenderedBackend('unknown', 'webgl2')).toThrow(/requested backend/i);
+});
diff --git a/site/scripts/verify-islands.mjs b/site/scripts/verify-islands.mjs
index ea658eda..7b2b87e2 100644
--- a/site/scripts/verify-islands.mjs
+++ b/site/scripts/verify-islands.mjs
@@ -4,6 +4,7 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import puppeteer from 'puppeteer-core';
import { chromeExecutable } from './build-site-media.mjs';
+import { sceneBrowserOptions } from '../../scenes/scripts/browser-options.mjs';
const base = process.argv[2];
const review = process.argv[3];
@@ -14,7 +15,9 @@ const farm = JSON.parse(await readFile(new URL('../src/data/packs/farm.json', im
const farmhouse = farm.assets.find((asset) => asset.id === 'farmhouse');
assert.ok(farmhouse, 'The selected Farm delivery must contain farmhouse.');
const results = { browser: '', pages: [], behaviors: [], errors: [] };
-const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: true, pipe: true, args: ['--no-sandbox'] });
+const launch = sceneBrowserOptions();
+const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: launch.headless, pipe: true, args: ['--no-sandbox', ...launch.args] });
+results.browserLaunch = launch;
results.browser = await browser.version();
const page = await browser.newPage();
page.on('pageerror', (error) => results.errors.push(error.message));
@@ -47,7 +50,8 @@ try {
// The island is ready when the scene reports its first complete frame (or, in a build without
// the scene package, when the stand-in mounts). Either way the shell says so in data-scene-state.
await page.waitForFunction(() => ['ready', 'error'].includes(document.querySelector('scene-shell')?.dataset.sceneState), { timeout: 120000 });
- assert.equal(await page.$eval('scene-shell', (element) => element.dataset.sceneState), 'ready', 'The Farm island must reach its ready state.');
+ results.sceneStartup = await page.$eval('scene-shell', (element) => ({ state: element.dataset.sceneState, error: element.dataset.sceneError ?? null, backend: element.dataset.sceneBackend ?? null, status: element.querySelector('[data-status]')?.textContent }));
+ assert.equal(results.sceneStartup.state, 'ready', `The Farm island must reach its ready state: ${JSON.stringify(results.sceneStartup)}`);
assert.equal(await page.$eval('[data-exit]', (element) => element === document.activeElement), true);
assert.equal(await page.$eval('body > header', (element) => element.inert), true);
await mkdir(join(review, 'screenshots/scene-open'), { recursive: true });
diff --git a/site/scripts/verify-scene-controls.mjs b/site/scripts/verify-scene-controls.mjs
new file mode 100644
index 00000000..af6251a0
--- /dev/null
+++ b/site/scripts/verify-scene-controls.mjs
@@ -0,0 +1,287 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import puppeteer from 'puppeteer-core';
+import { sceneBrowserOptions } from '../../scenes/scripts/browser-options.mjs';
+import { installTimingEvidence } from '../../scenes/scripts/timing-evidence.ts';
+import { chromeExecutable } from './build-site-media.mjs';
+import { assertControlBackend, assertPanelObservation, assertPositionMotion, movingFreightKinds, freightScanPlan, visibleFreightKinds, assertFreightScanCamera } from './scene-controls-proof.mjs';
+
+const site = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const hash = bytes => createHash('sha256').update(bytes).digest('hex');
+const sleep = ms => new Promise(done => setTimeout(done, ms));
+
+/** Read-only observer using Three's existing DevTools event and Fiber's mounted root.
+ * Public scene test hooks are deliberately absent. Never invoke scene controllers here.
+ * The snapshot retains only the live root's camera, named farmer and visible freight buffers.
+ */
+export function installControlObserver(scope = globalThis) {
+ const scenes = new Set();
+ const devtools = scope.__THREE_DEVTOOLS__ ?? new scope.EventTarget();
+ scope.__THREE_DEVTOOLS__ = devtools;
+ devtools.addEventListener('observe', event => { if (event.detail?.isScene && scenes.size < 64) scenes.add(event.detail); });
+ scope.__siteControlSnapshot = () => {
+ const states = [...scenes].map(scene => scene.__r3f?.root?.getState()).filter(state => state?.scene?.isScene && state.gl?.domElement?.isConnected && state.gl.domElement.closest('.ks-root'));
+ const unique = [...new Set(states)];
+ if (unique.length !== 1) throw Error(`Expected one mounted Fiber root, observed ${unique.length}`);
+ const state = unique[0], root = state.gl.domElement.closest('.ks-root');
+ const at = (subject, object) => object ? { subject, position: [object.matrixWorld.elements[12], object.matrixWorld.elements[13], object.matrixWorld.elements[14]] } : null;
+ const freight = [];
+ state.scene.traverse(object => {
+ if (!/^traffic-(truck-tractor|trailer-(dryvan|flatbed|tanker))-lod\d$/.test(object.name) || !object.visible) return;
+ const geometry = object.geometry, values = geometry?.attributes?.iA?.array, count = geometry?.instanceCount;
+ if (!values || !Number.isFinite(count) || count < 1) return;
+ const positions = [];
+ for (let index = 0; index < Math.min(count, 64); index++) positions.push(Array.from(values.slice(index * 4, index * 4 + 4)));
+ freight.push({ name: object.name, positions });
+ });
+ const backend = root.getAttribute('data-kiln-backend');
+ let glRenderer = null;
+ if (backend === 'webgl2') {
+ const context = state.gl.backend?.gl ?? state.gl.getContext?.();
+ const extension = context?.getExtension('WEBGL_debug_renderer_info');
+ if (extension) glRenderer = context.getParameter(extension.UNMASKED_RENDERER_WEBGL);
+ }
+ return { backend, glRenderer, gpu: backend === 'webgpu' ? scope.__timingEvidence?.gpu() : null,
+ camera: { ...at('camera', state.camera), fov: state.camera.fov, forward: [8, 9, 10].map(index => -state.camera.matrixWorld.elements[index]) },
+ canvas: { width: state.gl.domElement.clientWidth, height: state.gl.domElement.clientHeight },
+ farmer: at('farmer-yard-0', state.scene.getObjectByName('farmer-yard-0')), freight,
+ canvases: root.querySelectorAll('canvas').length, visibility: scope.document.visibilityState };
+ };
+}
+
+export async function main(argv = process.argv.slice(2)) {
+ const [base, destination, expected, sceneFilter = 'all', backendFilter = 'both'] = argv;
+ assert.ok(base && destination && /^[a-f0-9]{64}$/.test(expected ?? '') && argv.length <= 5,
+ 'Usage: node scripts/verify-scene-controls.mjs <site-url> <report-directory> <artifact-sha256> [all|farm|golden-gate|foundry-floor] [both|webgpu|webgl2]');
+ assert.ok(['all', 'farm', 'golden-gate', 'foundry-floor'].includes(sceneFilter));
+ assert.ok(['both', 'webgpu', 'webgl2'].includes(backendFilter));
+ const options = sceneBrowserOptions();
+ assert.equal(options.headless, false, 'Set KILN_SCENE_HEADED=1; this gate is a headed desktop touch-emulation check');
+ const output = resolve(destination); await mkdir(output, { recursive: true });
+ const report = { schema: 'kiln.site-live-controls/1', artifactSha256: expected, startedAt: new Date().toISOString(),
+ scope: 'Actual public HUDs and real desktop-emulated touch; no physical-device, performance, owner appearance, collision completeness or freight joint-alignment acceptance.',
+ browserOptions: options, verifierSha256: hash(await readFile(fileURLToPath(import.meta.url))),
+ dependencies: {}, selected: { sceneFilter, backendFilter }, scenarios: [], errors: [], complete: false };
+ for (const path of ['./scene-controls-proof.mjs', '../../scenes/scripts/timing-evidence.ts']) report.dependencies[path] = hash(await readFile(new URL(path, import.meta.url)));
+ async function pin() {
+ assert.equal(hash(await readFile(join(site, 'dist/artifact-files.json'))), expected, 'Local artifact changed');
+ const response = await fetch(new URL('/_review/receipt.json', base)); assert.equal(response.status, 200);
+ assert.equal((await response.json()).productionArtifactSha256, expected, 'Served review artifact differs');
+ }
+ await pin();
+ const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: false, pipe: true, args: ['--no-sandbox', ...options.args] });
+ report.browser = await browser.version();
+ try {
+ const scenes = sceneFilter === 'all' ? ['golden-gate', 'foundry-floor', 'farm'] : [sceneFilter];
+ const backends = backendFilter === 'both' ? ['webgpu', 'webgl2'] : [backendFilter];
+ for (const backend of backends) for (const scene of scenes) {
+ await pin();
+ const result = { scene, backend, checks: [], observations: {}, complete: false }; report.scenarios.push(result);
+ const page = await browser.newPage();
+ page.setDefaultTimeout(60000);
+ page.on('pageerror', error => report.errors.push({ scene, backend, message: error.message }));
+ await page.setViewport({ width: 390, height: 844, deviceScaleFactor: 1, isMobile: true, hasTouch: true });
+ if (backend === 'webgpu') await page.evaluateOnNewDocument(installTimingEvidence);
+ else await page.evaluateOnNewDocument(() => Object.defineProperty(navigator, 'gpu', { configurable: true, value: undefined }));
+ await page.evaluateOnNewDocument(installControlObserver);
+ try {
+ await page.goto(new URL(`/scenes/${scene}/`, base).href, { waitUntil: 'networkidle0' });
+ await page.bringToFront();
+ await page.$eval('scene-shell', element => element.scrollIntoView({ block: 'start' }));
+ await page.tap('[data-explore]');
+ await page.waitForFunction(() => ['ready', 'error'].includes(document.querySelector('scene-shell')?.dataset.sceneState), { timeout: 240000 });
+ assert.equal(await page.$eval('scene-shell', element => element.dataset.sceneState), 'ready');
+ const iframe = await page.$('[data-mount] iframe');
+ const frame = iframe ? await iframe.contentFrame() : page.mainFrame(); assert.ok(frame);
+ await frame.waitForSelector('.ks-root canvas');
+ const snapshot = () => frame.evaluate(() => window.__siteControlSnapshot());
+ const record = (name, detail) => { result.checks.push({ name, pass: true, detail }); console.log(`ok ${backend}/${scene}: ${name}`); };
+ await sleep(2000);
+ result.observations.initial = await snapshot();
+ assertControlBackend(backend, result.observations.initial, true);
+ assert.equal(result.observations.initial.canvases, 1);
+ assert.equal(result.observations.initial.visibility, 'visible');
+ record('Actual headed renderer and single visible scene canvas', result.observations.initial.backend);
+ async function findButton(label) {
+ for (const handle of await frame.$$('button')) {
+ if (await handle.evaluate((element, name) => !element.disabled && element.checkVisibility() && (element.getAttribute('aria-label') ?? element.textContent).replace(/\s+/g, ' ').trim() === name, label)) return handle;
+ await handle.dispose();
+ }
+ return null;
+ }
+ async function tap(label, menu = 'More') {
+ let handle = await findButton(label);
+ if (!handle) { const trigger = await findButton(menu); assert.ok(trigger, `Missing ${menu} menu for ${label}`); await trigger.tap(); await trigger.dispose(); }
+ await frame.waitForFunction(name => [...document.querySelectorAll('button')].some(element => !element.disabled && element.checkVisibility() && (element.getAttribute('aria-label') ?? element.textContent).replace(/\s+/g, ' ').trim() === name), {}, label);
+ handle ??= await findButton(label); assert.ok(handle, `Missing ${label}`); await handle.tap(); await handle.dispose();
+ }
+ const cdp = await page.createCDPSession();
+ async function gesture(selector, dx, dy, held = 700, extraSelector = null) {
+ const element = await frame.$(selector); assert.ok(element, `Missing ${selector}`);
+ const bounds = await element.boundingBox(); assert.ok(bounds, `Invisible ${selector}`);
+ const start = { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2, id: 1 };
+ const points = [start];
+ if (extraSelector) { const extra = await frame.$(extraSelector); const box = await extra?.boundingBox(); assert.ok(box); points.push({ x: box.x + box.width / 2, y: box.y + box.height / 2, id: 2 }); }
+ try {
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: points });
+ for (let step = 1; step <= 6; step++) { await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ ...start, x: start.x + dx * step / 6, y: start.y + dy * step / 6 }, ...points.slice(1)] }); await sleep(35); }
+ await sleep(held);
+ } finally { await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); await element.dispose(); }
+ }
+ async function closeAutoHelp() { if (await frame.$('.ks-help')) await tap('Close controls'); }
+ async function panels() {
+ await tap('Controls'); await frame.waitForSelector('.ks-help');
+ await tap('Credits'); await frame.waitForSelector('.ks-credits');
+ const before = await snapshot();
+ const scrollBefore = await frame.$eval('.ks-credits', element => element.scrollTop);
+ await gesture('.ks-credits', 0, -90, 100);
+ const observation = await frame.$eval('.ks-credits', (element, scrollBefore) => {
+ const rect = element.getBoundingClientRect(), root = element.closest('.ks-root').getBoundingClientRect();
+ const box = value => ({ left: value.left, top: value.top, right: value.right, bottom: value.bottom });
+ return { rect: box(rect), root: box(root), hitWithin: element.contains(document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2)), scrollHeight: element.scrollHeight, clientHeight: element.clientHeight, scrollBefore, scrollAfter: element.scrollTop };
+ }, scrollBefore);
+ result.observations.panels = { observation, before, after: await snapshot() };
+ assertPanelObservation(observation);
+ assert.ok(await frame.$('.ks-help'), 'Opening credits must preserve the underlying help panel');
+ const after = result.observations.panels.after;
+ assert.ok(Math.hypot(...before.camera.position.map((value, index) => after.camera.position[index] - value)) < 0.03, 'Panel touch leaked into camera movement');
+ const close = await frame.$('.ks-credits button'); await close.focus(); await page.keyboard.press('Escape');
+ await frame.waitForSelector('.ks-credits', { hidden: true });
+ assert.ok(await frame.$('.ks-help'), 'Escape should dismiss the focused credits panel only');
+ const focus = await frame.evaluate(() => ({ text: document.activeElement?.textContent?.trim(), within: Boolean(document.activeElement?.closest('.ks-toolbar')), visible: document.activeElement?.checkVisibility() }));
+ result.observations.panels.focusAfterDismissal = focus;
+ assert.ok(focus.within && focus.visible, 'Panel dismissal must restore focus to a visible toolbar control');
+ await tap('Close controls');
+ record('Help and credits stack, scroll by touch, block camera gestures and restore focus', { ...observation, focus });
+ }
+ async function joystick(subject) {
+ const attempts = [];
+ for (const [dx, dy] of [[0, -42], [42, 0], [0, 42], [-42, 0]]) {
+ const before = (await snapshot())[subject]; await gesture('.ks-joystick', dx, dy, 1000); const after = (await snapshot())[subject];
+ attempts.push({ dx, dy, before, after });
+ try { const metres = assertPositionMotion(before, after); record('Nested touch joystick moves the actual subject', { subject, metres, attempts }); return; } catch (error) { if (attempts.length === 4) throw error; }
+ }
+ }
+ async function freightScan() {
+ const evidence = { scope: 'Public orbit gestures locate visible tractor/trailer buffers before testing motion; no individual identity, occlusion or coupling-alignment claim.', motionControls: [], gestures: [], scan: [], movement: [] };
+ result.observations.freight = evidence;
+ const rendered = () => frame.evaluate(() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(() => done()))));
+ async function closeMenus() {
+ for (const trigger of await frame.$$('.ks-menu[data-open]>.ks-menu-trigger')) { await trigger.tap(); await trigger.dispose(); }
+ }
+ async function motion(paused) {
+ const labels = () => frame.evaluate(() => [...document.querySelectorAll('button')]
+ .filter(button => ['Pause motion', 'Resume motion'].includes(button.textContent.trim()))
+ .map(button => ({ label: button.textContent.trim(), pressed: button.getAttribute('aria-pressed'), visible: button.checkVisibility() })));
+ const before = await labels(); assert.equal(before.length, 1, 'Expected one public motion control');
+ const expected = paused ? 'Resume motion' : 'Pause motion';
+ if (before[0].label !== expected) await tap(before[0].label);
+ await rendered();
+ const after = await labels(); evidence.motionControls.push({ requestedPaused: paused, before, after });
+ assert.equal(after.length, 1); assert.equal(after[0].label, expected); assert.equal(after[0].pressed, String(paused));
+ await closeMenus();
+ }
+ async function dragCanvas(dx, button, dy = 0) {
+ const canvas = await frame.$('.ks-root canvas'); assert.ok(canvas);
+ try {
+ const bounds = await canvas.boundingBox(); assert.ok(bounds && bounds.width > 80 && bounds.height > 80);
+ assert.ok(Math.abs(dy) < bounds.height / 4, 'Vertical freight gesture exceeds its bound');
+ const segments = Math.ceil(Math.abs(dx) / (bounds.width - 64)), delta = dx / segments, deltaY = dy / segments;
+ for (let index = 0; index < segments; index++) {
+ const x = bounds.x + bounds.width / 2 - delta / 2, y = bounds.y + bounds.height * 0.55 - deltaY / 2;
+ const hit = await canvas.evaluate((element, delta, deltaY) => {
+ const rect = element.getBoundingClientRect();
+ return document.elementFromPoint(rect.x + rect.width / 2 - delta / 2, rect.y + rect.height * 0.55 - deltaY / 2) === element;
+ }, delta, deltaY);
+ assert.ok(hit, 'Freight gesture starts behind another element');
+ const gesture = { type: 'mouse-drag', button, dx: delta, dy: deltaY, start: { x, y }, canvasBounds: bounds, before: await snapshot() };
+ evidence.gestures.push(gesture);
+ await page.mouse.move(x, y); await page.mouse.down({ button });
+ try { await page.mouse.move(x + delta, y + deltaY, { steps: 8 }); }
+ finally { await page.mouse.up({ button }); }
+ await rendered(); gesture.after = await snapshot();
+ }
+ } finally { await canvas.dispose(); }
+ }
+ await motion(true);
+ await tap('The split', 'View'); await closeMenus(); await rendered();
+ const initial = await snapshot(); evidence.initial = initial;
+ const plan = freightScanPlan(initial.canvas, initial.camera); evidence.plan = plan;
+ await dragCanvas(plan.rotatePixels, 'left', plan.rotateYPixels);
+ await dragCanvas(plan.panWestPixels, 'right');
+ const canvas = await frame.$('.ks-root canvas'); assert.ok(canvas);
+ try {
+ const bounds = await canvas.boundingBox(); assert.ok(bounds);
+ await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height * 0.55);
+ const gesture = { type: 'mouse-wheel', deltaY: plan.wheelDelta, canvasBounds: bounds, before: await snapshot() };
+ evidence.gestures.push(gesture);
+ await page.mouse.wheel({ deltaY: plan.wheelDelta }); await rendered(); gesture.after = await snapshot();
+ } finally { await canvas.dispose(); }
+ let located = false;
+ for (let step = 0; step < plan.maxPositions; step++) {
+ const observed = await snapshot(); evidence.scan.push({ step, observed });
+ assertFreightScanCamera(observed.camera, plan, step);
+ if (visibleFreightKinds(observed.freight).length === 2) { located = true; break; }
+ if (step + 1 < plan.maxPositions) await dragCanvas(plan.scanPanPixels, 'right');
+ }
+ assert.ok(located, `No visible tractor and trailer after ${plan.maxPositions} public camera positions`);
+ await motion(false);
+ const moved = new Set(); let previous = await snapshot(); evidence.movement.push(previous);
+ for (let attempt = 0; attempt < 15 && moved.size < 2; attempt++) {
+ await sleep(1000); const next = await snapshot(); evidence.movement.push(next);
+ // Camera movement must not stand in for resumed traffic movement.
+ assert.ok(Math.hypot(...next.camera.position.map((value, index) => value - previous.camera.position[index])) < 0.03, 'Camera moved during freight motion observation');
+ for (const kind of movingFreightKinds(previous.freight, next.freight)) moved.add(kind);
+ previous = next;
+ }
+ evidence.movedKinds = [...moved].sort(); assert.deepEqual(evidence.movedKinds, ['tractor', 'trailer']);
+ record('Public camera scan finds ambient tractor and trailer buffers, and Resume motion advances both', 'Visible buffer motion only; no individual coupling/alignment claim');
+ }
+ if (scene === 'farm') {
+ await tap('Walk the farm'); await frame.waitForSelector('.farm-play-touch .ks-joystick'); await closeAutoHelp(); await sleep(600);
+ await joystick('farmer'); await tap('Back to overview'); await frame.waitForSelector('.farm-overview-touch');
+ record('Farm returns from play to overview');
+ } else {
+ await panels();
+ if (scene === 'foundry-floor') {
+ await freightScan();
+ await tap('Enter the fab'); await frame.waitForSelector('.ff-hud');
+ await frame.waitForFunction(() => !document.querySelector('.fc-exit')?.disabled);
+ assert.match(await frame.$eval('.fc-interior-location', element => element.textContent), /South-west building.*Level 1.*Cutaway/);
+ assertControlBackend(backend, await snapshot(), true);
+ await tap('Walk', 'View'); await frame.waitForSelector('.ff-camera-walk .ks-joystick'); await closeAutoHelp(); await sleep(600);
+ await joystick('camera');
+ await tap('Stop walking'); await frame.waitForSelector('.ff-camera-orbit');
+ await tap('Exit to campus'); await frame.waitForSelector('.fc-hud');
+ record('Registered cutaway entry, walking and return to campus');
+ }
+ await tap('Drive the sedan'); await frame.waitForSelector('.ks-joystick'); await closeAutoHelp(); await sleep(700);
+ const before = (await snapshot()).camera;
+ if (scene === 'foundry-floor') await gesture('.ks-joystick', 20, 0, 1800, '.ks-touch-button[aria-label="Throttle"]');
+ else await gesture('.ks-joystick', 8, -44, 1800);
+ const after = (await snapshot()).camera;
+ const speed = await frame.$eval(scene === 'golden-gate' ? '.gg-speed' : '.fc-speed', element => element.textContent);
+ assert.ok(Number.parseFloat(speed) > 0, `Drive did not accelerate: ${speed}`);
+ const metres = assertPositionMotion(before, after);
+ record('Drive touch input accelerates the sedan and advances its follow camera', { before, after, speed, metres, simultaneousSteeringAndThrottle: scene === 'foundry-floor' });
+ await tap('Leave the car'); await frame.waitForSelector('.ks-joystick', { hidden: true });
+ record('Leave car returns to orbit controls');
+ }
+ await page.screenshot({ path: join(output, `${backend}-${scene}.png`) });
+ await page.tap('[data-exit]'); await page.waitForFunction(() => document.querySelector('scene-shell')?.dataset.sceneState === 'idle');
+ assert.equal(await page.$eval('[data-explore]', element => element === document.activeElement), true);
+ record('Scene exit disposes the mount and restores Explore focus');
+ await pin(); result.complete = true;
+ } catch (error) { result.error = error.stack ?? String(error); throw error; }
+ finally { await page.close(); }
+ }
+ assert.equal(report.errors.length, 0, JSON.stringify(report.errors)); report.complete = true;
+ } catch (error) { report.failure = error.stack ?? String(error); throw error; }
+ finally { await browser.close(); report.finishedAt = new Date().toISOString(); await writeFile(join(output, 'controls.json'), JSON.stringify(report, null, 2) + '\n'); }
+ console.log(`Live control gate passed ${report.scenarios.length} selected scene/backend scenarios. Desktop touch emulation only.`);
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) await main();
diff --git a/site/scripts/verify-scene-island.mjs b/site/scripts/verify-scene-island.mjs
index 0fcc5ab9..8fd8c4ac 100644
--- a/site/scripts/verify-scene-island.mjs
+++ b/site/scripts/verify-scene-island.mjs
@@ -1,8 +1,10 @@
+import { sceneBrowserOptions } from '../../scenes/scripts/browser-options.mjs';
import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import puppeteer from 'puppeteer-core';
import { chromeExecutable } from './build-site-media.mjs';
+import { classifyExploreConsole } from './scene-console.mjs';
const positional = process.argv.slice(2).filter((argument) => !argument.startsWith('--'));
const [base, sceneId = 'farm', screenshot = `.tmp/${sceneId}-island.png`] = positional;
@@ -26,16 +28,12 @@ const sceneRoot = (page) => page.evaluate((frame) => {
return { backend: root?.getAttribute('data-kiln-backend') ?? null, canvas: canvas ? [canvas.width, canvas.height] : null, region: root?.getAttribute('role') ?? null };
}, scene.frame);
const check = (message) => report.checks.push(message);
-// @react-three/fiber 9.8.1 constructs THREE.Clock, which three 0.186 marks deprecated. The
-// gallery viewers on this site log the same line, so it is expected here and still reported.
-const KNOWN_WARNINGS = [/^THREE\.Clock: This module has been deprecated/];
-
-// Headless only, with an explicit window size. No frame or load timings are recorded.
+// Explicit window size; host may opt into headed GPU qualification. No frame/load timings recorded.
const browser = await puppeteer.launch({
executablePath: chromeExecutable(),
- headless: true,
+ headless: sceneBrowserOptions().headless,
pipe: true,
- args: ['--no-sandbox', '--window-size=1440,900', ...(process.env.KILN_SWIFTSHADER ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : [])],
+ args: ['--no-sandbox', '--window-size=1440,900', ...sceneBrowserOptions().args, ...(process.env.KILN_SWIFTSHADER ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : [])],
defaultViewport: { width: 1440, height: 900, deviceScaleFactor: 1 },
});
report.browser = await browser.version();
@@ -68,7 +66,21 @@ try {
if (/\.js(?:$|\?)/.test(response.url())) scripts.push(Number(response.headers()['content-length'] ?? 0));
if (response.url().includes(scene.runtime)) served.push(response);
});
- await page.goto(route, { waitUntil: 'networkidle0' });
+ const documentResponse = await page.goto(route, { waitUntil: 'networkidle0' });
+ report.consoleEnvironment = {
+ browser: report.browser,
+ responseUrl: documentResponse?.url() ?? null,
+ permissionsPolicy: documentResponse?.headers()['permissions-policy'] ?? null,
+ ...await page.evaluate(() => {
+ const policy = document.permissionsPolicy ?? document.featurePolicy;
+ return {
+ platform: navigator.platform,
+ secureContext: window.isSecureContext,
+ bluetoothApiPresent: 'bluetooth' in navigator,
+ supportedPolicyFeatures: typeof policy?.features === 'function' ? policy.features() : null,
+ };
+ }),
+ };
assert.equal(await page.$eval('meta[name="robots"]', (meta) => meta.content), 'noindex, nofollow');
check('The page carries robots noindex, nofollow.');
assert.equal(requests.some((url) => url.includes('/scene-packs/') || url.includes('/scene-runtime/')), false);
@@ -106,10 +118,12 @@ try {
await mkdir(dirname(resolve(screenshot)), { recursive: true });
await page.screenshot({ path: resolve(screenshot) });
if (await page.$eval('[data-fullscreen]', (element) => !element.hidden)) {
- await page.click('[data-fullscreen]');
- assert.equal(await page.evaluate(() => Boolean(document.fullscreenElement)), true);
- await page.click('[data-fullscreen]');
- assert.equal(await page.evaluate(() => Boolean(document.fullscreenElement)), false);
+ // Fullscreen changes the viewport asynchronously. A locator waits for the
+ // visible button's stable bounding box before issuing each real click.
+ await page.locator('[data-fullscreen]').click();
+ await page.waitForFunction(() => document.fullscreenElement === document.querySelector('scene-shell'));
+ await page.locator('[data-fullscreen]').click();
+ await page.waitForFunction(() => document.fullscreenElement === null);
check('Fullscreen enters and leaves while the scene runs.');
}
}
@@ -225,10 +239,8 @@ try {
} finally {
await browser.close();
}
-// Puppeteer reports console warnings as "warn". A known upstream line is listed, never hidden.
-const flagged = report.console.filter((entry) => entry.scenario === 'explore' && ['error', 'warn', 'warning'].includes(entry.type));
-const isKnown = (entry) => KNOWN_WARNINGS.some((pattern) => pattern.test(entry.text));
-report.exploreConsole = { known: flagged.filter(isKnown), unexpected: flagged.filter((entry) => !isKnown(entry)) };
+// Known upstream/platform warnings are retained with their observed environment.
+report.exploreConsole = classifyExploreConsole(report.console, report.consoleEnvironment);
report.multipleInstances = report.console.filter((entry) => /Multiple instances of Three\.js/i.test(entry.text));
console.log(JSON.stringify(report, null, 2));
assert.equal(report.multipleInstances.length, 0, 'three logged its Multiple instances warning: the page loaded two copies.');
diff --git a/site/scripts/verify-scene-served.mjs b/site/scripts/verify-scene-served.mjs
index bf33f2fb..2daae23e 100644
--- a/site/scripts/verify-scene-served.mjs
+++ b/site/scripts/verify-scene-served.mjs
@@ -3,6 +3,7 @@ import { existsSync, readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { verifyRuntimePayload } from './served-runtime.mjs';
+import { verifySceneDeliveryBinding } from './scene-delivery-binding.mjs';
/**
* What the site serves for each staged scene, hashed and compared with what the site's own records say.
@@ -38,6 +39,10 @@ const envName = (id) => `KILN_SITE_SCENE_PACK_DIR_${id.toUpperCase().replace(/-/
for (const [id, record] of Object.entries(records)) {
const runtime = JSON.parse((await get(`/scene-runtime/${id}/runtime.json`)).toString('utf8'));
+ const shellHtml = (await get(`/scenes/${id}/`)).toString('utf8');
+ const frameHtml = runtime.kind === 'frame' ? (await get(`/scene-runtime/${id}/frame.html`)).toString('utf8') : undefined;
+ const binding = verifySceneDeliveryBinding({ id, record, runtime, shellHtml, frameHtml });
+ console.log(`${id}: emitted shell and ${binding.kind} entry bind the selected ${record.release} pack and catalog runtime.`);
const payload = await verifyRuntimePayload(runtime, get);
console.log(`${id}: ${payload.files} served chunks verified, ${payload.bytes} B, ${payload.gzipBytes} B gzip, entry sha256 ${runtime.sha256}`);
const initial = runtime.initialLoad ?? payload;
diff --git a/site/scripts/verify-scene-small.mjs b/site/scripts/verify-scene-small.mjs
index e6426810..51d61f1f 100644
--- a/site/scripts/verify-scene-small.mjs
+++ b/site/scripts/verify-scene-small.mjs
@@ -3,11 +3,14 @@ import { mkdir, writeFile } from 'node:fs/promises';
import { resolve, join } from 'node:path';
import puppeteer from 'puppeteer-core';
import { chromeExecutable } from './build-site-media.mjs';
+import { sceneBrowserOptions } from '../../scenes/scripts/browser-options.mjs';
const [base = 'http://127.0.0.1:4407', destination = '.cache/round-4/small-scenes'] = process.argv.slice(2);
const out = resolve(destination); await mkdir(out, { recursive: true });
const report = { runs: [], errors: [] };
+const launch = sceneBrowserOptions();
+report.browserLaunch = launch;
for (const disabled of [false, true]) {
- const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: true, pipe: true, args: ['--no-sandbox', ...(disabled ? ['--disable-3d-apis', '--disable-gpu'] : [])] });
+ const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: launch.headless, pipe: true, args: ['--no-sandbox', ...launch.args, ...(disabled ? ['--disable-3d-apis', '--disable-gpu'] : [])] });
try {
for (const scene of ['farm', 'golden-gate', 'foundry-floor']) {
const page = await browser.newPage();
diff --git a/site/scripts/verify-scene-touch.mjs b/site/scripts/verify-scene-touch.mjs
index 0ff7fdd9..6478580e 100644
--- a/site/scripts/verify-scene-touch.mjs
+++ b/site/scripts/verify-scene-touch.mjs
@@ -1,3 +1,4 @@
+import { sceneBrowserOptions } from '../../scenes/scripts/browser-options.mjs';
import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
@@ -20,7 +21,7 @@ if (!base || !review) throw new Error('Usage: node scripts/verify-scene-touch.mj
const PAD = new Set(['+', '-', '−', '←', '→', '↑', '↓']);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
-const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: true, pipe: true, args: ['--no-sandbox'] });
+const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: sceneBrowserOptions().headless, pipe: true, args: ['--no-sandbox', ...sceneBrowserOptions().args] });
const results = { browser: await browser.version(), viewport: '390x844, touch, mobile', checks: [], observed: {}, errors: [] };
const check = (name, pass, detail) => results.checks.push(detail === undefined ? { name, pass: Boolean(pass) } : { name, pass: Boolean(pass), detail });
await mkdir(screenshotDirectory, { recursive: true });
diff --git a/site/scripts/verify-scene-widths.mjs b/site/scripts/verify-scene-widths.mjs
index 093bf9d4..2919699a 100644
--- a/site/scripts/verify-scene-widths.mjs
+++ b/site/scripts/verify-scene-widths.mjs
@@ -1,8 +1,10 @@
+import { sceneBrowserOptions } from '../../scenes/scripts/browser-options.mjs';
import assert from 'node:assert/strict';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import puppeteer from 'puppeteer-core';
import { chromeExecutable } from './build-site-media.mjs';
+import { observeSceneLayoutShifts, sceneHasRoom } from './scene-viewport.mjs';
/**
* The scene pages at 390, 768, 1280 and 1440 px, in each state a visitor can be in:
@@ -12,7 +14,8 @@ import { chromeExecutable } from './build-site-media.mjs';
* - layout shift: what the page moves by while it loads (Explore is revealed by the shell's script), under 0.01.
* - loaded: the poster, the state copy and the Explore control. No horizontal scroll, the poster inside the window, Explore
* shown, at least 44 px each way, inside the window, the element that answers a tap at its centre, reachable by keyboard.
- * - no JavaScript: the poster, the copy and the noscript notice are readable and nothing scrolls sideways.
+ * - no JavaScript: the poster, the copy and the noscript notice are readable and nothing scrolls sideways. The hidden
+ * Explore control retains its button box so revealing it cannot add a row after hydration.
* - error: Explore pressed with the scene's runtime failing; the failure copy is readable in place and Explore is back.
* - unavailable: a build with no runtime for the scene (the shell's `data-kind` is "none", which is what such a build emits, set
* before Explore so the component's own code shows its own copy); the fallback the overlay shows is readable and its link reachable.
@@ -56,7 +59,7 @@ const measure = () => {
documentScrollWidth: document.documentElement.scrollWidth,
shellClipped: shell.scrollWidth > shell.clientWidth + 1,
poster: poster && { ...box(poster), loaded: poster.complete && poster.naturalWidth > 0 },
- explore: explore && { ...box(explore), shown: !explore.hidden && explore.checkVisibility() },
+ explore: explore && { ...box(explore), hidden: explore.hidden, visibility: getComputedStyle(explore).visibility, shown: !explore.hidden && explore.checkVisibility() },
introCopy: [...shell.querySelectorAll('[data-intro] p')].filter((element) => element.checkVisibility()).map(text),
status: (() => { const element = shell.querySelector('[data-status]'); return element && !element.classList.contains('sr-only') && element.textContent.trim() ? text(element) : null; })(),
noscript: (() => { const element = shell.querySelector('noscript p'); return element ? text(element) : null; })(),
@@ -131,7 +134,7 @@ const measureNote = () => {
};
const results = { browser: '', scenes: [], errors: [], failures: [] };
-const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: true, pipe: true, args: ['--no-sandbox'] });
+const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: sceneBrowserOptions().headless, pipe: true, args: ['--no-sandbox', ...sceneBrowserOptions().args] });
results.browser = await browser.version();
const lines = [];
try {
@@ -192,18 +195,14 @@ try {
for (const width of widths) {
const shifted = await browser.newPage();
try {
- await shifted.evaluateOnNewDocument(() => {
- window.__shifts = [];
- new PerformanceObserver((list) => {
- for (const entry of list.getEntries()) window.__shifts.push({ value: entry.value, hadRecentInput: entry.hadRecentInput });
- }).observe({ type: 'layout-shift', buffered: true });
- });
+ await shifted.evaluateOnNewDocument(observeSceneLayoutShifts);
await shifted.setViewport({ width, height: 900, deviceScaleFactor: 1 });
await shifted.goto(url, { waitUntil: 'networkidle0' });
await shifted.evaluate(async () => { await document.fonts.ready; });
await new Promise((resolve) => setTimeout(resolve, 800));
- const total = await shifted.evaluate(() => window.__shifts.filter((entry) => !entry.hadRecentInput).reduce((sum, entry) => sum + entry.value, 0));
- step(item, width, { [`layout shift under ${MAX_SHIFT}`]: total < MAX_SHIFT }, { total, summary: total.toFixed(4) });
+ const shifts = await shifted.evaluate(() => window.__shifts);
+ const total = shifts.filter((entry) => !entry.hadRecentInput).reduce((sum, entry) => sum + entry.value, 0);
+ step(item, width, { [`layout shift under ${MAX_SHIFT}`]: total < MAX_SHIFT }, { total, shifts, summary: total.toFixed(4) });
} finally { await shifted.close(); }
}
}
@@ -252,6 +251,7 @@ try {
'no horizontal scroll': shown.documentScrollWidth <= shown.innerWidth && !shown.shellClipped,
'poster inside the window and loaded': !shown.poster || (insideWindow(shown.poster, width) && shown.poster.loaded),
'Explore stays out of sight': !shown.explore?.shown,
+ [`hidden Explore reserves at least ${MIN_TARGET_PX} px each way`]: shown.explore?.hidden && shown.explore.width >= MIN_TARGET_PX && shown.explore.height >= MIN_TARGET_PX,
'copy readable': readable(shown.introCopy, width),
'noscript notice readable': Boolean(shown.noscript) && shown.noscript.visible && shown.noscript.fontSize >= MIN_TEXT_PX && !shown.noscript.clipped && insideWindow(shown.noscript, width),
}, { measured: shown, summary: `notice "${shown.noscript?.text}"` });
@@ -343,14 +343,16 @@ try {
const controls = await live.evaluate(() => {
const rectOf = (selector) => { const element = document.querySelector(selector); if (!element || element.hidden || !element.checkVisibility()) return null; const rect = element.getBoundingClientRect(); return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom, width: rect.width, height: rect.height }; };
const overlay = document.querySelector('scene-shell [data-active]');
- return { scrollWidth: overlay.scrollWidth, clientWidth: overlay.clientWidth, exit: rectOf('scene-shell [data-exit]'), fullscreen: rectOf('scene-shell [data-fullscreen]'), mount: rectOf('scene-shell [data-mount]'), innerHeight };
+ return { scrollWidth: overlay.scrollWidth, clientWidth: overlay.clientWidth, viewportWidth: innerWidth, documentClientWidth: document.documentElement.clientWidth,
+ overlay: rectOf('scene-shell [data-active]'), overlayClientWidth: overlay.clientWidth,
+ exit: rectOf('scene-shell [data-exit]'), fullscreen: rectOf('scene-shell [data-fullscreen]'), mount: rectOf('scene-shell [data-mount]'), innerHeight };
});
await live.screenshot({ path: join(shots, `open-${width}.png`) });
step(opened, width, {
'no horizontal scroll in the overlay': controls.scrollWidth <= controls.clientWidth,
'Exit inside the window and large enough': Boolean(controls.exit) && insideWindow(controls.exit, width) && controls.exit.height >= MIN_TARGET_PX && controls.exit.top >= 0,
'Fullscreen, when offered, inside the window': !controls.fullscreen || insideWindow(controls.fullscreen, width),
- 'the scene has room': Boolean(controls.mount) && controls.mount.width >= width - 1 && controls.mount.height >= 200,
+ 'the scene has room': sceneHasRoom(controls),
}, { measured: controls, summary: `Exit ${Math.round(controls.exit?.width ?? 0)}x${Math.round(controls.exit?.height ?? 0)}, scene ${Math.round(controls.mount?.width ?? 0)}x${Math.round(controls.mount?.height ?? 0)}` });
}
await live.click('scene-shell [data-exit]');
diff --git a/site/scripts/verify-viewer-tone.mjs b/site/scripts/verify-viewer-tone.mjs
index e825bb75..f90e85ec 100644
--- a/site/scripts/verify-viewer-tone.mjs
+++ b/site/scripts/verify-viewer-tone.mjs
@@ -5,6 +5,7 @@ import { join } from 'node:path';
import puppeteer from 'puppeteer-core';
import sharp from 'sharp';
import { chromeExecutable } from './build-site-media.mjs';
+import { sceneBrowserOptions } from '../../scenes/scripts/browser-options.mjs';
/**
* Check, in a real browser, the tone mapping control of the 3D view.
@@ -83,8 +84,9 @@ const grab = async (page, file) => {
return { data, hash: sha256(data), width: info.width, height: info.height };
};
-const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: true, pipe: true, args: ['--no-sandbox'] });
-const results = { browser: await browser.version(), rig: 'review-neutral-v1', repeat, noiseFraction: NOISE_FRACTION, pages: [], errors: [], consoleProblems: [] };
+const launch = sceneBrowserOptions();
+const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: launch.headless, pipe: true, args: ['--no-sandbox', ...launch.args] });
+const results = { browser: await browser.version(), browserLaunch: launch, rig: 'review-neutral-v1', repeat, noiseFraction: NOISE_FRACTION, pages: [], errors: [], consoleProblems: [] };
await mkdir(screenshotDirectory, { recursive: true });
try {
for (const route of routes) {
diff --git a/site/src/data/commons-build.json b/site/src/data/commons-build.json
index 8116cb64..3ee24893 100644
--- a/site/src/data/commons-build.json
+++ b/site/src/data/commons-build.json
@@ -1528,6 +1528,24 @@
"srcsetWebp": "/media/scenes/golden-gate/g9/golden-gate-scene-day-320.webp 320w, /media/scenes/golden-gate/g9/golden-gate-scene-day-480.webp 480w, /media/scenes/golden-gate/g9/golden-gate-scene-day-672.webp 672w, /media/scenes/golden-gate/g9/golden-gate-scene-day-768.webp 768w, /media/scenes/golden-gate/g9/golden-gate-scene-day-1024.webp 1024w, /media/scenes/golden-gate/g9/golden-gate-scene-day-1440.webp 1440w",
"srcsetAvif": "/media/scenes/golden-gate/g9/golden-gate-scene-day-320.avif 320w, /media/scenes/golden-gate/g9/golden-gate-scene-day-480.avif 480w, /media/scenes/golden-gate/g9/golden-gate-scene-day-672.avif 672w, /media/scenes/golden-gate/g9/golden-gate-scene-day-768.avif 768w, /media/scenes/golden-gate/g9/golden-gate-scene-day-1024.avif 1024w, /media/scenes/golden-gate/g9/golden-gate-scene-day-1440.avif 1440w",
"inputPath": "media/scenes/golden-gate/g9/golden-gate-scene-day.png"
+ },
+ {
+ "src": "/media/scenes/golden-gate/g9-code5/golden-gate-scene-day.webp",
+ "width": 1440,
+ "height": 925,
+ "alt": "The Golden Gate Bridge scene from above the water by day: the full span between its two towers, with the headlands on either side.",
+ "srcsetWebp": "/media/scenes/golden-gate/g9-code5/golden-gate-scene-day-320.webp 320w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-480.webp 480w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-672.webp 672w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-768.webp 768w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-1024.webp 1024w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-1440.webp 1440w",
+ "srcsetAvif": "/media/scenes/golden-gate/g9-code5/golden-gate-scene-day-320.avif 320w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-480.avif 480w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-672.avif 672w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-768.avif 768w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-1024.avif 1024w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-1440.avif 1440w",
+ "inputPath": "media/scenes/golden-gate/g9-code5/golden-gate-scene-day.png"
+ },
+ {
+ "src": "/media/scenes/golden-gate/g9-code5/golden-gate-scene-drive.webp",
+ "width": 1440,
+ "height": 925,
+ "alt": "A blue sedan driving across the deck of the Golden Gate Bridge scene, with traffic around it and both towers ahead.",
+ "srcsetWebp": "/media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-320.webp 320w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-480.webp 480w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-672.webp 672w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-768.webp 768w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-1024.webp 1024w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-1440.webp 1440w",
+ "srcsetAvif": "/media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-320.avif 320w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-480.avif 480w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-672.avif 672w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-768.avif 768w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-1024.avif 1024w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-1440.avif 1440w",
+ "inputPath": "media/scenes/golden-gate/g9-code5/golden-gate-scene-drive.png"
}
],
"archives": [
diff --git a/site/src/data/mirror-manifest.json b/site/src/data/mirror-manifest.json
index 8ee848ac..779b8e6f 100644
--- a/site/src/data/mirror-manifest.json
+++ b/site/src/data/mirror-manifest.json
@@ -2290,6 +2290,16 @@
"path": "media/scenes/golden-gate/g9/golden-gate-scene-day.png",
"bytes": 963303,
"sha256": "50a2ecf3bd0eec02231ce614c56128be3bdb61bba8cf6be46535b2742c56e945"
+ },
+ {
+ "path": "media/scenes/golden-gate/g9-code5/golden-gate-scene-day.png",
+ "bytes": 886155,
+ "sha256": "3b75ae261e59a034165ec705d20931484b03600d39fae51c42fc02db22ba42e5"
+ },
+ {
+ "path": "media/scenes/golden-gate/g9-code5/golden-gate-scene-drive.png",
+ "bytes": 728452,
+ "sha256": "487793596f730d5424c1b25016fbc27408d6d2ab707c57343acbbc6a52b1bc56"
}
]
}
diff --git a/site/src/data/packs/foundry-floor.json b/site/src/data/packs/foundry-floor.json
index 026fee9e..35fbfc22 100644
--- a/site/src/data/packs/foundry-floor.json
+++ b/site/src/data/packs/foundry-floor.json
@@ -7,11 +7,11 @@
"assetCount": 62,
"placedInScene": 62,
"acceptance": {
- "statement": "This 62-model pack combines the staged interior and campus deliveries. Its source pins, licence identities and downloaded bytes have been checked together. Those checks do not establish the owner’s visual or simulation acceptance; the pack stays in production until that review.",
+ "statement": "This 62-model pack combines the staged interior and campus deliveries. Its source pins, licence identities and downloaded bytes have been checked together. Those checks do not establish the owner\u2019s visual or simulation acceptance; the pack stays in production until that review.",
"source": "Sealed pack.json source pins and credits, data/assets.json, data/campus-assets.json when present, and the licence text"
},
"license": "CC0-1.0",
- "licenseScope": "CC0-1.0 covers authored asset content only, to the extent of the owner’s rights. Kiln and any software that opens these files retain their own licenses.",
+ "licenseScope": "CC0-1.0 covers authored asset content only, to the extent of the owner\u2019s rights. Kiln and any software that opens these files retain their own licenses.",
"licenceNote": "The licence text comes from the sealed Foundry Floor scene pack. It names every model, its saved revision, author attribution and the SHA-256 of its GLB, and is published here unchanged.",
"licence": {
"path": "packs/foundry-floor/ff3-review2/licenses/ASSET-LICENSE.txt",
@@ -22,9 +22,9 @@
"models": 62
},
"scenePack": {
- "release": "ff3-review2",
- "base": "/scene-packs/foundry-floor/ff3-review2/",
- "packJsonSha256": "6ce49d05791bf42d21f3628237a5cf005ce9f2fa15938f0c321430d781c2c5d4",
+ "release": "ff3-review2-code5",
+ "base": "/scene-packs/foundry-floor/ff3-review2-code5/",
+ "packJsonSha256": "822be1171621273dfdf857fe6ca320ed41d16e03c49fc49860c13e7092be4836",
"sha256sumsSha256": "21ec914770e35ced418015e1e9965488d96cb8e457bbc1602273cc3936712e7c",
"assetMapSha256": "e898b0f3b78cbc49cf828433ea0203273e3844ec761bde451a22f3b7ec4352d3"
},
@@ -32,7 +32,7 @@
"frame": "Metres. Interior assets use +X forward, +Y up and +Z right. Campus assets retain the coordinate frames of their source models.",
"lod": "43 models declare optional MSFT_lod tiers. A loader that ignores this extension draws the default detailed form; an LOD-aware application can select the separate lower tiers.",
"hidden": "Two models carry parts the scene hides when it loads them: the FOUP (waferStack) and the level section module (raisedFloor, ffuPlenum, cutFaceCaps_raisedFloor, cutFaceCaps_ffuWhite, cutFaceCaps_ffuHousing). They are part of the file, and a plain viewer draws them.",
- "materials": "No model uses a texture; colours are material factors. The pack’s accent colours are invented for readability and are not any maker’s livery.",
+ "materials": "No model uses a texture; colours are material factors. The pack\u2019s accent colours are invented for readability and are not any maker\u2019s livery.",
"clips": "Animation clips carry no loop flags; the scene decides what loops.",
"source": "Interior conventions come from data/assets.json; every figure on this page was read from its sealed GLB. Campus assets retain their source conventions."
},
@@ -82,7 +82,7 @@
"url": "https://assets.kilnstudio.tools/packs/foundry-floor/ff3-review2/foundry-floor-ff3-review2-models.zip",
"contents": [
"The 62 model GLBs",
- "The pack’s licence text, naming every model, its revision and its SHA-256",
+ "The pack\u2019s licence text, naming every model, its revision and its SHA-256",
"Sealed asset metadata and replacement lineage where supplied",
"A delivery.json inventory with member hashes"
],
@@ -105,9 +105,9 @@
"description": "The FOUP model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_f639b02180994fdd978a427bffb4de15",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "foup",
"requestedEffort": null,
"confirmedEffort": null
@@ -191,9 +191,9 @@
"description": "The OHT vehicle model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_a4fd2dfb3a3f4276b28464458cb0fbb9",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "oht-vehicle",
"requestedEffort": null,
"confirmedEffort": null
@@ -277,9 +277,9 @@
"description": "The load port model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_b45a5f436cd14d7294bc6866dcebb5f7",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "load-port",
"requestedEffort": null,
"confirmedEffort": null
@@ -363,9 +363,9 @@
"description": "The stocker model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_2719dba3ca554c159e41daa769233182",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "stocker",
"requestedEffort": null,
"confirmedEffort": null
@@ -446,9 +446,9 @@
"description": "The signal tower model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_0af702f0a7364dffbac3255c04a909ff",
"reviewStatus": "accepted",
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"asset": "signal-tower",
"requestedEffort": "max",
"confirmedEffort": null
@@ -522,9 +522,9 @@
"description": "The under-track storage model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_093ce3746e9c449585f6543f9db94f87",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "under-track-storage",
"requestedEffort": null,
"confirmedEffort": null
@@ -603,9 +603,9 @@
"description": "The OHT rail, straight model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_ed0c4b464c3f44419b6efed936349a64",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "oht-rail-straight",
"requestedEffort": null,
"confirmedEffort": null
@@ -684,9 +684,9 @@
"description": "The OHT rail, curve model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_a2af1537d2cc4396a4d94bce0c19598c",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "oht-rail-curve",
"requestedEffort": null,
"confirmedEffort": null
@@ -765,9 +765,9 @@
"description": "The OHT rail, switch model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_b7fcebf6547545eab077be69796ec893",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "oht-rail-switch",
"requestedEffort": null,
"confirmedEffort": null
@@ -848,9 +848,9 @@
"description": "The raised-floor module model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_f0104891f44a4c99a52739033e900757",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "raised-floor-module",
"requestedEffort": null,
"confirmedEffort": null
@@ -929,9 +929,9 @@
"description": "The FFU ceiling module model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_6d370c36023f401ea7ee526631bcf4df",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "ffu-ceiling-module",
"requestedEffort": null,
"confirmedEffort": null
@@ -1010,9 +1010,9 @@
"description": "The cleanroom wall kit model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_4e0249fdfb804779a0adb8c6cae9d2dd",
"reviewStatus": "accepted",
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"asset": "cleanroom-wall-kit",
"requestedEffort": "max",
"confirmedEffort": null
@@ -1089,9 +1089,9 @@
"description": "The etch cluster tool model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_6456090ae2cb42f09b3ff18670f55c3e",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "etch-cluster-tool",
"requestedEffort": null,
"confirmedEffort": null
@@ -1174,9 +1174,9 @@
"description": "The CVD/ALD cluster tool model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_5555be8ebedc496ba137ba5d47132e1b",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "cvd-ald-cluster-tool",
"requestedEffort": null,
"confirmedEffort": null
@@ -1259,9 +1259,9 @@
"description": "The PVD cluster tool model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_3ef2fa3a9e594f94b65dffe40253bd0c",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "pvd-cluster-tool",
"requestedEffort": null,
"confirmedEffort": null
@@ -1344,9 +1344,9 @@
"description": "The single-wafer clean tool model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_c268a0f6f6174f7ba2b87e120c4344e8",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "single-wafer-clean-tool",
"requestedEffort": null,
"confirmedEffort": null
@@ -1427,9 +1427,9 @@
"description": "The CMP polisher model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_a8c4d8680a7f4aca96b240daa294bc4b",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "cmp-polisher",
"requestedEffort": null,
"confirmedEffort": null
@@ -1512,9 +1512,9 @@
"description": "The vertical furnace model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_72680f2e5830442f93afff6a94519629",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "vertical-furnace",
"requestedEffort": null,
"confirmedEffort": null
@@ -1596,9 +1596,9 @@
"description": "The ion implanter model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_703483bb04b240bbaada2327534f7eef",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "ion-implanter",
"requestedEffort": null,
"confirmedEffort": null
@@ -1681,9 +1681,9 @@
"description": "The metrology inspection tool model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_a8395c71bb304806b3093749f7ab4ed4",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "metrology-inspection-tool",
"requestedEffort": null,
"confirmedEffort": null
@@ -1764,9 +1764,9 @@
"description": "The wafer prober/tester model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_7357b53066af464abb6556bdde7866d4",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "wafer-prober-tester",
"requestedEffort": null,
"confirmedEffort": null
@@ -1849,9 +1849,9 @@
"description": "The coater/developer track model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_a2be2a40435341b9b196f678130109b4",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "coater-developer-track",
"requestedEffort": null,
"confirmedEffort": null
@@ -1932,9 +1932,9 @@
"description": "The EUV scanner model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_5fb445d57eec47fa9c7238b1a5ee4242",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "euv-scanner",
"requestedEffort": null,
"confirmedEffort": null
@@ -2017,9 +2017,9 @@
"description": "The DUV immersion scanner model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_21ec88e7bb5b4c2c9ceae59c8142d978",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "duv-immersion-scanner",
"requestedEffort": null,
"confirmedEffort": null
@@ -2102,9 +2102,9 @@
"description": "The subfab pump/abatement kit model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_d0ff94d7e74c487b9b822f61a1ccd171",
"reviewStatus": "accepted",
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"asset": "subfab-pump-abatement-kit",
"requestedEffort": "max",
"confirmedEffort": null
@@ -2180,9 +2180,9 @@
"description": "The visitor gallery segment model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_cf68f8f819f34684ac183610c45596cc",
"reviewStatus": "accepted",
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"asset": "visitor-gallery-segment",
"requestedEffort": "max",
"confirmedEffort": null
@@ -2256,9 +2256,9 @@
"description": "The cleanroom technician model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_e1d7c6935493484d9586bcf0c21604de",
"reviewStatus": "accepted",
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"asset": "cleanroom-technician",
"requestedEffort": "max",
"confirmedEffort": null
@@ -2336,9 +2336,9 @@
"description": "The humanoid work robot model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_9f717d17eec74f2dbd4c338612207ed5",
"reviewStatus": "accepted",
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"asset": "humanoid-work-robot",
"requestedEffort": "high",
"confirmedEffort": null
@@ -2418,9 +2418,9 @@
"description": "The AMR floor robot model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_a27481224b474e9cb1dd747c45a71e23",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "amr-floor-robot-fit",
"requestedEffort": null,
"confirmedEffort": null
@@ -2502,9 +2502,9 @@
"description": "The tool-front robot arm model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_14bc5f09d6064a6aa8c20234c34b5d78",
"reviewStatus": "review-candidate",
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"attribution": {
- "author": "Codex · model and harness version not recorded",
+ "author": "Codex \u00b7 model and harness version not recorded",
"asset": "tool-front-robot-arm-fit",
"requestedEffort": null,
"confirmedEffort": null
@@ -2588,9 +2588,9 @@
"description": "The level section module model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_3b3d090fa0494380bdcaafaf6f3a22f2",
"reviewStatus": "accepted",
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"asset": "level-section-module",
"requestedEffort": "high",
"confirmedEffort": null
@@ -2670,9 +2670,9 @@
"description": "The s1 head w model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_c2d99522b58344b69dca0ad1ce41928a",
"reviewStatus": "review-candidate",
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"asset": "a_99c239a460b54a6db070df7d28338c63",
"requestedEffort": "max",
"confirmedEffort": null
@@ -2746,9 +2746,9 @@
"description": "The s1 head e model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_df7dae73a55c46f1853280912ac1d593",
"reviewStatus": "review-candidate",
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"asset": "a_a56d232bf5674ad78607864566f2e4e0",
"requestedEffort": "max",
"confirmedEffort": null
@@ -2822,9 +2822,9 @@
"description": "The s1 head w far model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_e8204a9885e14c2c9d09a22f755a80da",
"reviewStatus": "review-candidate",
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"asset": "a_eb6754b1b7fe4c7a8560895c763cb48c",
"requestedEffort": "max",
"confirmedEffort": null
@@ -2898,9 +2898,9 @@
"description": "The s1 head e far model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_2e4899a609764cf6a993093253b75fd8",
"reviewStatus": "review-candidate",
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"asset": "a_7d13f66d7d7b45a98136055b3a759856",
"requestedEffort": "max",
"confirmedEffort": null
@@ -2974,9 +2974,9 @@
"description": "The s4 canopy model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_e6e9b7f634014bc6ab698dcbb0df91a5",
"reviewStatus": "review-candidate",
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Opus 5.5 · claude 2.1.280",
+ "author": "Claude Opus 5.5 \u00b7 claude 2.1.280",
"asset": "a_ac56fc354640463fabb09a9d9b1a3879",
"requestedEffort": "max",
"confirmedEffort": null
@@ -3050,9 +3050,9 @@
"description": "The s2 hall w model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_360a18d9520a47ba8f74803411d880d7",
"reviewStatus": "review-candidate",
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"asset": "a_700fda75271246d686ed6ecbd9c02520",
"requestedEffort": "max",
"confirmedEffort": null
@@ -3126,9 +3126,9 @@
"description": "The s2 hall e model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_9240eafbf13942e4a6263b1012889b2d",
"reviewStatus": "review-candidate",
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"asset": "a_20881fa191c9400e8253ee566f285583",
"requestedEffort": "max",
"confirmedEffort": null
@@ -3202,9 +3202,9 @@
"description": "The s2 hall w far model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_47f890f3d7314130ade16990037c4519",
"reviewStatus": "review-candidate",
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"asset": "a_c6f2f32770a741e88e2adbd699c717bb",
"requestedEffort": "max",
"confirmedEffort": null
@@ -3278,9 +3278,9 @@
"description": "The s2 hall e far model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_d946a31fc6c041a8b3d6ca0e6006fb36",
"reviewStatus": "review-candidate",
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"asset": "a_3446d4140fb441929bafb1858ddfbc56",
"requestedEffort": "max",
"confirmedEffort": null
@@ -3354,9 +3354,9 @@
"description": "The s3 link model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_b2f1a7eab1cc48fb8d2561914e8888d3",
"reviewStatus": "review-candidate",
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"asset": "a_f5fc41aa4c354116908f4b2cd26c4958",
"requestedEffort": "max",
"confirmedEffort": null
@@ -3430,9 +3430,9 @@
"description": "The s5 split bridge model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_8bbd9104498f4aad974d4f3cb29e810e",
"reviewStatus": "review-candidate",
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"asset": "s5-split-bridge",
"requestedEffort": "max",
"confirmedEffort": null
@@ -3506,9 +3506,9 @@
"description": "The s5 split bridge far model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_51b50c962e754a098db9b438367ed1b1",
"reviewStatus": "review-candidate",
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"attribution": {
- "author": "Claude Sonnet 5.5 · claude 2.1.280",
+ "author": "Claude Sonnet 5.5 \u00b7 claude 2.1.280",
"asset": "s5-split-bridge-far",
"requestedEffort": "max",
"confirmedEffort": null
@@ -3582,9 +3582,9 @@
"description": "The sedan model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_92ee0ac3d5cf4b258cc97d20ec941461",
"reviewStatus": "review-candidate",
- "author": "GPT-6 Astra · codex 0.159.2",
+ "author": "GPT-6 Astra \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6 Astra · codex 0.159.2",
+ "author": "GPT-6 Astra \u00b7 codex 0.159.2",
"asset": "generic-sedan",
"requestedEffort": "ultra",
"confirmedEffort": null,
@@ -3663,9 +3663,9 @@
"description": "The hatchback model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_74f393f06996497a9dce6c5ed50c2d62",
"reviewStatus": "review-candidate",
- "author": "GPT-6 Astra · codex 0.159.2",
+ "author": "GPT-6 Astra \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6 Astra · codex 0.159.2",
+ "author": "GPT-6 Astra \u00b7 codex 0.159.2",
"asset": "generic-hatchback",
"requestedEffort": "ultra",
"confirmedEffort": null,
@@ -3744,9 +3744,9 @@
"description": "The suv model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_b4cc9048731b4c039de0b87ca6e75c17",
"reviewStatus": "review-candidate",
- "author": "GPT-6 Astra · codex 0.159.2",
+ "author": "GPT-6 Astra \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6 Astra · codex 0.159.2",
+ "author": "GPT-6 Astra \u00b7 codex 0.159.2",
"asset": "generic-suv",
"requestedEffort": "ultra",
"confirmedEffort": null,
@@ -3825,9 +3825,9 @@
"description": "The pickup model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_218be4189a1b43e7b307c2263ba4f954",
"reviewStatus": "review-candidate",
- "author": "GPT-6 Astra · codex 0.159.2",
+ "author": "GPT-6 Astra \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6 Astra · codex 0.159.2",
+ "author": "GPT-6 Astra \u00b7 codex 0.159.2",
"asset": "a_557b9bd6c2c34340804e802081a9b983",
"requestedEffort": "ultra",
"confirmedEffort": null,
@@ -3906,9 +3906,9 @@
"description": "The box truck model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_538b8a19c46d4086b456e27b32ee7d33",
"reviewStatus": "review-candidate",
- "author": "GPT-6 Astra · codex 0.159.2",
+ "author": "GPT-6 Astra \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6 Astra · codex 0.159.2",
+ "author": "GPT-6 Astra \u00b7 codex 0.159.2",
"asset": "a_2092ca0610c749b386c14c07dbaf4236",
"requestedEffort": "ultra",
"confirmedEffort": null,
@@ -3987,9 +3987,9 @@
"description": "The transit bus model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_85ff097a61384efab445c55372d3b6f5",
"reviewStatus": "review-candidate",
- "author": "GPT-6 Astra · codex 0.159.2",
+ "author": "GPT-6 Astra \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6 Astra · codex 0.159.2",
+ "author": "GPT-6 Astra \u00b7 codex 0.159.2",
"asset": "a_a8c030b2570f4ae5aa54eefbd3767f4c",
"requestedEffort": "ultra",
"confirmedEffort": null,
@@ -4068,9 +4068,9 @@
"description": "The tree broad l model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_9f23088183b1495a9d398603dae05ff5",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_b78c96bc78ba49f3ad8cea40aa50eb4c",
"requestedEffort": "high",
"confirmedEffort": null
@@ -4148,9 +4148,9 @@
"description": "The tree broad m model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_947dbc2b30b94fdf85804e19fb665b4d",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_af17477e70f74a5dacd28c8440fb857d",
"requestedEffort": "high",
"confirmedEffort": null
@@ -4228,9 +4228,9 @@
"description": "The tree broad s model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_aad434508024485a80b48effabe15185",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_57cf88474beb46d19832ce0f43e93b9c",
"requestedEffort": "high",
"confirmedEffort": null
@@ -4308,9 +4308,9 @@
"description": "The tree conifer l model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_b7d3879520f24b349d6a6ae6701ae2c3",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_2314a308a2074b0089a66cd18acac29e",
"requestedEffort": "high",
"confirmedEffort": null
@@ -4388,9 +4388,9 @@
"description": "The tree conifer m model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_e551108244024278bd4ae74f4d30346e",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_9152a27cdfac4d47abfd3eeecba986f5",
"requestedEffort": "high",
"confirmedEffort": null
@@ -4468,9 +4468,9 @@
"description": "The tree ornamental model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_6f6398c81f134c3fb7880fd2bc7537e4",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_d652aa1bc6594109ab5792a12847f75f",
"requestedEffort": "high",
"confirmedEffort": null
@@ -4548,9 +4548,9 @@
"description": "The shrub mound model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_37b46919727c4c8a8bafe8884635a17b",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_04e07c6b49f94dce8bb469a89b253bab",
"requestedEffort": "high",
"confirmedEffort": null
@@ -4628,9 +4628,9 @@
"description": "The hedge 4m model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_7b34245c9ea04e96ad8e449006f1f806",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_4168e827aacb40aeb1847781e1c5d88d",
"requestedEffort": "high",
"confirmedEffort": null
@@ -4708,9 +4708,9 @@
"description": "The truck tractor model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_bbd6fc0083764d728aa0c796fb33ab91",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_94bce49c4e934f20a3c188bc1d7f51d5",
"requestedEffort": "high",
"confirmedEffort": null,
@@ -4789,9 +4789,9 @@
"description": "The trailer dryvan model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_900808c392da42e899ba67a161845870",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_33ef365199464573912c7c7a771b37c7",
"requestedEffort": "high",
"confirmedEffort": null,
@@ -4870,9 +4870,9 @@
"description": "The trailer flatbed model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_7e81c6c0166b4142abad776a6ebb68d1",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_1c0fdc7dfefd4b1593e587f5a964467f",
"requestedEffort": "high",
"confirmedEffort": null,
@@ -4951,9 +4951,9 @@
"description": "The trailer tanker model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_247bb2b5dbd048889d3efd6c95aa20e0",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_2f10f10f73ab474c9d624e25f363b469",
"requestedEffort": "high",
"confirmedEffort": null,
@@ -5032,9 +5032,9 @@
"description": "The van delivery model from the Foundry Floor pack, seen from the front right.",
"revisionId": "r_961acb32238d428192bdd939da41ae6c",
"reviewStatus": "review-candidate",
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"attribution": {
- "author": "GPT-6.1 Sol · codex 0.159.2",
+ "author": "GPT-6.1 Sol \u00b7 codex 0.159.2",
"asset": "a_595dd1e9c1ce4f9d9e6e9d19daace9ac",
"requestedEffort": "high",
"confirmedEffort": null,
diff --git a/site/src/data/scene-inputs.json b/site/src/data/scene-inputs.json
index 9ec0c79f..6e6b042c 100644
--- a/site/src/data/scene-inputs.json
+++ b/site/src/data/scene-inputs.json
@@ -10,17 +10,17 @@
},
{
"id": "golden-gate",
- "release": "g9",
- "path": "scene-inputs/v09-review4/golden-gate.zip",
- "bytes": 8335422,
- "sha256": "5645e6d67d899c521cadb43da71f01dc1769a6ff931f29f374f9e65134275546"
+ "release": "g9-code5",
+ "path": "scene-inputs/alignment-motion3-20261003/golden-gate.zip",
+ "bytes": 8329648,
+ "sha256": "78f956059db0b6265f250f64b96bbc5bf4e52e02eec629cc9dcf7cb4aa991f8d"
},
{
"id": "foundry-floor",
- "release": "ff3-review2",
- "path": "scene-inputs/v09-review4/foundry-floor.zip",
- "bytes": 2858786,
- "sha256": "9043809403236964ffac8401358a1a946fde44d98e73ace1933b03e3ba9764ee"
+ "release": "ff3-review2-code5",
+ "path": "scene-inputs/alignment-motion3-20261003/foundry-floor.zip",
+ "bytes": 2868640,
+ "sha256": "22a49f2ef8e48fcdb37c12a9c475d94798870a3dca39d6798a3a6e60dd812ee4"
}
]
}
diff --git a/site/src/data/scene-media.json b/site/src/data/scene-media.json
index aa970b3a..a6974070 100644
--- a/site/src/data/scene-media.json
+++ b/site/src/data/scene-media.json
@@ -1,54 +1,64 @@
{
"golden-gate": {
"poster": {
- "src": "/media/scenes/golden-gate/g5/golden-gate-scene-drive.webp",
+ "src": "/media/scenes/golden-gate/g9-code5/golden-gate-scene-drive.webp",
"width": 1440,
"height": 925,
"alt": "A blue sedan driving across the deck of the Golden Gate Bridge scene, with traffic around it and both towers ahead.",
- "srcsetWebp": "/media/scenes/golden-gate/g5/golden-gate-scene-drive-320.webp 320w, /media/scenes/golden-gate/g5/golden-gate-scene-drive-480.webp 480w, /media/scenes/golden-gate/g5/golden-gate-scene-drive-672.webp 672w, /media/scenes/golden-gate/g5/golden-gate-scene-drive-768.webp 768w, /media/scenes/golden-gate/g5/golden-gate-scene-drive-1024.webp 1024w, /media/scenes/golden-gate/g5/golden-gate-scene-drive-1440.webp 1440w",
- "srcsetAvif": "/media/scenes/golden-gate/g5/golden-gate-scene-drive-320.avif 320w, /media/scenes/golden-gate/g5/golden-gate-scene-drive-480.avif 480w, /media/scenes/golden-gate/g5/golden-gate-scene-drive-672.avif 672w, /media/scenes/golden-gate/g5/golden-gate-scene-drive-768.avif 768w, /media/scenes/golden-gate/g5/golden-gate-scene-drive-1024.avif 1024w, /media/scenes/golden-gate/g5/golden-gate-scene-drive-1440.avif 1440w",
- "inputPath": "media/scenes/golden-gate/g5/golden-gate-scene-drive.png"
+ "srcsetWebp": "/media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-320.webp 320w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-480.webp 480w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-672.webp 672w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-768.webp 768w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-1024.webp 1024w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-1440.webp 1440w",
+ "srcsetAvif": "/media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-320.avif 320w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-480.avif 480w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-672.avif 672w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-768.avif 768w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-1024.avif 1024w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-drive-1440.avif 1440w",
+ "inputPath": "media/scenes/golden-gate/g9-code5/golden-gate-scene-drive.png"
},
"capture": {
"tool": "scripts/capture-scene-poster.mjs",
"view": "drive",
- "release": "g5",
+ "release": "g9-code5",
"size": [
1440,
925
],
- "browser": "Chrome/154.0.8037.58",
- "source": "The staged scene frame page with its controls hidden; nothing composited or retouched.",
- "runtimeSha256": "28aea5ca7efe35f4bdb6cdb19aefa080660cd55f302aadd3285862570d96ddc3",
- "packJsonSha256": "45fd9e8ef1e7bdec173863ad520e42e8f996c943dfcf57c4842d432ea006335c",
- "pngBytes": 740271,
- "pngSha256": "871dc9f068e8509ee477c9873b62978b90e2960f3ae358ce01f7b6b2d41c095b"
+ "browser": "Chrome/150.0.7871.128",
+ "source": "The staged scene runtime, captured from its canvas with controls hidden in headed Chrome on NVIDIA WebGPU; nothing composited or retouched.",
+ "runtimeSha256": "1a01a81a912157936f05a2060f1df377c418607a83567753e4db2b0257bdb556",
+ "packJsonSha256": "748536356d9639c65c76bc18f1e865c3426f5ee49904239efcb9b9c24c8a1524",
+ "pngBytes": 728452,
+ "pngSha256": "487793596f730d5424c1b25016fbc27408d6d2ab707c57343acbbc6a52b1bc56",
+ "renderer": {
+ "backend": "webgpu",
+ "vendor": "nvidia",
+ "architecture": "turing"
+ }
},
"captures": {
"day": {
"poster": {
- "src": "/media/scenes/golden-gate/g9/golden-gate-scene-day.webp",
+ "src": "/media/scenes/golden-gate/g9-code5/golden-gate-scene-day.webp",
"width": 1440,
"height": 925,
"alt": "The Golden Gate Bridge scene from above the water by day: the full span between its two towers, with the headlands on either side.",
- "srcsetWebp": "/media/scenes/golden-gate/g9/golden-gate-scene-day-320.webp 320w, /media/scenes/golden-gate/g9/golden-gate-scene-day-480.webp 480w, /media/scenes/golden-gate/g9/golden-gate-scene-day-672.webp 672w, /media/scenes/golden-gate/g9/golden-gate-scene-day-768.webp 768w, /media/scenes/golden-gate/g9/golden-gate-scene-day-1024.webp 1024w, /media/scenes/golden-gate/g9/golden-gate-scene-day-1440.webp 1440w",
- "srcsetAvif": "/media/scenes/golden-gate/g9/golden-gate-scene-day-320.avif 320w, /media/scenes/golden-gate/g9/golden-gate-scene-day-480.avif 480w, /media/scenes/golden-gate/g9/golden-gate-scene-day-672.avif 672w, /media/scenes/golden-gate/g9/golden-gate-scene-day-768.avif 768w, /media/scenes/golden-gate/g9/golden-gate-scene-day-1024.avif 1024w, /media/scenes/golden-gate/g9/golden-gate-scene-day-1440.avif 1440w",
- "inputPath": "media/scenes/golden-gate/g9/golden-gate-scene-day.png"
+ "srcsetWebp": "/media/scenes/golden-gate/g9-code5/golden-gate-scene-day-320.webp 320w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-480.webp 480w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-672.webp 672w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-768.webp 768w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-1024.webp 1024w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-1440.webp 1440w",
+ "srcsetAvif": "/media/scenes/golden-gate/g9-code5/golden-gate-scene-day-320.avif 320w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-480.avif 480w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-672.avif 672w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-768.avif 768w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-1024.avif 1024w, /media/scenes/golden-gate/g9-code5/golden-gate-scene-day-1440.avif 1440w",
+ "inputPath": "media/scenes/golden-gate/g9-code5/golden-gate-scene-day.png"
},
"capture": {
"tool": "scripts/capture-scene-poster.mjs",
"view": "day",
- "release": "g9",
+ "release": "g9-code5",
"size": [
1440,
925
],
- "browser": "Chrome/154.0.8037.58",
- "source": "The staged scene runtime, captured from its canvas with controls hidden; nothing composited or retouched.",
- "runtimeSha256": "203118926ca1e11c43542ce1605d06d19b9a984ebe1877251ae152c73bc634d6",
- "packJsonSha256": "c2a1d83fce6caf07a7b3e87070ccb8a983dd68e0c7f98eee3f1ba5255ce059cb",
- "pngBytes": 963303,
- "pngSha256": "50a2ecf3bd0eec02231ce614c56128be3bdb61bba8cf6be46535b2742c56e945"
+ "browser": "Chrome/150.0.7871.128",
+ "source": "The staged scene runtime, captured from its canvas with controls hidden in headed Chrome on NVIDIA WebGPU; nothing composited or retouched.",
+ "runtimeSha256": "1a01a81a912157936f05a2060f1df377c418607a83567753e4db2b0257bdb556",
+ "packJsonSha256": "748536356d9639c65c76bc18f1e865c3426f5ee49904239efcb9b9c24c8a1524",
+ "pngBytes": 886155,
+ "pngSha256": "3b75ae261e59a034165ec705d20931484b03600d39fae51c42fc02db22ba42e5",
+ "renderer": {
+ "backend": "webgpu",
+ "vendor": "nvidia",
+ "architecture": "turing"
+ }
}
}
}
diff --git a/site/src/data/scene-packs.json b/site/src/data/scene-packs.json
index b3466a13..2d6ed314 100644
--- a/site/src/data/scene-packs.json
+++ b/site/src/data/scene-packs.json
@@ -17,90 +17,98 @@
"golden-gate": {
"schema": "kiln.scene-pack/1",
"id": "golden-gate",
- "release": "g9",
+ "release": "g9-code5",
"three": "0.186.0",
"source": ".cache/site-inputs/golden-gate/standalone",
- "base": "/scene-packs/golden-gate/g9/",
+ "base": "/scene-packs/golden-gate/g9-code5/",
"sealedFiles": 103,
"sealedBytes": 12186327,
"totalFiles": 106,
- "totalBytes": 12240923,
- "packJsonSha256": "c2a1d83fce6caf07a7b3e87070ccb8a983dd68e0c7f98eee3f1ba5255ce059cb",
+ "totalBytes": 12240929,
+ "packJsonSha256": "748536356d9639c65c76bc18f1e865c3426f5ee49904239efcb9b9c24c8a1524",
"sha256sumsSha256": "75ce79fc746eafd27d7b597396489294a821fef5d88a05981b6bb9572159a58a",
- "noticesSha256": "4bf6f2bd1d803606c88eb540c8e207ddee4a76be4d12fe14d6110bb7505e4ebc",
+ "noticesSha256": "1c27b112542ccdf247a592f918c7753cea14852a1e5234012bc06bd5ef9b859b",
"runtime": {
"kind": "frame",
- "file": "index-BDTQ3svb.js",
- "bytes": 1724619,
- "gzipBytes": 518716,
+ "file": "index-DhpWxFro.js",
+ "bytes": 1708928,
+ "gzipBytes": 512680,
"gzipMethod": "bun-zlib",
- "sha256": "203118926ca1e11c43542ce1605d06d19b9a984ebe1877251ae152c73bc634d6",
- "modulesSha256": "928ffa3a06eb8c8f227c4ab842a51b1c5b4cda46e58ce7e65423e7cd1ca4466b"
+ "sha256": "1a01a81a912157936f05a2060f1df377c418607a83567753e4db2b0257bdb556",
+ "modulesSha256": "ace29d2d8e9395d6887ca2b30ca68ce5ed596a781ec214ad68538902995553ae"
}
},
"foundry-floor": {
"schema": "kiln.scene-pack/1",
"id": "foundry-floor",
- "release": "ff3-review2",
+ "release": "ff3-review2-code5",
"three": "0.186.0",
"source": ".cache/site-inputs/foundry-floor/standalone",
- "base": "/scene-packs/foundry-floor/ff3-review2/",
+ "base": "/scene-packs/foundry-floor/ff3-review2-code5/",
"sealedFiles": 85,
"sealedBytes": 11519818,
"totalFiles": 88,
- "totalBytes": 11637133,
- "packJsonSha256": "6ce49d05791bf42d21f3628237a5cf005ce9f2fa15938f0c321430d781c2c5d4",
+ "totalBytes": 11637139,
+ "packJsonSha256": "822be1171621273dfdf857fe6ca320ed41d16e03c49fc49860c13e7092be4836",
"sha256sumsSha256": "21ec914770e35ced418015e1e9965488d96cb8e457bbc1602273cc3936712e7c",
- "noticesSha256": "4bf6f2bd1d803606c88eb540c8e207ddee4a76be4d12fe14d6110bb7505e4ebc",
+ "noticesSha256": "1c27b112542ccdf247a592f918c7753cea14852a1e5234012bc06bd5ef9b859b",
"runtime": {
"kind": "frame",
- "file": "index-Y86dU6mu.js",
- "bytes": 1705082,
- "gzipBytes": 517258,
+ "file": "index-BpDIz-38.js",
+ "bytes": 1710132,
+ "gzipBytes": 519928,
"gzipMethod": "bun-zlib",
- "sha256": "fdf0724ffc38717f3289aaaa0de3891be907a74a2a1570b1a9e926e4e306398d",
- "modulesSha256": "429151e104015482e5e29d7b8d7bebb8d1e868664de36ff7106bff7028a64339",
+ "sha256": "252a06c4a8812d803942e581182e5e3a73951982def9e4ae1fea686d7c5a3899",
+ "modulesSha256": "7ed7a35df2406548c5e1065bf08e777e1e4dd9da3f2fa0f48215bd97bc39e27d",
"initialLoad": {
"files": [
- "data-CtFNqKxF.js",
- "exterior-BhOIr0wM.js",
- "index-Y86dU6mu.js"
+ "data-D6ylNSp1.js",
+ "exterior-DhGtl-eu.js",
+ "index-BpDIz-38.js",
+ "session-B17LXo16.js"
],
- "bytes": 1527808,
- "gzipBytes": 446414,
+ "bytes": 1532295,
+ "gzipBytes": 448748,
"deferredFiles": [
- "interior-CaAk33CR.js"
+ "interior-CvvOKxxa.js"
],
- "receiptSha256": "637febfc07fbae74c57933d5edfc83a7624168fa5fca0cf31616a2c46ce1f108"
+ "receiptSha256": "628545d568431c5000e1d683b7fea4230eb1fd9c1c377636e000e2cac3fdf029"
},
"chunks": [
{
- "file": "data-CtFNqKxF.js",
- "bytes": 42050,
- "gzipBytes": 11708,
+ "file": "data-D6ylNSp1.js",
+ "bytes": 41809,
+ "gzipBytes": 11688,
"gzipMethod": "bun-zlib",
- "sha256": "221e0bb094f1246917827439b92b18d4826e3c248b50191c4590c6b61dfc113f"
+ "sha256": "45fdb75ca785b1f7b7261977f5f73da4b209c806d9f74ed12f07bd1417f812ce"
},
{
- "file": "exterior-BhOIr0wM.js",
- "bytes": 73389,
- "gzipBytes": 28182,
+ "file": "exterior-DhGtl-eu.js",
+ "bytes": 75547,
+ "gzipBytes": 28943,
"gzipMethod": "bun-zlib",
- "sha256": "de54e858f5d70550caa1083e09fc673ecbe2bf67496dbc5ccd46590422ffc678"
+ "sha256": "889c81e92b8f20ba4b9d973774c2bbb367b943c2b91be3ee87ffa706b03cfc61"
},
{
- "file": "index-Y86dU6mu.js",
- "bytes": 1412369,
- "gzipBytes": 406524,
+ "file": "index-BpDIz-38.js",
+ "bytes": 8667,
+ "gzipBytes": 3767,
"gzipMethod": "bun-zlib",
- "sha256": "fdf0724ffc38717f3289aaaa0de3891be907a74a2a1570b1a9e926e4e306398d"
+ "sha256": "252a06c4a8812d803942e581182e5e3a73951982def9e4ae1fea686d7c5a3899"
},
{
- "file": "interior-CaAk33CR.js",
- "bytes": 177274,
- "gzipBytes": 70844,
+ "file": "interior-CvvOKxxa.js",
+ "bytes": 177837,
+ "gzipBytes": 71180,
"gzipMethod": "bun-zlib",
- "sha256": "918836da73f0e67c8ffa54dc3c77c221d4c25e7f3feed294e4ff520f474a41d8"
+ "sha256": "058074e51339c7494afbc62a42e6daa98746280c6ff65f43f402e2f1372321a7"
+ },
+ {
+ "file": "session-B17LXo16.js",
+ "bytes": 1406272,
+ "gzipBytes": 404350,
+ "gzipMethod": "bun-zlib",
+ "sha256": "3bb2adb93396a112785afc79e5945f30181a0464a7e6e4107d49a6aba6f6483c"
}
]
}
diff --git a/site/src/styles/global.css b/site/src/styles/global.css
index 6877d6cd..6f4263da 100644
--- a/site/src/styles/global.css
+++ b/site/src/styles/global.css
@@ -70,6 +70,8 @@
pre {max-width:100%;overflow-x:auto;tab-size:2;}
summary {min-height:44px;display:list-item;padding:1rem;}
[hidden] {display:none!important;}
+ /* Reserve Explore's row before the shell initializes, including without JavaScript. */
+ scene-shell [data-explore][hidden] {display:inline-flex!important;visibility:hidden;}
::selection {background:var(--color-ember);color:var(--color-sheet);}
}
@utility container {width:100%;max-width:var(--container-site);margin-inline:auto;padding-inline:1rem;@media(min-width:48rem){padding-inline:2rem;}@media(min-width:80rem){padding-inline:4.5rem;}}
@@ -100,7 +102,7 @@
#menu-toggle[aria-expanded=true] {background:var(--color-ink);color:var(--color-sheet);}
/* The bar over a running scene is one short row. In fullscreen it gives way to a single faint chip at the middle of the left edge, clear of every scene's own controls, so the scene has the screen and touch devices keep a way out. */
.scene-topbar {border-bottom:1px solid var(--color-rule);padding:.25rem .5rem;}
- .scene-topbar-button {display:inline-flex;align-items:center;gap:.375rem;min-height:2.5rem;padding:.25rem .75rem;border:1px solid var(--color-rule);border-radius:var(--radius-control);background:var(--color-sheet);color:var(--color-ink);font-size:.875rem;font-weight:600;white-space:nowrap;}
+ .scene-topbar-button {display:inline-flex;align-items:center;gap:.375rem;min-height:2.75rem;padding:.25rem .75rem;border:1px solid var(--color-rule);border-radius:var(--radius-control);background:var(--color-sheet);color:var(--color-ink);font-size:.875rem;font-weight:600;white-space:nowrap;}
.scene-topbar-button:hover {background:var(--color-stage);border-color:var(--color-ink);}
scene-shell:fullscreen .scene-topbar {position:absolute;top:50%;left:max(.5rem,env(safe-area-inset-left));z-index:10;transform:translateY(-50%);border:0;padding:0;}
scene-shell:fullscreen [data-exit] {display:none;}
diff --git a/skills/kiln-author-asset/references/geometry-recipes.md b/skills/kiln-author-asset/references/geometry-recipes.md
index 67d0b08e..a0d36767 100644
--- a/skills/kiln-author-asset/references/geometry-recipes.md
+++ b/skills/kiln-author-asset/references/geometry-recipes.md
@@ -106,9 +106,29 @@ shape while preserving a correct wrist pivot and attachment frame, then check ha
clearance through the relevant motion and against the complete carried tool.
When reducing draw calls, consolidate compatible geometry within the same rigid
-motion parent. Preserve independently moving nodes, attachment markers and names
-that the consumer uses. Recheck clip targets and intermediate poses after export;
-fewer meshes alone does not establish a successful optimization.
+motion parent. Give independently moving groups real, named `Joint_*` pivots and
+put their rigid geometry beneath them. Preserve attachment markers and consumer
+lookups. In builds with rigid-group `full` optimization, the rigid-merge pass retains
+node names, but a named mesh outside a protected boundary can become empty or contain
+other parts' geometry. If each named part must keep its geometry, use `off` or
+`palette` optimization and disable the separate GPU-instancing pass, which can remove
+named instance nodes (`instance: 'off'` in library calls or `KILN_BAKE_INSTANCE=off`
+in the host). Recheck what each
+lookup controls, clip targets and intermediate poses after export; fewer meshes
+alone does not establish a successful optimization.
+
+Budget materials within each rigid group. Reuse the parent's material for tiny
+fixed details when it gives the intended appearance; a separate material adds a
+potential draw even when the detail is small. One material does not guarantee
+one draw: vertex layouts, protected parts, transparency and vertex-limit splits
+also constrain merging. Available `drawDiagnostics` can help locate these costs;
+read its scope and skip reasons, then measure in the destination.
+
+Avoid unintentionally overlapping coplanar faces on separate parts. Merging can
+change which face wins a depth tie even when geometry and colours are preserved.
+Use a shared surface, remove hidden duplicate faces or give a deliberate overlay
+the separation it needs. Inspect the actual exported surface from relevant views;
+do not offset every touching joint or treat a sampled coplanar flag as a defect.
## Materials and directional UVs
diff --git a/skills/kiln-compose-scene/references/runtime-scenes.md b/skills/kiln-compose-scene/references/runtime-scenes.md
index 371be4ef..272527c3 100644
--- a/skills/kiln-compose-scene/references/runtime-scenes.md
+++ b/skills/kiln-compose-scene/references/runtime-scenes.md
@@ -2,6 +2,8 @@
Read this for an environment or proving application, rather than a simple asset
arrangement. These are consumer workflows, not additional Kiln CLI/MCP commands.
+The examples describe consumer implementations; the private proving-scene kit is
+not installed by the Kiln engine package. Verify the destination's available APIs.
## Layout and environment
@@ -40,6 +42,18 @@ For a follow camera, run its actual update and controls during passage checks.
A controller-only loop can pass while the rendered camera hides the actor behind
an eave or lintel. Inspect the animated head and accessories, not only a clear
ray toward the torso; keep camera dimensions and fixes in the consuming scene.
+Keep the user's orbit and zoom separate from obstacle-induced camera pull-in.
+Exercise a continuous drag with rendered frames between touch moves, and check
+both heading and distance; a heading-only check misses progressive zoom drift.
+Verify two-finger pinch in both directions, gesture changes, obstruction recovery
+and release without moving the actor. Touch emulation is functional evidence,
+not a substitute for physical-device rendering or timing evidence.
+
+When switching between touch and keyboard controls, release only the movement
+owned by the control being removed. Test the first keyboard press after both an
+idle and an active joystick, plus delayed touch release, cancellation and unmount;
+old cleanup must not erase newer input. Also verify that releasing the current
+control stops movement and that disabling input clears every source.
Separate in-place animation from world movement. A representative animated scene
may need both, including changing camera visibility, instead of every actor
@@ -47,6 +61,27 @@ walking at its origin. Preview controllers should restore inspection poses and
hand control back cleanly. State limitations such as kinematic driving or lack of
navigation instead of presenting a scripted preview as complete gameplay.
+When animation runs every rendered frame but movement uses fixed steps, apply the
+final pose and attachment corrections after animation on every rendered frame,
+including frames with no simulation step. Check start/stop, tool removal, seating
+and return to overview at substep intervals. Hand clearance alone does not prove
+that an empty hand has a relaxed gesture or a natural wrist orientation.
+
+For shaders using a moving local origin, compensate every wave phase and texture
+lookup in the same signed, rotated and scaled coordinates as its shader stage.
+Freeze animation and move the camera a small distance across origin and tile
+boundaries on both axes; compare against a repeated capture at the same position.
+Review low and aerial camera paths as well as static views for surface snapping.
+
+For an embedded HUD, size panels against the scene's own box, including short
+landscape views. The optional proving kit anchors its default help and credits
+panels to the HUD independently of toolbar height, and lets nested joystick and
+touch buttons receive pointer input. Scene CSS may keep an inline panel or bottom
+sheet; preserve its intended stacking above play controls. Check scrolling,
+keyboard entry and Escape focus return, then use actual touch events to verify
+movement, release and no click-through. Desktop mouse success alone does not
+establish the touch contract or physical-device acceptance.
+
## Optimization and measurement
Use instancing for compatible repeated geometry/materials, with useful spatial
@@ -76,11 +111,18 @@ proving scenes, one farm view drew 583: 312 main, 270 shadow and 1 output. A
bridge drew 148 of the 180 draws at the lowest tier. Rank levers per scene from
its own numbers; the same lever can matter in one scene and be absent in another.
-Merge rigid parts by material inside anchors, and keep every anchor as a real
-node with its name, transform and children. Anchors are animation targets,
-pivots the application moves, nodes it looks up by name, nodes carrying
-semantic data, and visibility or LOD switches. Leave transparent, multi-material,
-skinned and morphed parts separate. A per-material merge kept doors, wheels,
+Merge compatible material/layout groups inside real animation and interaction
+anchors. Preserve every anchor's name, transform, children and own geometry.
+For builds with Kiln's rigid-group `full` mode, consult the named-part contract in the QA skill's
+`references/engine-handoff.md`: a name alone does not make a boundary, and a
+named non-boundary mesh can become empty or absorb its group's geometry.
+Check the meshes each runtime lookup controls. Disable separate GPU instancing
+when per-node identity or geometry matters (`instance: 'off'` in library calls);
+that pass can remove named instance nodes. The rigid-merge pass protects animation,
+joint, semantic, visibility and LOD boundaries and composition placement roots;
+its locked primitives and vertex splits can leave several draws per material.
+The scene-specific merge behind the following measurements separately excluded
+transparent, multi-material, skinned and morphed parts. It kept doors, wheels,
limbs, colliders and the frame graph working while a farmhouse went from 16 to
11 draws and a bridge from 148 to 20. Split very long structures into a few
spatial groups so culling still works. Two side effects need checks:
@@ -90,9 +132,17 @@ spatial groups so culling still works. Two side effects need checks:
that now won the depth tie against a walkway stippled the kerbs; ordering the
curbs first inside the merged mesh fixed it at no extra draw. Parts in
different buckets keep one fixed order for every view, so split a bucket
- where the per-part draw order matters: splitting a bridge's tower panels at
- the ribs' height, one draw per tower, brought a 193 px tie under a 100 px
- budget.
+ where the per-part draw order matters. In an experimental bridge variant,
+ splitting tower panels at the ribs' height, one draw per tower, brought a
+ 193 px tie under a 100 px budget. That prototype was not the adopted bridge
+ solution; do not treat its result as acceptance of a shipped scene.
+
+Use available `drawDiagnostics` as a bounded inspection aid; the QA skill's
+`references/integration-checks.md` explains its scope, skips and observations.
+Its per-anchor estimate uses existing materials and eligible rigid groups,
+including locks and splits; it is not a full-mode or renderer prediction.
+Mirrored-tangent and sampled coplanar candidates direct destination checks,
+not automatic repairs or acceptance. Count the actual extra passes separately.
Treat each extra pass as its own budget:
- **Shadow pass.** Use material-free depth stand-ins per anchor and shadow side.
@@ -113,6 +163,16 @@ A cached shadow only pays where its frustum stays still. A shadow box that
follows a driven car re-renders every frame, so measure moving workloads before
enabling it.
+The current proving kit watches `morphTargetInfluences` on casters registered
+under a `movable` node, alongside matrices, visibility, casting and instance
+matrix/count changes. Changing morph weights promotes them to the live map until
+they settle; watched skins remain live. This does not scan geometry or shader
+graphs. Register continuous shader-position animation, custom instance attributes
+and other unobserved deformation with the `live` predicate on the first track;
+call `invalidate` after discrete unobserved changes to static casters. Verify
+that the deformation also reaches the shadow pass. These are consumer cache APIs,
+not extra requirements on standalone assets.
+
In three r186's WebGPU renderer every `InstancedMesh` binds its own pipeline,
because its uuid is part of the material cache key. `EXT_mesh_gpu_instancing`
therefore saves draws but adds a pipeline per instanced group: instancing one
@@ -122,6 +182,11 @@ and roughness as vertex data, instance matrices as attributes of plain meshes.
That took a campus planting from 21 pipelines to 10 at the overview and from
40-49 to 11-13 near the ground, with pixel parity.
+Transforms implemented only in a material graph may be bypassed by override
+materials in shadow, depth or picking passes. Supply equivalent transforms for
+those passes or keep the affected meshes out of them. The planting example has
+no such pass and explicitly prevents the shared plant meshes from casting shadows.
+
When a frame's main pass is never split by a mid-pass copy (for example a
depth-texture read for water), its multisampled attachments need not be stored
after the resolve. Discarding them changed nothing measurable on a desktop GPU.
@@ -136,10 +201,19 @@ tablet's busy column read mixed, busy × clock fell by 15% and 24%.
Over long view distances, a 24-bit depth buffer with a 0.5 m near plane steps
by about 0.12 m at 1 km, 3 m at 5 km and 48 m at 20 km, growing with distance
squared, so distant near-coplanar surfaces flicker as the camera moves.
-Reversed depth is the remedy. In three r186 it needs three adaptations: draw
+Reversed depth addresses that loss of precision. In three r186 it needs three adaptations: draw
the sky first without a depth test, rebuild a planar reflector's oblique
projection, and flip the sign of polygon offsets. On WebGL2 it also needs
`EXT_clip_control`, or three falls back to a standard buffer.
+This repository's optional scene-kit exposes `reversedDepthBuffer` on
+`SceneDefinition` and `RendererFactoryOptions`, defaulting to `false`. A scene
+must opt in and implement its own adaptations. After renderer initialization,
+use the effective `renderer.reversedDepthBuffer` for projection and offset
+changes: a request can become `false` on unsupported WebGL2. Pass the camera's
+coordinate system and effective reversed-depth flag to custom frustum tests.
+Recheck sky, reflection clipping, offsets and depth-reading materials on both
+backends when upgrading three; support in the renderer alone is not scene
+qualification. These are consumer runtime APIs, not Kiln CLI/MCP switches.
Report cached features in both their settled and their running state. With the
clock running, the farm view that drew 583 drew 314-337, with about ten static
diff --git a/skills/kiln-qa-asset/references/engine-handoff.md b/skills/kiln-qa-asset/references/engine-handoff.md
index 2dd69752..5d812101 100644
--- a/skills/kiln-qa-asset/references/engine-handoff.md
+++ b/skills/kiln-qa-asset/references/engine-handoff.md
@@ -116,6 +116,28 @@ replace edited skills. Consult the updated runtime documentation when working in
Bake Animation. Reimport the FBX and check offsets; materials and sidedness can still change.
See [Blender's option documentation](https://docs.blender.org/api/main/bpy.ops.export_scene.html).
+### Full optimization and named parts
+
+In builds with rigid-group `full` optimization, the rigid-merge pass retains every node's name,
+transform and hierarchy. It preserves geometry directly attached to boundaries:
+animation targets, skin joints, `Joint_*` pivots, nodes carrying extras or named by semantic
+relationships, visibility switches, LOD owners and levels, shared scene roots,
+and composition placement roots. Compatible rigid descendants can merge inside
+each boundary. A name alone is not a boundary: another named mesh may become
+empty or hold merged geometry from its rigid group.
+
+Check the exact meshes each consumer lookup moves, replaces, hides or uses for
+collision. If those depend on geometry staying on a particular unprotected node,
+retain `palette`/`off` or establish a supported boundary before using `full`.
+Also disable separate GPU instancing when per-node identity or geometry matters:
+that pass can remove named instance nodes. Set `instance: 'off'` in library calls
+or `KILN_BAKE_INSTANCE=off` in the host; this is not a new tool input.
+Full optimization is separate from the editable/runtime delivery profile and
+does not retroactively change a saved asset. Check merge warnings and the
+[bounded diagnostic guidance](integration-checks.md#performance-evidence), then
+verify the exported derivative's interactions and material appearance in the
+destination. Preserved names alone do not prove compatibility.
+
## Measured LOD import behavior
On 2026-09-30, headless structural checks imported 13 static vegetation and freight GLBs
@@ -208,7 +230,9 @@ and silhouette remain part of owner review.
extension shows LOD0 only, as three.js `GLTFLoader` 0.186 does. The measured Blender and
glTFast behavior is recorded above; automatic threshold switching still needs destination
qualification. An imported GLB's chains survive save, optimisation and export too. GPU
- instancing skips a file with chains, and full optimisation falls back to palette.
+ instancing skips a file with chains. In builds with rigid-group `full` optimisation,
+ the rigid-merge pass preserves the chain owner and every referenced level as separate boundaries; compatible rigid descendants
+ can merge within those boundaries. This does not qualify destination LOD switching.
- More extensions in a valid GLB do not guarantee support in every importer or shader. GPU
appearance, runtime-loaded shader inclusion, compression codecs and other render pipelines
need their own checks. This option does not change KTX2 defaults or fix unsupported Node versions.
diff --git a/skills/kiln-qa-asset/references/integration-checks.md b/skills/kiln-qa-asset/references/integration-checks.md
index dd86b082..0701cc8a 100644
--- a/skills/kiln-qa-asset/references/integration-checks.md
+++ b/skills/kiln-qa-asset/references/integration-checks.md
@@ -54,6 +54,31 @@ file as a derivative with its own hash and keep the editable source and baseline
## Performance evidence
+In builds that provide it, `drawDiagnostics` appears in `kiln_inspect` compact/full
+results, `kiln_export`, and CLI export JSON for GLBs/bundles. It is advisory output,
+not a QA rule or acceptance result. Read `status` and `reason` first: `input-limit`,
+`unreadable-glb` or `analysis-failed` means no assessment. An absent field in an older
+installation or a lean response is not a clean result.
+
+Read `scope` and `mergeEstimate.method` with the numbers. These are static single-pass
+primitive counts across document scenes with node visibility, without culling,
+alternate LOD selections, shadows, reflections, depth or other renderer passes.
+The estimate uses current materials and the rigid merge's layouts, boundaries,
+locks, byte budget and vertex splits; it excludes palette consolidation and
+instancing, so it does not predict complete `full` output or GPU speed. Check
+`mergeEstimate.skipped` and rejected buckets. Compare per-anchor `draws` and
+`afterRigidMerge` by ID, and report `anchors.omitted` when the listing is truncated.
+Measure actual destination draws by anchor, material and pass after export, then
+exercise the interactions and attachments those anchors protect.
+
+Read each observation's `evidence` and sampling/omission counts.
+`mirroredTangents` identifies static tangent-bearing parts with mirrored transforms;
+it does not establish a shading defect. `coplanarParts` samples triangle overlaps
+between parts; it neither proves visible z-fighting nor clears unsampled faces.
+Skinned, morphed and GPU-instanced uses are unexamined by these observations.
+Review candidate surfaces and normal-map lighting in the destination before
+changing geometry or material behavior.
+
Separate cold loading/compilation and first interactions from warmed playback.
Record actual renderer/backend, versions, resolution, quality and representative
instances. Distinguish CPU submission/update time, browser frame intervals and
diff --git a/src/__tests__/draw-diagnostics.test.ts b/src/__tests__/draw-diagnostics.test.ts
new file mode 100644
index 00000000..71dd15cc
--- /dev/null
+++ b/src/__tests__/draw-diagnostics.test.ts
@@ -0,0 +1,164 @@
+import { expect, test } from 'bun:test';
+import { Document, type Material, type Primitive } from '@gltf-transform/core';
+import { KHRNodeVisibility } from '@gltf-transform/extensions';
+import { analyzeDrawDiagnostics, inspectDrawDiagnostics } from '../draw-diagnostics';
+import { createGltfIO } from '../gltf-io';
+
+function fixture() {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const scene = doc.createScene('Scene');
+ const material = doc.createMaterial('M');
+ const primitive = (count = 3, mat: Material = material) => {
+ const positions = new Float32Array(count * 3);
+ for (let i = 0; i < count; i++)
+ positions.set([Math.floor(i / 3) * 2 + (i % 3 === 1 ? 1 : 0), i % 3 === 2 ? 1 : 0, 0], i * 3);
+ return doc
+ .createPrimitive()
+ .setMaterial(mat)
+ .setAttribute(
+ 'POSITION',
+ doc.createAccessor().setType('VEC3').setArray(positions).setBuffer(buffer),
+ )
+ .setIndices(
+ doc
+ .createAccessor()
+ .setType('SCALAR')
+ .setArray(Uint16Array.from({ length: count }, (_, i) => i))
+ .setBuffer(buffer),
+ );
+ };
+ const node = (name: string, p: Primitive = primitive()) => {
+ const n = doc.createNode(name).setMesh(doc.createMesh().addPrimitive(p));
+ scene.addChild(n);
+ return n;
+ };
+ return { doc, scene, material, primitive, node, buffer };
+}
+
+test('draw estimates use actual rigid groups, layouts and locks and never change the input', async () => {
+ const f = fixture();
+ f.node('A');
+ f.node('B').setTranslation([2, 0, 0]);
+ const different = f
+ .primitive()
+ .setAttribute(
+ 'TEXCOORD_0',
+ f.doc.createAccessor().setType('VEC2').setArray(new Float32Array(6)).setBuffer(f.buffer),
+ );
+ f.node('DifferentLayout', different);
+ const pivot = f.doc.createNode('Joint_Hinge');
+ f.scene.addChild(pivot);
+ pivot.addChild(f.node('HingeChild'));
+ f.node('Glass', f.primitive(3, f.doc.createMaterial('Glass').setAlphaMode('BLEND')));
+ const io = createGltfIO();
+ const bytes = await io.writeBinary(f.doc);
+
+ const report = analyzeDrawDiagnostics(f.doc);
+
+ expect(report.status).toBe('assessed');
+ expect(report.currentDraws).toBe(5);
+ expect(report.mergeEstimate).toMatchObject({ draws: 4, saved: 1 });
+ expect(report.anchors?.items.find((a) => a.name === 'Joint_Hinge')).toMatchObject({
+ draws: 1,
+ afterRigidMerge: 1,
+ });
+ expect(report.scope).toMatch(/shadow.*reflection/i);
+ expect(report.mergeEstimate?.method).toMatch(/existing materials/i);
+ expect(analyzeDrawDiagnostics(f.doc, { keep: ['A'] }).mergeEstimate?.draws).toBe(5);
+ expect(await io.writeBinary(f.doc)).toEqual(bytes);
+ expect(await inspectDrawDiagnostics(bytes)).toEqual(report);
+});
+
+test('estimates include the shared-byte budget and the 65,534-vertex split', () => {
+ const shared = fixture();
+ const p = shared.primitive(900);
+ shared.node('A', p);
+ shared.node('B', p.clone());
+ expect(analyzeDrawDiagnostics(shared.doc).mergeEstimate).toMatchObject({ draws: 2, saved: 0 });
+
+ const split = fixture();
+ for (let i = 0; i < 3; i++) split.node(String(i), split.primitive(24_000));
+ expect(analyzeDrawDiagnostics(split.doc).mergeEstimate).toMatchObject({ draws: 2, saved: 1 });
+});
+
+test('flags sampled overlapping coplanar parts and mirrored tangents without claiming visual defects', () => {
+ const f = fixture();
+ f.node('A');
+ f.node('Overlap').setTranslation([0.1, 0.1, 0]);
+ f.node('Separated').setTranslation([5, 0, 0]);
+ const p = f.primitive().setAttribute(
+ 'TANGENT',
+ f.doc
+ .createAccessor()
+ .setType('VEC4')
+ .setArray(new Float32Array([1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1]))
+ .setBuffer(f.buffer),
+ );
+ f.node('Mirrored', p).setScale([-1, 1, 1]).setTranslation([10, 0, 0]);
+ const hidden = f.node('Hidden', p.clone()).setScale([-1, 1, 1]);
+ hidden.setExtension(
+ 'KHR_node_visibility',
+ f.doc.createExtension(KHRNodeVisibility).createVisibility().setVisible(false),
+ );
+
+ const report = analyzeDrawDiagnostics(f.doc);
+
+ expect(report.currentDraws).toBe(4);
+ expect(report.observations?.mirroredTangents.count).toBe(1);
+ expect(report.observations?.coplanarParts.candidates).toHaveLength(1);
+ expect(report.observations?.coplanarParts.evidence).toMatch(/sampled.*not.*z-fighting/i);
+ expect(report.observations?.mirroredTangents.evidence).toMatch(/not.*shading/i);
+});
+
+test('large inputs explicitly skip estimates and bounded output reports omitted anchors', async () => {
+ const f = fixture();
+ for (let i = 0; i < 60; i++) f.node(`Joint_${i}_${'x'.repeat(400)}`);
+ const report = analyzeDrawDiagnostics(f.doc);
+ expect(report.anchors!.total).toBeGreaterThan(16);
+ expect(report.anchors!.omitted).toBe(report.anchors!.total - report.anchors!.items.length);
+ expect(JSON.stringify(report).length).toBeLessThan(8000);
+ const large = new Document();
+ for (let i = 0; i < 2049; i++) large.createNode();
+ expect(analyzeDrawDiagnostics(large)).toMatchObject({ status: 'skipped', reason: 'input-limit' });
+ expect(analyzeDrawDiagnostics(large).mergeEstimate).toBeUndefined();
+ expect(await inspectDrawDiagnostics(new Uint8Array([1, 2, 3]))).toMatchObject({
+ status: 'skipped',
+ reason: 'unreadable-glb',
+ });
+});
+
+test('coplanar candidates exclude adjacent triangles and geometry in different scenes', () => {
+ const f = fixture();
+ f.node('First');
+ const adjacent = f.primitive();
+ adjacent.getAttribute('POSITION')!.setArray(new Float32Array([1, 0, 0, 1, 1, 0, 0, 1, 0]));
+ f.node('Adjacent', adjacent);
+ const alternative = f.doc.createScene('Alternative');
+ const alternateNode = f.node('Same coordinates in another scene');
+ f.scene.removeChild(alternateNode);
+ alternative.addChild(alternateNode);
+
+ const report = analyzeDrawDiagnostics(f.doc);
+
+ expect(report.currentDraws).toBe(3);
+ expect(report.observations?.coplanarParts.candidatePairs).toBe(0);
+});
+
+test('draw estimates count each scene placement without moving geometry across shared entry points', () => {
+ const f = fixture();
+ const shared = f.node('Shared');
+ shared.addChild(f.node('DetailA').setTranslation([0, 2, 0]));
+ shared.addChild(f.node('DetailB').setTranslation([0, 4, 0]));
+ f.node('OnlyFirstScene').setTranslation([4, 0, 0]);
+ f.doc.createScene('Alternative').addChild(shared);
+
+ const report = analyzeDrawDiagnostics(f.doc);
+
+ expect(report.currentDraws).toBe(7);
+ expect(report.mergeEstimate).toMatchObject({ draws: 5, saved: 2 });
+ const anchors = report.anchors!.items.filter((a) => a.name === 'Shared');
+ expect(anchors).toHaveLength(2);
+ expect(new Set(anchors.map((a) => a.id)).size).toBe(2);
+ for (const anchor of anchors) expect(anchor).toMatchObject({ draws: 3, afterRigidMerge: 2 });
+});
diff --git a/src/__tests__/kit.test.ts b/src/__tests__/kit.test.ts
index 531ebeb1..3c9a603d 100644
--- a/src/__tests__/kit.test.ts
+++ b/src/__tests__/kit.test.ts
@@ -8,13 +8,21 @@
*/
import { describe, expect, test } from 'bun:test';
-import { Document, WebIO } from '@gltf-transform/core';
+import {
+ Document,
+ type Material,
+ type Texture,
+ type TextureInfo,
+ WebIO,
+} from '@gltf-transform/core';
import {
KHRMaterialsEmissiveStrength,
KHRMaterialsVariants,
KHRTextureBasisu,
KHRTextureTransform,
+ type Transform,
} from '@gltf-transform/extensions';
+import sharp from 'sharp';
import {
applyKitContract,
@@ -154,7 +162,210 @@ function occlusionBesideMetallicRoughness(occlusionUv: number, metallicRoughness
return { doc, material, occlusion, metallicRoughness };
}
+async function sharedOrmFixture(reverse = false) {
+ const doc = new Document();
+ const texture = async (name: string, rgba: [number, number, number, number]) =>
+ doc
+ .createTexture(name)
+ .setMimeType('image/png')
+ .setImage(
+ await sharp(Buffer.from(rgba), { raw: { width: 1, height: 1, channels: 4 } })
+ .png()
+ .toBuffer(),
+ );
+ const mr = await texture('Shared MR', [100, 130, 170, 60]);
+ const a = await texture('AO A', [40, 0, 0, 255]);
+ const b = await texture('AO B', [220, 0, 0, 255]);
+ const materials = new Map<string, Material>();
+ const entries: [string, Texture][] = [
+ ['A', a],
+ ['B', b],
+ ['A again', a],
+ ];
+ for (const [name, ao] of reverse ? entries.reverse() : entries) {
+ materials.set(
+ name,
+ doc.createMaterial(name).setOcclusionTexture(ao).setMetallicRoughnessTexture(mr),
+ );
+ }
+ return { doc, mr, materials };
+}
+
+async function rgba(texture: Texture | null): Promise<number[]> {
+ return Array.from(await sharp(texture!.getImage()!).ensureAlpha().raw().toBuffer());
+}
+
+function sampling(info: TextureInfo) {
+ const transform = info.getExtension<Transform>('KHR_texture_transform');
+ return {
+ texCoord: info.getTexCoord(),
+ magFilter: info.getMagFilter(),
+ minFilter: info.getMinFilter(),
+ wrapS: info.getWrapS(),
+ wrapT: info.getWrapT(),
+ transform: transform && {
+ texCoord: transform.getTexCoord(),
+ offset: transform.getOffset(),
+ rotation: transform.getRotation(),
+ scale: transform.getScale(),
+ },
+ };
+}
+
describe('ORM channel packing', () => {
+ test('shared metallic-roughness retains each occlusion independently of material order', async () => {
+ for (const reverse of [false, true]) {
+ const { doc, materials } = await sharedOrmFixture(reverse);
+ const summary = await applyKitContract(doc, { ktx2: false });
+
+ for (const [name, red] of [
+ ['A', 40],
+ ['B', 220],
+ ['A again', 40],
+ ] as const) {
+ const material = materials.get(name)!;
+ expect(await rgba(material.getOcclusionTexture())).toEqual([red, 130, 170, 255]);
+ expect(material.getOcclusionTexture()).toBe(material.getMetallicRoughnessTexture());
+ }
+ expect(materials.get('A')!.getOcclusionTexture()).toBe(
+ materials.get('A again')!.getOcclusionTexture(),
+ );
+ expect(doc.getRoot().listTextures()).toHaveLength(2);
+ expect(summary.ormPacked).toBe(3);
+ expect(summary.ormSkipped).toBeUndefined();
+ doc.createBuffer();
+ const serialized = await io().writeBinary(doc);
+ expect((await applyKitContract(doc, { ktx2: false })).ormPacked).toBe(0);
+ expect(await io().writeBinary(doc)).toEqual(serialized);
+ }
+ });
+
+ test('packing keeps already-packed, unpaired and other-slot consumers unchanged', async () => {
+ const { doc, mr, materials } = await sharedOrmFixture();
+ const original = Uint8Array.from(mr.getImage()!);
+ const packed = doc
+ .createMaterial('Already packed')
+ .setOcclusionTexture(mr)
+ .setMetallicRoughnessTexture(mr);
+ const unpaired = doc.createMaterial('MR only').setMetallicRoughnessTexture(mr);
+ // The same material can use the image in multiple slots: counting parents alone
+ // would miss the base-color/alpha dependency after the other MR users move.
+ const baseColor = materials.get('A')!.setBaseColorTexture(mr).setAlphaMode('BLEND');
+ const normal = doc.createMaterial('Normal').setNormalTexture(mr);
+
+ await applyKitContract(doc, { ktx2: false });
+
+ expect(mr.getImage()).toEqual(original);
+ expect(await rgba(packed.getOcclusionTexture())).toEqual([100, 130, 170, 60]);
+ expect(unpaired.getMetallicRoughnessTexture()).toBe(mr);
+ expect(baseColor.getBaseColorTexture()).toBe(mr);
+ expect(normal.getNormalTexture()).toBe(mr);
+ expect(await rgba(baseColor.getOcclusionTexture())).toEqual([40, 130, 170, 255]);
+ expect(doc.getRoot().listTextures()).toHaveLength(3);
+ });
+
+ test('a sole material using MR as base color keeps its original pixels and alpha', async () => {
+ const { doc, material, metallicRoughness } = occlusionBesideMetallicRoughness(0, 0);
+ const original = await sharp(
+ Buffer.from(Array.from({ length: 16 }, () => [100, 130, 170, 60]).flat()),
+ { raw: { width: 4, height: 4, channels: 4 } },
+ )
+ .png()
+ .toBuffer();
+ metallicRoughness.setImage(original);
+ material.setBaseColorTexture(metallicRoughness).setAlphaMode('BLEND');
+
+ await applyKitContract(doc, { ktx2: false });
+
+ expect(material.getBaseColorTexture()!.getImage()).toEqual(original);
+ expect(material.getOcclusionTexture()).not.toBe(metallicRoughness);
+ expect((await rgba(material.getOcclusionTexture())).slice(0, 4)).toEqual([200, 130, 170, 255]);
+ });
+
+ test('serialized shared ORM pairs keep pixels, slot sampling and material factors', async () => {
+ const { doc, mr, materials } = await sharedOrmFixture();
+ const transforms = doc.createExtension(KHRTextureTransform);
+ const a = materials.get('A')!;
+ a.setOcclusionStrength(0.4).setRoughnessFactor(0.6).setMetallicFactor(0.8);
+ const aoInfo = a.getOcclusionTextureInfo()!;
+ const mrInfo = a.getMetallicRoughnessTextureInfo()!;
+ for (const [index, info] of [aoInfo, mrInfo].entries()) {
+ info
+ .setTexCoord(index)
+ .setMagFilter(index === 0 ? 9728 : 9729)
+ .setMinFilter(index === 0 ? 9984 : 9987)
+ .setWrapS(index === 0 ? 33071 : 10497)
+ .setWrapT(index === 0 ? 33648 : 10497)
+ .setExtension(
+ 'KHR_texture_transform',
+ transforms
+ .createTransform()
+ .setTexCoord(1)
+ .setOffset([0.25, 0.5])
+ .setScale([2, 3])
+ .setRotation(0.2),
+ );
+ }
+ const expectedSampling = [sampling(aoInfo), sampling(mrInfo)];
+ a.setBaseColorTexture(mr).setAlphaMode('BLEND');
+ const buffer = doc.createBuffer();
+ const position = doc
+ .createAccessor()
+ .setType('VEC3')
+ .setBuffer(buffer)
+ .setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]));
+ const uv = doc
+ .createAccessor()
+ .setType('VEC2')
+ .setBuffer(buffer)
+ .setArray(new Float32Array([0, 0, 1, 0, 0, 1]));
+ const scene = doc.createScene();
+ for (const material of materials.values()) {
+ scene.addChild(
+ doc
+ .createNode()
+ .setMesh(
+ doc
+ .createMesh()
+ .addPrimitive(
+ doc
+ .createPrimitive()
+ .setAttribute('POSITION', position)
+ .setAttribute('TEXCOORD_0', uv)
+ .setAttribute('TEXCOORD_1', uv)
+ .setMaterial(material),
+ ),
+ ),
+ );
+ }
+ const serializer = io().registerExtensions([KHRTextureTransform]);
+ const result = await packKitGlb(await serializer.writeBinary(doc), { ktx2: false });
+ expect(result!.gltfValidation.issues.numErrors).toBe(0);
+ expect(result!.summary.ormPacked).toBe(3);
+ const after = await serializer.readBinary(result!.bytes);
+ const byName = new Map(
+ after
+ .getRoot()
+ .listMaterials()
+ .map((m) => [m.getName(), m]),
+ );
+ const afterA = byName.get('A')!;
+ expect(await rgba(afterA.getOcclusionTexture())).toEqual([40, 130, 170, 255]);
+ expect(await rgba(byName.get('B')!.getOcclusionTexture())).toEqual([220, 130, 170, 255]);
+ expect(await rgba(afterA.getBaseColorTexture())).toEqual([100, 130, 170, 60]);
+ expect([
+ sampling(afterA.getOcclusionTextureInfo()!),
+ sampling(afterA.getMetallicRoughnessTextureInfo()!),
+ ]).toEqual(expectedSampling);
+ expect([
+ afterA.getOcclusionStrength(),
+ afterA.getRoughnessFactor(),
+ afterA.getMetallicFactor(),
+ ]).toEqual([0.4, 0.6, 0.8]);
+ expect(afterA.getOcclusionTexture()).toBe(byName.get('A again')!.getOcclusionTexture());
+ expect(await packKitGlb(result!.bytes, { ktx2: false })).toBeUndefined();
+ });
+
test('the occlusion image is folded in AND removed from the file', async () => {
const original = await glbOf(ORM);
const packed = await packKitGlb(original, { ktx2: false });
diff --git a/src/__tests__/msft-lod.test.ts b/src/__tests__/msft-lod.test.ts
index 3843ba66..a1a4ad0c 100644
--- a/src/__tests__/msft-lod.test.ts
+++ b/src/__tests__/msft-lod.test.ts
@@ -190,10 +190,10 @@ for (const fixture of FIXTURES) {
}
});
- test('full consolidation degrades to palette instead of flattening a LOD chain', async () => {
+ test('full consolidation preserves every referenced LOD level', async () => {
const result = await optimizeGlbBytes(await fixture.make(), { mode: 'full' });
- expect(result?.summary?.mode).toBe('palette');
+ expect(result?.summary?.mode).toBe('full');
expectLodChains(result!.bytes, ['Bus'], fixture);
});
diff --git a/src/__tests__/optimize.test.ts b/src/__tests__/optimize.test.ts
index 8e74d1af..ded9de69 100644
--- a/src/__tests__/optimize.test.ts
+++ b/src/__tests__/optimize.test.ts
@@ -4,7 +4,7 @@
* Covers the pass's load-bearing guarantees:
* - palette collapses many distinct flat materials -> ~1 and lifts the grade
* - the grade is recomputed on the OPTIMIZED document
- * - `full` auto-degrades to `palette` when the asset is animated (rig-safe)
+ * - `full` merges rigid groups without deleting static or animated pivots
* - transparency is never flattened into opaque (glass stays its own material)
* - prune keeps named pivots (Kiln City behaviors target createPivot Joint_ by name)
* - `optimize='off'` is byte-stable (deterministic, no consolidation)
@@ -21,7 +21,8 @@ import {
gameMaterial,
glassMaterial,
} from '../primitives';
-import { renderSceneToGLB, optimizeGlbBytes } from '../render';
+import { renderSceneToGLB, optimizeGlbBytes, composeSceneGLB, renderGLBInProcess } from '../render';
+import { createGltfIO } from '../gltf-io';
import { WebIO } from '@gltf-transform/core';
/** A distinct flat color per index (HSL hue sweep — guaranteed unique materials). */
@@ -119,8 +120,8 @@ describe('optimize=palette (material collapse)', () => {
});
});
-describe('optimize=full (static-only; auto-degrade on animation)', () => {
- it('auto-degrades to palette when the asset is animated', async () => {
+describe('optimize=full (rigid groups)', () => {
+ it('merges within an animated pivot while preserving its animation target', async () => {
const root = createRoot('Spinner');
const hub = createPivot('Spin', [0, 1, 0], root);
for (let i = 0; i < 8; i++) {
@@ -140,10 +141,75 @@ describe('optimize=full (static-only; auto-degrade on animation)', () => {
const after = await renderSceneToGLB(root, { optimize: 'full', clips: [clip] });
expect(after.optimize).toBeDefined();
- // full requested, but animated -> degrades to palette (rig stays intact).
- expect(after.optimize!.mode).toBe('palette');
+ expect(after.optimize!.mode).toBe('full');
+ expect(after.optimize!.drawsAfter).toBeLessThan(after.optimize!.drawsBefore);
const names = await nodeNamesOf(after.bytes);
expect(names.has('Joint_Spin')).toBe(true);
+ const doc = await createGltfIO().readBinary(after.bytes);
+ expect(doc.getRoot().listAnimations()[0]!.listChannels()[0]!.getTargetNode()!.getName()).toBe(
+ 'Joint_Spin',
+ );
+ });
+
+ it('preserves an unanimated joint and reports its merge boundaries', async () => {
+ const root = createRoot('Cabinet');
+ const material = gameMaterial(0x888888);
+ for (let i = 0; i < 3; i++)
+ createPart(`Body${i}`, boxGeo(1, 1, 1), material, { position: [i, 0, 0], parent: root });
+ const door = createPivot('Door', [0, 1, 0], root);
+ createPart('Panel', boxGeo(1, 0.1, 1), material, { parent: door });
+ const after = await renderSceneToGLB(root, { optimize: 'full' });
+ const doc = await createGltfIO().readBinary(after.bytes);
+ const joint = doc
+ .getRoot()
+ .listNodes()
+ .find((n) => n.getName() === 'Joint_Door');
+ expect(joint).toBeDefined();
+ expect(joint!.getTranslation()).toEqual([0, 1, 0]);
+ expect(joint!.listChildren()).toHaveLength(1);
+ expect(after.optimize?.rigidMerge?.boundaries).toContainEqual({
+ node: 'Joint_Door',
+ reasons: ['joint-pivot'],
+ });
+ expect(after.optimize?.drawsAfter).toBe(2);
+ });
+
+ it('keeps separate placement wrappers and reports composition optimization', async () => {
+ const asset = await renderSceneToGLB(manyColorScene(6), { optimize: 'off' });
+ const composed = await composeSceneGLB(
+ [
+ {
+ name: 'First',
+ bytes: asset.bytes,
+ transform: { pos: [0, 0, 0], rotDeg: [0, 0, 0], scale: [1, 1, 1] },
+ },
+ {
+ name: 'Second',
+ bytes: asset.bytes,
+ transform: { pos: [0, 0, 5], rotDeg: [0, 90, 0], scale: [1, 1, 1] },
+ },
+ ],
+ { optimize: 'full' },
+ );
+ const doc = await createGltfIO().readBinary(composed.bytes);
+ const placements = doc.getRoot().listScenes()[0]!.listChildren();
+ expect(placements.map((n) => n.getName())).toEqual(['First', 'Second']);
+ const draws = (node: (typeof placements)[number]): number =>
+ (node.getMesh()?.listPrimitives().length ?? 0) +
+ node.listChildren().reduce((n, child) => n + draws(child), 0);
+ expect(placements.map(draws)).toEqual([1, 1]);
+ expect(composed.optimize?.rigidMerge?.boundaries).toEqual([
+ { node: 'First', reasons: ['kept'] },
+ { node: 'Second', reasons: ['kept'] },
+ ]);
+ });
+
+ it('records the full optimizer pipeline version and is byte deterministic', async () => {
+ const code = `const meta={name:'Pair'}; function build(){const r=createRoot('Root');const m=gameMaterial(0x888888);createPart('A',boxGeo(1,1,1),m,{parent:r});createPart('B',boxGeo(1,1,1),m,{parent:r,position:[1,0,0]});return r;}`;
+ const a = await renderGLBInProcess(code, { optimize: 'full', instance: 'off' });
+ const b = await renderGLBInProcess(code, { optimize: 'full', instance: 'off' });
+ expect(a.rebuildOptions?.optimizationPipeline).toBe('rigid-v1');
+ expect(b.glb).toEqual(a.glb);
});
});
diff --git a/src/__tests__/render-service-host.test.ts b/src/__tests__/render-service-host.test.ts
index 215ab328..bfce1c0d 100644
--- a/src/__tests__/render-service-host.test.ts
+++ b/src/__tests__/render-service-host.test.ts
@@ -81,7 +81,7 @@ describe('localRenderServiceState', () => {
expect(localRenderServiceState(nested)).toBe('dependencies-incompatible');
await writeFile(
join(installation, 'node_modules/webgpu/package.json'),
- JSON.stringify({ name: 'webgpu', version: '0.6.1', main: 'index.js' }),
+ JSON.stringify({ name: 'webgpu', version: '0.6.2', main: 'index.js' }),
);
expect(localRenderServiceState(nested)).toBe('ready');
});
diff --git a/src/__tests__/rigid-merge.test.ts b/src/__tests__/rigid-merge.test.ts
new file mode 100644
index 00000000..8b8d9047
--- /dev/null
+++ b/src/__tests__/rigid-merge.test.ts
@@ -0,0 +1,1195 @@
+/**
+ * Rigid-group merge (`src/rigid-merge.ts`), the draw-call step proposed for `optimize: 'full'`.
+ *
+ * Fixtures are small Documents named like Kiln exports (`Mesh_*` parts, `Joint_*` pivots). Every
+ * merge is checked against what draws: per-material triangle count, area, centroid, signed volume
+ * and winding agreement in world space, exact drawn bounds, and per-vertex world frames.
+ */
+import { describe, expect, test } from 'bun:test';
+import {
+ Document,
+ type Material,
+ type Node,
+ Primitive,
+ type Scene,
+ type TypedArray,
+} from '@gltf-transform/core';
+import {
+ EXTMeshGPUInstancing,
+ KHRMaterialsTransmission,
+ KHRMaterialsVariants,
+ KHRMaterialsVolume,
+ KHRNodeVisibility,
+} from '@gltf-transform/extensions';
+import * as THREE from 'three';
+import { KILN_SEMANTIC_EXTRAS_KEY } from '../contracts/semantic';
+import { createGltfIO, MSFT_LOD, MSFTLod } from '../gltf-io';
+import { collectGlbMetrics } from '../metrics';
+import { drawnSceneBounds } from '../node-visibility';
+import {
+ boxGeo,
+ createPart,
+ createPivot,
+ createRoot,
+ gameMaterial,
+ glassMaterial,
+} from '../primitives';
+import { renderSceneToGLB } from '../render';
+import { mergeRigidGroups, type RigidMergeSummary, rigidMerge } from '../rigid-merge';
+
+type Vec3 = [number, number, number];
+type Quat = [number, number, number, number];
+
+interface PartOptions {
+ t?: Vec3;
+ r?: Quat;
+ s?: Vec3;
+ size?: Vec3;
+ tangents?: boolean;
+ indexed?: boolean;
+}
+
+/** Box faces as (normal, u, v) with u x v = normal, so (0,1,2)(0,2,3) winds outward. */
+const FACES: [Vec3, Vec3, Vec3][] = [
+ [
+ [1, 0, 0],
+ [0, 0, -1],
+ [0, 1, 0],
+ ],
+ [
+ [-1, 0, 0],
+ [0, 0, 1],
+ [0, 1, 0],
+ ],
+ [
+ [0, 1, 0],
+ [1, 0, 0],
+ [0, 0, -1],
+ ],
+ [
+ [0, -1, 0],
+ [1, 0, 0],
+ [0, 0, 1],
+ ],
+ [
+ [0, 0, 1],
+ [1, 0, 0],
+ [0, 1, 0],
+ ],
+ [
+ [0, 0, -1],
+ [-1, 0, 0],
+ [0, 1, 0],
+ ],
+];
+
+const quat = (axis: Vec3, angle: number): Quat =>
+ new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(...axis), angle).toArray() as Quat;
+
+function fixture() {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const scene = doc.createScene('Scene');
+ const accessor = (type: 'SCALAR' | 'VEC2' | 'VEC3' | 'VEC4', array: TypedArray) =>
+ doc.createAccessor().setType(type).setArray(array).setBuffer(buffer);
+ const box = (material: Material | null, o: PartOptions = {}): Primitive => {
+ const size = o.size ?? [1, 1, 1];
+ const pos: number[] = [];
+ const nrm: number[] = [];
+ const tan: number[] = [];
+ const uv: number[] = [];
+ const idx: number[] = [];
+ for (const [n, u, v] of FACES) {
+ const base = pos.length / 3;
+ for (const [a, b] of [
+ [-1, -1],
+ [1, -1],
+ [1, 1],
+ [-1, 1],
+ ] as const) {
+ for (let k = 0; k < 3; k++) pos.push(((n[k]! + a * u[k]! + b * v[k]!) * size[k]!) / 2);
+ nrm.push(...n);
+ tan.push(...u, 1);
+ uv.push((a + 1) / 2, (b + 1) / 2);
+ }
+ idx.push(base, base + 1, base + 2, base, base + 2, base + 3);
+ }
+ const indexed = o.indexed ?? true;
+ const flat = (values: number[], width: number) =>
+ indexed ? values : idx.flatMap((i) => values.slice(i * width, i * width + width));
+ const prim = doc
+ .createPrimitive()
+ .setMaterial(material)
+ .setAttribute('POSITION', accessor('VEC3', new Float32Array(flat(pos, 3))))
+ .setAttribute('NORMAL', accessor('VEC3', new Float32Array(flat(nrm, 3))))
+ .setAttribute('TEXCOORD_0', accessor('VEC2', new Float32Array(flat(uv, 2))));
+ if (o.tangents ?? true)
+ prim.setAttribute('TANGENT', accessor('VEC4', new Float32Array(flat(tan, 4))));
+ if (indexed) prim.setIndices(accessor('SCALAR', new Uint16Array(idx)));
+ return prim;
+ };
+ const node = (name: string, parent: Node | Scene, o: PartOptions = {}): Node => {
+ const created = doc.createNode(name);
+ if (o.t) created.setTranslation(o.t);
+ if (o.r) created.setRotation(o.r);
+ if (o.s) created.setScale(o.s);
+ parent.addChild(created);
+ return created;
+ };
+ const part = (
+ name: string,
+ material: Material | null,
+ parent: Node | Scene,
+ o: PartOptions = {},
+ ) => node(name, parent, o).setMesh(doc.createMesh(name).addPrimitive(box(material, o)));
+ const material = (name: string) => doc.createMaterial(name);
+ return { doc, scene, accessor, box, node, part, material };
+}
+
+/** Fourteen static parts over nine materials and a two-part door on `Joint_FrontDoor`. */
+function farmhouseLike() {
+ const f = fixture();
+ const m = Object.fromEntries(
+ ['masonry', 'stone', 'trim', 'glass', 'flue', 'wood', 'roof', 'shutter', 'iron', 'door'].map(
+ (name) => [name, f.material(name)],
+ ),
+ ) as Record<string, Material>;
+ m['glass']!.setAlphaMode('BLEND');
+ const root = f.node('Farmhouse', f.scene);
+ const shell = f.node('Shell', root);
+ const roof = f.node('Roof', root, { t: [0, 3, 0], r: quat([0, 0, 1], 0.2), s: [1.5, 0.5, 1] });
+ const porch = f.node('Porch', root, { t: [0, 0, 4], r: quat([0, 1, 0], Math.PI / 2) });
+ const steps = f.node('Steps', root, { t: [2, 0, 5] });
+ const shutters = f.node('Shutters', root);
+ const door = f.node('Door', root, { t: [1, 0, 2] });
+ let x = 0;
+ const part = (name: string, material: string, parent: Node) => {
+ x += 1.25;
+ return f.part(name, m[material]!, parent, { t: [x, 0.5, 0] });
+ };
+ part('Mesh_ShellMasonry', 'masonry', shell);
+ part('Mesh_ShellStone', 'stone', shell);
+ part('Mesh_ShellTrim', 'trim', shell);
+ part('Mesh_ShellGlass', 'glass', shell);
+ part('Mesh_ChimneyFlue', 'flue', shell);
+ part('Mesh_InteriorCeiling', 'trim', shell);
+ part('Mesh_InteriorFloor', 'wood', shell);
+ part('Mesh_RoofShingles', 'roof', roof);
+ part('Mesh_PorchTimber', 'wood', porch);
+ part('Mesh_PorchPlinth', 'stone', porch);
+ part('Mesh_PorchRoof', 'roof', porch);
+ part('Mesh_StepTreads', 'wood', steps);
+ part('Mesh_ShutterPanels', 'shutter', shutters);
+ part('Mesh_ShutterHinges', 'iron', shutters);
+ const hinge = f.node('Joint_FrontDoor', door, { t: [2.8, 0.4, -0.49], r: quat([0, 1, 0], 0.3) });
+ f.part('Mesh_DoorLeaf', m['door']!, hinge, { t: [0.45, 1, 0], size: [0.9, 2, 0.08] });
+ f.part('Mesh_DoorHardware', m['iron']!, hinge, { t: [0.8, 1, 0.05], size: [0.1, 0.1, 0.1] });
+ return { ...f, hinge };
+}
+
+function sceneNodes(doc: Document): Node[] {
+ const out: Node[] = [];
+ for (const scene of doc.getRoot().listScenes())
+ for (const child of scene.listChildren()) child.traverse((node) => out.push(node));
+ return out;
+}
+
+const named = (doc: Document, name: string): Node =>
+ doc
+ .getRoot()
+ .listNodes()
+ .find((node) => node.getName() === name)!;
+const nodeNames = (doc: Document) =>
+ doc
+ .getRoot()
+ .listNodes()
+ .map((node) => node.getName())
+ .sort();
+const subtreePrims = (node: Node): Primitive[] => {
+ const out: Primitive[] = [];
+ node.traverse((n) => out.push(...(n.getMesh()?.listPrimitives() ?? [])));
+ return out;
+};
+const ownTriangles = (node: Node): number =>
+ (node.getMesh()?.listPrimitives() ?? []).reduce((sum, p) => sum + triangles(p).length, 0);
+
+function triangles(prim: Primitive): [number, number, number][] {
+ const indices = prim.getIndices();
+ const count = indices?.getCount() ?? prim.getAttribute('POSITION')!.getCount();
+ const at = (i: number) => indices?.getScalar(i) ?? i;
+ const out: [number, number, number][] = [];
+ for (let i = 0; i + 2 < count; i += 3) out.push([at(i), at(i + 1), at(i + 2)]);
+ return out;
+}
+
+/** Per material: [triangles, area, area-weighted centroid xyz, signed volume, winding agreement]. */
+function fingerprint(doc: Document): Map<string, number[]> {
+ const out = new Map<string, number[]>();
+ for (const node of sceneNodes(doc)) {
+ const mesh = node.getMesh();
+ if (!mesh) continue;
+ const world = new THREE.Matrix4().fromArray(node.getWorldMatrix());
+ const normalMatrix = new THREE.Matrix3().getNormalMatrix(world);
+ const facing = Math.sign(world.determinant());
+ for (const prim of mesh.listPrimitives()) {
+ const key = prim.getMaterial()?.getName() ?? '(none)';
+ const acc = out.get(key) ?? [0, 0, 0, 0, 0, 0, 0];
+ const position = prim.getAttribute('POSITION')!;
+ const normal = prim.getAttribute('NORMAL');
+ const p = (i: number) =>
+ new THREE.Vector3().fromArray(position.getElement(i, [])).applyMatrix4(world);
+ for (const [a, b, c] of triangles(prim)) {
+ const [pa, pb, pc] = [p(a), p(b), p(c)];
+ const face = pb.clone().sub(pa).cross(pc.clone().sub(pa)).multiplyScalar(facing);
+ const area = face.length() / 2;
+ const centroid = pa.clone().add(pb).add(pc).divideScalar(3);
+ acc[0]! += 1;
+ acc[1]! += area;
+ acc[2]! += centroid.x * area;
+ acc[3]! += centroid.y * area;
+ acc[4]! += centroid.z * area;
+ acc[5]! += (facing * pa.dot(pb.clone().cross(pc))) / 6;
+ if (normal) {
+ const shading = new THREE.Vector3()
+ .fromArray(normal.getElement(a, []))
+ .applyMatrix3(normalMatrix);
+ acc[6]! += Math.sign(face.dot(shading));
+ }
+ }
+ out.set(key, acc);
+ }
+ }
+ return out;
+}
+
+/** Float32 baking moves sums by a few ulps; a wrong transform moves them by whole units. */
+const close = (a: number, b: number) => Math.abs(a - b) <= 1e-4 * Math.max(1, Math.abs(a));
+
+function expectSameFingerprint(before: Map<string, number[]>, after: Map<string, number[]>) {
+ expect([...after.keys()].sort()).toEqual([...before.keys()].sort());
+ const differences = [...before].flatMap(([key, values]) =>
+ values.flatMap((value, i) => {
+ const moved = after.get(key)![i]!;
+ return close(value, moved) ? [] : [`${key}[${i}] ${value} -> ${moved}`];
+ }),
+ );
+ expect(differences).toEqual([]);
+}
+
+function expectSameBounds(before: Document, after: Document) {
+ const a = drawnSceneBounds(before.getRoot().listScenes()[0]!);
+ const b = drawnSceneBounds(after.getRoot().listScenes()[0]!);
+ const extent = Math.max(1, ...a.max.map((v, i) => v - a.min[i]!));
+ for (let i = 0; i < 3; i++) {
+ expect(Math.abs(b.min[i]! - a.min[i]!)).toBeLessThanOrEqual(1e-6 * extent);
+ expect(Math.abs(b.max[i]! - a.max[i]!)).toBeLessThanOrEqual(1e-6 * extent);
+ }
+}
+
+interface Frame {
+ p: THREE.Vector3;
+ n: THREE.Vector3;
+ t: THREE.Vector3;
+ three: THREE.Vector3;
+ corrected: THREE.Vector3;
+}
+
+/**
+ * Every vertex's world position, normal and tangent, with the bitangent as two renderer
+ * families build it: three r186 uses cross(N, T) * w (normal_vertex.glsl.js:9); a renderer that
+ * corrects mirrored transforms also multiplies by sign(det(world)).
+ */
+function frames(doc: Document): Frame[] {
+ const out: Frame[] = [];
+ for (const node of sceneNodes(doc)) {
+ const mesh = node.getMesh();
+ if (!mesh) continue;
+ const world = new THREE.Matrix4().fromArray(node.getWorldMatrix());
+ const linear = new THREE.Matrix3().setFromMatrix4(world);
+ const normalMatrix = new THREE.Matrix3().getNormalMatrix(world);
+ const det = Math.sign(world.determinant());
+ for (const prim of mesh.listPrimitives()) {
+ const [pos, nrm, tan] = (['POSITION', 'NORMAL', 'TANGENT'] as const).map(
+ (s) => prim.getAttribute(s)!,
+ );
+ for (let i = 0; i < pos!.getCount(); i++) {
+ const p = new THREE.Vector3().fromArray(pos!.getElement(i, [])).applyMatrix4(world);
+ const n = new THREE.Vector3().fromArray(nrm!.getElement(i, [])).applyMatrix3(normalMatrix);
+ const t4 = tan!.getElement(i, []);
+ const t = new THREE.Vector3().fromArray(t4).applyMatrix3(linear).normalize();
+ n.normalize();
+ const three = n.clone().cross(t).multiplyScalar(t4[3]!);
+ out.push({ p, n, t, three, corrected: three.clone().multiplyScalar(det) });
+ }
+ }
+ }
+ return out;
+}
+
+/** Pairs each vertex with the one at the same world position and normal; counts differences. */
+function compareFrames(before: Frame[], after: Frame[]) {
+ const near = (a: THREE.Vector3, b: THREE.Vector3) => a.distanceTo(b) < 1e-5;
+ const result = { unmatched: 0, tangent: 0, three: 0, corrected: 0 };
+ if (after.length !== before.length) result.unmatched += Math.abs(after.length - before.length);
+ for (const a of before) {
+ const b = after.find((f) => near(f.p, a.p) && near(f.n, a.n));
+ if (!b) result.unmatched += 1;
+ else {
+ if (!near(a.t, b.t)) result.tangent += 1;
+ if (!near(a.three, b.three)) result.three += 1;
+ if (!near(a.corrected, b.corrected)) result.corrected += 1;
+ }
+ }
+ return result;
+}
+
+describe('mergeRigidGroups: farmhouse-shaped asset', () => {
+ test('keeps Joint_FrontDoor with its own two primitives and merges by material elsewhere', () => {
+ const { doc, hinge } = farmhouseLike();
+ const before = fingerprint(doc);
+ const reference = farmhouseLike().doc;
+ const metricsBefore = collectGlbMetrics(doc);
+ const doorPrims = subtreePrims(hinge);
+ const names = nodeNames(doc);
+
+ const summary = mergeRigidGroups(doc);
+
+ expect(metricsBefore.drawCalls).toBe(16);
+ expect(summary.primitivesBefore).toBe(16);
+ // 14 static parts over 9 materials (the one BLEND glass stays alone) + 2 door parts.
+ expect(summary.primitivesAfter).toBe(11);
+ const metricsAfter = collectGlbMetrics(doc);
+ expect(metricsAfter.drawCalls).toBeLessThanOrEqual(11);
+ expect(metricsAfter.triangles).toBe(metricsBefore.triangles);
+ expect(summary.boundaries).toEqual([{ node: 'Joint_FrontDoor', reasons: ['joint-pivot'] }]);
+
+ const joint = named(doc, 'Joint_FrontDoor');
+ expect(joint).toBe(hinge);
+ expect(subtreePrims(joint)).toEqual(doorPrims);
+ expect(
+ subtreePrims(joint)
+ .map((p) => p.getMaterial()!.getName())
+ .sort(),
+ ).toEqual(['door', 'iron']);
+ expect(nodeNames(doc)).toEqual(names);
+ expectSameFingerprint(before, fingerprint(doc));
+ expectSameBounds(reference, doc);
+
+ // The pivot still swings its own geometry, and only that.
+ hinge.setRotation(quat([0, 1, 0], -1.2));
+ named(reference, 'Joint_FrontDoor').setRotation(quat([0, 1, 0], -1.2));
+ expectSameFingerprint(fingerprint(reference), fingerprint(doc));
+ });
+
+ test('a Kiln export of the same shape merges the same way', async () => {
+ const root = createRoot('Farmhouse');
+ const mats = {
+ masonry: gameMaterial(0xe8dcc0),
+ stone: gameMaterial(0x8a8478),
+ trim: gameMaterial(0xf2ead8),
+ glass: glassMaterial(0x88aacc, { opacity: 0.35 }),
+ flue: gameMaterial(0x222222),
+ wood: gameMaterial(0xb08040),
+ roof: gameMaterial(0x3a3a40),
+ shutter: gameMaterial(0x6b7a3a),
+ iron: gameMaterial(0x303030, { metalness: 0.8 }),
+ door: gameMaterial(0x9a2a20),
+ };
+ const group = (name: string) => {
+ const g = new THREE.Object3D();
+ g.name = name;
+ root.add(g);
+ return g;
+ };
+ const [shell, roof, porch, steps, shutters, doorGroup] = [
+ 'Shell',
+ 'Roof',
+ 'Porch',
+ 'Steps',
+ 'Shutters',
+ 'Door',
+ ].map(group) as THREE.Object3D[];
+ let x = 0;
+ const part = (name: string, mat: THREE.Material, parent: THREE.Object3D) => {
+ x += 1.25;
+ return createPart(name, boxGeo(1, 1, 1), mat, { position: [x, 0.5, 0], parent });
+ };
+ part('ShellMasonry', mats.masonry, shell!);
+ part('ShellStone', mats.stone, shell!);
+ part('ShellTrim', mats.trim, shell!);
+ part('ShellGlass', mats.glass, shell!);
+ part('ChimneyFlue', mats.flue, shell!);
+ part('InteriorCeiling', mats.trim, shell!);
+ part('InteriorFloor', mats.wood, shell!);
+ part('RoofShingles', mats.roof, roof!);
+ part('PorchTimber', mats.wood, porch!);
+ part('PorchPlinth', mats.stone, porch!);
+ part('PorchRoof', mats.roof, porch!);
+ part('StepTreads', mats.wood, steps!);
+ part('ShutterPanels', mats.shutter, shutters!);
+ part('ShutterHinges', mats.iron, shutters!);
+ const hinge = createPivot('FrontDoor', [2.8, 0.4, -0.49], doorGroup!);
+ hinge.rotation.y = 0.3;
+ createPart('DoorLeaf', boxGeo(0.9, 2, 0.08), mats.door, {
+ position: [0.45, 1, 0],
+ parent: hinge,
+ });
+ createPart('DoorHardware', boxGeo(0.1, 0.1, 0.1), mats.iron, {
+ position: [0.8, 1, 0.05],
+ parent: hinge,
+ });
+ const { bytes } = await renderSceneToGLB(root, { optimize: 'off' });
+ const doc = await createGltfIO().readBinary(bytes);
+ const reference = await createGltfIO().readBinary(bytes);
+ const before = collectGlbMetrics(doc);
+
+ const summary = mergeRigidGroups(doc);
+
+ expect(before.drawCalls).toBe(16);
+ expect(collectGlbMetrics(doc).drawCalls).toBe(11);
+ expect(collectGlbMetrics(doc).triangles).toBe(before.triangles);
+ expect(subtreePrims(named(doc, 'Joint_FrontDoor'))).toHaveLength(2);
+ expect(summary.boundaries.map((b) => b.node)).toContain('Joint_FrontDoor');
+ expect(nodeNames(doc)).toEqual(nodeNames(reference));
+ expectSameFingerprint(fingerprint(reference), fingerprint(doc));
+ expectSameBounds(reference, doc);
+ // The merged document still writes and reads back.
+ const written = await createGltfIO().writeBinary(doc);
+ expect(collectGlbMetrics(await createGltfIO().readBinary(written)).drawCalls).toBe(11);
+ });
+});
+
+describe('mergeRigidGroups: tangents', () => {
+ function tangentParts() {
+ const f = fixture();
+ const m = f.material('Painted');
+ f.part('Mesh_A', m, f.scene);
+ f.part('Mesh_RotY', m, f.scene, { t: [3, 0, 0], r: quat([0, 1, 0], Math.PI / 2) });
+ f.part('Mesh_Skewed', m, f.scene, {
+ t: [0, 3, 0],
+ r: quat([0, 0, 1], Math.PI / 6),
+ s: [2, 1, 1],
+ });
+ // A rotated child of a non-uniformly scaled parent is sheared in world space: its normals
+ // need the inverse transpose, not the 3x3 itself.
+ const squash = f.node('Squash', f.scene, { t: [0, -4, 0], s: [1, 3, 1] });
+ f.part('Mesh_Sheared', m, squash, { r: quat([0, 0, 1], Math.PI / 4) });
+ f.part('Mesh_MirrorX', m, f.scene, { t: [6, 0, 0], s: [-1, 1, 1] });
+ f.part('Mesh_MirrorZ', m, f.scene, { t: [9, 0, 0], r: quat([1, 0, 0], 0.4), s: [1, 1, -1] });
+ return f;
+ }
+
+ test('rotated and mirrored tangent-bearing parts keep their world frames for every renderer', () => {
+ const { doc } = tangentParts();
+ const before = frames(doc);
+ const shape = fingerprint(doc);
+
+ const summary = mergeRigidGroups(doc);
+
+ // Tangent-bearing parts join only within one world handedness: {A, RotY, Skewed, Sheared} and
+ // {MirrorX, MirrorZ}, so neither renderer convention sees a changed bitangent.
+ expect(summary.primitivesAfter).toBe(2);
+ expect(compareFrames(before, frames(doc))).toEqual({
+ unmatched: 0,
+ tangent: 0,
+ three: 0,
+ corrected: 0,
+ });
+ expectSameFingerprint(shape, fingerprint(doc));
+ expect(named(doc, 'Mesh_RotY').getMesh()).toBeNull();
+ expect(named(doc, 'Mesh_MirrorZ').getMesh()).toBeNull();
+ });
+
+ test('mergeMirroredTangents joins across handedness with w *= sign(det)', () => {
+ const { doc } = tangentParts();
+ const before = frames(doc);
+ const shape = fingerprint(doc);
+
+ const summary = mergeRigidGroups(doc, { mergeMirroredTangents: true });
+
+ expect(summary.primitivesAfter).toBe(1);
+ expectSameFingerprint(shape, fingerprint(doc));
+ // A renderer that applies the world determinant sees the same frame everywhere, while
+ // three r186, which does not, sees both mirrored parts' bitangents flip (2 x 24 vertices).
+ expect(compareFrames(before, frames(doc))).toEqual({
+ unmatched: 0,
+ tangent: 0,
+ three: 48,
+ corrected: 0,
+ });
+ });
+
+ test('mirrored parts without tangents join with flipped winding and normals intact', () => {
+ const f = fixture();
+ const m = f.material('Plain');
+ f.part('Mesh_Left', m, f.scene, { tangents: false, indexed: false });
+ f.part('Mesh_Right', m, f.scene, {
+ t: [4, 0, 0],
+ s: [-1, 1, 1],
+ tangents: false,
+ indexed: false,
+ });
+ f.part('Mesh_Flipped', m, f.scene, { t: [0, 4, 0], s: [1, -2, 1], tangents: false });
+ f.part('Mesh_Indexed', m, f.scene, { t: [0, 0, 4], tangents: false });
+ const shape = fingerprint(f.doc);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ // Indexed and unindexed layouts cannot join each other.
+ expect(summary.primitivesAfter).toBe(2);
+ const after = fingerprint(f.doc);
+ expectSameFingerprint(shape, after);
+ expect(after.get('Plain')![6]).toBe(after.get('Plain')![0]!);
+ });
+});
+
+describe('mergeRigidGroups: boundaries and locks', () => {
+ test('BLEND and transmissive parts stay separate draws; volume never merges', () => {
+ const f = fixture();
+ const glass = f.material('Glass').setAlphaMode('BLEND');
+ const water = f.material('Water');
+ water.setExtension(
+ 'KHR_materials_transmission',
+ f.doc.createExtension(KHRMaterialsTransmission).createTransmission().setTransmissionFactor(1),
+ );
+ const ice = f.material('Ice');
+ ice.setExtension(
+ 'KHR_materials_volume',
+ f.doc.createExtension(KHRMaterialsVolume).createVolume().setThicknessFactor(0.5),
+ );
+ const paint = f.material('Paint');
+ f.part('Mesh_Glass1', glass, f.scene);
+ f.part('Mesh_Glass2', glass, f.scene, { t: [2, 0, 0] });
+ f.part('Mesh_Water1', water, f.scene, { t: [4, 0, 0] });
+ f.part('Mesh_Water2', water, f.scene, { t: [6, 0, 0] });
+ f.part('Mesh_Ice1', ice, f.scene, { t: [8, 0, 0] });
+ f.part('Mesh_Ice2', ice, f.scene, { t: [10, 0, 0] });
+ f.part('Mesh_Paint1', paint, f.scene, { t: [12, 0, 0] });
+ f.part('Mesh_Paint2', paint, f.scene, { t: [14, 0, 0] });
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.primitivesAfter).toBe(7);
+ expect(summary.locked).toEqual(
+ expect.arrayContaining([
+ { node: 'Mesh_Glass1', reason: 'transparent', primitives: 1 },
+ { node: 'Mesh_Glass2', reason: 'transparent', primitives: 1 },
+ { node: 'Mesh_Water1', reason: 'transparent', primitives: 1 },
+ { node: 'Mesh_Ice1', reason: 'volume', primitives: 1 },
+ ]),
+ );
+ for (const name of ['Mesh_Glass1', 'Mesh_Glass2', 'Mesh_Water1', 'Mesh_Water2'])
+ expect(ownTriangles(named(f.doc, name))).toBe(12);
+
+ const opted = fixture();
+ const g = opted.material('Glass').setAlphaMode('BLEND');
+ opted.part('Mesh_Glass1', g, opted.scene);
+ opted.part('Mesh_Glass2', g, opted.scene, { t: [2, 0, 0] });
+ expect(mergeRigidGroups(opted.doc, { mergeTransparent: true }).primitivesAfter).toBe(1);
+ });
+
+ test('every boundary keeps its own primitives and every lock is reported', () => {
+ const f = fixture();
+ const m = f.material('M');
+ const own = new Map<string, Primitive>();
+ const add = (name: string, o: PartOptions = {}) => {
+ const node = f.part(name, m, f.scene, { t: [own.size * 2, 0, 0], ...o });
+ own.set(name, node.getMesh()!.listPrimitives()[0]!);
+ return node;
+ };
+ add('Mesh_A');
+ add('Mesh_B');
+ const wheel = add('Mesh_Wheel');
+ const sampler = f.doc
+ .createAnimationSampler()
+ .setInput(f.accessor('SCALAR', new Float32Array([0, 1])))
+ .setOutput(f.accessor('VEC4', new Float32Array([0, 0, 0, 1, 0, 0, 0, 1])));
+ f.doc
+ .createAnimation('Spin')
+ .addSampler(sampler)
+ .addChannel(
+ f.doc
+ .createAnimationChannel()
+ .setSampler(sampler)
+ .setTargetNode(wheel)
+ .setTargetPath('rotation'),
+ );
+ add('Mesh_Tagged').setExtras({ note: 'kept' });
+ add('Mesh_Hidden').setExtension(
+ 'KHR_node_visibility',
+ f.doc.createExtension(KHRNodeVisibility).createVisibility().setVisible(false),
+ );
+ const level = f.doc.createNode('Mesh_Lod1');
+ add('Mesh_Lod0').setExtension(
+ MSFT_LOD,
+ f.doc.createExtension(MSFTLod).createLod().addLevel(level),
+ );
+ const bone = f.node('Bone', f.scene, { t: [0, 5, 0] });
+ add('Mesh_Skinned').setSkin(f.doc.createSkin('Skin').addJoint(bone));
+ add('Mesh_Batch').setExtension(
+ 'EXT_mesh_gpu_instancing',
+ f.doc
+ .createExtension(EXTMeshGPUInstancing)
+ .createInstancedMesh()
+ .setAttribute('TRANSLATION', f.accessor('VEC3', new Float32Array([0, 0, 0, 0, 1, 0]))),
+ );
+ const morph = add('Mesh_Morph');
+ morph
+ .getMesh()!
+ .listPrimitives()[0]!
+ .addTarget(
+ f.doc
+ .createPrimitiveTarget()
+ .setAttribute('POSITION', f.accessor('VEC3', new Float32Array(24 * 3))),
+ );
+ add('Mesh_Strip').getMesh()!.listPrimitives()[0]!.setMode(Primitive.Mode.TRIANGLE_STRIP!);
+ add('Mesh_PrimExtras').getMesh()!.listPrimitives()[0]!.setExtras({ id: 1 });
+ const variants = f.doc.createExtension(KHRMaterialsVariants);
+ add('Mesh_Variant')
+ .getMesh()!
+ .listPrimitives()[0]!
+ .setExtension(
+ 'KHR_materials_variants',
+ variants
+ .createMappingList()
+ .addMapping(
+ variants.createMapping().setMaterial(m).addVariant(variants.createVariant('Alt')),
+ ),
+ );
+ add('Mesh_MeshExtras').getMesh()!.setExtras({ lod: 'kept' });
+ add('Mesh_Flat', { s: [1, 0, 1] });
+ const before = fingerprint(f.doc);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.primitivesAfter).toBe(summary.primitivesBefore - 1);
+ expect(named(f.doc, 'Mesh_B').getMesh()).toBeNull();
+ for (const [name, prim] of own)
+ if (name !== 'Mesh_A' && name !== 'Mesh_B')
+ expect(named(f.doc, name).getMesh()!.listPrimitives()).toEqual([prim]);
+ expectSameFingerprint(before, fingerprint(f.doc));
+ const reasons = Object.fromEntries(summary.boundaries.map((b) => [b.node, b.reasons]));
+ expect(reasons).toEqual({
+ Mesh_Wheel: ['animated'],
+ Bone: ['skin-joint'],
+ Mesh_Tagged: ['extras'],
+ Mesh_Hidden: ['visibility'],
+ Mesh_Lod0: ['lod'],
+ });
+ const locks = Object.fromEntries(summary.locked.map((l) => [l.node, l.reason]));
+ expect(locks).toEqual({
+ Mesh_Wheel: 'boundary',
+ Mesh_Tagged: 'boundary',
+ Mesh_Hidden: 'boundary',
+ Mesh_Lod0: 'boundary',
+ Mesh_Skinned: 'skinned',
+ Mesh_Batch: 'instanced',
+ Mesh_Morph: 'morph-targets',
+ Mesh_Strip: 'primitive-mode',
+ Mesh_PrimExtras: 'primitive-extras',
+ Mesh_Variant: 'primitive-extensions',
+ Mesh_MeshExtras: 'mesh-extras',
+ Mesh_Flat: 'singular-matrix',
+ });
+ });
+
+ test('children of a boundary merge among themselves, never with the parent group', () => {
+ const f = fixture();
+ const m = f.material('M');
+ f.part('Mesh_Base', m, f.scene);
+ const pivot = f.node('Joint_Lid', f.scene, { t: [0, 2, 0], r: quat([1, 0, 0], 0.5) });
+ f.part('Mesh_LidA', m, pivot);
+ f.part('Mesh_LidB', m, pivot, { t: [1.5, 0, 0] });
+ const before = fingerprint(f.doc);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.groups).toBe(2);
+ expect(summary.primitivesAfter).toBe(2);
+ expect(subtreePrims(pivot)).toHaveLength(1);
+ expect(triangles(subtreePrims(pivot)[0]!)).toHaveLength(24);
+ expect(ownTriangles(named(f.doc, 'Mesh_Base'))).toBe(12);
+ expectSameFingerprint(before, fingerprint(f.doc));
+ });
+
+ test('a node a semantic relationship names is a boundary', () => {
+ const f = fixture();
+ const metal = f.material('Metal');
+ f.part('Mesh_Bracket', metal, f.scene).setExtras({
+ [KILN_SEMANTIC_EXTRAS_KEY]: {
+ schemaVersion: 1,
+ roles: ['mount'],
+ relationships: [{ kind: 'attachedTo', target: 'Mesh_Hinge', targetType: 'node' }],
+ frames: [],
+ sockets: [],
+ },
+ });
+ f.part('Mesh_Hinge', metal, f.scene, { t: [2, 0, 0] });
+ f.part('Mesh_PanelA', metal, f.scene, { t: [4, 0, 0] });
+ f.part('Mesh_PanelB', metal, f.scene, { t: [6, 0, 0] });
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.boundaries).toEqual([
+ { node: 'Mesh_Bracket', reasons: ['extras'] },
+ { node: 'Mesh_Hinge', reasons: ['relationship-target'] },
+ ]);
+ expect(summary.primitivesAfter).toBe(3);
+ expect(ownTriangles(named(f.doc, 'Mesh_Hinge'))).toBe(12);
+ expect(ownTriangles(named(f.doc, 'Mesh_PanelA'))).toBe(24);
+ });
+
+ test('contract: a named non-boundary node keeps its name, not its geometry, unless kept', async () => {
+ const build = () => {
+ const f = fixture();
+ const asphalt = f.material('Asphalt');
+ f.part('Roadway', asphalt, f.scene);
+ f.part('Rail', asphalt, f.scene, { t: [0, 1, 3] });
+ return f.doc;
+ };
+ const merged = build();
+ mergeRigidGroups(merged);
+ // The names survive, but `Roadway` now draws the rail too and `Rail` draws nothing.
+ expect(nodeNames(merged)).toEqual(['Rail', 'Roadway']);
+ expect(ownTriangles(named(merged, 'Roadway'))).toBe(24);
+ expect(named(merged, 'Rail').getMesh()).toBeNull();
+
+ // Declared parts survive; the transform form reports the same summary.
+ const kept = build();
+ let summary: RigidMergeSummary | undefined;
+ await kept.transform(rigidMerge({ keep: ['Roadway'] }, (s) => (summary = s)));
+ expect(summary!.boundaries).toEqual([{ node: 'Roadway', reasons: ['kept'] }]);
+ expect(summary!.unmatchedKeep).toEqual([]);
+ expect(ownTriangles(named(kept, 'Roadway'))).toBe(12);
+ expect(ownTriangles(named(kept, 'Rail'))).toBe(12);
+ });
+
+ test('keep names no scene node carries are reported, not silently ignored', () => {
+ const f = fixture();
+ const asphalt = f.material('Asphalt');
+ f.part('Roadway', asphalt, f.scene);
+ f.part('Rail', asphalt, f.scene, { t: [0, 1, 3] });
+ // Outside every scene, so keeping it protects nothing that draws.
+ f.doc.createNode('Offstage');
+
+ const summary = mergeRigidGroups(f.doc, { keep: ['Rail', 'Roadwya', 'Offstage', 'Roadwya'] });
+
+ expect(summary.unmatchedKeep).toEqual(['Roadwya', 'Offstage']);
+ expect(summary.boundaries).toEqual([{ node: 'Rail', reasons: ['kept'] }]);
+ expect(ownTriangles(named(f.doc, 'Roadway'))).toBe(12);
+ expect(mergeRigidGroups(fixture().doc).unmatchedKeep).toEqual([]);
+ });
+
+ test('a mesh shared by several nodes is cloned before any user changes', () => {
+ const f = fixture();
+ const m = f.material('M');
+ const shared = f.part('Mesh_Left', m, f.scene).getMesh()!;
+ f.node('Mesh_Right', f.scene, { t: [3, 0, 0], r: quat([0, 1, 0], 1) }).setMesh(shared);
+ f.node('Mesh_Tagged', f.scene, { t: [6, 0, 0] })
+ .setMesh(shared)
+ .setExtras({ id: 'kept' });
+ f.part('Mesh_Other', m, f.scene, { t: [0, 3, 0] });
+ const before = fingerprint(f.doc);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.primitivesAfter).toBe(2);
+ expect(named(f.doc, 'Mesh_Tagged').getMesh()).toBe(shared);
+ expect(ownTriangles(named(f.doc, 'Mesh_Tagged'))).toBe(12);
+ expect(ownTriangles(named(f.doc, 'Mesh_Left'))).toBe(36);
+ expectSameFingerprint(before, fingerprint(f.doc));
+ });
+
+ test('expandSharedMeshes: false keeps shared meshes shared and reports their users', () => {
+ const f = fixture();
+ const m = f.material('M');
+ const shared = f.part('Mesh_Left', m, f.scene).getMesh()!;
+ const prim = shared.listPrimitives()[0]!;
+ f.node('Mesh_Right', f.scene, { t: [3, 0, 0], r: quat([0, 1, 0], 1) }).setMesh(shared);
+ f.node('Mesh_Tagged', f.scene, { t: [6, 0, 0] })
+ .setMesh(shared)
+ .setExtras({ id: 'kept' });
+ const pair = f.part('Mesh_PairA', m, f.scene, { t: [0, 0, 3] }).getMesh()!;
+ f.node('Mesh_PairB', f.scene, { t: [0, 0, 6] }).setMesh(pair);
+ f.part('Mesh_Other', m, f.scene, { t: [0, 3, 0] });
+ f.part('Mesh_Other2', m, f.scene, { t: [0, 6, 0] });
+ const before = fingerprint(f.doc);
+ const meshes = f.doc.getRoot().listMeshes().length;
+
+ const summary = mergeRigidGroups(f.doc, { expandSharedMeshes: false });
+
+ // Each user of the shared mesh still draws it from the one stored copy; only Other* join.
+ expect(summary.primitivesAfter).toBe(6);
+ expect(summary.merges).toBe(1);
+ for (const name of ['Mesh_Left', 'Mesh_Right', 'Mesh_Tagged'])
+ expect(named(f.doc, name).getMesh()).toBe(shared);
+ expect(named(f.doc, 'Mesh_PairB').getMesh()).toBe(pair);
+ expect(shared.listPrimitives()).toEqual([prim]);
+ expect(f.doc.getRoot().listMeshes()).toHaveLength(meshes - 1);
+ expect(summary.locked).toEqual([
+ { node: 'Mesh_Left', reason: 'shared-mesh', primitives: 1 },
+ { node: 'Mesh_Right', reason: 'shared-mesh', primitives: 1 },
+ { node: 'Mesh_Tagged', reason: 'boundary', primitives: 1 },
+ { node: 'Mesh_PairA', reason: 'shared-mesh', primitives: 1 },
+ { node: 'Mesh_PairB', reason: 'shared-mesh', primitives: 1 },
+ ]);
+ expect(ownTriangles(named(f.doc, 'Mesh_Other'))).toBe(24);
+ expectSameFingerprint(before, fingerprint(f.doc));
+ });
+
+ test('an animation channel without a target node stops the merge', () => {
+ const f = fixture();
+ const m = f.material('M');
+ f.part('Mesh_A', m, f.scene);
+ f.part('Mesh_B', m, f.scene, { t: [2, 0, 0] });
+ const sampler = f.doc.createAnimationSampler();
+ f.doc
+ .createAnimation('Pointer')
+ .addSampler(sampler)
+ .addChannel(f.doc.createAnimationChannel().setSampler(sampler));
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.skipped).toBe('unbounded-animation');
+ expect(summary.primitivesAfter).toBe(2);
+ expect(ownTriangles(named(f.doc, 'Mesh_B'))).toBe(12);
+ });
+});
+
+describe('mergeRigidGroups: atomic buckets', () => {
+ test('an allocation failure inside the join leaves no orphan properties or serialized changes', async () => {
+ const f = fixture();
+ const m = f.material('M');
+ f.part('A', m, f.scene);
+ f.part('B', m, f.scene, { t: [2, 0, 0] });
+ const io = createGltfIO();
+ const bytes = await io.writeBinary(f.doc);
+ const accessors = f.doc.getRoot().listAccessors().length;
+ const edges = f.doc.getGraph().listEdges().length;
+ const createAccessor = f.doc.createAccessor.bind(f.doc);
+ let calls = 0;
+ f.doc.createAccessor = (...args) => {
+ if (++calls === 2) throw new Error('join allocation failure');
+ return createAccessor(...args);
+ };
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.merges).toBe(0);
+ expect(summary.rejected).toEqual([
+ { node: 'A', primitives: 2, error: 'join allocation failure' },
+ ]);
+ expect(f.doc.getRoot().listAccessors()).toHaveLength(accessors);
+ expect(f.doc.getGraph().listEdges()).toHaveLength(edges);
+ expect(await io.writeBinary(f.doc)).toEqual(bytes);
+ });
+
+ test('a bucket that fails part-way leaves the document byte-identical', async () => {
+ const f = fixture();
+ const m = f.material('M');
+ f.part('Mesh_A', m, f.scene);
+ const victim = f
+ .part('Mesh_B', m, f.scene, { t: [2, 0, 0] })
+ .getMesh()!
+ .listPrimitives()[0]!;
+ f.part('Mesh_C', m, f.scene, { t: [4, 0, 0] });
+ Object.assign(victim, {
+ clone: () => {
+ throw new Error('forced failure');
+ },
+ });
+ const io = createGltfIO();
+ const bytes = await io.writeBinary(f.doc);
+ const accessors = f.doc.getRoot().listAccessors().length;
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.rejected).toEqual([{ node: 'Mesh_A', primitives: 3, error: 'forced failure' }]);
+ expect(summary.merges).toBe(0);
+ expect(summary.primitivesAfter).toBe(3);
+ expect(f.doc.getRoot().listAccessors()).toHaveLength(accessors);
+ expect(Buffer.from(await io.writeBinary(f.doc)).equals(Buffer.from(bytes))).toBe(true);
+ });
+
+ test('a bucket that would write non-finite values is rejected; the others still merge', () => {
+ const f = fixture();
+ const good = f.material('Good');
+ const bad = f.material('Bad');
+ f.part('Mesh_Good1', good, f.scene);
+ f.part('Mesh_Good2', good, f.scene, { t: [2, 0, 0] });
+ const badA = f.part('Mesh_Bad1', bad, f.scene, { t: [4, 0, 0] });
+ const badB = f.part('Mesh_Bad2', bad, f.scene, { t: [6, 0, 0] });
+ const position = badB.getMesh()!.listPrimitives()[0]!.getAttribute('POSITION')!;
+ position.setElement(0, [Number.NaN, 0, 0]);
+ const badPrims = [badA, badB].map((n) => n.getMesh()!.listPrimitives()[0]);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.merges).toBe(1);
+ expect(summary.rejected).toHaveLength(1);
+ expect(summary.rejected[0]!.node).toBe('Mesh_Bad1');
+ expect(summary.rejected[0]!.error).toMatch(/non-finite/);
+ expect([badA, badB].map((n) => n.getMesh()!.listPrimitives()[0])).toEqual(badPrims);
+ expect(summary.primitivesAfter).toBe(3);
+ });
+});
+
+describe('mergeRigidGroups: release policies', () => {
+ test('shared scene entry points keep their geometry while descendants merge within the shared subtree', () => {
+ for (const nested of [false, true])
+ for (const onlyFirst of [false, true]) {
+ const f = fixture();
+ const m = f.material('M');
+ if (onlyFirst) f.part('OnlyA', m, f.scene, { t: [4, 0, 0] });
+ const shared = f.part('Shared', m, f.scene);
+ const parent = nested ? f.node('Container', shared) : shared;
+ f.part('DetailA', m, parent, { t: [0, 2, 0] });
+ f.part('DetailB', m, parent, { t: [0, 4, 0] });
+ if (!onlyFirst) f.part('OnlyA', m, f.scene, { t: [4, 0, 0] });
+ f.doc.createScene('Alternative').addChild(shared);
+ const before = fingerprint(f.doc);
+ const original = shared.getMesh()!.listPrimitives();
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.boundaries).toContainEqual({ node: 'Shared', reasons: ['shared-scene'] });
+ expect(shared.getMesh()!.listPrimitives()).toEqual(original);
+ expect(subtreePrims(shared)).toHaveLength(2);
+ expect(ownTriangles(named(f.doc, 'OnlyA'))).toBe(12);
+ expectSameFingerprint(before, fingerprint(f.doc));
+ }
+ });
+
+ test('rejects a bake frame that collapses small geometry far from the destination', async () => {
+ const f = fixture();
+ const m = f.material('M');
+ f.part('Far', m, f.scene, { t: [1e8, 0, 0] });
+ f.part('Origin', m, f.scene);
+ const io = createGltfIO();
+ const bytes = await io.writeBinary(f.doc);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.merges).toBe(0);
+ expect(summary.rejected[0]?.error).toMatch(/position precision/);
+ expect(await io.writeBinary(f.doc)).toEqual(bytes);
+ });
+
+ test('breaks equally conditioned frame ties with a practical coordinate scale', () => {
+ const f = fixture();
+ const m = f.material('M');
+ f.part('Tiny', m, f.scene, { s: [2 ** -32, 2 ** -32, 2 ** -32] });
+ const stable = f.part('Stable', m, f.scene);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.merges).toBe(1);
+ expect(stable.getMesh()).not.toBeNull();
+ for (const value of stable
+ .getMesh()!
+ .listPrimitives()[0]!
+ .getAttribute('POSITION')!
+ .getArray()!)
+ expect(Math.abs(value)).toBeLessThan(10);
+ });
+
+ test('an in-scene LOD reference keeps its own geometry and descendant boundary', () => {
+ const f = fixture();
+ const m = f.material('Shared');
+ const base = f.part('Lod0', m, f.scene);
+ const level = f.part('Lod1', m, f.scene, { t: [4, 0, 0] });
+ f.part('Lod1Detail', m, level);
+ f.part('WallA', m, f.scene, { t: [8, 0, 0] });
+ f.part('WallB', m, f.scene, { t: [12, 0, 0] });
+ base.setExtension(MSFT_LOD, f.doc.createExtension(MSFTLod).createLod().addLevel(level));
+ const original = level.getMesh()!.listPrimitives();
+ const before = fingerprint(f.doc);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.boundaries).toContainEqual({ node: 'Lod1', reasons: ['lod'] });
+ expect(level.getMesh()!.listPrimitives()).toEqual(original);
+ expect(ownTriangles(level)).toBe(12);
+ expect(subtreePrims(level)).toHaveLength(2);
+ expect(summary.primitivesAfter).toBe(4);
+ expectSameFingerprint(before, fingerprint(f.doc));
+ });
+
+ test('chooses a conditioned contributor frame instead of magnifying coordinates in the first one', () => {
+ const f = fixture();
+ const m = f.material('Shared');
+ f.part('FirstThin', m, f.scene, { s: [1, 1e-6, 1], tangents: false });
+ const stable = f.part('Stable', m, f.scene, { t: [0, 2, 0], tangents: false });
+ const before = fingerprint(f.doc);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.merges).toBe(1);
+ expect(stable.getMesh()).not.toBeNull();
+ for (const mesh of f.doc.getRoot().listMeshes())
+ for (const prim of mesh.listPrimitives())
+ for (const value of prim.getAttribute('POSITION')!.getArray()!)
+ expect(Math.abs(value)).toBeLessThan(10);
+ expectSameFingerprint(before, fingerprint(f.doc));
+ });
+
+ function densePrimitive(f: ReturnType<typeof fixture>, material: Material, count: number) {
+ const positions = new Float32Array(count * 3);
+ const colors = new Uint8Array(count * 4);
+ for (let i = 0; i < count; i++) {
+ positions.set([Math.floor(i / 3), i % 3 === 1 ? 1 : 0, i % 3 === 2 ? 1 : 0], i * 3);
+ colors.set([i % 251, 128, 255, 255], i * 4);
+ }
+ return f.doc
+ .createPrimitive()
+ .setMaterial(material)
+ .setAttribute('POSITION', f.accessor('VEC3', positions))
+ .setAttribute('COLOR_0', f.accessor('VEC4', colors).setNormalized(true))
+ .setIndices(
+ f.accessor('SCALAR', new Uint16Array(Array.from({ length: count }, (_, i) => i))),
+ );
+ }
+
+ test('counts accessor storage shared across distinct meshes and retains independent affordable merges', () => {
+ const f = fixture();
+ const m = f.material('M');
+ const shared = densePrimitive(f, m, 900).setAttribute('COLOR_0', null);
+ const a = f.node('SharedA', f.scene).setMesh(f.doc.createMesh().addPrimitive(shared));
+ const b = f
+ .node('SharedB', f.scene, { t: [0, 2, 0] })
+ .setMesh(f.doc.createMesh().addPrimitive(shared.clone()));
+ for (const name of ['IndependentA', 'IndependentB'])
+ f.node(name, f.scene).setMesh(
+ f.doc.createMesh().addPrimitive(densePrimitive(f, m, 90).setAttribute('COLOR_0', null)),
+ );
+ const bytes = () =>
+ f.doc
+ .getRoot()
+ .listAccessors()
+ .reduce((sum, accessor) => sum + (accessor.getArray()?.byteLength ?? 0), 0);
+ const beforeBytes = bytes();
+ const before = fingerprint(f.doc);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.primitivesBefore).toBe(4);
+ expect(summary.primitivesAfter).toBe(3);
+ expect(bytes() - beforeBytes).toBeLessThanOrEqual(4096);
+ expect(a.getMesh()!.listPrimitives()).toEqual([shared]);
+ expect(b.getMesh()!.listPrimitives()).toHaveLength(1);
+ expect(summary.locked).toContainEqual({
+ node: 'SharedA',
+ reason: 'shared-byte-budget',
+ primitives: 1,
+ });
+ expectSameFingerprint(before, fingerprint(f.doc));
+ });
+
+ test('prices retained shared attributes across material buckets and partially locked meshes', () => {
+ for (const transparent of [false, true]) {
+ for (const count of [90, 180]) {
+ const f = fixture();
+ const first = densePrimitive(f, f.material('Opaque'), count).setAttribute('COLOR_0', null);
+ const otherMaterial = f.material('Other').setAlphaMode(transparent ? 'BLEND' : 'OPAQUE');
+ const second = first.clone().setMaterial(otherMaterial);
+ const mesh = f.doc.createMesh().addPrimitive(first).addPrimitive(second);
+ f.node('A', f.scene).setMesh(mesh);
+ f.node('B', f.scene, { t: [0, 2, 0] }).setMesh(mesh);
+ const held = f.node('Joint_Held', f.scene).setMesh(mesh);
+ const bytes = () =>
+ f.doc
+ .getRoot()
+ .listAccessors()
+ .reduce((sum, accessor) => sum + (accessor.getArray()?.byteLength ?? 0), 0);
+ const beforeBytes = bytes();
+ const before = fingerprint(f.doc);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ const savedDraws = count === 90 ? (transparent ? 1 : 2) : 0;
+ expect(summary.primitivesBefore - summary.primitivesAfter).toBe(savedDraws);
+ expect(bytes() - beforeBytes).toBeLessThanOrEqual(savedDraws * 4096);
+ expect(held.getMesh()).toBe(mesh);
+ expect(mesh.listPrimitives()).toEqual([first, second]);
+ expectSameFingerprint(before, fingerprint(f.doc));
+ }
+ }
+ });
+
+ test('prices 6,300 added bytes against one actual saved draw, not two mesh users', () => {
+ const f = fixture();
+ const m = f.material('Shared');
+ const prim = densePrimitive(f, m, 450).setAttribute('COLOR_0', null);
+ const shared = f.doc.createMesh('Shared').addPrimitive(prim);
+ const a = f.node('A', f.scene).setMesh(shared);
+ const b = f.node('B', f.scene, { t: [0, 2, 0] }).setMesh(shared);
+ const before = fingerprint(f.doc);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.merges).toBe(0);
+ expect(summary.primitivesAfter).toBe(2);
+ expect(a.getMesh()).toBe(shared);
+ expect(b.getMesh()).toBe(shared);
+ expect(summary.locked).toContainEqual({
+ node: 'A',
+ reason: 'shared-byte-budget',
+ primitives: 1,
+ });
+ expectSameFingerprint(before, fingerprint(f.doc));
+ });
+
+ test('merges an affordable shared mesh while preserving an untouched boundary user', () => {
+ const f = fixture();
+ const prim = densePrimitive(f, f.material('Shared'), 90).setAttribute('COLOR_0', null);
+ const shared = f.doc.createMesh('Shared').addPrimitive(prim);
+ f.node('A', f.scene).setMesh(shared);
+ f.node('B', f.scene, { t: [0, 2, 0] }).setMesh(shared);
+ const pivot = f.node('Joint_Held', f.scene).setMesh(shared);
+ const before = fingerprint(f.doc);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.merges).toBe(1);
+ expect(summary.primitivesAfter).toBe(2);
+ expect(pivot.getMesh()).toBe(shared);
+ expect(shared.listPrimitives()).toEqual([prim]);
+ expectSameFingerprint(before, fingerprint(f.doc));
+ });
+
+ test('splits a large joined bucket into 16-bit primitives without dropping attributes or elements', async () => {
+ const f = fixture();
+ const m = f.material('Shared');
+ for (let i = 0; i < 3; i++)
+ f.node(`Part${i}`, f.scene, { t: [0, i * 2, 0] }).setMesh(
+ f.doc.createMesh().addPrimitive(densePrimitive(f, m, 24_000)),
+ );
+ const before = fingerprint(f.doc);
+
+ const summary = mergeRigidGroups(f.doc);
+
+ expect(summary.primitivesBefore).toBe(3);
+ expect(summary.primitivesAfter).toBe(2);
+ const drawn = f.doc
+ .getRoot()
+ .listNodes()
+ .flatMap((n) => n.getMesh()?.listPrimitives() ?? []);
+ expect(drawn).toHaveLength(2);
+ for (const prim of drawn) {
+ expect(prim.getAttribute('POSITION')!.getCount()).toBeLessThanOrEqual(65_534);
+ expect(prim.getIndices()!.getArray()).toBeInstanceOf(Uint16Array);
+ expect(prim.getAttribute('COLOR_0')!.getCount()).toBe(
+ prim.getAttribute('POSITION')!.getCount(),
+ );
+ expect(prim.getAttribute('COLOR_0')!.getNormalized()).toBe(true);
+ }
+ expect(drawn.reduce((sum, p) => sum + p.getIndices()!.getCount(), 0)).toBe(72_000);
+ expectSameFingerprint(before, fingerprint(f.doc));
+ const { weld } = await import('@gltf-transform/functions');
+ await f.doc.transform(weld());
+ expectSameFingerprint(before, fingerprint(f.doc));
+ for (const node of f.doc.getRoot().listNodes())
+ for (const prim of node.getMesh()?.listPrimitives() ?? [])
+ expect(prim.getIndices()!.getArray()).toBeInstanceOf(Uint16Array);
+ });
+});
diff --git a/src/asset-cli.test.ts b/src/asset-cli.test.ts
index cdc477c8..5b85779f 100644
--- a/src/asset-cli.test.ts
+++ b/src/asset-cli.test.ts
@@ -112,6 +112,11 @@ test('CLI saves, exports, imports, and restores a revision across independent st
profile: 'editable',
format: 'glb',
files: [{ kind: 'glb', path: editable, bytes: canonical.length, sha256: sha256(canonical) }],
+ drawDiagnostics: expect.objectContaining({
+ version: 'kiln.draw-diagnostics.v1',
+ status: 'assessed',
+ currentDraws: expect.any(Number),
+ }),
});
expect(new Uint8Array(await readFile(editable))).toEqual(Uint8Array.from(canonical));
const runtime = join(root, 'runtime.glb');
@@ -129,6 +134,11 @@ test('CLI saves, exports, imports, and restores a revision across independent st
const metadataPath = join(root, 'runtime.kiln-metadata.json');
const receipt = JSON.parse(runtimeRun.stdout);
expect(receipt).toMatchObject({ ok: true, profile: 'runtime', format: 'glb' });
+ expect(receipt.drawDiagnostics).toMatchObject({
+ version: 'kiln.draw-diagnostics.v1',
+ status: 'assessed',
+ currentDraws: expect.any(Number),
+ });
expect(receipt.files).toEqual(
await Promise.all(
[
diff --git a/src/asset-cli.ts b/src/asset-cli.ts
index 167bad88..a808bb75 100644
--- a/src/asset-cli.ts
+++ b/src/asset-cli.ts
@@ -10,13 +10,14 @@ import { programRefPattern, retainProgram } from './program-store';
import { createKilnProgramToolRegistry, newestRevision } from './tools/registry';
import { writeNewDestinationsAtomic } from './cli-output';
import { exportAssetGlb } from './asset-export';
+import { inspectDrawDiagnostics } from './draw-diagnostics';
import { createPackagedLocalToolContext } from './local-runtime';
import { buildRenderPort, resolveRenderMode } from './cli-render-mode';
import { startAssetViewer } from './asset-viewer';
import { FileWorkspace, localWorkspaceRoot } from './workspace-node';
import { FileLiveReview } from './live-review-node';
import { resolveAssetMaterialPayload } from './project-bundle-node';
-import { rebuildOptionsSchema } from './rebuild-options';
+import { FULL_OPTIMIZATION_PIPELINE, rebuildOptionsSchema } from './rebuild-options';
import { assertSavedRequirementsAuthorized } from './requirements-assets';
import { resolveRequirementsContext } from './requirements-context';
import { assetViewerHref } from './viewer/deep-link';
@@ -295,13 +296,22 @@ export async function assetMain(argv: readonly string[]): Promise<number> {
throw new Error(
'Saved exporter settings are incomplete; use an explicit new authoring run instead of an exact rebuild.',
);
+ if (
+ parsed.data.optimize === 'full' &&
+ parsed.data.optimizationPipeline !== FULL_OPTIMIZATION_PIPELINE
+ )
+ throw new Error(
+ 'Saved revision uses an unversioned full optimization pipeline; rebuild with its original pinned engine, or explicitly author and save a new child revision to migrate.',
+ );
+ // The pipeline version is replay metadata, not an evaluator input option.
+ const { optimizationPipeline: _pipeline, ...renderOptions } = parsed.data;
const materialResources = await resolveAssetMaterialPayload(
new FileWorkspace(localWorkspaceRoot()),
record,
);
const code = new TextDecoder().decode(source);
const rendered = await context.evaluatorPort!.render(code, {
- ...parsed.data,
+ ...renderOptions,
materialResources,
requirements,
});
@@ -404,6 +414,14 @@ export async function assetMain(argv: readonly string[]): Promise<number> {
revisionId,
profile,
format,
+ ...(format !== 'source'
+ ? {
+ drawDiagnostics: await inspectDrawDiagnostics(
+ written.find(({ kind }) => kind === 'glb')?.data ??
+ record.files['asset.glb']!,
+ ),
+ }
+ : {}),
files: written.map(({ kind, path, data }) => ({
kind,
path,
diff --git a/src/asset-rebuild-cli.test.ts b/src/asset-rebuild-cli.test.ts
index 9e6cd384..81b90b16 100644
--- a/src/asset-rebuild-cli.test.ts
+++ b/src/asset-rebuild-cli.test.ts
@@ -118,3 +118,69 @@ test('CLI rebuild after project import uses exact saved source/options/materials
await rm(root, { recursive: true, force: true });
}
}, 20000);
+
+for (const versioned of [false, true]) {
+ test(`CLI full rebuild ${versioned ? 'replays a versioned artifact exactly' : 'refuses an unversioned legacy pipeline before writing'}`, async () => {
+ const root = await mkdtemp(join(tmpdir(), 'kiln-full-rebuild-cli-'));
+ try {
+ const workspace = new FileWorkspace(root);
+ const library = new FileAssetLibrary({ project: join(root, 'assets', 'kiln') });
+ const code = `const meta={name:'Pair'}; function build(){const r=createRoot('Root');const m=gameMaterial(0x888888);createPart('A',boxGeo(1,1,1),m,{parent:r});createPart('B',boxGeo(1,1,1),m,{parent:r,position:[1,0,0]});return r;}`;
+ const rendered = await renderGLBInProcess(code, { optimize: 'full', instance: 'off' });
+ const { optimizationPipeline, ...olderOptions } = rendered.rebuildOptions!;
+ expect(optimizationPipeline).toBe('rigid-v1');
+ const asset = await library.save('project', {
+ name: 'Pair',
+ code,
+ glb: rendered.glb,
+ build: {
+ engine: 'fixture',
+ warnings: [],
+ options: {
+ ...(versioned ? rendered.rebuildOptions : olderOptions),
+ requirements: rendered.requirements,
+ },
+ },
+ });
+ const output = join(root, 'rebuilt.glb');
+ const rebuilt = spawnSync(
+ process.execPath,
+ [
+ resolve('src/cli.ts'),
+ 'asset',
+ asset.assetId,
+ asset.revisionId,
+ '--rebuild',
+ '--out',
+ output,
+ ],
+ {
+ cwd: root,
+ env: {
+ ...process.env,
+ KILN_WORKSPACE: workspace.root,
+ KILN_PROJECT: '',
+ KILN_PROGRAM_STORE: '',
+ KILN_COLLECTIONS: '',
+ KILN_EVALUATOR_MODE: 'in-process',
+ KILN_BUILD_CACHE: 'memory',
+ KILN_RENDER: 'cpu',
+ },
+ encoding: 'utf8',
+ windowsHide: true,
+ },
+ );
+ if (versioned) {
+ expect(rebuilt.status, rebuilt.stderr).toBe(0);
+ expect(JSON.parse(rebuilt.stdout).matchesSavedArtifact).toBe(true);
+ expect(new Uint8Array(await readFile(output))).toEqual(Uint8Array.from(rendered.glb));
+ } else {
+ expect(rebuilt.status, rebuilt.stderr).toBe(1);
+ expect(rebuilt.stderr).toContain('unversioned full optimization pipeline');
+ await expect(readFile(output)).rejects.toMatchObject({ code: 'ENOENT' });
+ }
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ }, 20000);
+}
diff --git a/src/assets-resources.ts b/src/assets-resources.ts
index 880ceb05..89615b18 100644
--- a/src/assets-resources.ts
+++ b/src/assets-resources.ts
@@ -4,7 +4,7 @@ import {
type AssetManifest,
type AssetRecord,
} from './assets';
-import { exportAssetGlb } from './asset-export';
+import { exportAssetGlb, type AssetGlbExport } from './asset-export';
export interface AssetLink {
type: 'resource_link';
@@ -79,8 +79,9 @@ export function assetMime(name: string): string {
export async function runtimeAssetLinks(
collection: string,
record: AssetRecord,
+ derived?: Extract<AssetGlbExport, { profile: 'runtime' }>,
): Promise<AssetLink[]> {
- const output = await exportAssetGlb(record, { profile: 'runtime' });
+ const output = derived ?? (await exportAssetGlb(record, { profile: 'runtime' }));
if (output.profile !== 'runtime') throw new Error('Expected runtime export');
return [
{ name: 'runtime.glb', bytes: output.glb },
diff --git a/src/draw-diagnostics.ts b/src/draw-diagnostics.ts
new file mode 100644
index 00000000..e5b94690
--- /dev/null
+++ b/src/draw-diagnostics.ts
@@ -0,0 +1,313 @@
+/** Bounded, advisory draw analysis. Never mutates geometry or supplies QA acceptance evidence. */
+import { type Document, type Node, Primitive } from '@gltf-transform/core';
+import { cloneDocument } from '@gltf-transform/functions';
+import * as THREE from 'three';
+import { createGltfIO } from './gltf-io';
+import { isHiddenGltfNode } from './metrics';
+import { findRigidBoundaries, mergeRigidGroups } from './rigid-merge';
+
+const MAX_NODES = 2048;
+const MAX_USES = 256;
+const MAX_VERTICES = 262_144;
+const MAX_BYTES = 32 * 1024 * 1024;
+const MAX_ANCHORS = 16;
+const MAX_SAMPLES = 256;
+const MAX_FINDINGS = 4;
+const SCOPE =
+ 'Static single-pass primitive draws across document scenes, respecting node visibility. Excludes culling, alternate LOD selections, shadow, reflection and depth passes, and renderer-specific extra passes; GPU instances count once per primitive. IDs use scene/node indices; names are bounded labels.';
+const METHOD =
+ 'Current rigid-merge policy on a bounded clone with existing materials: includes layouts, boundaries, locks, shared-byte budget and vertex splits. Excludes palette consolidation and instancing; not a full-mode or GPU performance prediction.';
+
+interface PartRef {
+ id: string;
+ name: string;
+}
+interface Anchor extends PartRef {
+ draws: number;
+ afterRigidMerge: number;
+}
+export interface DrawDiagnostics {
+ version: 'kiln.draw-diagnostics.v1';
+ status: 'assessed' | 'skipped';
+ scope: string;
+ reason?: 'input-limit' | 'unreadable-glb' | 'analysis-failed';
+ currentDraws?: number;
+ mergeEstimate?: {
+ method: string;
+ draws: number;
+ saved: number;
+ rejectedBuckets: number;
+ skipped?: string;
+ };
+ anchors?: { total: number; omitted: number; items: Anchor[] };
+ observations?: {
+ mirroredTangents: { count: number; omitted: number; parts: PartRef[]; evidence: string };
+ coplanarParts: {
+ sampledTriangles: number;
+ eligibleTriangles: number;
+ unexaminedPrimitiveUses: number;
+ candidatePairs: number;
+ omitted: number;
+ candidates: { parts: [PartRef, PartRef] }[];
+ evidence: string;
+ };
+ };
+}
+interface Use {
+ node: Node;
+ primitive: Primitive;
+ part: PartRef;
+}
+const nameOf = (name: string) => (name.length <= 80 ? name : `${name.slice(0, 79)}…`);
+const skipped = (reason: DrawDiagnostics['reason']): DrawDiagnostics => ({
+ version: 'kiln.draw-diagnostics.v1',
+ status: 'skipped',
+ scope: SCOPE,
+ reason,
+});
+
+/** Bound clone/bake work by stored resources and placed uses, including invisible geometry. */
+function withinLimits(doc: Document): boolean {
+ const root = doc.getRoot();
+ if (
+ root.listNodes().length > MAX_NODES ||
+ root.listAccessors().length > 4096 ||
+ root.listMaterials().length > 2048 ||
+ root.listTextures().length > 256 ||
+ root.listScenes().length > 32 ||
+ doc.getGraph().listEdges().length > 32768
+ )
+ return false;
+ let bytes =
+ root.listAccessors().reduce((n, a) => n + (a.getArray()?.byteLength ?? 0), 0) +
+ root.listTextures().reduce((n, t) => n + (t.getImage()?.byteLength ?? 0), 0);
+ let uses = 0;
+ let vertices = 0;
+ const walk = (node: Node, depth: number): boolean => {
+ if (depth > 128) return false;
+ for (const p of node.getMesh()?.listPrimitives() ?? []) {
+ uses++;
+ vertices += p.getAttribute('POSITION')?.getCount() ?? 0;
+ bytes +=
+ p.listAttributes().reduce((n, a) => n + (a.getArray()?.byteLength ?? 0), 0) +
+ (p.getIndices()?.getArray()?.byteLength ?? 0);
+ }
+ return (
+ uses <= MAX_USES &&
+ vertices <= MAX_VERTICES &&
+ bytes <= MAX_BYTES &&
+ node.listChildren().every((n) => walk(n, depth + 1))
+ );
+ };
+ return (
+ bytes <= MAX_BYTES && root.listScenes().every((s) => s.listChildren().every((n) => walk(n, 0)))
+ );
+}
+
+function collect(doc: Document, keep: readonly string[]) {
+ const root = doc.getRoot();
+ const boundaries = findRigidBoundaries(doc, new Set(keep));
+ const nodeIds = new Map(root.listNodes().map((n, i) => [n, i]));
+ const anchors = new Map<string, Anchor>();
+ const uses: Use[] = [];
+ for (const [sceneIndex, scene] of root.listScenes().entries()) {
+ const id = `scene:${sceneIndex}`;
+ const initial = { id, name: nameOf(scene.getName() || 'Scene'), draws: 0, afterRigidMerge: 0 };
+ anchors.set(id, initial);
+ const walk = (node: Node, anchor: Anchor): void => {
+ if (isHiddenGltfNode(node)) return;
+ const part = { id: `${id}/node:${nodeIds.get(node)}`, name: nameOf(node.getName()) };
+ if (boundaries.has(node)) {
+ anchor = { ...part, draws: 0, afterRigidMerge: 0 };
+ anchors.set(part.id, anchor);
+ }
+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
+ anchor.draws++;
+ uses.push({ node, primitive, part });
+ }
+ for (const child of node.listChildren()) walk(child, anchor);
+ };
+ for (const child of scene.listChildren()) walk(child, initial);
+ }
+ return { anchors, uses };
+}
+
+interface Sample {
+ points: THREE.Vector3[];
+ normal: THREE.Vector3;
+ bounds: THREE.Box3;
+ part: PartRef;
+}
+type Point2 = [number, number];
+const cross2 = (a: Point2, b: Point2, p: Point2) =>
+ (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]);
+
+/** Positive projected overlap excludes mere shared edges and vertices. */
+function overlaps(a: Sample, b: Sample): boolean {
+ if (Math.abs(a.normal.dot(b.normal)) < 1 - 1e-8 || !a.bounds.intersectsBox(b.bounds))
+ return false;
+ const tolerance =
+ Math.max(
+ a.bounds.getSize(new THREE.Vector3()).length(),
+ b.bounds.getSize(new THREE.Vector3()).length(),
+ 1e-12,
+ ) * 1e-6;
+ if (b.points.some((p) => Math.abs(a.normal.dot(p.clone().sub(a.points[0]!))) > tolerance))
+ return false;
+ const normal = a.normal.toArray().map(Math.abs);
+ const drop = normal.indexOf(Math.max(...normal));
+ const project = (p: THREE.Vector3): Point2 => p.toArray().filter((_, i) => i !== drop) as Point2;
+ const clip = a.points.map(project);
+ if (cross2(clip[0]!, clip[1]!, clip[2]!) < 0) clip.reverse();
+ let polygon = b.points.map(project);
+ for (let i = 0; i < 3 && polygon.length; i++) {
+ const x = clip[i]!,
+ y = clip[(i + 1) % 3]!;
+ const output: Point2[] = [];
+ for (let j = 0; j < polygon.length; j++) {
+ const p = polygon[j]!,
+ q = polygon[(j + 1) % polygon.length]!;
+ const dp = cross2(x, y, p),
+ dq = cross2(x, y, q);
+ if (dp >= 0) output.push(p);
+ if (dp >= 0 !== dq >= 0) {
+ const t = dp / (dp - dq);
+ output.push([p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])]);
+ }
+ }
+ polygon = output;
+ }
+ let area = 0;
+ for (let i = 0; i < polygon.length; i++) {
+ const p = polygon[i]!,
+ q = polygon[(i + 1) % polygon.length]!;
+ area += p[0] * q[1] - p[1] * q[0];
+ }
+ return Math.abs(area) / 2 > tolerance * tolerance;
+}
+
+function observe(uses: Use[]): NonNullable<DrawDiagnostics['observations']> {
+ const mirrored = new Map<string, PartRef>();
+ const samples: Sample[] = [];
+ let eligibleTriangles = 0;
+ let unexaminedPrimitiveUses = 0;
+ for (const { node, primitive, part } of uses) {
+ if (
+ node.getSkin() ||
+ node.getExtension('EXT_mesh_gpu_instancing') ||
+ primitive.listTargets().length
+ ) {
+ unexaminedPrimitiveUses++;
+ continue;
+ }
+ const matrix = new THREE.Matrix4().fromArray(node.getWorldMatrix());
+ if (primitive.getAttribute('TANGENT') && matrix.determinant() < 0) mirrored.set(part.id, part);
+ const position = primitive.getAttribute('POSITION');
+ if (!position || primitive.getMode() !== Primitive.Mode.TRIANGLES) {
+ unexaminedPrimitiveUses++;
+ continue;
+ }
+ const indices = primitive.getIndices();
+ const count = Math.floor((indices?.getCount() ?? position.getCount()) / 3);
+ eligibleTriangles += count;
+ const amount = Math.min(count, 8, MAX_SAMPLES - samples.length);
+ for (let i = 0; i < amount; i++) {
+ const start = Math.floor((i * count) / amount) * 3;
+ const points = [0, 1, 2].map((j) =>
+ new THREE.Vector3()
+ .fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, []))
+ .applyMatrix4(matrix),
+ );
+ const normal = points[1]!.clone().sub(points[0]!).cross(points[2]!.clone().sub(points[0]!));
+ if (!Number.isFinite(normal.lengthSq()) || normal.lengthSq() === 0) continue;
+ samples.push({
+ points,
+ normal: normal.normalize(),
+ bounds: new THREE.Box3().setFromPoints(points),
+ part,
+ });
+ }
+ }
+ const pairs = new Map<string, { parts: [PartRef, PartRef] }>();
+ for (let i = 0; i < samples.length; i++)
+ for (let j = i + 1; j < samples.length; j++) {
+ const a = samples[i]!,
+ b = samples[j]!;
+ if (a.part.id === b.part.id || a.part.id.split('/')[0] !== b.part.id.split('/')[0]) continue;
+ const key = [a.part.id, b.part.id].sort().join('|');
+ if (!pairs.has(key) && overlaps(a, b)) pairs.set(key, { parts: [a.part, b.part] });
+ }
+ return {
+ mirroredTangents: {
+ count: mirrored.size,
+ omitted: Math.max(0, mirrored.size - MAX_FINDINGS),
+ parts: [...mirrored.values()].slice(0, MAX_FINDINGS),
+ evidence:
+ 'Visible static nodes with tangent attributes and negative world determinant; not proof of a shading defect. Skinned, morphed and GPU-instanced uses are not assessed.',
+ },
+ coplanarParts: {
+ sampledTriangles: samples.length,
+ eligibleTriangles,
+ unexaminedPrimitiveUses,
+ candidatePairs: pairs.size,
+ omitted: Math.max(0, pairs.size - MAX_FINDINGS),
+ candidates: [...pairs.values()].slice(0, MAX_FINDINGS),
+ evidence:
+ 'Sampled overlapping coplanar triangles in separate static nodes; not proof of visible z-fighting. At most 8 triangles per primitive and 256 total; unexamined faces may contain other candidates.',
+ },
+ };
+}
+
+/** Same-material merge estimate only; byte limits return an explicit skipped assessment. */
+export function analyzeDrawDiagnostics(
+ doc: Document,
+ options: { keep?: readonly string[] } = {},
+): DrawDiagnostics {
+ try {
+ if (!withinLimits(doc)) return skipped('input-limit');
+ const keep = options.keep ?? [];
+ const before = collect(doc, keep);
+ const copy = cloneDocument(doc);
+ const merge = mergeRigidGroups(copy, { keep });
+ const after = collect(copy, keep);
+ const all = [...before.anchors.values()].map((anchor) => ({
+ ...anchor,
+ afterRigidMerge: after.anchors.get(anchor.id)?.draws ?? 0,
+ }));
+ const currentDraws = before.uses.length;
+ return {
+ version: 'kiln.draw-diagnostics.v1',
+ status: 'assessed',
+ scope: SCOPE,
+ currentDraws,
+ mergeEstimate: {
+ method: METHOD,
+ draws: after.uses.length,
+ saved: currentDraws - after.uses.length,
+ rejectedBuckets: merge.rejected.length,
+ ...(merge.skipped ? { skipped: merge.skipped } : {}),
+ },
+ anchors: {
+ total: all.length,
+ omitted: Math.max(0, all.length - MAX_ANCHORS),
+ items: all.slice(0, MAX_ANCHORS),
+ },
+ observations: observe(before.uses),
+ };
+ } catch {
+ return skipped('analysis-failed');
+ }
+}
+
+/** Best-effort diagnostics for exact delivery bytes; unsupported GLBs still remain exportable. */
+export async function inspectDrawDiagnostics(
+ bytes: Uint8Array,
+ options: { keep?: readonly string[] } = {},
+): Promise<DrawDiagnostics> {
+ if (bytes.byteLength > MAX_BYTES) return skipped('input-limit');
+ try {
+ return analyzeDrawDiagnostics(await createGltfIO().readBinary(bytes), options);
+ } catch {
+ return skipped('unreadable-glb');
+ }
+}
diff --git a/src/inspect.ts b/src/inspect.ts
index 780509af..8d6dc3a2 100644
--- a/src/inspect.ts
+++ b/src/inspect.ts
@@ -19,6 +19,7 @@
import * as THREE from 'three';
import type { RequirementsBinding } from './requirements-store';
import type { RequirementsContext } from './requirements-context';
+import type { DrawDiagnostics } from './draw-diagnostics';
import { inspectGeneratedAnimation } from './render';
import { listHelperSpecs } from './discovery/helper-specs';
@@ -63,6 +64,8 @@ export interface InspectBoundingBox {
export interface InspectResult {
requirements: RequirementsContext;
+ /** Bounded, advisory single-pass draws and same-material merge observations. */
+ drawDiagnostics: DrawDiagnostics;
/** Total triangle count across every mesh in the scene graph. */
triangles: number;
/** Unique material count (by reference equality). */
@@ -270,9 +273,11 @@ export async function inspect(
const boundingBox = computeBoundingBox(root);
const animationTracks = collectAnimationTracks(root, clips);
const warnings = [...rendered.warnings, ...inspectGeneratedAnimation(root, clips)];
+ const { inspectDrawDiagnostics } = await import('./draw-diagnostics');
return {
requirements: rendered.requirements,
+ drawDiagnostics: await inspectDrawDiagnostics(rendered.glb),
triangles,
materials,
boundingBox,
diff --git a/src/kit.ts b/src/kit.ts
index 40f1babf..c855b205 100644
--- a/src/kit.ts
+++ b/src/kit.ts
@@ -206,6 +206,13 @@ async function packOcclusionIntoMetallicRoughness(
const sharp = (await import('sharp')).default;
let packed = 0;
const skipped: string[] = [];
+ // Reuse images for the same source pair; sampling stays on each material slot.
+ const packedPairs = new Map<Texture, Map<Texture, Texture>>();
+ const assign = (material: Material, mr: Texture, ao: Texture, result: Texture): void => {
+ material.setMetallicRoughnessTexture(result).setOcclusionTexture(result);
+ disposeIfOrphaned(ao);
+ if (mr !== result) disposeIfOrphaned(mr);
+ };
for (const [index, material] of doc.getRoot().listMaterials().entries()) {
const occlusion = material.getOcclusionTexture();
@@ -217,6 +224,12 @@ async function packOcclusionIntoMetallicRoughness(
skipped.push(mismatch);
continue;
}
+ const cached = packedPairs.get(metallicRoughness)?.get(occlusion);
+ if (cached) {
+ assign(material, metallicRoughness, occlusion, cached);
+ packed += 1;
+ continue;
+ }
const occlusionBytes = occlusion.getImage();
const mrBytes = metallicRoughness.getImage();
@@ -256,11 +269,24 @@ async function packOcclusionIntoMetallicRoughness(
.png({ compressionLevel: 9 })
.toBuffer();
- metallicRoughness.setImage(new Uint8Array(png));
- // Only the image changes: the occlusion slot keeps its own UV set and transform,
- // which the mismatch check above found equal to the metallic-roughness slot's.
- material.setOcclusionTexture(metallicRoughness);
- disposeIfOrphaned(occlusion);
+ // Another slot may need the original R or alpha, including another slot on
+ // this same material. Count reference edges, not just parent materials.
+ const shared = doc
+ .getGraph()
+ .listParentEdges(metallicRoughness)
+ .some(
+ (edge) =>
+ edge.getParent().propertyType !== 'Root' &&
+ (edge.getParent() !== material || edge.getName() !== 'metallicRoughnessTexture'),
+ );
+ // Clear a cloned image's URI so a later JSON export cannot overwrite its source.
+ const result = shared ? metallicRoughness.clone().setURI('') : metallicRoughness;
+ result.setImage(new Uint8Array(png));
+ const pairs = packedPairs.get(metallicRoughness) ?? new Map<Texture, Texture>();
+ pairs.set(occlusion, result);
+ packedPairs.set(metallicRoughness, pairs);
+ // Rebinding leaves each slot's UV, transform and sampler settings intact.
+ assign(material, metallicRoughness, occlusion, result);
packed += 1;
} catch {
// A texture we cannot decode stays as it is. The file is still valid.
diff --git a/src/qa/architecture.test.ts b/src/qa/architecture.test.ts
index 068472ff..0c7556ee 100644
--- a/src/qa/architecture.test.ts
+++ b/src/qa/architecture.test.ts
@@ -148,13 +148,13 @@ describe('ARCH-010–016 validator policy', () => {
}
});
- test('final export preserves helper portal/roof semantics and safely degrades full optimize', async () => {
+ test('final export preserves helper portal/roof semantics with full optimize', async () => {
const { shell, intent } = canonicalHelperShell('x');
const rendered = await renderSceneToGLB(shell.root, {
requirements: bindLegacyFixtureRequirements(intent),
optimize: 'full',
});
- expect(rendered.optimize?.mode).toBe('palette');
+ expect(rendered.optimize?.mode).toBe('full');
expect(rendered.qaReport.dimensions.exportIntegrity.status).toBe('pass');
expect(rendered.qaReport.rules.find((r) => r.id === 'ARCHITECTURE_PROFILE')?.status).toBe(
'evaluated',
diff --git a/src/qa/architecture.ts b/src/qa/architecture.ts
index 2f7bbce7..e9245b70 100644
--- a/src/qa/architecture.ts
+++ b/src/qa/architecture.ts
@@ -1327,7 +1327,13 @@ export const ARCHITECTURE_QA_RULE: QaRule = {
promotion: conformancePromotionAuthorization(
'architecture-qa-v1',
'src/qa/architecture.test.ts',
- 'c3a3bdc764c62238cede39813995fcaa428131d0aa3774bcd86cfc8b60f36671',
+ // Full-mode export now retains the semantic boundaries directly. Only the
+ // mode assertion/title changed; all architecture conformance assertions remain.
+ 'ce42ab6baef737d109f272413d902ea0903bd66c4da13ea723a52aff2f9e6c66',
+ KILN_ENGINE_QA_OWNER,
+ '2026-10-03T05:45:42.000Z',
+ 'enforce',
+ 'cpu-raster:0.10.0',
),
defaultMode: 'enforce',
evaluate: (context) =>
diff --git a/src/rebuild-options.ts b/src/rebuild-options.ts
index f44f7534..e5dab592 100644
--- a/src/rebuild-options.ts
+++ b/src/rebuild-options.ts
@@ -1,5 +1,8 @@
import { z } from 'zod';
+/** Full-mode artifact bytes changed when rigid-group merging replaced flatten/join. */
+export const FULL_OPTIMIZATION_PIPELINE = 'rigid-v1' as const;
+
/** Recorded effective export inputs. This excludes host credentials, execution mode and QA authority. */
export const rebuildOptionsSchema = z.object({
// Optional when reading older saved receipts; new builds always record the effective policy.
@@ -7,6 +10,7 @@ export const rebuildOptionsSchema = z.object({
gltfExporter: z.enum(['legacy', 'three']),
geometryPolicy: z.enum(['warn', 'strict']),
optimize: z.enum(['off', 'auto', 'palette', 'full']),
+ optimizationPipeline: z.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
instance: z.enum(['off', 'auto', 'on']),
});
export type RebuildOptions = z.infer<typeof rebuildOptionsSchema>;
diff --git a/src/render.ts b/src/render.ts
index 17f12dc2..873e4206 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -47,18 +47,9 @@ import {
type GeometryExportPolicy,
} from './geometry-export';
import { createHash } from 'node:crypto';
-import { Document } from '@gltf-transform/core';
+import { Document, Logger } from '@gltf-transform/core';
import { KHRMaterialsEmissiveStrength } from '@gltf-transform/extensions';
-import {
- dedup,
- instance,
- palette,
- flatten,
- join,
- weld,
- prune,
- mergeDocuments,
-} from '@gltf-transform/functions';
+import { dedup, instance, palette, weld, prune, mergeDocuments } from '@gltf-transform/functions';
import {
buildSlotIndex,
@@ -108,7 +99,8 @@ import {
} from './material-resources';
import { DEFAULT_TEXTURE_RESOLVER, type TextureResolver } from './texture-resolver';
import type { MaterialLibraryPayloadV1, MaterialManifestV1 } from './material-library';
-import type { RebuildOptions } from './rebuild-options';
+import { FULL_OPTIMIZATION_PIPELINE, type RebuildOptions } from './rebuild-options';
+import { rigidMerge, type RigidMergeSummary } from './rigid-merge';
import { assertGeneratedSourceSafe } from './validation';
import { applyKitContract, type KitPackOptions, type KitPackSummary } from './kit';
import {
@@ -1097,9 +1089,11 @@ export interface RenderResult {
* named pivots, and animations are fully preserved, so it is safe
* for animated assets + Kiln City behaviors. Lifts the grade by
* collapsing the material count (the grade's primary axis).
- * - `full` — `palette` plus `flatten → join` to also cut draw calls. STATIC
- * assets only: auto-degrades to `palette` when the Document has
- * animations or skins (flatten/join must not disturb a rig).
+ * - `full` — `palette` plus rigid-group merging. Animation targets, joints,
+ * semantic, visibility and LOD boundaries keep their geometry;
+ * every node keeps its name and hierarchy. Other named meshes
+ * may become empty or hold a merged group. Shared geometry is
+ * copied only within the byte budget; merged indices stay 16-bit.
* A render that omits the mode takes `KILN_BAKE_OPTIMIZE` (else `off`); what every
* pass keeps intact is listed on {@link consolidateMaterials}.
*/
@@ -1113,6 +1107,8 @@ export interface OptimizeSummary {
materialsAfter: number;
drawsBefore: number;
drawsAfter: number;
+ /** Full-mode boundaries, locks and rejected buckets, before final cleanup. */
+ rigidMerge?: RigidMergeSummary;
}
/**
@@ -1441,11 +1437,9 @@ async function applyGpuInstancing(
*
* `palette` collapses distinct untextured flat-color materials into one palette
* material + a small palette texture (textured materials pass through untouched);
- * `weld` + `prune` clean up. `full` adds `flatten → join` to also reduce draws,
- * but ONLY for static, semantics-free assets — animations, skins, `MSFT_lod`
- * chains, or any reserved semantic extras auto-degrade to `palette` so a rig,
- * LOD level, portal-clearance node, socket, or separable role is never flattened
- * away. `prune` keeps empty leaf nodes + extras so named pivots that Kiln City
+ * `weld` + `prune` clean up. `full` merges rigid groups, preserving animation,
+ * joint, semantic, LOD and visibility boundaries while optimizing their rigid
+ * descendants independently. `prune` keeps empty leaf nodes + extras so named pivots that Kiln City
* behaviors target by name survive, and LOD levels that only a chain references.
* palette groups by alpha mode, so opaque + the one glass slot stay distinct
* materials (transparency is never flattened into opaque).
@@ -1456,18 +1450,13 @@ async function applyGpuInstancing(
async function consolidateMaterials(
doc: Document,
mode: 'palette' | 'full',
+ keep: readonly string[] = [],
): Promise<OptimizeSummary> {
+ // Transform progress must not corrupt CLI/MCP JSON on stdout. Warnings and
+ // errors remain visible on stderr; structured merge diagnostics ride below.
+ doc.setLogger(new Logger(Logger.Verbosity.WARN));
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: 'palette' | 'full' =
- mode === 'full' &&
- (animatedOrSkinned || semanticGraph || hasNodeLevelsOfDetail(doc) || hasPreservedNodeState(doc))
- ? 'palette'
- : mode;
// palette() groups by shading properties and copies only one material's extras.
// Keep authored material identities whenever those carry application metadata.
@@ -1476,12 +1465,13 @@ async function consolidateMaterials(
.some((material) => Object.keys(material.getExtras()).length > 0)
? []
: [palette({ min: PALETTE_MIN })];
- if (effective === 'full') {
- // flatten() leaves skeletons + animation-targeted nodes in place, but it may
- // remove empty semantic clearance/socket nodes even when prune keeps leaves
- // and extras. Full therefore runs only on static, semantics-free graphs.
- steps.push(flatten(), join({ keepNamed: true }));
- }
+ let merge: RigidMergeSummary | undefined;
+ if (mode === 'full')
+ steps.push(
+ rigidMerge({ keep }, (summary) => {
+ merge = summary;
+ }),
+ );
// A solid texture can be semantically meaningful in more than one slot (for
// example the same unnamed bytes used as base color, normal, and packed MR).
// gltf-transform's default solid-texture pruning folds base/MR pixels into
@@ -1495,14 +1485,33 @@ async function consolidateMaterials(
const after = collectGlbMetrics(doc);
return {
- mode: effective,
+ mode,
materialsBefore: before.uniqueMaterials,
materialsAfter: after.uniqueMaterials,
drawsBefore: before.drawCalls,
drawsAfter: after.drawCalls,
+ ...(merge ? { rigidMerge: merge } : {}),
};
}
+/** Surface incomplete full-mode work without flooding compact render output per part. */
+function optimizeWarnings(summary: OptimizeSummary): string[] {
+ const merge = summary.rigidMerge;
+ if (!merge) return [];
+ const warnings: string[] = [];
+ if (merge.skipped)
+ warnings.push(`Rigid merge skipped: ${merge.skipped}; geometry left separate.`);
+ if (merge.rejected.length)
+ warnings.push(
+ `Rigid merge retained ${merge.rejected.length} rejected buckets; first: ${merge.rejected[0]!.error}`,
+ );
+ if (merge.unmatchedKeep.length)
+ warnings.push(
+ `Rigid merge did not find ${merge.unmatchedKeep.length} requested boundary names.`,
+ );
+ return warnings;
+}
+
/**
* Serialize a pre-built Three.js scene graph to a GLB byte stream.
*
@@ -1681,6 +1690,7 @@ export async function renderSceneToGLB(
if (effectiveOptimize !== 'off') {
try {
optimize = await consolidateMaterials(doc, effectiveOptimize);
+ warnings.push(...optimizeWarnings(optimize));
} catch (err) {
warnings.push(
`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`,
@@ -1859,6 +1869,9 @@ export async function renderGLBInProcess(
gltfExporter: resolveGltfExporter(opts.gltfExporter),
geometryPolicy: opts.geometryPolicy ?? 'warn',
optimize: resolveOptimize(opts.optimize),
+ ...(resolveOptimize(opts.optimize) === 'full'
+ ? { optimizationPipeline: FULL_OPTIMIZATION_PIPELINE }
+ : {}),
instance: resolveInstance(opts.instance),
};
let materialLibraryDependencies: MaterialManifestV1[] | undefined;
@@ -1993,6 +2006,8 @@ export interface OptimizeGlbResult {
instancing?: InstancingSummary;
/** Official Khronos report for the exact rebaked bytes. */
gltfValidation: KhronosGltfValidationReport;
+ /** Nonfatal optimization diagnostics; exact bucket details are in summary.rigidMerge. */
+ warnings?: string[];
}
/**
@@ -2051,6 +2066,7 @@ export async function optimizeGlbBytes(
gltfValidation,
...(report ? { report } : {}),
...(summary ? { summary } : {}),
+ ...(summary ? { warnings: optimizeWarnings(summary) } : {}),
...(instancing ? { instancing } : {}),
};
} catch (error) {
@@ -2257,6 +2273,8 @@ export interface SceneComposeResult {
warnings: string[];
/** Official Khronos report for the exact composed bytes. */
gltfValidation: KhronosGltfValidationReport;
+ /** Consolidation and rigid-boundary diagnostics when an optimization pass ran. */
+ optimize?: OptimizeSummary;
}
/** Euler degrees (XYZ) → a glTF quaternion [x, y, z, w] via THREE (the viewer's frame). */
@@ -2298,6 +2316,7 @@ export async function composeSceneGLB(
const masterScene = master.createScene(opts.sceneName ?? 'Scene');
master.getRoot().setDefaultScene(masterScene);
let composed = 0;
+ const placementNames: string[] = [];
for (let i = 0; i < parts.length; i++) {
const part = parts[i]!;
@@ -2323,6 +2342,7 @@ export async function composeSceneGLB(
mergedScene.dispose();
}
masterScene.addChild(wrap);
+ placementNames.push(wrap.getName());
composed++;
} catch (err) {
warnings.push(
@@ -2350,9 +2370,11 @@ export async function composeSceneGLB(
if (optimizeMode === 'auto' && collectGlbMetrics(master).uniqueMaterials >= PALETTE_MIN) {
effectiveOptimize = 'palette';
}
+ let optimize: OptimizeSummary | undefined;
if (effectiveOptimize !== 'off') {
try {
- await consolidateMaterials(master, effectiveOptimize);
+ optimize = await consolidateMaterials(master, effectiveOptimize, placementNames);
+ warnings.push(...optimizeWarnings(optimize));
} catch (err) {
warnings.push(
`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`,
@@ -2386,6 +2408,7 @@ export async function composeSceneGLB(
materials: metrics.uniqueMaterials,
warnings,
gltfValidation,
+ ...(optimize ? { optimize } : {}),
};
}
diff --git a/src/rigid-merge.ts b/src/rigid-merge.ts
new file mode 100644
index 00000000..af2fa590
--- /dev/null
+++ b/src/rigid-merge.ts
@@ -0,0 +1,691 @@
+/**
+ * Rigid-group merge: the draw-call step proposed for `optimize: 'full'`.
+ *
+ * A rigid group is a scene, or a boundary node, plus every descendant that is not itself a
+ * boundary. Nothing in one group moves against the rest of it at runtime, so primitives that
+ * share a material and vertex layout are baked into a well-conditioned contributing node's frame
+ * and joined into fewer draws. No node is removed, renamed or reparented; a node whose
+ * primitives all moved keeps its name with no mesh.
+ *
+ * Boundaries: animation targets, skin joints, `Joint_*` pivots (`hasJointPivots`' rule), nodes
+ * with any extras (a superset of Kiln semantic metadata), nodes a semantic relationship names
+ * (`targetType: 'node'`, resolved by name in `assembly.ts`), `KHR_node_visibility`, `MSFT_lod`,
+ * shared scene entry points, and names the caller keeps. A boundary's own primitives never move.
+ *
+ * Contract: the merge keeps every node name and the geometry of every boundary. It does NOT keep
+ * the geometry of a named non-boundary node: `Roadway` may come back holding its group's other
+ * parts, or empty. A consumer that addresses nodes by name must list them in `keep`, or not merge;
+ * `unmatchedKeep` reports kept names that no scene node carries.
+ *
+ * A mesh several nodes share is baked once per user that merges. Additional geometry bytes are
+ * capped at 4 KiB per saved draw, after the 65,534-vertex split and accounting for originals that
+ * remain in use. `expandSharedMeshes: false` locks shared users instead.
+ *
+ * Locked, never moved or joined: skinned or GPU-instanced nodes, meshes with extras, nodes with a
+ * singular world matrix, primitives with morph targets, extensions or extras, strip/fan/loop
+ * modes (a join inserts restart indices, which needs `KHR_mesh_primitive_restart`), primitives
+ * without POSITION, `KHR_materials_volume` (thickness is in node space) and, unless
+ * `mergeTransparent`, BLEND or transmissive materials: three sorts transparency per object, so a
+ * joined draw would freeze one triangle order for every viewpoint.
+ *
+ * Tangents are baked here, not with gltf-transform's `transformPrimitive` (4.5.0's
+ * `applyTangentMatrix` reads x after overwriting it and never flips w): xyz through the upper
+ * 3x3, normalised, w *= sign(det). Renderers disagree on mirrored frames. three r186 builds the
+ * bitangent as cross(N, T) * w with no determinant term (`normal_vertex.glsl.js:9`,
+ * `nodes/accessors/Bitangent.js:58`); a renderer that applies the world determinant does not. So
+ * by default a tangent-bearing primitive joins only parts of the same world handedness, where both
+ * agree; `mergeMirroredTangents` joins across handedness and keeps the determinant-corrected frame.
+ *
+ * Each bucket is built and checked detached from the scene before anything is removed; a bucket
+ * that fails leaves its primitives untouched and is reported in `rejected`.
+ */
+import {
+ type Accessor,
+ ComponentTypeToTypedArray,
+ type Document,
+ type Material,
+ type Mesh,
+ type Node,
+ Primitive,
+ type Property,
+ PropertyType,
+ type Transform,
+} from '@gltf-transform/core';
+import { createTransform, dequantizePrimitive, joinPrimitives } from '@gltf-transform/functions';
+import * as THREE from 'three';
+import { KILN_SEMANTIC_EXTRAS_KEY, type SemanticRelationshipV1 } from './contracts/semantic';
+import { type Lod, MSFT_LOD } from './gltf-io';
+
+export type RigidBoundaryReason =
+ | 'animated'
+ | 'skin-joint'
+ | 'joint-pivot'
+ | 'extras'
+ | 'relationship-target'
+ | 'visibility'
+ | 'lod'
+ | 'shared-scene'
+ | 'kept';
+
+export type RigidLockReason =
+ | 'boundary'
+ | 'skinned'
+ | 'instanced'
+ | 'mesh-extras'
+ | 'shared-mesh'
+ | 'shared-byte-budget'
+ | 'singular-matrix'
+ | 'morph-targets'
+ | 'primitive-mode'
+ | 'primitive-extensions'
+ | 'primitive-extras'
+ | 'no-position'
+ | 'transparent'
+ | 'volume';
+
+export interface RigidMergeOptions {
+ /** Node names to treat as boundaries: parts a consumer finds by name. */
+ keep?: readonly string[];
+ /** Join BLEND and transmissive primitives too (fixes their triangle order). */
+ mergeTransparent?: boolean;
+ /** Join tangent-bearing primitives across world handedness (see the module note). */
+ mergeMirroredTangents?: boolean;
+ /**
+ * Permit shared-mesh copies within the 4 KiB per saved draw budget (default true).
+ * False locks every user as `shared-mesh`.
+ */
+ expandSharedMeshes?: boolean;
+}
+
+export interface RigidMergeSummary {
+ /** Primitives on scene nodes, before and after; a GPU-instanced node counts once. */
+ primitivesBefore: number;
+ primitivesAfter: number;
+ /** Rigid groups walked: one per scene plus one per boundary. */
+ groups: number;
+ /** Buckets joined into fewer primitives, after the vertex-limit split. */
+ merges: number;
+ boundaries: { node: string; reasons: RigidBoundaryReason[] }[];
+ locked: { node: string; reason: RigidLockReason; primitives: number }[];
+ /** Buckets left as authored because building or checking the join failed. */
+ rejected: { node: string; primitives: number; error: string }[];
+ /** `keep` names no scene node carries: a misspelt or off-scene name protects nothing. */
+ unmatchedKeep: string[];
+ /** Set when nothing ran: an animation channel without a target node cannot be bounded. */
+ skipped?: 'unbounded-animation';
+}
+
+interface Entry {
+ node: Node;
+ prim: Primitive;
+}
+
+const JOINT_PIVOT = /^joint[_-]/i;
+/** LINE_LOOP, LINE_STRIP, TRIANGLE_STRIP, TRIANGLE_FAN. */
+const RESTART_MODES: ReadonlySet<number> = new Set([2, 3, 5, 6]);
+const BAKED = /^(POSITION|NORMAL|TANGENT)$/;
+const MAX_VERTICES = 65_534;
+const MAX_BYTES_PER_SAVED_DRAW = 4_096;
+
+const hasKeys = (value: object) => Object.keys(value).length > 0;
+const worldOf = (node: Node) => new THREE.Matrix4().fromArray(node.getWorldMatrix());
+const nodeUsers = (mesh: Mesh) =>
+ mesh.listParents().filter((parent) => parent.propertyType === PropertyType.NODE).length;
+
+/** |det| against the column lengths, so a tiny part is not mistaken for a flat one. */
+function isSingular(matrix: THREE.Matrix4): boolean {
+ const e = matrix.elements;
+ const scale =
+ Math.hypot(e[0]!, e[1]!, e[2]!) *
+ Math.hypot(e[4]!, e[5]!, e[6]!) *
+ Math.hypot(e[8]!, e[9]!, e[10]!);
+ const det = matrix.determinant();
+ return !Number.isFinite(det) || Math.abs(det) <= 1e-9 * scale;
+}
+
+export function findRigidBoundaries(
+ doc: Document,
+ keep: ReadonlySet<string>,
+): Map<Node, RigidBoundaryReason[]> {
+ const root = doc.getRoot();
+ const found = new Map<Node, RigidBoundaryReason[]>();
+ const add = (node: Node, reason: RigidBoundaryReason) => {
+ const reasons = found.get(node) ?? [];
+ if (!reasons.includes(reason)) reasons.push(reason);
+ found.set(node, reasons);
+ };
+ for (const animation of root.listAnimations())
+ for (const channel of animation.listChannels()) {
+ const target = channel.getTargetNode();
+ if (target) add(target, 'animated');
+ }
+ for (const skin of root.listSkins())
+ for (const joint of skin.listJoints()) add(joint, 'skin-joint');
+ const targets = new Set<string>();
+ for (const node of root.listNodes()) {
+ const semantic = node.getExtras()[KILN_SEMANTIC_EXTRAS_KEY] as
+ | { relationships?: unknown }
+ | undefined;
+ if (Array.isArray(semantic?.relationships))
+ for (const relationship of semantic.relationships as Partial<SemanticRelationshipV1>[])
+ if (relationship?.targetType === 'node' && typeof relationship.target === 'string')
+ targets.add(relationship.target);
+ }
+ for (const node of root.listNodes()) {
+ const name = node.getName();
+ const sceneParents = node
+ .listParents()
+ .filter((parent) => parent.propertyType === PropertyType.SCENE).length;
+ // Scene roots can be shared; nodes otherwise have a single parent. Only
+ // merges wholly inside a shared subtree are safe in every scene using it.
+ if (sceneParents > 1) add(node, 'shared-scene');
+ if (JOINT_PIVOT.test(name)) add(node, 'joint-pivot');
+ if (hasKeys(node.getExtras())) add(node, 'extras');
+ if (targets.has(name)) add(node, 'relationship-target');
+ if (node.getExtension('KHR_node_visibility')) add(node, 'visibility');
+ const lod = node.getExtension<Lod>(MSFT_LOD);
+ if (lod) {
+ add(node, 'lod');
+ for (const level of lod.listLevels())
+ if (level.propertyType === PropertyType.NODE) add(level as Node, 'lod');
+ }
+ if (keep.has(name)) add(node, 'kept');
+ }
+ return found;
+}
+
+function nodeLock(
+ node: Node,
+ mesh: Mesh,
+ world: THREE.Matrix4,
+ expandShared: boolean,
+): RigidLockReason | undefined {
+ if (node.getSkin()) return 'skinned';
+ if (node.getExtension('EXT_mesh_gpu_instancing')) return 'instanced';
+ if (hasKeys(mesh.getExtras())) return 'mesh-extras';
+ if (!expandShared && nodeUsers(mesh) > 1) return 'shared-mesh';
+ if (isSingular(world)) return 'singular-matrix';
+ return undefined;
+}
+
+function primLock(prim: Primitive, mergeTransparent: boolean): RigidLockReason | undefined {
+ if (prim.listTargets().length > 0) return 'morph-targets';
+ if (RESTART_MODES.has(prim.getMode())) return 'primitive-mode';
+ if (prim.listExtensions().length > 0) return 'primitive-extensions';
+ if (hasKeys(prim.getExtras())) return 'primitive-extras';
+ if (!prim.getAttribute('POSITION')) return 'no-position';
+ const material = prim.getMaterial();
+ if (material?.getExtension('KHR_materials_volume')) return 'volume';
+ if (
+ !mergeTransparent &&
+ material &&
+ (material.getAlphaMode() === 'BLEND' ||
+ material.getExtension('KHR_materials_transmission') ||
+ material.getExtension('KHR_materials_diffuse_transmission'))
+ )
+ return 'transparent';
+ return undefined;
+}
+
+/** gltf-transform's join key (`createPrimGroupKey`, not exported) plus `normalized`. */
+function bucketKey(
+ prim: Primitive,
+ materials: ReadonlyMap<Material | null, number>,
+ handedness: number | null,
+): string {
+ const layout = prim
+ .listSemantics()
+ .sort()
+ .map((semantic) => {
+ const a = prim.getAttribute(semantic)!;
+ return `${semantic}:${a.getElementSize()}:${a.getComponentType()}:${a.getNormalized()}`;
+ })
+ .join('+');
+ const hand = handedness !== null && prim.getAttribute('TANGENT') ? `|${handedness}` : '';
+ return `${materials.get(prim.getMaterial()) ?? -1}|${prim.getMode()}|${!!prim.getIndices()}|${layout}${hand}`;
+}
+
+function reverseWinding(prim: Primitive): void {
+ const indices = prim.getIndices()?.getArray();
+ const swap = (array: { [i: number]: number }, size: number, i: number) => {
+ for (let k = 0; k < size; k++) {
+ const [j, l] = [(i + 1) * size + k, (i + 2) * size + k];
+ [array[j], array[l]] = [array[l]!, array[j]!];
+ }
+ };
+ if (indices) {
+ for (let i = 0; i + 2 < indices.length; i += 3) swap(indices, 1, i);
+ return;
+ }
+ for (const semantic of prim.listSemantics()) {
+ const attribute = prim.getAttribute(semantic)!;
+ for (let i = 0; i + 2 < attribute.getCount(); i += 3)
+ swap(attribute.getArray()!, attribute.getElementSize(), i);
+ }
+}
+
+/** Bake `matrix` into a dequantized primitive copy. */
+function bake(prim: Primitive, matrix: THREE.Matrix4): void {
+ const linear = new THREE.Matrix3().setFromMatrix4(matrix);
+ const normalMatrix = new THREE.Matrix3().getNormalMatrix(matrix);
+ const mirrored = matrix.determinant() < 0;
+ const v = new THREE.Vector3();
+ const each = (semantic: string, apply: (element: number[]) => void) => {
+ const attribute = prim.getAttribute(semantic);
+ const element: number[] = [];
+ for (let i = 0; i < (attribute?.getCount() ?? 0); i++) {
+ apply(attribute!.getElement(i, element));
+ attribute!.setElement(i, element);
+ }
+ };
+ each('POSITION', (e) => v.fromArray(e).applyMatrix4(matrix).toArray(e));
+ each('NORMAL', (e) => v.fromArray(e).applyMatrix3(normalMatrix).normalize().toArray(e));
+ each('TANGENT', (e) => {
+ v.fromArray(e).applyMatrix3(linear).normalize().toArray(e);
+ if (mirrored) e[3] = -e[3]!;
+ });
+ if (mirrored && prim.getMode() === Primitive.Mode.TRIANGLES) reverseWinding(prim);
+}
+
+const accessorsOf = (prim: Primitive): Accessor[] => {
+ const indices = prim.getIndices();
+ return indices ? [...prim.listAttributes(), indices] : prim.listAttributes();
+};
+
+/** Prefer the least anisotropic frame, then scales closest to unit; input order breaks ties. */
+function destinationOf(entries: Entry[]): Node {
+ let chosen = entries[0]!.node;
+ let best = Infinity;
+ let bestScale = Infinity;
+ for (const { node } of entries) {
+ const linear = new THREE.Matrix3().setFromMatrix4(worldOf(node));
+ const norm = Math.hypot(...linear.elements);
+ const inverseNorm = Math.hypot(...linear.clone().invert().elements);
+ const condition = norm * inverseNorm;
+ const scale = Math.max(norm, inverseNorm);
+ if (
+ condition < best * (1 - 1e-12) ||
+ (Math.abs(condition - best) <= best * 1e-12 && scale < bestScale)
+ ) {
+ chosen = node;
+ best = condition;
+ bestScale = scale;
+ }
+ }
+ return chosen;
+}
+
+/** Float32 storage in a distant frame must not erase detail that the original node retained. */
+function checkPositionPrecision(
+ input: Accessor,
+ output: Accessor,
+ sourceWorld: THREE.Matrix4,
+ destinationWorld: THREE.Matrix4,
+ reversed: boolean,
+): void {
+ const expected = new THREE.Vector3();
+ const actual = new THREE.Vector3();
+ const bounds = new THREE.Box3();
+ const element: number[] = [];
+ let error = 0;
+ let magnitude = 0;
+ for (let i = 0; i < input.getCount(); i++) {
+ const out = reversed ? (i % 3 === 1 ? i + 1 : i % 3 === 2 ? i - 1 : i) : i;
+ expected.fromArray(input.getElement(i, element)).applyMatrix4(sourceWorld);
+ actual.fromArray(output.getElement(out, element)).applyMatrix4(destinationWorld);
+ bounds.expandByPoint(expected);
+ error = Math.max(error, expected.distanceTo(actual));
+ magnitude = Math.max(magnitude, expected.length());
+ }
+ const tolerance = Math.max(
+ bounds.getSize(expected).length() * 1e-6,
+ magnitude * Number.EPSILON * 32,
+ Number.EPSILON,
+ );
+ if (error > tolerance) throw new Error('rigid merge: destination frame loses position precision');
+}
+
+/** Split complete points/lines/triangles, remapping every vertex attribute together. */
+function splitVertices(prim: Primitive, created: Property[]): Primitive[] {
+ if (prim.getAttribute('POSITION')!.getCount() <= MAX_VERTICES) return [prim];
+ const width =
+ prim.getMode() === Primitive.Mode.POINTS ? 1 : prim.getMode() === Primitive.Mode.LINES ? 2 : 3;
+ const sourceIndices = prim.getIndices()?.getArray();
+ const count = sourceIndices?.length ?? prim.getAttribute('POSITION')!.getCount();
+ if (count % width !== 0) throw new Error('rigid merge: incomplete primitive element');
+ const chunks: Primitive[] = [];
+ let remap = new Map<number, number>();
+ let indices: number[] = [];
+ const flush = () => {
+ if (!indices.length) return;
+ const chunk = prim.clone();
+ created.push(chunk);
+ const vertices = [...remap.keys()];
+ for (const semantic of prim.listSemantics()) {
+ const source = prim.getAttribute(semantic)!;
+ const size = source.getElementSize();
+ const ArrayType = ComponentTypeToTypedArray[source.getComponentType()];
+ if (!ArrayType) throw new Error(`rigid merge: unsupported component type for ${semantic}`);
+ const data = new ArrayType(vertices.length * size);
+ const sourceData = source.getArray()!;
+ for (const [out, input] of vertices.entries())
+ data.set(sourceData.subarray(input * size, (input + 1) * size), out * size);
+ const attribute = source.clone().setArray(data);
+ created.push(attribute);
+ chunk.setAttribute(semantic, attribute);
+ }
+ if (prim.getIndices()) {
+ const accessor = prim.getIndices()!.clone().setArray(new Uint16Array(indices));
+ created.push(accessor);
+ chunk.setIndices(accessor);
+ }
+ chunks.push(chunk);
+ remap = new Map();
+ indices = [];
+ };
+ for (let offset = 0; offset < count; offset += width) {
+ const element = Array.from(
+ { length: width },
+ (_, i) => sourceIndices?.[offset + i] ?? offset + i,
+ );
+ const extra = new Set(element.filter((index) => !remap.has(index))).size;
+ if (remap.size + extra > MAX_VERTICES) flush();
+ for (const index of element) {
+ if (!remap.has(index)) remap.set(index, remap.size);
+ indices.push(remap.get(index)!);
+ }
+ }
+ flush();
+ for (const property of [prim, ...accessorsOf(prim)]) property.dispose();
+ return chunks;
+}
+
+/** Join one bucket into detached, checked primitives without touching the originals. */
+function prepare(entries: Entry[], dst: Node, created: Property[]): Primitive[] {
+ const destinationWorld = worldOf(dst);
+ const inverse = destinationWorld.clone().invert();
+ const copies = entries.map(({ node, prim }) => {
+ const copy = prim.clone();
+ created.push(copy);
+ for (const semantic of copy.listSemantics()) {
+ const attribute = copy.getAttribute(semantic)!.clone();
+ created.push(attribute);
+ copy.setAttribute(semantic, attribute);
+ }
+ const indices = copy.getIndices()?.clone();
+ if (indices) {
+ created.push(indices);
+ copy.setIndices(indices);
+ }
+ dequantizePrimitive(copy, { pattern: BAKED });
+ if (node !== dst) {
+ const sourceWorld = worldOf(node);
+ const matrix = inverse.clone().multiply(sourceWorld);
+ bake(copy, matrix);
+ const reversed =
+ !copy.getIndices() &&
+ copy.getMode() === Primitive.Mode.TRIANGLES &&
+ matrix.determinant() < 0;
+ checkPositionPrecision(
+ prim.getAttribute('POSITION')!,
+ copy.getAttribute('POSITION')!,
+ sourceWorld,
+ destinationWorld,
+ reversed,
+ );
+ }
+ return copy;
+ });
+ const merged = joinPrimitives(copies);
+ created.push(merged, ...accessorsOf(merged));
+ for (const semantic of ['POSITION', 'NORMAL', 'TANGENT']) {
+ const array = merged.getAttribute(semantic)?.getArray();
+ if (array && !array.every(Number.isFinite))
+ throw new Error(`rigid merge: non-finite ${semantic} in the joined primitive`);
+ }
+ const elements = (p: Primitive) =>
+ p.getIndices()?.getCount() ?? p.getAttribute('POSITION')!.getCount();
+ const expected = copies.reduce((sum, copy) => sum + elements(copy), 0);
+ if (elements(merged) !== expected)
+ throw new Error(`rigid merge: joined ${elements(merged)} of ${expected} elements`);
+ for (const copy of copies)
+ for (const property of [copy, ...accessorsOf(copy)]) property.dispose();
+ return splitVertices(merged, created);
+}
+
+/** Bytes guaranteed to disappear when these exact node/primitive uses are removed. */
+function removableBytes(entries: Entry[]): number {
+ const uses = new Map<Primitive, Set<Node>>();
+ for (const { node, prim } of entries) {
+ const nodes = uses.get(prim) ?? new Set<Node>();
+ nodes.add(node);
+ uses.set(prim, nodes);
+ }
+ const removed = new Set<Primitive>();
+ for (const [prim, nodes] of uses) {
+ const retained = prim.listParents().some((parent) => {
+ if (parent.propertyType === PropertyType.ROOT) return false;
+ if (parent.propertyType !== PropertyType.MESH) return true;
+ return parent
+ .listParents()
+ .some(
+ (user) =>
+ user.propertyType !== PropertyType.ROOT &&
+ (user.propertyType !== PropertyType.NODE || !nodes.has(user as Node)),
+ );
+ });
+ if (!retained) removed.add(prim);
+ }
+ const accessors = new Set([...removed].flatMap(accessorsOf));
+ let bytes = 0;
+ for (const accessor of accessors)
+ if (
+ accessor
+ .listParents()
+ .every(
+ (parent) => parent.propertyType === PropertyType.ROOT || removed.has(parent as Primitive),
+ )
+ )
+ bytes += accessor.getArray()?.byteLength ?? 0;
+ return bytes;
+}
+
+const primitiveBytes = (primitives: Primitive[]) =>
+ [...new Set(primitives.flatMap(accessorsOf))].reduce(
+ (sum, a) => sum + (a.getArray()?.byteLength ?? 0),
+ 0,
+ );
+
+function sceneNodes(doc: Document): Set<Node> {
+ const seen = new Set<Node>();
+ const visit = (node: Node): void => {
+ if (seen.has(node)) return;
+ seen.add(node);
+ for (const child of node.listChildren()) visit(child);
+ };
+ for (const scene of doc.getRoot().listScenes())
+ for (const child of scene.listChildren()) visit(child);
+ return seen;
+}
+
+const countPrimitives = (nodes: Iterable<Node>): number =>
+ [...nodes].reduce((sum, node) => sum + (node.getMesh()?.listPrimitives().length ?? 0), 0);
+
+/** Merge primitives by material within each rigid group, in place. */
+export function mergeRigidGroups(
+ doc: Document,
+ options: RigidMergeOptions = {},
+): RigidMergeSummary {
+ const root = doc.getRoot();
+ const keep = new Set(options.keep ?? []);
+ const nodes = sceneNodes(doc);
+ const names = new Set([...nodes].map((node) => node.getName()));
+ const summary: RigidMergeSummary = {
+ primitivesBefore: countPrimitives(nodes),
+ primitivesAfter: 0,
+ groups: 0,
+ merges: 0,
+ boundaries: [],
+ locked: [],
+ rejected: [],
+ unmatchedKeep: [...keep].filter((name) => !names.has(name)),
+ };
+ if (root.listAnimations().some((a) => a.listChannels().some((c) => !c.getTargetNode()))) {
+ summary.skipped = 'unbounded-animation';
+ summary.primitivesAfter = summary.primitivesBefore;
+ return summary;
+ }
+
+ const boundaries = findRigidBoundaries(doc, keep);
+ const materials = new Map<Material | null, number>(root.listMaterials().map((m, i) => [m, i]));
+ const groups: Map<string, Entry[]>[] = [];
+ const locks = new Map<string, RigidMergeSummary['locked'][number]>();
+ const lock = (node: Node, reason: RigidLockReason, primitives: number) => {
+ const key = `${node.getName()}|${reason}`;
+ const known = locks.get(key);
+ if (known) known.primitives += primitives;
+ else {
+ const entry = { node: node.getName(), reason, primitives };
+ locks.set(key, entry);
+ summary.locked.push(entry);
+ }
+ };
+ const seen = new Set<Node>();
+ const visit = (node: Node, parentGroup: Map<string, Entry[]>): void => {
+ if (seen.has(node)) return;
+ seen.add(node);
+ const reasons = boundaries.get(node);
+ let group = parentGroup;
+ if (reasons) {
+ summary.boundaries.push({ node: node.getName(), reasons });
+ group = new Map();
+ groups.push(group);
+ }
+ const mesh = node.getMesh();
+ if (mesh) {
+ const world = worldOf(node);
+ const nodeReason = reasons
+ ? 'boundary'
+ : nodeLock(node, mesh, world, options.expandSharedMeshes !== false);
+ const handedness = options.mergeMirroredTangents ? null : Math.sign(world.determinant());
+ if (nodeReason) lock(node, nodeReason, mesh.listPrimitives().length);
+ else
+ for (const prim of mesh.listPrimitives()) {
+ const primReason = primLock(prim, options.mergeTransparent === true);
+ if (primReason) lock(node, primReason, 1);
+ else {
+ const key = bucketKey(prim, materials, handedness);
+ const list = group.get(key);
+ if (list) list.push({ node, prim });
+ else group.set(key, [{ node, prim }]);
+ }
+ }
+ }
+ for (const child of node.listChildren()) visit(child, group);
+ };
+ for (const scene of root.listScenes()) {
+ const group = new Map<string, Entry[]>();
+ groups.push(group);
+ for (const child of scene.listChildren()) visit(child, group);
+ }
+ summary.groups = groups.length;
+
+ // Build every join first; only a bucket that built and checked cleanly changes the graph.
+ const plans: { entries: Entry[]; destination: Node; merged: Primitive[] }[] = [];
+ for (const group of groups)
+ for (const bucket of group.values()) {
+ let entries = bucket;
+ while (entries.length >= 2) {
+ const created: Property[] = [];
+ // The library can allocate accessors before joinPrimitives throws. Track
+ // its creation events too, so rejecting a bucket restores the whole graph.
+ const track = (event: { target: unknown }) => created.push(event.target as Property);
+ doc.getGraph().addEventListener('node:create', track);
+ try {
+ const destination = destinationOf(entries);
+ const merged = prepare(entries, destination, created);
+ const savedDraws = entries.length - merged.length;
+ const shared = entries.filter(
+ (entry) => removableBytes([entry]) < primitiveBytes([entry.prim]),
+ );
+ const addedBytes = Math.max(0, primitiveBytes(merged) - removableBytes(entries));
+ if (savedDraws > 0 && addedBytes <= savedDraws * MAX_BYTES_PER_SAVED_DRAW) {
+ plans.push({ entries, destination, merged });
+ break;
+ }
+ for (const property of created) property.dispose();
+ if (!shared.length || savedDraws <= 0) break;
+ // Remove the costliest shared mesh first, retaining useful merges among affordable inputs.
+ const costly = shared.reduce((best, entry) =>
+ primitiveBytes(entry.node.getMesh()!.listPrimitives()) >
+ primitiveBytes(best.node.getMesh()!.listPrimitives())
+ ? entry
+ : best,
+ );
+ const mesh = costly.node.getMesh()!;
+ for (const entry of entries.filter((entry) => entry.node.getMesh() === mesh))
+ lock(entry.node, 'shared-byte-budget', 1);
+ entries = entries.filter((entry) => entry.node.getMesh() !== mesh);
+ } catch (error) {
+ for (const property of created) property.dispose();
+ summary.rejected.push({
+ node: entries[0]!.node.getName(),
+ primitives: entries.length,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ break;
+ } finally {
+ doc.getGraph().removeEventListener('node:create', track);
+ }
+ }
+ }
+
+ const owned = new Map<Node, Mesh>();
+ const ownMesh = (node: Node): Mesh => {
+ let mesh = owned.get(node);
+ if (mesh) return mesh;
+ mesh = node.getMesh()!;
+ // Mesh.clone() shares primitive references, so other users keep theirs.
+ if (nodeUsers(mesh) > 1) {
+ mesh = mesh.clone();
+ node.setMesh(mesh);
+ }
+ owned.set(node, mesh);
+ return mesh;
+ };
+ const removed = new Set<Primitive>();
+ for (const { entries, destination, merged } of plans) {
+ for (const { node, prim } of entries) {
+ ownMesh(node).removePrimitive(prim);
+ removed.add(prim);
+ }
+ for (const primitive of merged) ownMesh(destination).addPrimitive(primitive);
+ }
+ for (const [node, mesh] of owned)
+ if (mesh.listPrimitives().length === 0) {
+ node.setMesh(null);
+ if (nodeUsers(mesh) === 0) mesh.dispose();
+ }
+ for (const prim of removed) {
+ if (prim.listParents().some((parent) => parent.propertyType === PropertyType.MESH)) continue;
+ const accessors = accessorsOf(prim);
+ prim.dispose();
+ for (const accessor of accessors)
+ if (accessor.listParents().every((parent) => parent.propertyType === PropertyType.ROOT))
+ accessor.dispose();
+ }
+ summary.merges = plans.length;
+ summary.primitivesAfter = countPrimitives(nodes);
+ return summary;
+}
+
+/** {@link mergeRigidGroups} as a gltf-transform step, e.g. between `palette()` and `weld()`. */
+export function rigidMerge(
+ options: RigidMergeOptions = {},
+ onSummary?: (summary: RigidMergeSummary) => void,
+): Transform {
+ return createTransform('kilnRigidMerge', (doc: Document) => {
+ const summary = mergeRigidGroups(doc, options);
+ onSummary?.(summary);
+ });
+}
diff --git a/src/tools/__tests__/draw-diagnostics.test.ts b/src/tools/__tests__/draw-diagnostics.test.ts
new file mode 100644
index 00000000..93f82ac5
--- /dev/null
+++ b/src/tools/__tests__/draw-diagnostics.test.ts
@@ -0,0 +1,136 @@
+import { expect, spyOn, test } from 'bun:test';
+import { Document } from '@gltf-transform/core';
+import { createHash } from 'node:crypto';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { FileAssetLibrary } from '../../assets-node';
+import * as assetExport from '../../asset-export';
+import { readAssetResource } from '../../assets-resources';
+import { createGltfIO } from '../../gltf-io';
+import type { DrawDiagnostics } from '../../draw-diagnostics';
+import { inspect } from '../../inspect';
+import { renderGLB } from '../../render';
+import { createKilnProgramToolRegistry } from '../registry';
+
+const code = `const meta={name:'TwoParts'}; function build(){const root=createRoot('TwoParts'); const m=gameMaterial('#888888');createPart('A',boxGeo(1,1,1),m,{parent:root});createPart('B',boxGeo(1,1,1),m,{parent:root,position:[2,0,0]});return root;}`;
+type Output = { ok: boolean; drawDiagnostics?: DrawDiagnostics };
+
+test('library inspection exposes bounded draw diagnostics', async () => {
+ const library = await inspect(code);
+ expect(library.drawDiagnostics.currentDraws).toBe(2);
+ expect(library.drawDiagnostics.mergeEstimate?.draws).toBe(1);
+});
+
+test('kiln_inspect exposes diagnostics while kiln_render stays unchanged', async () => {
+ const defs = createKilnProgramToolRegistry();
+ const report = (await defs
+ .find((t) => t.name === 'kiln_inspect')!
+ .run({ code, image: false, listParts: {} })) as Output;
+ expect(report.ok).toBe(true);
+ expect(report.drawDiagnostics?.mergeEstimate?.draws).toBe(1);
+ const render = (await defs
+ .find((t) => t.name === 'kiln_render')!
+ .run({ code, capture: { preset: '1x1' } })) as Output;
+ expect(render.ok).toBe(true);
+ expect(render.drawDiagnostics).toBeUndefined();
+});
+
+test('editable and runtime exports summarize the saved geometry without changing canonical revision bytes', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'kiln-draw-diagnostics-'));
+ try {
+ const assetLibrary = new FileAssetLibrary({ project: root });
+ const baked = await renderGLB(code, { optimize: 'off' });
+ const manifest = await assetLibrary.save('project', { name: 'TwoParts', code, glb: baked.glb });
+ const before = await assetLibrary.read('project', manifest.assetId, manifest.revisionId);
+ const tool = createKilnProgramToolRegistry({ assetLibrary }).find(
+ (t) => t.name === 'kiln_export',
+ )!;
+ for (const profile of ['editable', 'runtime']) {
+ const output = (await tool.run({
+ collection: 'project',
+ assetId: manifest.assetId,
+ revisionId: manifest.revisionId,
+ profile,
+ })) as Output;
+ expect(output.ok).toBe(true);
+ expect(output.drawDiagnostics?.currentDraws).toBe(2);
+ expect(output.drawDiagnostics?.mergeEstimate?.draws).toBe(1);
+ }
+ expect(await assetLibrary.read('project', manifest.assetId, manifest.revisionId)).toEqual(
+ before,
+ );
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test('runtime export diagnoses its derived bytes once when removed review data exceeded the analysis limit', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'kiln-runtime-diagnostics-'));
+ const digest = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex');
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const positions = doc
+ .createAccessor()
+ .setBuffer(buffer)
+ .setType('VEC3')
+ .setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]));
+ doc
+ .createScene('Scene')
+ .addChild(
+ doc
+ .createNode('Part')
+ .setMesh(
+ doc.createMesh().addPrimitive(doc.createPrimitive().setAttribute('POSITION', positions)),
+ ),
+ )
+ // Cross only the 32 MiB diagnostics limit; stay well below the 64 MiB asset limit.
+ .setExtras({
+ kilnReviewClipsV1: { version: 1, clips: [], fixturePadding: 'x'.repeat(32 * 1024 * 1024) },
+ });
+ const canonical = await createGltfIO().writeBinary(doc);
+ expect(canonical.length).toBeGreaterThan(32 * 1024 * 1024);
+ expect(canonical.length).toBeLessThan(32 * 1024 * 1024 + 4096);
+ const canonicalHash = digest(canonical);
+ try {
+ const assetLibrary = new FileAssetLibrary({ project: root });
+ const manifest = await assetLibrary.save('project', {
+ name: 'Runtime boundary',
+ glb: canonical,
+ });
+ const record = await assetLibrary.read('project', manifest.assetId, manifest.revisionId);
+ const expected = await assetExport.exportAssetGlb(record, { profile: 'runtime' });
+ expect(expected.glb.length).toBeLessThan(4096);
+ const tool = createKilnProgramToolRegistry({ assetLibrary }).find(
+ (t) => t.name === 'kiln_export',
+ )!;
+ const derive = spyOn(assetExport, 'exportAssetGlb');
+ let output: Output & { resources: { name: string; uri: string; size: number }[] };
+ try {
+ output = (await tool.run({
+ collection: 'project',
+ assetId: manifest.assetId,
+ revisionId: manifest.revisionId,
+ profile: 'runtime',
+ })) as typeof output;
+ expect(output.drawDiagnostics).toMatchObject({ status: 'assessed', currentDraws: 1 });
+ expect(derive).toHaveBeenCalledTimes(1);
+ } finally {
+ derive.mockRestore();
+ }
+ const glbLink = output.resources.find((link) => link.name === 'runtime.glb')!;
+ const delivered = await readAssetResource(assetLibrary, glbLink.uri);
+ expect(glbLink.size).toBe(expected.glb.length);
+ expect(delivered.bytes).toEqual(expected.glb);
+ expect(digest(delivered.bytes)).toBe(digest(expected.glb));
+ expect(
+ digest(
+ (await assetLibrary.read('project', manifest.assetId, manifest.revisionId)).files[
+ 'asset.glb'
+ ]!,
+ ),
+ ).toBe(canonicalHash);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index 7db20fde..291dc1e7 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -1837,6 +1837,7 @@ export const inspectBufferInput = inspectInput.omit({ code: true });
const inspectAdvertisedInput = inspectInput.extend({ shot: cameraShotRecordInput });
export interface KilnInspectResult extends EvaluationEvidence {
+ drawDiagnostics?: import('../draw-diagnostics').DrawDiagnostics;
partListing?: PartListing;
surfaceMeasurements?: ReturnType<typeof import('../views/surface-distance').measureSurfacePairs>;
comparison?: Awaited<ReturnType<typeof import('../revision-comparison').compareRevisionGlbs>> & {
@@ -1943,6 +1944,9 @@ async function runInspect(
if (input.measure && input.measure.mode !== 'surface')
measurement = measureAttachment(root, input.measure);
const measurements = {
+ drawDiagnostics: await (await import('../draw-diagnostics')).inspectDrawDiagnostics(
+ evaluated.glb,
+ ),
...(input.listParts ? { partListing: await listPartPage(root, input.listParts) } : {}),
...(measurement ? { measurement } : {}),
...(surfaceMeasurements ? { surfaceMeasurements } : {}),
@@ -3047,15 +3051,21 @@ export function createKilnAssetDefs(context: KilnToolContext): KilnToolDef[] {
inputSchema: profileExportInput,
run: async (raw) => {
const input = profileExportInput.parse(raw);
+ const record = await readSavedRevision(
+ library(),
+ input.collection,
+ input.assetId,
+ input.revisionId,
+ );
+ const { inspectDrawDiagnostics } = await import('../draw-diagnostics');
if (input.profile === 'runtime') {
- const record = await readSavedRevision(
- library(),
- input.collection,
- input.assetId,
- input.revisionId,
- );
+ const output = await (await import('../asset-export')).exportAssetGlb(record, {
+ profile: 'runtime',
+ });
+ if (output.profile !== 'runtime') throw new Error('Expected runtime export');
return {
ok: true,
+ drawDiagnostics: await inspectDrawDiagnostics(output.glb),
profile: input.profile,
collection: input.collection,
asset: {
@@ -3066,14 +3076,14 @@ export function createKilnAssetDefs(context: KilnToolContext): KilnToolDef[] {
resources: await (await import('../assets-resources')).runtimeAssetLinks(
input.collection,
record,
+ output,
),
};
}
- return links(
- input.collection,
- (await readSavedRevision(library(), input.collection, input.assetId, input.revisionId))
- .manifest,
- );
+ return {
+ ...(await links(input.collection, record.manifest)),
+ drawDiagnostics: await inspectDrawDiagnostics(record.files['asset.glb']!),
+ };
},
},
{
diff --git a/src/views/__tests__/architecture.test.ts b/src/views/__tests__/architecture.test.ts
index c57be714..27a1a397 100644
--- a/src/views/__tests__/architecture.test.ts
+++ b/src/views/__tests__/architecture.test.ts
@@ -79,7 +79,7 @@ describe('semantic architecture roof selection', () => {
source.add(roof, wall, opening);
const rendered = await renderSceneToGLB(source, { optimize: 'full' });
- expect(rendered.optimize?.mode).toBe('palette');
+ expect(rendered.optimize?.mode).toBe('full');
const document = await new WebIO().readBinary(rendered.bytes);
const reloadedOpening = document
.getRoot()
diff --git a/toolchain.json b/toolchain.json
index 4dffda87..93c67d40 100644
--- a/toolchain.json
+++ b/toolchain.json
@@ -1,5 +1,5 @@
{
"bun": "1.4.2",
- "node": "22.23.2",
- "npm": "12.0.2"
+ "node": "22.23.3",
+ "npm": "12.2.0"
}