@wildshard/engine 0.1.23 → 0.1.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/index.html +17 -4
  3. package/lint/engine-sides.json +7 -0
  4. package/package.json +29 -3
  5. package/scripts/app-build/titlePreloads.mjs +8 -5
  6. package/scripts/bake-road-surfaces.entry.ts +18 -0
  7. package/scripts/bake-road-surfaces.mjs +44 -0
  8. package/scripts/changelog.mjs +2 -1
  9. package/scripts/goldens/capture.mjs +18 -6
  10. package/scripts/goldens/native-residency.d.mts +1 -0
  11. package/scripts/goldens/native-residency.mjs +14 -1
  12. package/scripts/grid-road-lag.mjs +209 -0
  13. package/scripts/keep-copy.mjs +64 -12
  14. package/scripts/land.d.mts +4 -1
  15. package/scripts/land.mjs +85 -3
  16. package/scripts/loading-flow/benchmax.mjs +2 -0
  17. package/scripts/map-hash.mjs +1 -1
  18. package/scripts/nightly-tag.mjs +2 -4
  19. package/scripts/page-release/content.mjs +19 -10
  20. package/scripts/page-release/flow.d.mts +3 -2
  21. package/scripts/page-release/flow.mjs +31 -21
  22. package/scripts/page-release/packs.d.mts +5 -0
  23. package/scripts/page-release/packs.mjs +13 -3
  24. package/scripts/page-release/preview.d.mts +2 -0
  25. package/scripts/page-release/preview.mjs +74 -0
  26. package/scripts/page-release.mjs +13 -5
  27. package/scripts/road-drive-proof.mjs +269 -0
  28. package/scripts/road-memory-probe.mjs +129 -0
  29. package/scripts/scratch-dir.mjs +4 -4
  30. package/scripts/server-release/github.mjs +59 -26
  31. package/scripts/server-release/publish.mjs +15 -1
  32. package/scripts/server-release/sign.mjs +8 -4
  33. package/scripts/test_prebuilt_output.py +3 -1
  34. package/scripts/turn-in-shots.mjs +83 -0
  35. package/scripts/vitest-bench-observe-proof.py +168 -0
  36. package/scripts/vitest-bench.py +122 -77
  37. package/scripts/vps/rebuild.sh +3 -1
  38. package/scripts/worktree-reap.mjs +21 -9
  39. package/scripts/worktree.mjs +1 -1
  40. package/scripts/zone-gate-proof.mjs +93 -0
  41. package/src/client/engine/boot/sw.ts +3 -1
  42. package/src/client/engine/core/ktx2.ts +30 -9
  43. package/src/client/engine/models/place.ts +7 -5
  44. package/src/client/engine/pwa/sw.js +57 -2
  45. package/src/client/engine/render/precompile.ts +6 -0
  46. package/src/client/engine/render/tiers.ts +9 -0
  47. package/src/client/engine/ui/playerReload.ts +5 -5
  48. package/src/client/game/boot/bytes.generated.ts +4 -1
  49. package/src/client/game/boot/versions.generated.ts +8 -5
  50. package/src/client/game/grid/cellClip.ts +70 -6
  51. package/src/client/game/grid/gateCard.css +9 -0
  52. package/src/client/game/grid/gateCard.ts +67 -0
  53. package/src/client/game/grid/live.ts +17 -3
  54. package/src/client/game/grid/liveSession.ts +15 -5
  55. package/src/client/game/grid/neighbourLife.ts +10 -1
  56. package/src/client/game/grid/neighbourPanels.ts +29 -2
  57. package/src/client/game/grid/pageEntry.ts +21 -0
  58. package/src/client/game/grid/regionalWorld.ts +5 -0
  59. package/src/client/game/grid/roadCompressedSurfaces.ts +69 -0
  60. package/src/client/game/grid/roadLook.ts +5 -73
  61. package/src/client/game/grid/roadLookPlatform.ts +11 -6
  62. package/src/client/game/grid/roadSurfaceMaps.ts +80 -0
  63. package/src/client/game/grid/roadTilePool.ts +4 -0
  64. package/src/client/game/grid/session.ts +52 -12
  65. package/src/client/game/grid/softWallLook.ts +6 -1
  66. package/src/client/game/plugin/ui.ts +3 -0
  67. package/src/client/game/session/play.ts +3 -0
  68. package/src/client/game/shardfile/clientSource.ts +5 -2
  69. package/src/client/game/shardfile/clientWorker.ts +3 -2
  70. package/src/client/game/shardfile/slabLibrary.ts +37 -0
  71. package/src/client/game/shardfile/slabRanges.ts +145 -0
  72. package/src/client/host/online/shell.ts +2 -2
  73. package/src/client/host/standalone/shell.ts +4 -1
  74. package/src/server/game/grid/simulation.ts +27 -4
  75. package/src/server/game/plugin/simulation.ts +2 -0
  76. package/src/server/game/shardfile/dataRespawn.ts +47 -0
  77. package/src/server/host/standalone/cellWorld.ts +1 -1
  78. package/src/server/host/standalone/gridServer.ts +18 -6
  79. package/src/server/host/standalone/roadWorld.ts +30 -0
  80. package/src/server/host/standalone/serverHost.ts +2 -2
  81. package/src/shared/engine/entities/AnimalSim.ts +10 -0
  82. package/src/shared/engine/physics/transferWalls.ts +9 -4
  83. package/src/shared/game/grid/allocator.ts +8 -1
  84. package/src/shared/game/grid/gateCount.ts +27 -0
  85. package/src/shared/game/grid/zoneWalls.ts +64 -0
  86. package/src/shared/game/strings.ts +2 -0
  87. package/src/shared/host/standalone/harnessPlace.ts +4 -0
  88. package/src/test/engine/simState.ts +134 -0
  89. package/src/test/game/builtProduct.ts +6 -0
  90. package/src/test/game/headless/admittedProductCache.ts +61 -0
  91. package/src/test/game/headless/checkedReplayPipeline.ts +21 -0
  92. package/src/test/game/headless/nativeBounds.ts +27 -0
  93. package/src/test/game/headless/processUsage.ts +22 -0
  94. package/src/test/game/headless/productSession.ts +39 -0
  95. package/src/test/game/headless/ropeBodies.ts +60 -0
  96. package/src/test/game/headless/worker.ts +34 -0
  97. package/src/test/game/headlessNative.ts +114 -0
  98. package/src/test/game/headlessWorker.ts +43 -0
  99. package/src/test/tsconfig.game.json +3 -0
@@ -41,7 +41,7 @@ export function processDirectories(){
41
41
  }
42
42
  // From /, so lsof itself never shows up in the folder being checked.
43
43
  const listed=spawnSync('lsof',['-a','-d','cwd','-F','pn'],{cwd:'/',encoding:'utf8',maxBuffer:64<<20});
44
- if(listed.error!==undefined||listed.stdout==='')return undefined;
44
+ if(listed.error!==undefined||listed.status!==0||listed.stdout==='')return undefined;
45
45
  let pid=0;
46
46
  for(const line of listed.stdout.split('\n')){
47
47
  if(line.startsWith('p'))pid=Number(line.slice(1));
@@ -50,13 +50,14 @@ export function processDirectories(){
50
50
  return found;
51
51
  }
52
52
 
53
- /** pid -> parent pid and command line, from `ps`. @returns {Map<number,{ppid:number,command:string}>} */
53
+ /** pid -> parent pid and command line, from `ps`. @returns {Map<number,{ppid:number,state:string,command:string}>} */
54
54
  function processTable(){
55
- /** @type {Map<number,{ppid:number,command:string}>} */const table=new Map();
56
- const listed=spawnSync('ps',['-Ao','pid=,ppid=,command='],{encoding:'utf8',maxBuffer:64<<20});
55
+ /** @type {Map<number,{ppid:number,state:string,command:string}>} */const table=new Map();
56
+ const listed=spawnSync('ps',['-Ao','pid=,ppid=,stat=,command='],{encoding:'utf8',maxBuffer:64<<20});
57
+ if(listed.error!==undefined||listed.status!==0)throw new Error('process table unreadable');
57
58
  for(const line of (listed.stdout??'').split('\n')){
58
- const match=/^\s*(\d+)\s+(\d+)\s(.*)$/u.exec(line);
59
- if(match!==null)table.set(Number(match[1]),{ppid:Number(match[2]),command:match[3]??''});
59
+ const match=/^\s*(\d+)\s+(\d+)\s+(\S+)\s(.*)$/u.exec(line);
60
+ if(match!==null)table.set(Number(match[1]),{ppid:Number(match[2]),state:match[3]??'',command:match[4]??''});
60
61
  }
61
62
  return table;
62
63
  }
@@ -71,10 +72,10 @@ function processTable(){
71
72
  * @returns {number[]} */
72
73
  export function stopWorktreeProcesses(tree,options={}){
73
74
  const directories=processDirectories();
74
- if(directories===undefined)return [];
75
+ if(directories===undefined)throw new Error('process directories unreadable');
75
76
  const table=processTable(),spared=new Set();
76
- // Without the table nothing tells land's own parents apart (J206 review): stop nothing.
77
- if(!table.has(process.pid))return [];
77
+ // Without the table nothing tells land's own parents apart: retain the tree.
78
+ if(!table.has(process.pid))throw new Error('process ancestry unreadable');
78
79
  for(let pid=process.pid;pid>1&&!spared.has(pid);pid=table.get(pid)?.ppid??0)spared.add(pid);
79
80
  const shell=(/** @type {string} */ command)=>/^-?(?:\S*\/)?(?:ba|z|da|fi|k|tc|c)?sh$/u.test(command.trim());
80
81
  // Only processes whose own working directory is inside: a daemon's children elsewhere are not this worktree's.
@@ -86,6 +87,17 @@ export function stopWorktreeProcesses(tree,options={}){
86
87
  const until=Date.now()+3000,nap=new Int32Array(new SharedArrayBuffer(4));
87
88
  while(Date.now()<until&&pids.some(pid=>signal(pid,0)))Atomics.wait(nap,0,0,50);
88
89
  for(const pid of pids)signal(pid,'SIGKILL');
90
+ const killedUntil=Date.now()+1000;
91
+ let remaining=pids;
92
+ do{
93
+ const current=processTable();
94
+ // Exited children may remain zombies until their blocked parent reaps them.
95
+ // They cannot write; a live or uninspectable process still retains the tree.
96
+ remaining=pids.filter(pid=>current.get(pid)?.state.startsWith('Z')===false);
97
+ if(remaining.length===0)break;
98
+ Atomics.wait(nap,0,0,25);
99
+ }while(Date.now()<killedUntil);
100
+ if(remaining.length>0)throw new Error('a worktree process is still alive');
89
101
  return pids;
90
102
  }
91
103
 
@@ -401,7 +401,7 @@ export function worktreeNew(argv,cwd=process.cwd(),env=process.env){
401
401
  let receiptOffset=null;
402
402
  try{receiptOffset=statSync(env.WS_LANE_RECEIPTS??join(homedir(),'.cache/wildshard/lane-receipts.log')).size;}
403
403
  catch(error){if(error instanceof Error&&'code'in error&&error.code==='ENOENT')receiptOffset=0;}
404
- const owner={lane,session:env.CLAUDE_SESSION_ID??env.CLAUDE_CODE_SESSION_ID??env.CODEX_THREAD_ID??lane,agent:env.CLAUDE_SESSION_ID||env.CLAUDE_CODE_SESSION_ID?'claude':env.CODEX_THREAD_ID||lane?'codex':'unknown',row:options.row??env.WS_PLAN_ROW??null,created,activeHours:null,receiptOffset};
404
+ const owner={lane,session:env.CODEX_THREAD_ID??env.CLAUDE_SESSION_ID??env.CLAUDE_CODE_SESSION_ID??lane,agent:env.CODEX_THREAD_ID?'codex':env.CLAUDE_SESSION_ID||env.CLAUDE_CODE_SESSION_ID?'claude':lane?'codex':'unknown',row:options.row??env.WS_PLAN_ROW??null,created,activeHours:null,receiptOffset};
405
405
  writeFileSync(join(tree,'.owner'),`${JSON.stringify(owner,null,2)}\n`,{flag:'wx'});
406
406
  mkdirSync(join(tree,'tmp'),{recursive:true});
407
407
  writeFileSync(join(tree,'tmp/worktree-setup.json'),`${JSON.stringify(record,null,2)}\n`);
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ // ZONE-ENTRY ZE5 and ZE8 (J352): the walls and the gate card, by real input. From Driftwood (Shard Select), step out of its east
3
+ // entryway onto the road and shoot Nalati's wall across it; walk into Nalati's west buffer and shoot the gate card at 5 and at 2;
4
+ // at 3 back out and shoot it gone; walk in again, read 5 (the reset) and shoot it at 2. Each shot's page state (the gate's cell, count and card text)
5
+ // goes in one JSON. `--fire` stands on to 0 and records the zone entry: the navigation, the loading screen and the cell as the new home (ZE10).
6
+ // scripts/browser-lane.sh node scripts/zone-gate-proof.mjs --base=<preview or loopback url> --out=<dir> [--device='iPhone 15 Pro'] [--viewport=2992x1434@2]
7
+ // The walker is set 20 m inside Driftwood's east entryway by the in-page harness pose, so preview or a loopback page only (J205).
8
+ import { mkdirSync, writeFileSync } from 'node:fs';
9
+ import { join, resolve as absolute } from 'node:path';
10
+ import { chromium, devices, webkit } from 'playwright';
11
+ import { KEYCHAIN_ARGS } from './chromium-keychain.mjs';
12
+ import { saveFixture } from './debug-settings.mjs';
13
+
14
+ /** @param {string} name @param {string} fallback */
15
+ const flag = (name, fallback) => process.argv.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback;
16
+ const base = flag('base', '').replace(/\/$/u, ''), out = absolute(flag('out', '')), engineName = flag('engine', 'chromium'), device = flag('device', ''), fire = process.argv.includes('--fire');
17
+ if (!/^https:\/\/preview\.wildshard\.io$|^http:\/\/127\.0\.0\.1:\d+$/u.test(base) || out === absolute('')) throw new Error('usage: zone-gate-proof.mjs --base=<preview or loopback url> --out=<dir>');
18
+ const desk = (/^(\d+)x(\d+)@([\d.]+)$/u.exec(flag('viewport', '2992x1434@2')) ?? [0, '2992', '1434', '2']).slice(1).map(Number);
19
+ const sleep = (/** @type {number} */ ms) => new Promise(resolve => { setTimeout(resolve, ms); });
20
+ const HALF = 250;
21
+ mkdirSync(out, { recursive: true });
22
+ const tag = `${engineName}${device === '' ? '' : '-phone'}`;
23
+ const result = { base, engine: engineName, viewport: '', at: new Date().toISOString(), build: '', shots: /** @type {Record<string, unknown>[]} */ ([]), fired: /** @type {unknown} */ (null), errors: /** @type {string[]} */ ([]), note: '' };
24
+ const browser = await (engineName === 'webkit' ? webkit : chromium).launch({ headless: true, args: engineName === 'chromium' ? [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist'] : [] });
25
+ let code = 1;
26
+ try {
27
+ result.build = await fetch(`${base}/version.json`).then(async found => String((await found.json()).build)).catch(() => '');
28
+ const phone = device === '' ? undefined : devices[device];
29
+ if (device !== '' && phone === undefined) throw new Error(`No Playwright device ${device}`);
30
+ result.viewport = phone === undefined ? `${String(desk[0])}x${String(desk[1])}@${String(desk[2])}` : `${device} ${String(phone.viewport.width)}x${String(phone.viewport.height)}@${String(phone.deviceScaleFactor)}`;
31
+ const context = await browser.newContext(phone ?? { viewport: { width: desk[0] ?? 2992, height: desk[1] ?? 1434 }, deviceScaleFactor: desk[2] ?? 2 }), page = await context.newPage();
32
+ page.on('pageerror', error => { result.errors.push(error.message.slice(0, 240)); });
33
+ await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
34
+ await saveFixture(context, { scope: 'device', key: 'devMode', data: true });
35
+ await saveFixture(context, { scope: 'global', key: 'settings', merge: true, data: { volume: 0 } });
36
+ await page.goto(`${base}/?mute=1&nolock=1`, { waitUntil: 'load' });
37
+ await page.locator('.ws-main-select').click({ timeout: 120_000 });
38
+ if (await page.locator('#ws-name-box input').waitFor({ timeout: 30_000 }).then(() => true).catch(() => false)) { await page.locator('#ws-name-box input').fill('gate'); await page.locator('#ws-name-box button[type=submit]').click(); }
39
+ await page.locator('.ws-menu-card').first().waitFor({ state: 'visible', timeout: 30_000 });
40
+ const index = await page.evaluate(() => [...document.querySelectorAll('.ws-menu-card')].findIndex(row => (row.textContent ?? '').includes('Driftwood Isle')));
41
+ if (index < 0) throw new Error('No Driftwood Isle card');
42
+ await page.locator('.ws-menu-dots i').nth(index).click();
43
+ await page.locator('.ws-menu-play').click();
44
+ await page.waitForFunction(() => /** @type {any} */ (window).__wildshard?.shard?.grid?.state?.().live?.live?.gameplayReady === true, undefined, { timeout: 180_000, polling: 100 });
45
+ await sleep(2000);
46
+ await page.getByText('DONE', { exact: true }).click({ timeout: 2000 }).catch(() => undefined);
47
+ const state = () => page.evaluate(() => { const W = /** @type {any} */ (window), st = W.__wildshard.shard.grid.state(), wf = st.live?.live?.worldFeet ?? W.__wildshard.world.player.position; return { x: Number(wf.x.toFixed(2)), z: Number(wf.z.toFixed(2)), gate: st.gate ?? null, walls: st.softWalls ?? null, inside: st.inside, cur: st.live?.live?.current ?? null }; });
48
+ const origin = await page.evaluate(() => { const W = /** @type {any} */ (window), wf = W.__wildshard.shard.grid.state().live.live.worldFeet, p = W.__wildshard.world.player.position; return { x: wf.x - p.x, z: wf.z - p.z }; });
49
+ const pitch = 562.5, nalatiEdge = origin.x + pitch - HALF;
50
+ const face = (/** @type {number} */ yaw) => page.evaluate(wanted => { /** @type {any} */ (window).__wildshard.world.player.yaw = wanted; }, yaw);
51
+ /** Walk with W held toward x (along z = origin.z) until within 0.4 m. */
52
+ const walkTo = async (/** @type {number} */ x) => {
53
+ for (const ends = Date.now() + 60_000; Date.now() < ends;) {
54
+ const at = await state(); if (Math.abs(at.x - x) < 0.4) break;
55
+ await face(Math.atan2(at.x - x, at.z - origin.z)); await page.keyboard.down('KeyW'); await sleep(Math.min(400, Math.abs(at.x - x) * 200)); await page.keyboard.up('KeyW');
56
+ }
57
+ };
58
+ const shoot = async (/** @type {string} */ name) => { await page.screenshot({ path: join(out, `${tag}-${name}.png`) }); result.shots.push({ name, ...await state() }); };
59
+ await page.evaluate(([px, pz]) => { const p = /** @type {any} */ (window).__wildshard.world.player; p.spawn(px, pz, p.yaw, 1.5); p.link?.place?.(p.position.x, p.position.y, p.position.z, p.yaw); }, [HALF - 20, 0]);
60
+ await sleep(4000);
61
+ await walkTo(origin.x + HALF + 31.25); await face(-Math.PI / 2); await sleep(1500);
62
+ await shoot('road-wall');
63
+ /** Poll the gate until `test` holds (or 8 s). */
64
+ const until = async (/** @type {(gate: any) => boolean} */ test) => { for (const ends = Date.now() + 8000; Date.now() < ends; await sleep(50)) if (test((await state()).gate)) return true; return false; };
65
+ // in, 2 m past the edge line: the card at 5; back out of the buffer at 3 (so the count can't reach 0 on the way out)
66
+ await walkTo(nalatiEdge + 2); await until(gate => gate?.count === 5); await shoot('gate-5');
67
+ await until(gate => gate?.count === 3);
68
+ await walkTo(nalatiEdge - 6); await face(-Math.PI / 2); await sleep(600);
69
+ await shoot('backed-away');
70
+ // in again: 5 (the reset), then 2
71
+ await walkTo(nalatiEdge + 2); await until(gate => gate?.count === 5); await shoot('gate-again');
72
+ await until(gate => gate?.count === 2); await shoot('gate-2');
73
+ if (fire) {
74
+ // stand on: 0 opens the loading screen and the page enters the cell as its home
75
+ const before = page.url();
76
+ const left = await page.waitForEvent('framenavigated', { timeout: 6000 }).then(() => true).catch(() => false);
77
+ await page.screenshot({ path: join(out, `${tag}-gate-0-loading.png`) }).catch(() => undefined);
78
+ const ready = await page.waitForFunction(() => /** @type {any} */ (window).__wildshard?.shard?.grid?.state?.().live?.live?.gameplayReady === true, undefined, { timeout: 180_000, polling: 250 }).then(() => true).catch(() => false);
79
+ const home = await page.evaluate(() => { const W = /** @type {any} */ (window), st = W.__wildshard?.shard?.grid?.state?.(); return { home: st?.live?.live?.home ?? st?.home ?? null, current: st?.live?.live?.current ?? null, slug: W.__wildshard?.shard?.slug ?? null }; }).catch(() => null);
80
+ if (ready) await page.screenshot({ path: join(out, `${tag}-entered.png`) });
81
+ result.fired = { navigated: left, before, after: page.url(), ready, home };
82
+ }
83
+ const named = (/** @type {string} */ name) => /** @type {any} */ (result.shots.find(row => row.name === name))?.gate;
84
+ const [at5, gone, again, at2] = ['gate-5', 'backed-away', 'gate-again', 'gate-2'].map(named);
85
+ console.log(JSON.stringify({ at5, at2, gone, again, fired: result.fired }));
86
+ await context.close();
87
+ code = at5?.count === 5 && at2?.count === 2 && gone?.cell === null && again?.count === 5 && result.errors.length === 0 && (!fire || /** @type {any} */ (result.fired)?.ready === true) ? 0 : 1;
88
+ } catch (error) { result.note = String(error).slice(0, 400); console.log(`FAIL ${result.note}`); }
89
+ finally {
90
+ writeFileSync(join(out, `${tag}-zone-gate.json`), `${JSON.stringify(result, null, 2)}\n`);
91
+ await browser.close();
92
+ }
93
+ process.exit(code);
@@ -348,6 +348,8 @@ function askPrecache(): void {
348
348
  };
349
349
  ask(reg.active);
350
350
  if (reg.waiting?.state === 'installed') post(reg.waiting);
351
+ // STALESHELL: an update installing now downloads its generation in its install (sw.js); this page's control resumes it too
352
+ if (reg.installing !== null && reg.active !== null) post(reg.installing);
351
353
  const installing = reg.installing;
352
354
  ask(installing); // it may have activated while the control frames ran
353
355
  if (!precacheAsked && installing !== null) pageScope.listen(installing, 'statechange', () => { ask(installing); });
@@ -385,7 +387,7 @@ async function register(s: ServiceWorkerContainer): Promise<void> {
385
387
  watch(reg);
386
388
  // DL1 (sp-x2): this page is loading. A waiting update (and the active worker, when this page is uncontrolled) sees
387
389
  // none of its fetches, so tell them to step their precache aside; this page's control resumes it (PRECACHE).
388
- if (!controlReached) for (const w of [reg.waiting, sw?.controller === null ? reg.active : null]) {
390
+ if (!controlReached) for (const w of [reg.waiting, reg.active === null ? null : reg.installing, sw?.controller === null ? reg.active : null]) {
389
391
  // oxlint-disable-next-line unicorn/require-post-message-target-origin -- ServiceWorker.postMessage has no targetOrigin parameter.
390
392
  if (w !== null && w !== undefined) try { w.postMessage({ type: 'PAUSE' }); } catch { /* a retired worker has nothing to pause */ }
391
393
  }
@@ -43,9 +43,17 @@ import { parseKtx2 } from '@wildshard/format/ktx2Cost';
43
43
  import { waitFor } from '../../../shared/engine/boot/waits';
44
44
  import { bootTask } from '../../../shared/engine/boot/timing';
45
45
 
46
- /** where scripts/app-build/basis.ts copies three's transcoder: versioned by three's revision, so the SW / HTTP caches never mix two */
47
46
  /** Before transcoding `files`: start what their parses will need (the raw-texel zstd decoder) from the caller's stack. */
48
47
  export function prepareKtx2Decode(files: Iterable<Uint8Array | undefined>): void { prepareKtx2Zstd(files); }
48
+ /** Whether a named native WebGL compressed format sampled correctly at every mip on this device.
49
+ * The name is a format label from the texture capability probe, for example SRGB8_ALPHA8_ASTC_6x6.
50
+ * Unknown formats and a device without a completed WebGL2 probe return false. */
51
+ export function nativeCompressedFormatSupported(format: string): boolean {
52
+ const probe = ktx2Probe();
53
+ return probe.ran && probe.formats.some(row => row.format === format && row.ok);
54
+ }
55
+
56
+ /** The transcoder path is versioned by three's revision, keeping SW and HTTP caches compatible. */
49
57
  export const BASIS_PATH: Parameters<KTX2Loader['setTranscoderPath']>[0] = `/basis/r${THREE.REVISION}/`;
50
58
 
51
59
  let loader: KTX2Loader | null = null;
@@ -305,21 +313,33 @@ const reading = new Map<string, Promise<ArrayBuffer>>();
305
313
  * ReadableStream nobody here listens to (T10: its enqueue / close were ~200 ms of a Pine cold entry at phone 4x). Same
306
314
  * URL resolution (the page's modifier on the default manager), credentials, headers and status rule, then the loader's
307
315
  * own parse. */
308
- export function loadKtx2(target: Pick<KTX2Loader, 'manager' | 'path' | 'requestHeader' | 'withCredentials' | 'parse'>, url: string): Promise<THREE.CompressedTexture> {
316
+ export function loadKtx2(target: Pick<KTX2Loader, 'manager' | 'path' | 'requestHeader' | 'withCredentials' | 'parse'>, url: string, signal?: AbortSignal): Promise<THREE.CompressedTexture> {
317
+ signal?.throwIfAborted();
309
318
  const resolved = target.manager.resolveURL(target.path + url);
310
- let bytes = reading.get(resolved);
319
+ let bytes = signal === undefined ? reading.get(resolved) : undefined;
311
320
  if (bytes === undefined) {
312
- bytes = bootTask(`texture:read ${resolved}`, () => waitFor('Reading texture', fetch(resolved, { headers: target.requestHeader, credentials: target.withCredentials ? 'include' : 'same-origin' }).then(response => {
321
+ bytes = bootTask(`texture:read ${resolved}`, () => waitFor('Reading texture', fetch(resolved, {
322
+ headers: target.requestHeader, credentials: target.withCredentials ? 'include' : 'same-origin',
323
+ ...(signal === undefined ? {} : {signal}),
324
+ }).then(response => {
313
325
  if (response.status !== 200 && response.status !== 0) throw new Error(`fetch for "${response.url}" responded with ${String(response.status)}: ${response.statusText}`);
314
326
  return response.arrayBuffer();
315
327
  }), 'file', resolved));
316
- reading.set(resolved, bytes);
328
+ if (signal === undefined) reading.set(resolved, bytes);
317
329
  const read = bytes;
318
330
  const clear = (): void => { if (reading.get(resolved) === read) reading.delete(resolved); };
319
331
  read.finally(clear).catch(() => undefined);
320
332
  }
321
- return bytes.then(buffer => bootTask(`texture:decode ${resolved}`, () => waitFor('Preparing texture', new Promise<THREE.CompressedTexture>((resolve, reject) => { target.parse(buffer, resolve, reject); }), 'worker', resolved)));
333
+ return bytes.then(buffer => {
334
+ signal?.throwIfAborted();
335
+ return bootTask(`texture:decode ${resolved}`, () => waitFor('Preparing texture', new Promise<THREE.CompressedTexture>((resolve, reject) => {
336
+ target.parse(buffer, texture => {
337
+ if (signal?.aborted === true) { texture.dispose(); reject(new Error('KTX2 read aborted', {cause: signal.reason})); } else resolve(texture);
338
+ }, reject);
339
+ }), 'worker', resolved));
340
+ });
322
341
  }
342
+
323
343
  function load(url: string, keep: boolean): Promise<THREE.CompressedTexture> {
324
344
  let p = transcoded.get(url);
325
345
  if (p === undefined) {
@@ -336,11 +356,12 @@ function load(url: string, keep: boolean): Promise<THREE.CompressedTexture> {
336
356
  * A KTX2 file at its own URL (a shardfile product's named blob, not the stand-in of another file) as a CompressedTexture
337
357
  * on the page's loader, in any texture mode: one transcode per file per wave, flipY = false (the file keeps its encoded
338
358
  * orientation), its mips dropped from JS once uploaded. The caller sets its sampler and colour space, then fences it with
339
- * `prepareCompressedTexture`.
359
+ * `prepareCompressedTexture`. An optional signal owns an isolated, cancellable read.
340
360
  */
341
- export async function ktx2File(url: string): Promise<THREE.CompressedTexture> {
361
+ export async function ktx2File(url: string, signal?: AbortSignal): Promise<THREE.CompressedTexture> {
342
362
  if (texMode() !== 'ktx2') markGpuOnly('KTX2 product files on the image path (their mips are dropped from JS once uploaded)');
343
- const t = (await load(url, true)).clone();
363
+ // Cancellable callers own their read and parsed texture; abort cannot cancel a shared wave.
364
+ const t = signal === undefined ? (await load(url, true)).clone() : await loadKtx2(ktx2Loader(), url, signal);
344
365
  t.flipY = false;
345
366
  t.generateMipmaps = false;
346
367
  sources.share(t, url, 0);
@@ -36,6 +36,7 @@ import { FrameCamera } from '../world/frameCamera';
36
36
  import { geometryBoundsSteps } from '../world/geometryBounds';
37
37
  import { keepShadowWhole } from '../world/shadowChunks';
38
38
  import { withTier } from '../explore/tiers';
39
+ import { TIER_CONFIG } from '../core/tier';
39
40
  import { loadingSpecimen } from './gear';
40
41
  import { specimenReady, paramsOf, seedOf, type ModelBuild, type ModelBuildVisit, type ModelContext, type ModelDef, type ModelPart, type Placement } from './model';
41
42
  import { drawnHullOwn, drawnHullWorld, placeCollider, poseGeometry, poseOf, type Pose } from './colliders';
@@ -423,10 +424,11 @@ function collideCopy<P extends object>(def: ModelDef<P>, params: P, pose: Pose,
423
424
  }
424
425
  }
425
426
 
426
- /** level start distances: 0 for the model's own parts, then each LOD's `from` */
427
- const levelsOf = <P extends object>(def: ModelDef<P>): number[] => [0, ...(def.lods ?? []).map((l) => l.from)];
428
- /** each level's dissolve band before its start (`ModelLod.fade`; level 0 has none) */
429
- const fadesOf = <P extends object>(def: ModelDef<P>): number[] => [0, ...(def.lods ?? []).map((l) => l.fade ?? 0)];
427
+ /** level start distances: 0 for the model's own parts, then each LOD's `from`, times the tier's `placedLodScale` (NB5: the
428
+ * phone's smaller pixels per metre switch levels nearer; the desktop's 1 keeps the authored distances) */
429
+ const levelsOf = <P extends object>(def: ModelDef<P>): number[] => [0, ...(def.lods ?? []).map((l) => l.from * TIER_CONFIG.placedLodScale)];
430
+ /** each level's dissolve band before its start (`ModelLod.fade`; level 0 has none), scaled with its start */
431
+ const fadesOf = <P extends object>(def: ModelDef<P>): number[] => [0, ...(def.lods ?? []).map((l) => (l.fade ?? 0) * TIER_CONFIG.placedLodScale)];
430
432
 
431
433
  /** A callback belongs to one place call, so nested builders cannot mix their copies. */
432
434
  type BuildOptions<P extends object> = PlaceOptions & { readonly visitBuild?: (build: ModelBuildVisit<P>) => void };
@@ -908,7 +910,7 @@ function drawSingle<P extends object>(def: ModelDef<P>, pls: readonly Placement<
908
910
  lod.addLevel(obj, 0);
909
911
  (def.lods ?? []).forEach((l, k) => {
910
912
  const lp = partsOf(buildModel(def, o, p, new Rng(seedOf(def) ^ Math.imul(k + 1, 0x9e3779b9)), pls.slice(i, i + 1), k + 1), def.id, o.draw);
911
- lod.addLevel(lp.length === 0 ? new THREE.Object3D() : wrap(lp.map((x) => meshOf(x)), `${def.id}:lod${k + 1}`), l.from);
913
+ lod.addLevel(lp.length === 0 ? new THREE.Object3D() : wrap(lp.map((x) => meshOf(x)), `${def.id}:lod${k + 1}`), l.from * TIER_CONFIG.placedLodScale);
912
914
  });
913
915
  obj = lod;
914
916
  }
@@ -160,9 +160,35 @@ workerScope.listen(self, 'install', event => {
160
160
  const namedShell = SHELL_FILES.filter(path => immutable(new URL(abs(path))));
161
161
  await Promise.all([precache(shell, SHELL_FILES.filter(path => !namedShell.includes(path))),
162
162
  precache(assets, namedShell, true)]);
163
+ // STALESHELL (QA 11-15 row 32, Jake: "the cache PWA one has to swap out new code"): an update (a worker already runs
164
+ // this origin) takes over by itself, so the next boot is the new build and nobody waits on a reload that never
165
+ // activates it. When the running build is whole on this device (its generation is held, so it boots offline), the new
166
+ // one first downloads its own whole generation here, in the background while the player plays; a download cut short
167
+ // (bad Wi-Fi) fails the install, the running build stays whole and nothing of the new one boots, and the browser's next
168
+ // update check resumes from what the shared cache already holds. A running build that is not whole has nothing to keep:
169
+ // it can't boot offline, and its document names code a newer deploy took off the server (Jake's phone sat on v0.1.19's
170
+ // title through every reload), so the new worker takes over after its shell. A first visit stays shell-only (DL1).
171
+ const running = self.registration?.active;
172
+ if (running === null || running === undefined) return;
173
+ const runningBuild = await buildOfWorker(running);
174
+ if (runningBuild !== undefined && await (await caches.open(BOOKS)).match(bookKey(runningBuild)) !== undefined) await precacheGeneration();
175
+ await self.skipWaiting();
163
176
  })());
164
177
  });
165
178
 
179
+ /** The build a worker serves (its `BUILD` reply, which every worker since the MF1 rewrite answers), or undefined after 3 s. */
180
+ function buildOfWorker(worker) {
181
+ return new Promise(resolve => {
182
+ workerScope.timeout(3000, () => { resolve(undefined); }); // the first answer wins
183
+ const done = build => { resolve(build); };
184
+ try {
185
+ const channel = new MessageChannel();
186
+ channel.port1.onmessage = event => { done(typeof event.data?.build === 'string' && event.data.build !== '' ? event.data.build : undefined); };
187
+ worker.postMessage({ type: 'BUILD' }, [channel.port2]);
188
+ } catch { done(undefined); }
189
+ });
190
+ }
191
+
166
192
  // DL1: the build's hashed code is precached only when a page reports control (PRECACHE), so a cold visit's level
167
193
  // download has the link to itself. Chunks that page already loaded come from the HTTP cache (force-cache).
168
194
  // Only a completely precached build is a generation; a failed precache never evicts working code and is asked again.
@@ -431,6 +457,33 @@ async function contentRead(request) {
431
457
  return response;
432
458
  }
433
459
 
460
+ /** The document baked into this worker: its build's own page, whatever URL asked (the page reads its route from the URL). */
461
+ const bakedDocument = () => new Response(DOCUMENT, { headers: { ...DOCUMENT_HEADERS, 'content-type': 'text/html;charset=utf-8', 'cache-control': 'no-store' } });
462
+ /** STALESHELL: how long a navigation waits on the network before a worker whose code is not all held answers with its own
463
+ * document anyway (offline, or a link that never answers). */
464
+ const NAVIGATION_WAIT_MS = 6000;
465
+ let generationHeld = false;
466
+ /** Whether this build's whole generation is held (its book is written only once every file is). Only a yes is remembered. */
467
+ async function holdsGeneration() {
468
+ if (generationHeld) return true;
469
+ try { generationHeld = await (await store(BOOKS)).match(bookKey(BUILD)) !== undefined; } catch { return false; }
470
+ return generationHeld;
471
+ }
472
+ /** STALESHELL (QA 11-15 row 32: Jake's phone sat on v0.1.19's title for good, "8 of 8 files", then "still waiting"): this
473
+ * worker answers a navigation with its own document only when it holds that document's whole generation, so the page boots
474
+ * complete from the cache, offline too. A worker that holds less (it never reached control on this build) can't promise the
475
+ * code its document names, and a newer deploy has removed it from the server: the network's page answers, and the baked
476
+ * document only when the network can't (offline, or no answer in NAVIGATION_WAIT_MS). The request's own URL is kept either
477
+ * way: a `/slug/<x>` stays itself.
478
+ * @param {Request} request */
479
+ async function navigation(request) {
480
+ if (await holdsGeneration()) return bakedDocument();
481
+ const waited = new Promise(resolve => { workerScope.timeout(NAVIGATION_WAIT_MS, () => { resolve(undefined); }); });
482
+ const online = fetch(request).then(response => response.type === 'opaqueredirect' || response.ok && isHtml(response) ? response : undefined,
483
+ () => undefined);
484
+ return await Promise.race([online, waited]) ?? bakedDocument();
485
+ }
486
+
434
487
  workerScope.listen(self, 'fetch', event => {
435
488
  const request = event.request, url = new URL(request.url);
436
489
  // A diagnostic document must reach its own host route, not the cached game
@@ -447,8 +500,10 @@ workerScope.listen(self, 'fetch', event => {
447
500
  if (url.pathname === '/version.json' || url.pathname === '/sw.js' || url.pathname.startsWith('/api/')) return;
448
501
  if (request.mode === 'navigate' || url.pathname === '/' || url.pathname === '/index.html') {
449
502
  const received=diagnosticNow();
450
- event.respondWith(new Response(DOCUMENT, { headers: { ...DOCUMENT_HEADERS, 'content-type': 'text/html;charset=utf-8', 'cache-control': 'no-store' } }));
451
- bootPublish(event,[{operation:'sw:navigation-handler-and-delivery',url:request.url,start:received,end:diagnosticNow(),result:'complete'}]);
503
+ event.respondWith(navigation(request).then(response => {
504
+ bootPublish(event,[{operation:'sw:navigation-handler-and-delivery',url:request.url,start:received,end:diagnosticNow(),result:'complete'}]);
505
+ return response;
506
+ }));
452
507
  return;
453
508
  }
454
509
  if (PAGE_PART.test(url.pathname)) {
@@ -121,6 +121,12 @@ export function registerExteriorLighting(scene: THREE.Scene, owner: Scope, root:
121
121
  owner.onDispose(() => { held.roots.delete(root); if (held.roots.size === 0) exteriorLighting.delete(scene); });
122
122
  }
123
123
 
124
+ /** The exterior lighting a scene declares (`registerExteriorLighting`): its root count and environment height, for proofs. */
125
+ export function exteriorLightingState(scene: THREE.Object3D): { readonly roots: number; readonly environment: unknown } | null {
126
+ const state = exteriorLighting.get(scene as THREE.Scene);
127
+ return state === undefined ? null : { roots: state.roots.size, environment: state.environment === null ? null : Reflect.get(state.environment.image ?? {}, 'height') };
128
+ }
129
+
124
130
  /** Hidden registered siblings cannot draw on this entered frame. Keep its entire hierarchy and any visible roots;
125
131
  * ordinary boot has no exclusion. Borrowed roots and their visibility are never changed. */
126
132
  export function entryFrameExclusions(scene: THREE.Scene, future?: THREE.Object3D): ReadonlySet<THREE.Object3D> | undefined {
@@ -49,6 +49,13 @@ export const TIER_TABLE = {
49
49
  // every PMREM environment's cube size (pmremSize.ts; 0 = each source's own): one size, so no lit program compiles twice
50
50
  // for two shards' environments (the HDR backdrops' 128 cube, a 512-wide equirect, drawn at Driftwood's 64)
51
51
  pmremCube: 64,
52
+ // NINE-DRAGON-BENCHMAX NB5 (mini-ninefps, 2026-11-15): a placed model's LOD start distances times this. The phone's
53
+ // portrait camera (vertical FOV ~100°, 874 px at 1×) draws a copy at 0.36× the desktop window's pixels per metre
54
+ // (1496x717 @2, ~70°), 0.72× at 2×: at 0.6 every level still switches at about the projected size the desktop switches at
55
+ placedLodScale: 0.6,
56
+ // NINE-DRAGON-BENCHMAX NB8 (mini-ninetris, 2026-11-15): a resident slab chunk's triangles in k-d order, drawn as the run
57
+ // its camera can see (`slabRanges.ts`): Nine's phone spawn view 0.56 to ~0.47 M slab triangles, other views ~half
58
+ slabRanges: true,
52
59
  },
53
60
  desktop: {
54
61
  maxTexture: 4096, layerSize: 1024, dpr: 1.5, ao: true,
@@ -74,6 +81,8 @@ export const TIER_TABLE = {
74
81
  pickupItemDist: 90, pickupOrbDist: 200,
75
82
  godRaysSamples: 60, godRaysScale: 0.5, volumetricSteps: 14, volumetricScale: 1, smaa: 'high' as 'off' | 'low' | 'high', bloomLevels: 8,
76
83
  pmremCube: 0,
84
+ placedLodScale: 1,
85
+ slabRanges: false,
77
86
  },
78
87
  };
79
88
 
@@ -13,14 +13,15 @@ import { leaveAfterPaint } from '../boot/leaveAfterPaint';
13
13
  *
14
14
  * RL3: the tap's own turn turns the control into a loading button and puts the full-page RELOADING cover up
15
15
  * (src/client/engine/ui/reloadCover.ts), before the save, the worker or anything else is awaited. The cover stays until
16
- * the page unloads. RL2: on the title it loads a fresh `/`, anywhere else the page reloads where it is.
16
+ * the page unloads. The page reloads where it is, its path, query and hash kept (Jake, 2026-11-15: "Tap to reload does not
17
+ * respect the URL ... I was on /slug/blender-template"; this replaces RL2's fresh `/` on the title).
17
18
  * QC3: a waiting worker is activated first (SKIP_WAITING, then its `activated` state) so the next document is the new
18
19
  * build's. RL5: that hand-over gets RELOAD_FALLBACK_MS from the tap; past it the page reloads hard and the cover says so.
19
20
  * Nothing to adopt (no worker, or it retired) is a plain reload. Every path ends in a navigation, one painted frame after
20
21
  * the cover (leaveAfterPaint).
21
22
  */
22
23
 
23
- /** The title (or its menus) is up: the reload lands on a fresh `/` rather than where the page is. */
24
+ /** The title (or its menus) is up: only what the next boot records differs; the reload keeps the URL either way. */
24
25
  export function titleShowing(): boolean {
25
26
  return document.querySelector('#hud.intro .ws-menu:not(.hide), #hud.intro .ws-main:not(.hide)') !== null;
26
27
  }
@@ -38,8 +39,7 @@ export function reloadForPlayer(control: HTMLElement | null, { newer = false, wh
38
39
  gone = true;
39
40
  leaveAfterPaint(() => {
40
41
  leftByPlayer(); markReload(reason);
41
- if (title) location.replace('/');
42
- else location.reload();
42
+ location.reload();
43
43
  });
44
44
  };
45
45
  if (sw === undefined) { leaveSaved(plain); return; }
@@ -49,7 +49,7 @@ export function reloadForPlayer(control: HTMLElement | null, { newer = false, wh
49
49
  // the hand-over ran out of time (not merely "nothing to adopt"): say so, in amber, on the way out
50
50
  const hard = (): void => { if (diagnosticNow() - tapped >= RELOAD_FALLBACK_MS - 50) reloadingLine(engineString('s_reloading_slow'), 'slow'); plain(); };
51
51
  if (left <= 0) { hard(); return; }
52
- void sw.adopt(title ? '/' : undefined, reason, left)
52
+ void sw.adopt(undefined, reason, left)
53
53
  .then(sent => { if (sent) gone = true; else hard(); return undefined; }, hard);
54
54
  });
55
55
  }
@@ -51,7 +51,7 @@ export const PUBLIC_BYTES = {
51
51
  "/assets/baked/ink-cel-valley/far.json": 949,
52
52
  "/assets/baked/ink-cel-valley/near.glb": 907100,
53
53
  "/assets/baked/ink-cel-valley/near.json": 461,
54
- "/assets/baked/nalati-grasslands/far-impostor.png": 40666,
54
+ "/assets/baked/nalati-grasslands/far-impostor.png": 40285,
55
55
  "/assets/baked/nalati-grasslands/far.glb": 239660,
56
56
  "/assets/baked/nalati-grasslands/far.json": 957,
57
57
  "/assets/baked/nalati-grasslands/near.glb": 3863736,
@@ -440,6 +440,9 @@ export const PUBLIC_BYTES = {
440
440
  "/assets/gpu/tex/wood_trunk_wall/arm_1k.phone-b7f1d0ec.ktx2": 43664,
441
441
  "/assets/gpu/tex/wood_trunk_wall/diffuse-3e7ff479.ktx2": 4796570,
442
442
  "/assets/gpu/tex/wood_trunk_wall/nor_gl-e1b1ecf7.ktx2": 5098654,
443
+ "/assets/grid-road/road-asphalt-phone.ktx2": 211919,
444
+ "/assets/grid-road/road-junction-phone.ktx2": 385931,
445
+ "/assets/grid-road/road-surfaces.json": 1401,
443
446
  "/assets/hdri/kloofendal_48d_partly_cloudy_puresky_2k.gain.png": 50440,
444
447
  "/assets/hdri/kloofendal_48d_partly_cloudy_puresky_2k.hdr": 5451493,
445
448
  "/assets/hdri/kloofendal_48d_partly_cloudy_puresky_2k.sky.jpg": 350530,
@@ -27,11 +27,11 @@ export const ASSET_VERSIONS: Readonly<Record<string, string>> = {
27
27
  "/assets/baked/ink-cel-valley/far.json": 'b9e66797',
28
28
  "/assets/baked/ink-cel-valley/near.glb": '43ca8313',
29
29
  "/assets/baked/ink-cel-valley/near.json": '6ced2af8',
30
- "/assets/baked/nalati-grasslands/far-impostor.png": '287b5d00',
31
- "/assets/baked/nalati-grasslands/far.glb": '6eb862e9',
32
- "/assets/baked/nalati-grasslands/far.json": 'b4ca5b6e',
33
- "/assets/baked/nalati-grasslands/near.glb": '77836045',
34
- "/assets/baked/nalati-grasslands/near.json": '9351f72d',
30
+ "/assets/baked/nalati-grasslands/far-impostor.png": '6aaf713e',
31
+ "/assets/baked/nalati-grasslands/far.glb": '55ace39b',
32
+ "/assets/baked/nalati-grasslands/far.json": '1cfe0d1c',
33
+ "/assets/baked/nalati-grasslands/near.glb": '2587e107',
34
+ "/assets/baked/nalati-grasslands/near.json": '25180ae9',
35
35
  "/assets/baked/nine-dragon-stack/far-impostor.png": '408be760',
36
36
  "/assets/baked/nine-dragon-stack/far.glb": '55623550',
37
37
  "/assets/baked/nine-dragon-stack/far.json": '0f4bcd2f',
@@ -147,6 +147,9 @@ export const ASSET_VERSIONS: Readonly<Record<string, string>> = {
147
147
  "/assets/far-reach/tex/mill-stone.webp": '5b09fa4f',
148
148
  "/assets/far-reach/tex/rock.webp": 'ed684c0d',
149
149
  "/assets/far-reach/tex/stormeye.webp": 'a8f28043',
150
+ "/assets/grid-road/road-asphalt-phone.ktx2": '1f9a805a',
151
+ "/assets/grid-road/road-junction-phone.ktx2": 'a94834d6',
152
+ "/assets/grid-road/road-surfaces.json": 'b291e0c8',
150
153
  "/assets/hdri/kloofendal_48d_partly_cloudy_puresky_2k.gain.png": '04afee5b',
151
154
  "/assets/hdri/kloofendal_48d_partly_cloudy_puresky_2k.hdr": '5244534e',
152
155
  "/assets/hdri/kloofendal_48d_partly_cloudy_puresky_2k.sky.jpg": 'dad57443',
@@ -100,6 +100,60 @@ function copySpheres(sphere: Sphere, m: ArrayLike<number>, count: number, target
100
100
  return target;
101
101
  }
102
102
 
103
+ /** ZE2: an instanced or batched draw's XZ bounds for the cell test, exact only where it matters. Each copy's bounding sphere,
104
+ * moved by its instance matrix and the draw's world matrix, settles a copy well inside the cell; only a copy whose sphere
105
+ * crosses takes its exact box (its geometry's box through both matrices). The union is inside exactly when every copy's exact
106
+ * box is, as three's whole walk (`computeBoundingBox`, eight corners of every copy) would say, without the walk: a forest
107
+ * re-choosing its copies as the feet came back in from the road re-walked thousands (46 to 75 ms of Pine's edge frame). */
108
+ interface CopyScratch { readonly box: Box3; readonly copy: Matrix4; readonly composed: Matrix4; readonly sphere: Sphere; readonly local: Box3 }
109
+ function worldScale(world: Matrix4): number {
110
+ const w = world.elements;
111
+ return Math.sqrt(Math.max(w[0] * w[0] + w[1] * w[1] + w[2] * w[2], w[4] * w[4] + w[5] * w[5] + w[6] * w[6], w[8] * w[8] + w[9] * w[9] + w[10] * w[10]));
112
+ }
113
+ /** One copy (its matrix at `o` in `m`) into `target`: its sphere's XZ box when inside, else its exact box. */
114
+ function addCopy(local: Box3, sphere: Sphere, m: ArrayLike<number>, o: number, world: Matrix4, scale: number, inside: (bounds: Box3) => boolean,
115
+ target: Box3, scratch: CopyScratch): void {
116
+ const w = world.elements, cx = sphere.center.x, cy = sphere.center.y, cz = sphere.center.z;
117
+ const a0 = m[o] ?? 0, a1 = m[o + 1] ?? 0, a2 = m[o + 2] ?? 0, a4 = m[o + 4] ?? 0, a5 = m[o + 5] ?? 0, a6 = m[o + 6] ?? 0;
118
+ const a8 = m[o + 8] ?? 0, a9 = m[o + 9] ?? 0, a10 = m[o + 10] ?? 0;
119
+ const k = sphere.radius * scale * Math.sqrt(Math.max(a0 * a0 + a1 * a1 + a2 * a2, a4 * a4 + a5 * a5 + a6 * a6, a8 * a8 + a9 * a9 + a10 * a10));
120
+ const x = a0 * cx + a4 * cy + a8 * cz + (m[o + 12] ?? 0), y = a1 * cx + a5 * cy + a9 * cz + (m[o + 13] ?? 0), z = a2 * cx + a6 * cy + a10 * cz + (m[o + 14] ?? 0);
121
+ const wx = w[0] * x + w[4] * y + w[8] * z + w[12], wz = w[2] * x + w[6] * y + w[10] * z + w[14], box = scratch.box;
122
+ box.min.set(wx - k, 0, wz - k); box.max.set(wx + k, 0, wz + k);
123
+ if (!inside(box)) projectBounds(local, scratch.composed.multiplyMatrices(world, scratch.copy.fromArray(m, o)), box);
124
+ target.union(box);
125
+ }
126
+ function copyBounds(local: Box3, sphere: Sphere, m: ArrayLike<number>, count: number, world: Matrix4, inside: (bounds: Box3) => boolean,
127
+ target: Box3, scratch: CopyScratch): Box3 {
128
+ target.makeEmpty();
129
+ if (sphere.radius < 0 || local.isEmpty()) return target;
130
+ const scale = worldScale(world);
131
+ for (let i = 0; i < count; i++) addCopy(local, sphere, m, i * 16, world, scale, inside, target, scratch);
132
+ return target;
133
+ }
134
+ /** A batched draw's copies the same way (three's `BatchedMesh.computeBoundingBox` walks every active one); null when its
135
+ * instance table is not the shape this reads, for the whole walk to decide. */
136
+ function batchedBounds(node: BatchedMesh, inside: (bounds: Box3) => boolean, target: Box3, scratch: CopyScratch): Box3 | null {
137
+ const info: unknown = Reflect.get(node, '_instanceInfo'), texture: unknown = Reflect.get(node, '_matricesTexture');
138
+ const data: unknown = typeof texture === 'object' && texture !== null ? Reflect.get(Reflect.get(texture, 'image') ?? {}, 'data') : undefined;
139
+ if (!Array.isArray(info) || !(data instanceof Float32Array)) return null;
140
+ target.makeEmpty();
141
+ const world = node.matrixWorld, scale = worldScale(world), shapes = new Map<number, { sphere: Sphere; local: Box3 } | null>();
142
+ for (let i = 0; i < info.length; i++) {
143
+ const row: unknown = info[i];
144
+ if (typeof row !== 'object' || row === null || Reflect.get(row, 'active') === false) continue;
145
+ const id: unknown = Reflect.get(row, 'geometryIndex');
146
+ if (typeof id !== 'number') return null;
147
+ let shape = shapes.get(id);
148
+ if (shape === undefined) {
149
+ const sphere = node.getBoundingSphereAt(id, new Sphere()), local = node.getBoundingBoxAt(id, new Box3());
150
+ shape = sphere === null || local === null || local.isEmpty() ? null : { sphere, local }; shapes.set(id, shape);
151
+ }
152
+ if (shape !== null) addCopy(shape.local, shape.sphere, data, i * 16, world, scale, inside, target, scratch);
153
+ }
154
+ return target;
155
+ }
156
+
103
157
  /** Exact affine XZ projection of an AABB. Height contributes through rotated
104
158
  * axes but has no clipping plane. Unusual projective object matrices keep the
105
159
  * general eight-corner path. */
@@ -130,6 +184,7 @@ const _joint = new Vector3();
130
184
  /** Clip edge-crossing draws at the exact inclusive cell edge. No road-band or dome exemption. */
131
185
  export function cellClip(root: Object3D, half: number, scope: Scope, options: CellClipOptions = {}): CellClip {
132
186
  const cell = { value: new Vector4(-half, -half, half, half) }, origin = new Vector3(), box = new Box3(), camera = { value: new Matrix4() }, submittedWorld = new Matrix4(), alternate = new Box3();
187
+ const copies: CopyScratch = { box: new Box3(), copy: new Matrix4(), composed: new Matrix4(), sphere: new Sphere(), local: new Box3() };
133
188
  root.updateWorldMatrix(true, false); origin.setFromMatrixPosition(root.matrixWorld);
134
189
  if (!Number.isFinite(origin.x) || !Number.isFinite(origin.z)) throw new Error('Cell origin is not finite');
135
190
  cell.value.set(origin.x - half, origin.z - half, origin.x + half, origin.z + half);
@@ -281,13 +336,22 @@ export function cellClip(root: Object3D, half: number, scope: Scope, options: Ce
281
336
  if (!(node instanceof InstancedMesh) || !(sphere instanceof Sphere)
282
337
  || !within(projectBounds(copySpheres(sphere, node.instanceMatrix.array, node.count, alternate), node.matrixWorld, box))) {
283
338
  const walked = node instanceof InstancedMesh ? instanceWalks.get(node) : undefined;
284
- if (node.boundingBox === null || !(node instanceof InstancedMesh) || walked === undefined || walked.geometry !== node.geometry
285
- || walked.version !== node.instanceMatrix.version || walked.count !== node.count) {
286
- node.computeBoundingBox();
287
- if (node instanceof InstancedMesh) instanceWalks.set(node, { geometry: node.geometry, version: node.instanceMatrix.version, count: node.count });
339
+ const affine = node.matrixWorld.elements[3] === 0 && node.matrixWorld.elements[7] === 0 && node.matrixWorld.elements[11] === 0 && node.matrixWorld.elements[15] === 1;
340
+ if (shape instanceof BufferGeometry && shape.boundingBox === null) shape.computeBoundingBox();
341
+ const local: unknown = shape instanceof BufferGeometry ? shape.boundingBox : null;
342
+ if (node instanceof InstancedMesh && sphere instanceof Sphere && local instanceof Box3 && affine) {
343
+ copyBounds(local, sphere, node.instanceMatrix.array, node.count, node.matrixWorld, within, box, copies);
344
+ } else if (node instanceof BatchedMesh && affine && batchedBounds(node, within, box, copies) !== null) {
345
+ // decided copy by copy (batchedBounds), as an instanced draw is
346
+ } else {
347
+ if (node.boundingBox === null || !(node instanceof InstancedMesh) || walked === undefined || walked.geometry !== node.geometry
348
+ || walked.version !== node.instanceMatrix.version || walked.count !== node.count) {
349
+ node.computeBoundingBox();
350
+ if (node instanceof InstancedMesh) instanceWalks.set(node, { geometry: node.geometry, version: node.instanceMatrix.version, count: node.count });
351
+ }
352
+ if (node.boundingBox === null) throw new Error('Cell draw has no instance bounds');
353
+ projectBounds(node.boundingBox, node.matrixWorld, box);
288
354
  }
289
- if (node.boundingBox === null) throw new Error('Cell draw has no instance bounds');
290
- projectBounds(node.boundingBox, node.matrixWorld, box);
291
355
  }
292
356
  } else {
293
357
  if (node.geometry.boundingBox === null) for (const _step of geometryBoundsSteps(node.geometry, 'box')) { /* exact admission scan */ }