@wildshard/engine 0.1.22 → 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 (179) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/index.html +17 -4
  3. package/lint/engine-sides.json +9 -0
  4. package/lint/sim-players.json +2 -13
  5. package/package.json +36 -3
  6. package/scripts/apfs-clone.mjs +5 -2
  7. package/scripts/app-build/catalogue.ts +39 -8
  8. package/scripts/app-build/serviceWorker.ts +4 -1
  9. package/scripts/app-build/splitOutput.mjs +33 -11
  10. package/scripts/app-build/titlePreloads.mjs +8 -5
  11. package/scripts/bake-road-surfaces.entry.ts +18 -0
  12. package/scripts/bake-road-surfaces.mjs +44 -0
  13. package/scripts/changelog.mjs +2 -1
  14. package/scripts/ci-pack.mjs +3 -3
  15. package/scripts/engine-ci-shard.mjs +11 -0
  16. package/scripts/fight-page-census.mjs +131 -0
  17. package/scripts/goldens/board.py +44 -11
  18. package/scripts/goldens/capture.mjs +18 -6
  19. package/scripts/goldens/native-residency.d.mts +2 -0
  20. package/scripts/goldens/native-residency.mjs +31 -4
  21. package/scripts/grid-road-lag.mjs +209 -0
  22. package/scripts/keep-copy.mjs +172 -0
  23. package/scripts/land.d.mts +4 -1
  24. package/scripts/land.mjs +121 -9
  25. package/scripts/lane-live.mjs +136 -0
  26. package/scripts/leftovers-report.mjs +47 -0
  27. package/scripts/loading-card-proof.mjs +42 -9
  28. package/scripts/loading-flow/benchmax.mjs +59 -7
  29. package/scripts/loading-flow/stalls.d.mts +2 -0
  30. package/scripts/loading-flow/stalls.mjs +13 -0
  31. package/scripts/map-hash.mjs +1 -1
  32. package/scripts/mmo-bots.mjs +5 -3
  33. package/scripts/mmo-grid-proof.mjs +74 -0
  34. package/scripts/mmo-seat-proof.mjs +43 -0
  35. package/scripts/nightly-heads.ts +13 -13
  36. package/scripts/nightly-model.ts +26 -12
  37. package/scripts/nightly-tag.mjs +2 -4
  38. package/scripts/nightly.proof.ts +18 -5
  39. package/scripts/nightly.ts +13 -8
  40. package/scripts/no-astc-boot.mjs +77 -0
  41. package/scripts/page-release/content.mjs +19 -10
  42. package/scripts/page-release/flow.d.mts +3 -2
  43. package/scripts/page-release/flow.mjs +31 -21
  44. package/scripts/page-release/packs.d.mts +5 -0
  45. package/scripts/page-release/packs.mjs +13 -3
  46. package/scripts/page-release/preview.d.mts +2 -0
  47. package/scripts/page-release/preview.mjs +74 -0
  48. package/scripts/page-release.mjs +13 -5
  49. package/scripts/physics-route.json +6 -6
  50. package/scripts/pins-reuse.mjs +1 -0
  51. package/scripts/pins-staging.ts +54 -0
  52. package/scripts/pins.ts +5 -0
  53. package/scripts/ring3.proof.ts +71 -0
  54. package/scripts/ring3.ts +100 -0
  55. package/scripts/road-drive-proof.mjs +269 -0
  56. package/scripts/road-memory-probe.mjs +129 -0
  57. package/scripts/scratch-dir.mjs +33 -14
  58. package/scripts/scratch-sweep.mjs +15 -23
  59. package/scripts/server-release/github.mjs +59 -26
  60. package/scripts/server-release/items.d.mts +7 -0
  61. package/scripts/server-release/items.mjs +28 -0
  62. package/scripts/server-release/publish.mjs +24 -2
  63. package/scripts/server-release/sign.mjs +8 -4
  64. package/scripts/side-parity.mjs +1 -1
  65. package/scripts/test-products.json +1 -0
  66. package/scripts/test_prebuilt_output.py +3 -1
  67. package/scripts/tsconfig.json +2 -0
  68. package/scripts/turn-in-shots.mjs +83 -0
  69. package/scripts/vitest-bench-observe-proof.py +168 -0
  70. package/scripts/vitest-bench.py +122 -77
  71. package/scripts/vitest-ci-files.ts +5 -1
  72. package/scripts/vps/rebuild.sh +3 -1
  73. package/scripts/vps/wildshard-config +106 -1
  74. package/scripts/warm-native-chrome.mjs +9 -3
  75. package/scripts/worker-client-fights.mjs +9 -3
  76. package/scripts/worktree-reap.mjs +36 -140
  77. package/scripts/worktree.mjs +92 -12
  78. package/scripts/zone-gate-proof.mjs +93 -0
  79. package/src/client/engine/audio/audioLog.ts +7 -2
  80. package/src/client/engine/boot/diagnostics.ts +69 -1
  81. package/src/client/engine/boot/sw.ts +3 -1
  82. package/src/client/engine/core/ktx2.ts +33 -10
  83. package/src/client/engine/core/ktx2Zstd.ts +2 -1
  84. package/src/client/engine/models/place.ts +7 -5
  85. package/src/client/engine/pwa/sw.js +83 -10
  86. package/src/client/engine/render/dataLook.ts +14 -7
  87. package/src/client/engine/render/lookLight.ts +64 -20
  88. package/src/client/engine/render/precompile.ts +6 -0
  89. package/src/client/engine/render/tiers.ts +9 -0
  90. package/src/client/engine/ui/Loading.ts +6 -8
  91. package/src/client/engine/ui/lookLightOption.ts +1 -1
  92. package/src/client/engine/ui/playerReload.ts +5 -5
  93. package/src/client/game/audio/cueDirector.ts +2 -1
  94. package/src/client/game/boot/bytes.generated.ts +4 -1
  95. package/src/client/game/boot/versions.generated.ts +8 -5
  96. package/src/client/game/boss/arenaRoom.ts +4 -3
  97. package/src/client/game/boss/roamingProjection.ts +1 -1
  98. package/src/client/game/devScene/hook.ts +1 -1
  99. package/src/client/game/devScene/liveLook.ts +1 -1
  100. package/src/client/game/grid/cellClip.ts +70 -6
  101. package/src/client/game/grid/dataCellKit.ts +9 -1
  102. package/src/client/game/grid/gateCard.css +9 -0
  103. package/src/client/game/grid/gateCard.ts +67 -0
  104. package/src/client/game/grid/live.ts +17 -3
  105. package/src/client/game/grid/liveSession.ts +15 -5
  106. package/src/client/game/grid/neighbourLife.ts +10 -1
  107. package/src/client/game/grid/neighbourPanels.ts +29 -2
  108. package/src/client/game/grid/pageEntry.ts +21 -0
  109. package/src/client/game/grid/products.ts +21 -7
  110. package/src/client/game/grid/regionalWorld.ts +5 -0
  111. package/src/client/game/grid/roadCompressedSurfaces.ts +69 -0
  112. package/src/client/game/grid/roadLook.ts +5 -73
  113. package/src/client/game/grid/roadLookPlatform.ts +11 -6
  114. package/src/client/game/grid/roadSurfaceMaps.ts +80 -0
  115. package/src/client/game/grid/roadTilePool.ts +4 -0
  116. package/src/client/game/grid/session.ts +58 -16
  117. package/src/client/game/grid/softWallLook.ts +6 -1
  118. package/src/client/game/plugin/ui.ts +3 -0
  119. package/src/client/game/population/signals.ts +1 -1
  120. package/src/client/game/quest/chapterDirector.ts +1 -0
  121. package/src/client/game/session/play.ts +3 -0
  122. package/src/client/game/shardfile/clientBossTelegraph.ts +4 -3
  123. package/src/client/game/shardfile/clientSource.ts +5 -2
  124. package/src/client/game/shardfile/clientWorker.ts +25 -8
  125. package/src/client/game/shardfile/look.ts +1 -1
  126. package/src/client/game/shardfile/runtimeProduct.ts +9 -5
  127. package/src/client/game/shardfile/slabLibrary.ts +37 -0
  128. package/src/client/game/shardfile/slabRanges.ts +145 -0
  129. package/src/client/game/shardfile/wirePage.ts +5 -2
  130. package/src/client/game/shardfile/worldSceneTextures.ts +15 -9
  131. package/src/client/host/online/shell.ts +2 -2
  132. package/src/client/host/standalone/shell.ts +4 -1
  133. package/src/cook/game/cookWorker.ts +8 -5
  134. package/src/cook/game/tierTextures.ts +5 -3
  135. package/src/server/engine/net/simWorld.ts +3 -4
  136. package/src/server/game/grid/cellHome.ts +58 -0
  137. package/src/server/game/grid/simulation.ts +32 -8
  138. package/src/server/game/plugin/mover.ts +18 -14
  139. package/src/server/game/plugin/simulation.ts +2 -0
  140. package/src/server/game/shardfile/dataRespawn.ts +47 -0
  141. package/src/server/game/shardfile/declaredKitItems.ts +31 -7
  142. package/src/server/host/bake/headlessWorker.ts +3 -3
  143. package/src/server/host/dedicated/cellWorker.ts +4 -2
  144. package/src/server/host/dedicated/main.ts +7 -4
  145. package/src/server/host/dedicated/packReader.ts +15 -2
  146. package/src/server/host/dedicated/playerStore.ts +1 -1
  147. package/src/server/host/headlessRuntime.ts +11 -6
  148. package/src/server/host/standalone/cellWorld.ts +20 -6
  149. package/src/server/host/standalone/gridServer.ts +20 -6
  150. package/src/server/host/standalone/roadWorld.ts +36 -0
  151. package/src/server/host/standalone/serverHost.ts +2 -2
  152. package/src/shared/engine/entities/AnimalSim.ts +10 -0
  153. package/src/shared/engine/physics/gridBorders.ts +15 -1
  154. package/src/shared/engine/physics/transferWalls.ts +9 -4
  155. package/src/shared/engine/sim/snapshot.ts +5 -5
  156. package/src/shared/game/grid/allocator.ts +8 -1
  157. package/src/shared/game/grid/gateCount.ts +27 -0
  158. package/src/shared/game/grid/zoneWalls.ts +64 -0
  159. package/src/shared/game/ledger.ts +13 -4
  160. package/src/shared/game/loot/platformCatalogue.ts +14 -0
  161. package/src/shared/game/quest/ledger.ts +3 -3
  162. package/src/shared/game/shardfile/items.ts +9 -1
  163. package/src/shared/game/strings.ts +2 -0
  164. package/src/shared/host/headlessJourney.ts +3 -3
  165. package/src/shared/host/headlessTape.ts +7 -6
  166. package/src/shared/host/releaseRows.ts +4 -1
  167. package/src/shared/host/standalone/harnessPlace.ts +4 -0
  168. package/src/test/engine/simState.ts +134 -0
  169. package/src/test/game/builtProduct.ts +6 -0
  170. package/src/test/game/headless/admittedProductCache.ts +61 -0
  171. package/src/test/game/headless/checkedReplayPipeline.ts +21 -0
  172. package/src/test/game/headless/nativeBounds.ts +27 -0
  173. package/src/test/game/headless/processUsage.ts +22 -0
  174. package/src/test/game/headless/productSession.ts +39 -0
  175. package/src/test/game/headless/ropeBodies.ts +60 -0
  176. package/src/test/game/headless/worker.ts +34 -0
  177. package/src/test/game/headlessNative.ts +114 -0
  178. package/src/test/game/headlessWorker.ts +43 -0
  179. package/src/test/tsconfig.game.json +3 -0
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+ // EG-15 (meta docs/plans/test-coverage/ENGINE.md, TEST-COVERAGE row 32): fight-page-census. What a server says, a page draws.
3
+ // It runs `worker-client-fights` journeys on four full heads (Nalati, Pine, Far Reach, Dunes) and holds, per head:
4
+ // heard every view word the server said to a page (`__workerClient().heard`, counted at the wire);
5
+ // drawn what the page drew of them (`__workerClient().drawn`, counted where a view applies a word);
6
+ // offstage words for a view the page hasn't built, a room nobody entered (`__workerClient().offstage`): not drawn, and not dark;
7
+ // bodies every fight the page shows a bar for has a body drawn (`__workerClientFights().shown`, or an open arena's own body): BUG-28;
8
+ // audio every directed cue and score change that asked for a sound, and whether one played (`window.__audioTally`): N1, N2.
9
+ // A word heard that the page never drew is dark, unless WORDS below says why it draws nothing. A dark word, a bar with no body, a cue that
10
+ // found no sound or a step that failed is red. Digests and verb tapes can't see any of these: they never run a page.
11
+ // scripts/browser-lane.sh node scripts/fight-page-census.mjs --base=http://127.0.0.1:4401/ [--heads=nalati,pine,far,dunes] [--journeys=titan] [--out=tmp/census/census.json]
12
+ import { mkdirSync, writeFileSync } from 'node:fs';
13
+ import { dirname } from 'node:path';
14
+ import { chromium, devices } from 'playwright';
15
+ import { KEYCHAIN_ARGS } from './chromium-keychain.mjs';
16
+ import { fights, pageCensus } from './worker-client-fights.mjs';
17
+
18
+ const arg = (key, fallback) => process.argv.find(value => value.startsWith(`--${key}=`))?.slice(key.length + 3) ?? fallback;
19
+ const base = arg('base', ''), out = arg('out', 'tmp/census/census.json');
20
+ if (base === '') throw new Error('Requires --base');
21
+
22
+ /** Each head and the journeys that fight on it (`fights(…, only)`). Flags the journeys read off argv go on with them. `qara` is left
23
+ * out: its captain comes only after a night patrol is thinned, and some runs it never comes (`sweep`'s Argymaq draws an elite lane). */
24
+ export const HEADS = {
25
+ nalati: { slug: 'nalati-grasslands', journeys: ['titan', 'sweep'], flags: ['--titanlook'] },
26
+ pine: { slug: 'pine-hollow', journeys: ['rig', 'pine'], flags: [] },
27
+ far: { slug: 'far-reach', journeys: ['roc', 'farreach'], flags: [] },
28
+ dunes: { slug: 'sunscar-dunes', journeys: ['sunscar'], flags: [] },
29
+ };
30
+ /** View words a page hears and rightly draws nothing for, and why. Everything else heard must be drawn. */
31
+ export const WORDS = [
32
+ // Exact words, not a prefix: a lane-sheet boss's strike must still be drawn (clientBossTelegraph.ts).
33
+ ['boss.strike.far.roc.stoop', 'the Roc\'s presentation is marked and names no strike: no page view takes it, its body plays the attack off its row'],
34
+ ['boss.strike.sunscar.matriarch.dive', 'the Matriarch\'s presentation is marked and names no strike: no page view takes it, its body plays the attack off its row'],
35
+ ];
36
+ const silent = name => WORDS.find(([word]) => name === word)?.[1] ?? null;
37
+ /** One row per kind of word. A pose is a pose whatever body and field it names (one taken is the census's proof that poses land);
38
+ * an elite's words are drawn each frame under its kind (`Elite.ts`: `elite lane`), so its heard words count there. */
39
+ export const family = name => name.startsWith('pose.') ? 'pose' : name.replace(/^elite\.(\w+):.*$/u, 'elite $1');
40
+
41
+ const picked = arg('heads', Object.keys(HEADS).join(',')).split(','), only = arg('journeys', '').split(',').filter(Boolean);
42
+ for (const name of picked) if (HEADS[name] === undefined) throw new Error(`Unknown head ${name}: ${Object.keys(HEADS).join(', ')}`);
43
+ const { defaultBrowserType: _engine, ...phone } = devices['iPhone 16 Pro'];
44
+ const launched = await chromium.launch({ args: [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist'] });
45
+ const browser = { close: () => launched.close(), newContext: options => launched.newContext(options) };
46
+
47
+ /** One sample of a page's fights: each in progress, whether its bar shows, and whether a body for it is drawn. */
48
+ const sampleFights = page => page.evaluate(() => {
49
+ const shown = selector => [...document.querySelectorAll(selector)].some(node => node.classList.contains('show'));
50
+ const bar = shown('[class*="ws-boss"]') || shown('[class*="ws-elite"]');
51
+ const open = Object.values(window.__wildshard?.shard ?? {}).flatMap(script => { try { const body = script?.openFight?.body; return body === undefined ? [] : [body.visible === true]; } catch { return []; } });
52
+ return (window.__workerClientFights?.() ?? []).filter(row => row.state === 'fight').map(row => ({ id: row.id, bar, body: row.shown ?? open.some(Boolean) }));
53
+ });
54
+ const readPage = page => page.evaluate(() => {
55
+ const report = window.__workerClient();
56
+ return { heard: report.heard ?? {}, drawn: report.drawn, offstage: report.offstage ?? {}, audio: window.__audioTally ?? {}, said: window.__said ?? [] };
57
+ });
58
+
59
+ const census = {};
60
+ for (const head of picked) {
61
+ const { slug, journeys, flags } = HEADS[head];
62
+ const row = census[head] = { slug, steps: [], heard: {}, drawn: {}, offstage: {}, audio: {}, bodies: {}, pages: 0 };
63
+ const sampling = new Map();
64
+ pageCensus.sink = {
65
+ opened(_slug, page) {
66
+ const timer = setInterval(() => {
67
+ void sampleFights(page).then(seen => {
68
+ for (const { id, bar, body } of seen) {
69
+ const fight = row.bodies[id] ??= { samples: 0, bar: 0, bodiless: 0 };
70
+ fight.samples++; if (bar) fight.bar++; if (bar && !body) fight.bodiless++;
71
+ }
72
+ return undefined;
73
+ }, () => undefined);
74
+ }, 1500);
75
+ sampling.set(page, timer);
76
+ },
77
+ async closing(_slug, page) {
78
+ clearInterval(sampling.get(page)); sampling.delete(page);
79
+ const seen = await readPage(page).catch(() => null);
80
+ if (seen === null) return;
81
+ row.pages++;
82
+ for (const [name, count] of Object.entries(seen.heard)) row.heard[family(name)] = (row.heard[family(name)] ?? 0) + count;
83
+ for (const [name, count] of Object.entries(seen.drawn)) row.drawn[family(name)] = (row.drawn[family(name)] ?? 0) + count;
84
+ for (const [name, count] of Object.entries(seen.offstage)) row.offstage[family(name)] = (row.offstage[family(name)] ?? 0) + count;
85
+ for (const [name, { played, silent: quiet }] of Object.entries(seen.audio)) { const sound = row.audio[name] ??= { played: 0, silent: 0 }; sound.played += played; sound.silent += quiet; }
86
+ },
87
+ };
88
+ process.argv.push(...flags);
89
+ for (const journey of only.length === 0 ? journeys : journeys.filter(name => only.includes(name))) {
90
+ await fights(browser, phone, base, journey, async (name, run) => {
91
+ const started = Date.now();
92
+ let result;
93
+ try { result = await run(); } catch (error) { result = { ok: false, error: String(error?.message ?? error).slice(0, 300) }; }
94
+ row.steps.push({ name, ok: result?.ok === true, seconds: Math.round((Date.now() - started) / 1000) });
95
+ console.log(`${result?.ok === true ? 'ok ' : 'FAIL'} ${head} ${name}${result?.ok === true ? '' : ` ${JSON.stringify(result).slice(0, 400)}`}`);
96
+ });
97
+ }
98
+ for (const flag of flags) process.argv.splice(process.argv.indexOf(flag), 1);
99
+ pageCensus.sink = null;
100
+ }
101
+ await browser.close();
102
+
103
+ /** The verdict: each head's words heard against drawn, its bodies and its sounds. */
104
+ const red = [];
105
+ for (const [head, row] of Object.entries(census)) {
106
+ console.log(`\n${head} (${row.slug}): ${row.pages} pages, ${row.steps.filter(step => step.ok).length}/${row.steps.length} steps`);
107
+ console.log(`${' word'.padEnd(44)}${'heard'.padStart(8)}${'drawn'.padStart(8)} verdict`);
108
+ for (const name of [...new Set([...Object.keys(row.heard), ...Object.keys(row.drawn)])].sort()) {
109
+ const heard = row.heard[name] ?? 0, drawn = row.drawn[name] ?? 0, offstage = row.offstage[name] ?? 0, why = silent(name);
110
+ // offstage: every word of it was for a view this page hadn't built (a room nobody entered)
111
+ const verdict = heard === 0 ? 'drawn only' : drawn > 0 ? 'drawn' : offstage === heard ? 'offstage: its room was never built' : why !== null ? `silent: ${why}` : 'DARK';
112
+ if (verdict === 'DARK') red.push(`${head}: ${name} heard ${heard}, drawn 0`);
113
+ console.log(` ${name.slice(0, 41).padEnd(42)}${String(heard).padStart(8)}${String(drawn).padStart(8)} ${verdict}`);
114
+ }
115
+ for (const [id, fight] of Object.entries(row.bodies)) {
116
+ console.log(` fight ${id}: ${fight.samples} samples, bar on ${fight.bar}, bar with no body ${fight.bodiless}`);
117
+ if (fight.bodiless > 0) red.push(`${head}: ${id} showed a bar with no body in ${fight.bodiless} of ${fight.bar} samples`);
118
+ }
119
+ for (const [name, sound] of Object.entries(row.audio).sort(([a], [b]) => a.localeCompare(b))) {
120
+ if (!name.startsWith('cue ') && !name.startsWith('music ')) continue;
121
+ console.log(` audio ${name}: played ${sound.played}, silent ${sound.silent}`);
122
+ if (name.startsWith('cue ') && sound.played === 0) red.push(`${head}: ${name} asked for a sound ${sound.silent} times and none played`);
123
+ }
124
+ // N2: a boss fight the page showed scores it. A sting before the first gesture finds no audio rig yet, so stings only report.
125
+ if (Object.values(row.bodies).some(fight => fight.bar > 0) && (row.audio['music mode:combat']?.played ?? 0) === 0) red.push(`${head}: a boss fight showed its bar and the score never went to combat`);
126
+ for (const step of row.steps) if (!step.ok) red.push(`${head}: step failed: ${step.name}`);
127
+ }
128
+ mkdirSync(dirname(out), { recursive: true });
129
+ writeFileSync(out, `${JSON.stringify({ base, census, red }, null, 1)}\n`);
130
+ console.log(red.length === 0 ? '\ncensus green' : `\ncensus RED (${red.length}):\n${red.map(line => ` ${line}`).join('\n')}`);
131
+ process.exit(red.length === 0 ? 0 : 1);
@@ -10,6 +10,9 @@ A shard (24 cameras). <goldens> is a shard repo's art/goldens/: cameras24.json,
10
10
  An open plot (8 views). <goldens> holds <plot>/cameras.json and <plot>/<n>-<view>.jpg:
11
11
  python3 scripts/goldens/board.py --goldens <goldens> --plot <plot> --now <dir> --out <dir> [...]
12
12
  NOW frames: <now>/<plot>/<n>-<view>.png|.jpg. Columns: GOLDEN | NOW.
13
+ Plot mask: when <n>-<view>-iso.png (other cells hidden) and <n>-<view>-bare.png (every cell hidden) sit beside a NOW
14
+ frame, the pixels where they differ are the plot's own. SSIM and the colour guard count only those, so a neighbour
15
+ the grid layout moved never scores, and a SCORED column shows NOW with everything else dimmed.
13
16
 
14
17
  Writes <out>/<id>.jpg (one big labelled row per camera: read every one) and <out>/board-<slug>.jpg (every camera on one
15
18
  labelled board, <= 500 KB; --red burns a red frame and RED onto those cameras). Prints SSIM per camera: a guide only,
@@ -45,15 +48,32 @@ def blur(a):
45
48
  return sum(k[i] * rows[:, i:i + a.shape[1]] for i in range(11))
46
49
 
47
50
 
48
- def ssim(a_img, b_img):
49
- """Luma SSIM at 402 x 681, the G859 page's measure."""
51
+ def fitted_mask(mask, size):
52
+ """A boolean mask resized to size (w, h)."""
53
+ return np.asarray(Image.fromarray(mask.astype(np.uint8) * 255).resize(size, Image.NEAREST)) > 127
54
+
55
+
56
+ def ssim(a_img, b_img, mask=None):
57
+ """Luma SSIM at 402 x 681, the G859 page's measure; with a mask, the mean over its pixels."""
50
58
  size = (402, 681)
51
59
  a, b = luma(a_img.resize(size, Image.BILINEAR)), luma(b_img.resize(size, Image.BILINEAR))
60
+ if mask is not None: # the same flat fill outside the plot in both, so edge windows never see a neighbour
61
+ inside = fitted_mask(mask, size); fill = b[inside].mean()
62
+ a, b = np.where(inside, a, fill), np.where(inside, b, fill)
52
63
  c1, c2 = (0.01 * 255) ** 2, (0.03 * 255) ** 2
53
64
  ma, mb = blur(a), blur(b)
54
65
  va, vb, cov = blur(a * a) - ma * ma, blur(b * b) - mb * mb, blur(a * b) - ma * mb
55
66
  m = ((2 * ma * mb + c1) * (2 * cov + c2)) / ((ma * ma + mb * mb + c1) * (va + vb + c2))
56
- return float(m.mean())
67
+ return float(m[fitted_mask(mask, size)].mean() if mask is not None else m.mean())
68
+
69
+
70
+ def plot_mask(iso, bare):
71
+ """Where the plot draws: other-cells-hidden against every-cell-hidden, a per-channel step over 24 (sky drift
72
+ and dithering stay under it), smoothed so single noisy pixels drop out. None when the two frames don't pair."""
73
+ if iso is None or bare is None or iso.size != bare.size: return None
74
+ a, b = (np.asarray(x.convert('RGB'), dtype=np.int16) for x in (iso, bare))
75
+ differs = (np.abs(a - b).max(axis=2) > 24).astype(np.float64)
76
+ return blur(differs) > 0.5
57
77
 
58
78
 
59
79
  def font(size):
@@ -98,19 +118,21 @@ def cameras(a):
98
118
  golden = Image.open(os.path.join(g, 'shardfile', f'{cid}.jpg')).convert('RGB')
99
119
  cols.append(('SHARDFILE golden', golden.crop((0, STRIP, golden.width, golden.height))))
100
120
  now = find(os.path.join(a.now, a.shard), (f'{cid}-shardfile.png', f'{cid}.png', f'{cid}.jpg'))
101
- out.append((c['n'], cid, cols, now))
121
+ out.append((c['n'], cid, cols, now, None))
102
122
  else:
103
123
  for v in json.load(open(os.path.join(g, a.plot, 'cameras.json')))['views']:
104
124
  vid = f'{v["n"]}-{v["name"]}'
105
125
  golden = Image.open(os.path.join(g, a.plot, f'{vid}.jpg')).convert('RGB')
106
- now = find(os.path.join(a.now, a.plot), (f'{vid}.png', f'{vid}.jpg'))
107
- out.append((v['n'], vid, [('GOLDEN', golden)], now))
126
+ base = os.path.join(a.now, a.plot)
127
+ now = find(base, (f'{vid}.png', f'{vid}.jpg'))
128
+ mask = plot_mask(find(base, (f'{vid}-iso.png',)), find(base, (f'{vid}-bare.png',)))
129
+ out.append((v['n'], vid, [('GOLDEN', golden)], now, mask))
108
130
  return out
109
131
 
110
132
 
111
133
  def promote(a, cams):
112
134
  if not a.shard or not a.source: raise SystemExit('--promote needs --shard and --source "<sha10> <ruling>"')
113
- for n, cid, _, now in cams:
135
+ for n, cid, _, now, _mask in cams:
114
136
  if n not in a.promote: continue
115
137
  if now is None: raise SystemExit(f'no NOW frame for {cid}')
116
138
  img, f = fit(now, 540), font(12)
@@ -136,20 +158,31 @@ def main():
136
158
  if not a.out: raise SystemExit('--out is required')
137
159
  os.makedirs(a.out, exist_ok=True)
138
160
  big, small, missing = [], [], []
139
- for n, cid, goldens, now in cams:
161
+ for n, cid, goldens, now, mask in cams:
140
162
  if now is None: missing.append(cid); continue
141
- s = ssim(goldens[-1][1], now)
142
- pixels = lambda image: image.convert('RGB').resize((128, 217), Image.BILINEAR).getdata()
163
+ if mask is not None and not mask.any(): mask = None # nothing of the plot in view: score the frame
164
+ s = ssim(goldens[-1][1], now, mask)
165
+ small_px = lambda image: np.asarray(image.convert('RGB').resize((128, 217), Image.BILINEAR)).reshape(-1, 3)
166
+ keep = fitted_mask(mask, (128, 217)).reshape(-1) if mask is not None else slice(None)
167
+ pixels = lambda image: [tuple(p) for p in small_px(image)[keep].tolist()]
143
168
  colour = colour_shift(pixels(goldens[-1][1]), pixels(now))
144
169
  if colour['red']: red.add(n)
145
170
  is_red = n in red
146
171
  shift = f'dY {colour["luma_delta"]:+.3f} dS {colour["saturation_delta"]:+.3f}'
172
+ if mask is not None: shift += f' plot {mask.mean():.0%}'
147
173
  flag = ' RED COLOUR' if colour['red'] else ' RED' if is_red else ''
148
174
  print(f'{cid:28s} {s:.3f} {shift}{flag}')
149
175
  for w, size, sink, title in ((360, 13, big, f'{slug} {cid} SSIM {s:.2f} {shift}'), (120, 9, small, f'{cid} {s:.2f}')):
150
176
  f = font(size)
151
177
  cells = [labelled(fit(img, w), label, INK, w, f) for label, img in goldens]
152
178
  cells.append(labelled(fit(now, w), a.label, RED if is_red else INK, w, f))
179
+ if any(c[4] is not None for c in cams):
180
+ scored = fit(now, w)
181
+ if mask is not None:
182
+ keep_w = fitted_mask(mask, scored.size)[..., None]
183
+ arr = np.asarray(scored, dtype=np.float64)
184
+ scored = Image.fromarray(np.where(keep_w, arr, arr * 0.2 + 8).astype(np.uint8))
185
+ cells.append(labelled(scored, 'SCORED (plot mask)' if mask is not None else 'SCORED (whole frame)', INK, w, f))
153
186
  sink.append(row(cells, title + flag, w, is_red, f))
154
187
  big[-1].save(os.path.join(a.out, f'{cid}.jpg'), quality=82)
155
188
  if missing: print('MISSING NOW frames:', ', '.join(missing))
@@ -157,7 +190,7 @@ def main():
157
190
  cols = 4; tw, th = small[0].width, max(t.height for t in small)
158
191
  f = font(16); head = 2 * f.size + 24
159
192
  board = Image.new('RGB', (cols * (tw + 4) + 4, head + -(-len(small) // cols) * (th + 4) + 4), BG)
160
- columns = ' . '.join([label for label, _ in cams[0][2]] + [a.label])
193
+ columns = ' . '.join([label for label, _ in cams[0][2]] + [a.label] + (['SCORED'] if any(c[4] is not None for c in cams) else []))
161
194
  draw = ImageDraw.Draw(board)
162
195
  draw.text((6, 6), f'GOLDEN RERUN {slug} | {columns}', fill=INK, font=f)
163
196
  status = f'RED: {",".join(map(str, sorted(red)))}' if red else 'No mean colour-shift flags; VISUAL REVIEW REQUIRED'
@@ -39,7 +39,7 @@ const exp=arg('exp','')?readFileSync(arg('exp',''),'utf8'):'';// --exp=<file.js>
39
39
  const only=selectGoldenCameraNumbers(arg('cams',''));
40
40
  const slugs=selectGoldenShards(canonical,arg('shards',undefined));
41
41
  const nativeBinding=mode==='shardfile'&&slugs.includes('nine-dragon-stack')?await goldenRefinementBinding(base,source):null;
42
- const FRAMES=120,SETTLE_MS=30000,LIVE=60,FREE=4,EYE=1.7,ON_FOOT=new Set(['far-reach']);
42
+ const FRAMES=120,SETTLE_MS=30000,LIVE=60,FREE=4,EYE=1.7,AWAY=20,ON_FOOT=new Set(['far-reach']);
43
43
  // --textures=ktx2|img pins the page's texture mode (the harness pin, src/engine/boot/gpuFiles.ts) to judge a texture-policy
44
44
  // change on a clean build; omitted, the shipped Auto policy picks
45
45
  const TEXTURES=arg('textures','');if(!['','ktx2','img'].includes(TEXTURES))throw Error(`--textures=${TEXTURES}`);
@@ -53,6 +53,9 @@ const LEVEL_DOWNLOAD=arg('level-download','');if(!['','packs','shardfile'].inclu
53
53
  // out at the URLs they stand in for) are judged on a served build. Pair it with --level-download=shardfile: a pack part is not a request.
54
54
  const SERVE_OVER=arg('serve-over',''),overHits=new Set();
55
55
  const DIRECT=process.argv.includes('--direct');
56
+ // A repeated stationary view can pause the solo room before posing: creatures remain where boot put them while the
57
+ // real local motor and the renderer stream the camera. This never removes a creature or changes authored geometry.
58
+ const STILL_ROOM=process.argv.includes('--still-room');if(STILL_ROOM&&!DIRECT)throw Error('--still-room requires --direct solo entry');
56
59
  mkdirSync(root,{recursive:true});
57
60
 
58
61
  // --engine=webkit: Playwright's WebKit (muted by the game's volume 0; its Escape is a plain key press)
@@ -88,7 +91,7 @@ async function settle(page,inflight){
88
91
 
89
92
  try{for(const slug of slugs){
90
93
  const dir=`${root}/${slug}`;mkdirSync(dir,{recursive:true});
91
- const row={slug,head,engine,device:'iPhone 16 Pro',tier:'phone',dpr:2,seed:357,levelDownload:LEVEL_DOWNLOAD===''?'default':LEVEL_DOWNLOAD,errors:[],warnings:{},poses:[]};
94
+ const row={slug,head,engine,device:'iPhone 16 Pro',tier:'phone',dpr:2,seed:357,stillRoom:STILL_ROOM,levelDownload:LEVEL_DOWNLOAD===''?'default':LEVEL_DOWNLOAD,errors:[],warnings:{},poses:[]};
92
95
  const context=await browser.newContext({...devices['iPhone 16 Pro']});let page;
93
96
  try{
94
97
  await developerSettings(context,{tier:'phone',volume:0,time:'midday',weather:'clear'});
@@ -156,8 +159,11 @@ try{for(const slug of slugs){
156
159
  row.entry=await page.evaluate(()=>({url:location.href,id:window.__wildshard.world.game.level.id}));
157
160
  const want=slug;if(row.entry.id!==want)throw Error(`Not ${mode}: ${row.entry.id}`);row.mode=mode;
158
161
  // the golden camera is a spectator: its player takes no damage (Pine's bear-den elite killed it, and the death fade put it
159
- // back at spawn with the ring and the grass field)
160
- await page.evaluate(()=>{const hp=window.__wildshard.world.game.app.player;if(hp)hp.attributes.incomingCap=0;});
162
+ // back at spawn with the ring and the grass field). The cap holds on a main-thread page. On a worker page only the server lands
163
+ // a blow: Pine's den bears woke, charged, knocked the eye-height player of camera 11 down the slope and killed it, and the shot
164
+ // streamed its ground cover round spawn, 250 m away (meta SH-ALL-11). There the server holds every creature where it stands.
165
+ row.still=await page.evaluate(()=>{const hp=window.__wildshard.world.game.app.player;if(hp)hp.attributes.incomingCap=0;
166
+ if(!window.__workerClientStill)return false;window.__workerClientStill();return true;});
161
167
  for(let i=0;i<canonical[slug].length;i++){
162
168
  const c=canonical[slug][i];if(only&&!only.has(c.n??i+1))continue;
163
169
  const probe=c.probe??{x:c.feet?.[0]??c.eye[0],z:c.feet?.[2]??c.eye[2],yaw:-c.yaw*Math.PI/180,pitch:c.pitch*Math.PI/180,...c.feet?{y:c.feet[1]}:{}};
@@ -166,9 +172,11 @@ try{for(const slug of slugs){
166
172
  const free=c.eye!==undefined&&Math.hypot(c.eye[0]-probe.x,c.eye[2]-probe.z,probe.y===undefined?0:c.eye[1]-EYE-probe.y)>FREE;
167
173
  const at=free?{...probe,x:c.eye[0],y:c.eye[1]-EYE,z:c.eye[2]}:probe;
168
174
  await page.evaluate(()=>{const w=window.__wildshard.world;w.game.hold=false;window.__wsEye=null;
175
+ if(window.__wsGoldenPractice){document.dispatchEvent(new CustomEvent('ws:practice-active',{detail:false}));window.__wsGoldenPractice=false;}
169
176
  // what hangs off the camera before any hover (the held weapon, the hands): the shot keeps only these visible. Taken
170
177
  // once per entry: a board stepped off a moment ago still shows while it fades
171
178
  window.__wsCamOff??=new Set(w.game.camera.children.filter(o=>o.visible));});
179
+ if(STILL_ROOM)await page.evaluate(()=>{document.dispatchEvent(new CustomEvent('ws:practice-active',{detail:true}));window.__wsGoldenPractice=true;});
172
180
  await board(page,false);await page.evaluate(p=>window.__wildshard.pose(p),at);if(free)await board(page,true);
173
181
  await frames(page,FRAMES);const idle=await settle(page,inflight);await frames(page,30);
174
182
  // a player on a slope slides off its pose while streaming settles (Pine's bear den slid into the lake and respawned at
@@ -207,6 +215,7 @@ try{for(const slug of slugs){
207
215
  g.shardFrame();g.composer.render(0);g.shardFrame();g.composer.render(0);
208
216
  return{eye:cam.position.toArray(),rotation:cam.rotation.toArray(),fov:cam.fov,frame:g.frameCount,player,hover:w.player.hover===true,settledEye:e.settled};
209
217
  });
218
+ if(!Number.isFinite(observed.player[0])||!Number.isFinite(observed.player[2])||Math.hypot(observed.player[0]-at.x,observed.player[2]-at.z)>FREE)row.errors.push(`camera ${c.n}: residency player left the probe; repeat solo with --still-room`);
210
219
  const shot=set?`${dir}/${String(c.n).padStart(2,'0')}-${c.name}-${mode}.png`:`${dir}/${i+1}-${c.name}-shardfile.png`;
211
220
  // the 24-camera set hides the HUD (every element but the canvases; a canvas read-back misses Nine's layered composite)
212
221
  // and the minimap: a canvas smaller than half the viewport stays hidden
@@ -215,12 +224,15 @@ try{for(const slug of slugs){
215
224
  await page.screenshot({path:shot,type:'png',scale:'device'});await hide.evaluate(e=>e.remove());}
216
225
  else await page.screenshot({path:shot,type:'png',scale:'css'});
217
226
  await page.evaluate(()=>{for(const o of window.__wsBoards??[])o.visible=true;window.__wsBoards=[];});
218
- row.poses.push({n:c.n??i+1,name:c.name,free,drifted,sunk,idle,live,residency,...observed,...(exp?{exp:expResult}:{}),shot});
227
+ // the ring, the grass and the culling stream round the player: one that ended up far from its pose (killed and respawned,
228
+ // knocked away) shot the camera's view with somewhere else's ground cover, so the frame is an error, not a golden
229
+ const away=Math.hypot(observed.player[0]-at.x,observed.player[2]-at.z);if(away>AWAY)row.errors.push(`camera ${c.n??i+1}: the player stood ${away.toFixed(0)} m from its pose at the shot`);
230
+ row.poses.push({n:c.n??i+1,name:c.name,free,drifted,sunk,away,idle,live,residency,...observed,...(exp?{exp:expResult}:{}),shot});
219
231
  writeFileSync(`${root}/receipts-${slug}.json`,JSON.stringify(row,null,1));
220
232
  }
221
233
  row.status=row.errors.length===0?'complete':'errors';
222
234
  }catch(error){row.status='failed';row.failure=String(error);if(page)await page.screenshot({path:`${dir}/failure.jpg`,type:'jpeg',quality:80,scale:'css'}).catch(()=>{});}
223
235
  finally{if(SERVE_OVER)row.servedOver=[...overHits].sort();rows.push(row);writeFileSync(`${root}/receipts-${slug}.json`,JSON.stringify(row,null,1));writeFileSync(`${root}/receipts.json`,JSON.stringify(rows,null,2));await context.close();
224
236
  console.log(JSON.stringify({slug,status:row.status,poses:row.poses.length,idle:row.poses.map(p=>p.idle.settled),failure:row.failure,errors:row.errors.slice(0,3),warnings:Object.values(row.warnings).reduce((n,c)=>n+c,0),...(SERVE_OVER?{servedOver:overHits.size}:{})}));}
225
- if(row.status==='failed')process.exitCode=1;
237
+ if(row.status!=='complete')process.exitCode=1;
226
238
  }}finally{try{await browser.close();}finally{await owner?.close();}}
@@ -3,8 +3,10 @@ export function workingGoldenPreviewFolder(record:string):string;
3
3
  export function goldenRefinementBinding(base:string,source:{build:string;sha:string}):Promise<{
4
4
  initializerExport:string;classExport:string;sha:string;build:string;preview:string;nineIndexSHA256:string;chunk:string;chunkSHA256:string;
5
5
  }>;
6
+ export function buildCodeChunks(root:string,build:string):string[];
6
7
  export function refinementExports(source:string):{initializerExport:string;classExport:string};
7
8
  export function observeRefinement<T extends readonly unknown[]>(proto:{add:(...args:T)=>Promise<boolean>}):{
8
9
  jobs:{id:T[0];at:T[1];state:string;error?:string}[];
9
10
  };
10
11
  export function heldGoldenResidency():Promise<unknown>;
12
+ export function goldenScriptPaths(graph: unknown, build: string): string[];
@@ -38,17 +38,44 @@ export async function goldenRefinementBinding(base,source) {
38
38
  throw new Error('Native reader requires the served Nine product');
39
39
  const servedIndex=Buffer.from(await(await fetch(new URL('/shardfiles/nine-dragon-stack/shard.json',base))).arrayBuffer());
40
40
  if(!servedIndex.equals(index))throw new Error('Served Nine index differs from exact preview');
41
- const code=`b/${source.build}`,codeFolder=existsSync(join(root,code))?code:'assets',dist=join(root,codeFolder);
42
- const chunks=readdirSync(dist).filter(file=>file.endsWith('.js')).map(file=>({file,bytes:readFileSync(join(dist,file))}))
41
+ const chunks=buildCodeChunks(root,source.build).map(chunk=>({chunk,bytes:readFileSync(join(root,chunk))}))
43
42
  .filter(row=>row.bytes.includes('Invalid or duplicate refinement job'));
44
43
  if (chunks.length!==1) throw new Error('Native refinement chunk is missing or ambiguous');
45
- const {file,bytes}=chunks[0],binding=refinementExports(bytes.toString('utf8'));
46
- const chunk=`/${codeFolder}/${file}`,served=Buffer.from(await(await fetch(new URL(chunk,base))).arrayBuffer());
44
+ const {chunk,bytes}=chunks[0],binding=refinementExports(bytes.toString('utf8'));
45
+ const served=Buffer.from(await(await fetch(new URL(chunk,base))).arrayBuffer());
47
46
  if (!served.equals(bytes)) throw new Error('Served native refinement differs from exact preview');
48
47
  return {...binding,sha:pinned?.sha??source.sha,build:source.build,preview:pinned===undefined?'working-tree':'pinned',
49
48
  nineIndexSHA256:createHash('sha256').update(index).digest('hex'),chunk,chunkSHA256:createHash('sha256').update(served).digest('hex')};
50
49
  }
51
50
 
51
+ /** Prefer the current build's chunk ownership graph (PZ5). Legacy builds use their own folder `b/<build>`, plus the
52
+ * content-named chunks in the shared `b/c` that its `importmap.json` names (J217
53
+ * LD6). The shared folder can also hold other builds' chunks, so it is never
54
+ * listed. A build without `b/<build>` keeps everything in `assets/`.
55
+ * @param {string} root the preview's dist @param {string} build */
56
+ export function buildCodeChunks(root,build) {
57
+ const graph=join(root,'deploy-chunks.json');
58
+ if (existsSync(graph)) return goldenScriptPaths(JSON.parse(readFileSync(graph,'utf8')),build).map(file=>`/${file}`);
59
+ const own=`b/${build}`;
60
+ if (!existsSync(join(root,own))) return readdirSync(join(root,'assets')).filter(file=>file.endsWith('.js')).map(file=>`/assets/${file}`);
61
+ const chunks=readdirSync(join(root,own)).filter(file=>file.endsWith('.js')).map(file=>`/${own}/${file}`);
62
+ const map=join(root,'importmap.json');
63
+ if (existsSync(map)) for (const target of Object.values(JSON.parse(readFileSync(map,'utf8')).imports??{}))
64
+ if (typeof target==='string'&&target.startsWith('/b/c/')&&target.endsWith('.js')&&!chunks.includes(target)) chunks.push(target);
65
+ return chunks;
66
+ }
67
+
68
+ /** The current build's owned JavaScript, including shared chunks, excluding carry-only files.
69
+ * @param {unknown} graph @param {string} build @returns {string[]} */
70
+ export function goldenScriptPaths(graph,build) {
71
+ const rows=typeof graph==='object'&&graph!==null?Reflect.get(graph,'builds'):undefined;
72
+ if (!Array.isArray(rows)) throw new Error('Golden chunk graph is missing');
73
+ const owners=rows.filter(row=>row?.build===build);
74
+ if (owners.length!==1||!Array.isArray(owners[0].files)) throw new Error('Golden build chunk ownership is ambiguous');
75
+ return owners[0].files.map(row=>row.path).filter(path=>typeof path==='string'&&path.endsWith('.js')
76
+ &&path.startsWith('b/')&&!path.split('/').some(part=>part==='..'||part===''||part.includes('\\')));
77
+ }
78
+
52
79
  /** Fail closed when the compiler shape changes; no guessed export or copied release binding.
53
80
  * @param {string} source */
54
81
  export function refinementExports(source) {
@@ -0,0 +1,209 @@
1
+ #!/usr/bin/env node
2
+ // Road lag (Jake, 2026-11-15: "Last time I tried going to the road, there was a lot of lag"): from a home cell, step out of its
3
+ // entryway onto the road and back in, by real input, a few times, and measure what the player feels at each line: every frame's
4
+ // time (requestAnimationFrame) in the window from 1 s before to 3 s after the feet cross, any loading card on screen in it, and the
5
+ // longest stretch under 90 % of the approach speed with the key held (the road bar's stop). One JSON per run, plus a printed line per crossing.
6
+ // scripts/browser-lane.sh node scripts/grid-road-lag.mjs --base=<staging, preview or loopback> --out=<dir> [--home=driftwood|nalati]
7
+ // [--viewport=2992x1434@2] [--reps=3] [--engine=chromium|webkit] [--run] (sprint) [--device='iPhone 15 Pro'] (a phone: its viewport, touch and agent)
8
+ // [--profile] (Chromium: the page thread's CPU profile over the first lap, with `at`, its start on the page's clock)
9
+ // On preview or a loopback page the walker is set 20 m inside the home cell's road-facing entryway by the in-page harness pose; on
10
+ // staging (an online seat can't be placed) only Driftwood is walked to its east entryway from the spawn. Never production (J205).
11
+ import { mkdirSync, writeFileSync } from 'node:fs';
12
+ import { join, resolve as absolute } from 'node:path';
13
+ import { chromium, devices, webkit } from 'playwright';
14
+ import { KEYCHAIN_ARGS } from './chromium-keychain.mjs';
15
+ import { saveFixture } from './debug-settings.mjs';
16
+
17
+ /** @param {string} name @param {string} fallback */
18
+ const flag = (name, fallback) => process.argv.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback;
19
+ /** A program row on a crossing's clock (`at`, its line), its `again` and `released` marks only when set. @param {any} r @param {number} at */
20
+ const programRow = (r, at) => ({ t: r.t - at, name: r.name, key: r.key, ...(r.again === true ? { again: true } : {}), ...(r.released === true ? { released: true } : {}) });
21
+ /** A row on a crossing's clock. @param {any} r @param {number} at */
22
+ const shifted = (r, at) => ({ ...r, t: r.t - at });
23
+ const base = flag('base', '').replace(/\/$/u, ''), out = absolute(flag('out', '')), engineName = flag('engine', 'chromium'), device = flag('device', ''), run = process.argv.includes('--run'), profile = process.argv.includes('--profile'), reps = Number(flag('reps', '3'));
24
+ if (!/^https:\/\/(preview|staging)\.wildshard\.io$|^http:\/\/127\.0\.0\.1:\d+$/u.test(base) || out === absolute('')) throw new Error('usage: grid-road-lag.mjs --base=<staging, preview or loopback url> --out=<dir> [--home=driftwood|nalati] [--viewport=WxH@dpr] [--reps=n]');
25
+ const online = base.includes('staging');
26
+ /** Each home's road-facing entryway (the middle of an edge, in the cell's own metres) and the yaw that walks out through it (the
27
+ * page's motor faces atan2(own - target): +x is -π/2, -x is π/2, +z is π, -z is 0). Driftwood's east faces Nalati, Nalati's west faces Driftwood. */
28
+ const HOMES = /** @type {Record<string, { slug: string, card: string, axis: 'x' | 'z', sign: number, approach: [number, number][] }>} */ ({
29
+ driftwood: { slug: 'driftwood-isle', card: 'Driftwood Isle', axis: 'x', sign: 1, approach: [[235, -194], [235, 0]] },
30
+ nalati: { slug: 'nalati-grasslands', card: 'Nalati Grasslands', axis: 'x', sign: -1, approach: [] },
31
+ sunscar: { slug: 'sunscar-dunes', card: 'Signal Dunes', axis: 'x', sign: 1, approach: [] },
32
+ pine: { slug: 'pine-hollow', card: 'Pine Hollow', axis: 'x', sign: 1, approach: [] } });
33
+ const homeName = flag('home', 'driftwood'), home = HOMES[homeName];
34
+ if (home === undefined) throw new Error(`No home ${homeName}: ${Object.keys(HOMES).join(', ')}`);
35
+ if (online && home.approach.length === 0) throw new Error(`${homeName} has no walked approach for an online seat: use preview or a loopback page`);
36
+ const desk = (/^(\d+)x(\d+)@([\d.]+)$/u.exec(flag('viewport', '2992x1434@2')) ?? [0, '2992', '1434', '2']).slice(1).map(Number);
37
+ const sleep = (/** @type {number} */ ms) => new Promise(resolve => { setTimeout(resolve, ms); });
38
+ mkdirSync(out, { recursive: true });
39
+
40
+ const result = { base, home: home.slug, engine: engineName, viewport: `${String(desk[0])}x${String(desk[1])}@${String(desk[2])}`, at: new Date().toISOString(), build: '', crossings: /** @type {Record<string, unknown>[]} */ ([]), errors: /** @type {string[]} */ ([]), note: '', crossingTiming: /** @type {unknown} */ (null) };
41
+ const browser = await (engineName === 'webkit' ? webkit : chromium).launch({ headless: true, args: engineName === 'chromium' ? [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist'] : [] });
42
+ let code = 1;
43
+ try {
44
+ result.build = await fetch(`${base}/version.json`).then(async found => String((await found.json()).build)).catch(() => '');
45
+ const phone = device === '' ? undefined : devices[device];
46
+ if (device !== '' && phone === undefined) throw new Error(`No Playwright device ${device}`);
47
+ if (phone !== undefined) result.viewport = `${device} ${String(phone.viewport.width)}x${String(phone.viewport.height)}@${String(phone.deviceScaleFactor)}`;
48
+ const context = await browser.newContext(phone ?? { viewport: { width: desk[0] ?? 2992, height: desk[1] ?? 1434 }, deviceScaleFactor: desk[2] ?? 2 }), page = await context.newPage();
49
+ page.on('pageerror', error => { result.errors.push(error.message.slice(0, 240)); });
50
+ await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
51
+ await saveFixture(context, { scope: 'device', key: 'devMode', data: true });
52
+ await saveFixture(context, { scope: 'global', key: 'settings', merge: true, data: { volume: 0 } });
53
+ await page.goto(`${base}/?mute=1&nolock=1`, { waitUntil: 'load' });
54
+ await page.locator('.ws-main-select').click({ timeout: 120_000 });
55
+ if (await page.locator('#ws-name-box input').waitFor({ timeout: 30_000 }).then(() => true).catch(() => false)) { await page.locator('#ws-name-box input').fill('roadlag'); await page.locator('#ws-name-box button[type=submit]').click(); }
56
+ await page.locator('.ws-menu-card').first().waitFor({ state: 'visible', timeout: 30_000 });
57
+ const index = await page.evaluate(card => [...document.querySelectorAll('.ws-menu-card')].findIndex(row => (row.textContent ?? '').includes(card)), home.card);
58
+ if (index < 0) throw new Error(`No ${home.card} card`);
59
+ await page.locator('.ws-menu-dots i').nth(index).click();
60
+ await page.locator('.ws-menu-play').click();
61
+ await page.waitForFunction(() => /** @type {any} */ (window).__wildshard?.shard?.grid?.state?.().live?.live?.gameplayReady === true, undefined, { timeout: 180_000, polling: 100 });
62
+ await sleep(2000);
63
+ await page.getByText('DONE', { exact: true }).click({ timeout: 2000 }).catch(() => undefined);
64
+ // every drawn frame [t, ms] and a 50 ms sample of where the feet are and what the screen shows
65
+ await page.evaluate(() => {
66
+ const W = /** @type {any} */ (window), q = W.__road = { frames: /** @type {number[][]} */ ([]), samples: /** @type {any[]} */ ([]), programs: /** @type {any[]} */ ([]), slowLinks: /** @type {any[]} */ ([]) };
67
+ // every shader program the renderer links, with when it was first seen: a crossing that compiles one stalls its frame
68
+ const known = new Set(W.__wildshard?.world?.game?.renderer?.info?.programs);
69
+ // a key linked once before and released since links again: `again` tells a re-link from a first link
70
+ const seenKeys = new Set([...known].map((/** @type {any} */ program) => String(program.cacheKey)));
71
+ let held = new Set(known);
72
+ // and every program whose first use blocked the page (a link the driver finished only when asked): which, and how long
73
+
74
+ const renderer = W.__wildshard?.world?.game?.renderer, gl = renderer?.getContext?.();
75
+ if (gl !== undefined) {
76
+ const ask = gl.getProgramParameter.bind(gl);
77
+ gl.getProgramParameter = (/** @type {WebGLProgram} */ handle, /** @type {number} */ name) => {
78
+ const t0 = performance.now(), value = ask(handle, name), ms = performance.now() - t0;
79
+ if (ms > 8) {
80
+ const all = renderer.info.programs ?? [], found = all.find((/** @type {any} */ row) => row.program === handle), key = String(found?.cacheKey ?? '');
81
+ // ZE2d: what this link differs in from the same material's programs already linked: the key's comma fields that differ
82
+ const custom = (/** @type {string} */ k) => k.slice(Math.max(0, k.lastIndexOf(',srgb,'))), head = (/** @type {string} */ k) => k.slice(0, Math.max(0, k.lastIndexOf(',srgb,')));
83
+ const fields = head(key).split(','), siblings = all.filter((/** @type {any} */ row) => row !== found && row.name === found?.name && custom(String(row.cacheKey)) === custom(key)).map((/** @type {any} */ row) => head(String(row.cacheKey)).split(','));
84
+ const diffs = siblings.slice(0, 4).map((/** @type {string[]} */ other) => other.length !== fields.length ? `len ${String(other.length)}/${String(fields.length)}` : fields.map((f, i) => f === other[i] ? null : `${String(i)}:${other[i] ?? ''}->${f}`).filter(x => x !== null).join(' '));
85
+ // who drew it
86
+ const owners = /** @type {string[]} */ ([]);
87
+ try { W.__wildshard.world.game.scene.traverse((/** @type {any} */ o) => { if (owners.length >= 3 || o.material === undefined) return; for (const m of Array.isArray(o.material) ? o.material : [o.material]) if (renderer.properties.get(m)?.currentProgram?.program === handle) { const n = []; for (let at = o; at !== null && at !== undefined && n.length < 5; at = at.parent) n.push(String(at.name === '' ? at.type : at.name)); owners.push(n.join('<')); } }); } catch { /* best effort */ }
88
+ q.slowLinks.push({ t: Math.round(t0), ms: Math.round(ms), name: String(found?.name ?? ''), fields: fields.length, tail: fields.slice(-24).join(','), diffs, owners, env: String(W.__wildshard.world.game.scene.environment?.image?.height ?? null) });
89
+ }
90
+ return value;
91
+ };
92
+ }
93
+ let last = performance.now();
94
+ const raf = (/** @type {number} */ now) => { q.frames.push([Math.round(now), Number((now - last).toFixed(1))]); last = now; requestAnimationFrame(raf); };
95
+ requestAnimationFrame(raf);
96
+ setInterval(() => { try {
97
+ const st = W.__wildshard.shard.grid.state(), p = W.__wildshard.world.player;
98
+ const wf = st.live?.live?.worldFeet ?? p.position;
99
+ const now = W.__wildshard.world.game?.renderer?.info?.programs ?? [];
100
+ for (const program of now) if (!known.has(program)) { known.add(program); const key = String(program.cacheKey ?? ''); q.programs.push({ t: Math.round(performance.now()), name: String(program.name ?? ''), key: key.length > 700 && !/creature|wildlife/u.test(String(program.name)) ? `${key.slice(0, 300)} … ${key.slice(-300)}` : key, again: seenKeys.has(key) }); seenKeys.add(key); }
101
+ const live = new Set(now);
102
+ for (const program of held) if (!live.has(program)) q.programs.push({ t: Math.round(performance.now()), name: String(program.name ?? ''), key: ((k) => k.length > 700 ? `${k.slice(0, 300)} … ${k.slice(-300)}` : k)(String(program.cacheKey ?? '')), released: true });
103
+ held = live;
104
+ q.samples.push({ t: Math.round(performance.now()), x: Number(wf.x.toFixed(2)), z: Number(wf.z.toFixed(2)), inside: st.inside, phase: st.live?.crossing?.phase ?? null, card: st.cellLoading ?? null, stage: st.cellStage ?? null, ready: st.live?.live?.gameplayReady, res: st.live?.live?.residents ?? null, cx: st.live?.live?.crossings ?? null, cur: st.live?.live?.current ?? null, hy: st.hybrid?.instance ?? null, hook: st.hybrid?.hook ?? null });
105
+ } catch (error) { q.samples.push({ err: String(error).slice(0, 700) }); } }, 50);
106
+ });
107
+ const sample = () => page.evaluate(() => { const rows = /** @type {any[]} */ (/** @type {any} */ (window).__road.samples); for (let at = rows.length - 1; at >= 0; at--) if (rows[at].err === undefined) return rows[at]; return undefined; });
108
+ const face = (/** @type {number} */ yaw) => page.evaluate(wanted => { /** @type {any} */ (window).__wildshard.world.player.yaw = wanted; }, yaw);
109
+ const edge = 250, along = home.axis;
110
+ if (online) {
111
+ await page.keyboard.down('ShiftLeft');
112
+ for (const [x, z] of home.approach) {
113
+ await page.keyboard.down('KeyW');
114
+ for (let ends = Date.now() + 90_000, near = Infinity; Date.now() < ends && near > 3; await sleep(250)) {
115
+ const at = await sample(); near = Math.hypot(at.x - x, at.z - z); await face(Math.atan2(at.x - x, at.z - z));
116
+ }
117
+ await page.keyboard.up('KeyW');
118
+ }
119
+ await page.keyboard.up('ShiftLeft');
120
+ } else {
121
+ const [x, z] = along === 'x' ? [home.sign * (edge - 20), 0] : [0, home.sign * (edge - 20)];
122
+ 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); }, [x, z]);
123
+ }
124
+ await sleep(4000);
125
+ // ZE2d: what the boot prelinked for the road before the first walk out: each road program's environment height and light
126
+ // fields (the key's 3, 4, 51, 52), and the environments the page and the root scene hold now
127
+ /** @type {any} */ (result).bootRoad = await page.evaluate(() => {
128
+ const W = /** @type {any} */ (window), game = W.__wildshard.world.game, height = (/** @type {any} */ t) => t?.image?.height ?? null;
129
+ const programs = (game.renderer.info.programs ?? []).filter((/** @type {any} */ p) => String(p.name).startsWith('grid-')).map((/** @type {any} */ p) => { const f = String(p.cacheKey).split(','); return `${String(p.name)} ${f[3] ?? ''} ${f[4] ?? ''} ${f[51] ?? ''} ${f[52] ?? ''}`; });
130
+ // and the home's creatures: each graph body's linked programs (key fields 3, 4, 51, 52) and the hidden warm rigs (DL24)
131
+ // parked anywhere in the page, by material
132
+ const creatures = (game.renderer.info.programs ?? []).filter((/** @type {any} */ p) => /creature|wildlife/u.test(String(p.name))).map((/** @type {any} */ p) => `${String(p.name)} ${String(p.cacheKey)}`);
133
+ const warm = /** @type {string[]} */ ([]);
134
+ for (const root of [game.scene, game.rootScene]) root?.traverse((/** @type {any} */ o) => { if (o.name !== 'creature-warm') return; o.traverse((/** @type {any} */ m) => { for (const mat of m.material === undefined ? [] : Array.isArray(m.material) ? m.material : [m.material]) warm.push(`${String(mat.name === '' ? mat.type : mat.name)}${(o.parent?.name ?? '') === '' ? '' : ` in ${String(o.parent.name)}`}`); }); });
135
+ return { programs, creatures, warm: [...new Set(warm)], scene: height(game.scene.environment), root: height(game.rootScene?.environment), exterior: W.__wildshard.shard.grid.exterior?.() ?? 'none', sameScene: game.scene === game.rootScene };
136
+ });
137
+ if (process.argv.includes('--reprelink')) {
138
+ await page.evaluate(() => { /** @type {any} */ (window).__wildshard.shard.grid.prelink(); });
139
+ await sleep(5000);
140
+ /** @type {any} */ (result).bootRoadAgain = await page.evaluate(() => (/** @type {any} */ (window).__wildshard.world.game.renderer.info.programs ?? []).filter((/** @type {any} */ p) => String(p.name).startsWith('grid-')).map((/** @type {any} */ p) => { const f = String(p.cacheKey).split(','); return `${String(p.name)} ${f[3] ?? ''} ${f[4] ?? ''} ${f[51] ?? ''} ${f[52] ?? ''}`; }));
141
+ }
142
+ // the walk's lines are in the home's own coordinates: world feet less the home cell's origin
143
+ const originAt = 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 }; });
144
+ const local = (/** @type {any} */ s) => s[along] - originAt[along];
145
+ const outward = along === 'x' ? (home.sign > 0 ? -Math.PI / 2 : Math.PI / 2) : (home.sign > 0 ? Math.PI : 0);
146
+ let heldUntil = Infinity;
147
+ const t = () => page.evaluate(() => Math.round(performance.now()));
148
+ /** Walk with W held until `done(sample)` or 40 s; returns the wall time it took. */
149
+ const walk = async (/** @type {number} */ yaw, /** @type {(s: any) => boolean} */ done) => {
150
+ await face(yaw); if (run) await page.keyboard.down('ShiftLeft'); await page.keyboard.down('KeyW');
151
+ const t0 = Date.now();
152
+ for (let s = await sample(); Date.now() - t0 < 40_000 && !done(s); s = await sample()) await sleep(100);
153
+ heldUntil = await t(); await page.keyboard.up('KeyW'); if (run) await page.keyboard.up('ShiftLeft'); return Date.now() - t0;
154
+ };
155
+ /** One crossing's numbers from the page's frames and samples around the first sample past the line */
156
+ const measure = async (/** @type {string} */ name, /** @type {number} */ fromT) => {
157
+ const { frames, samples, programs, slowLinks } = await page.evaluate(after => { const q = /** @type {any} */ (window).__road; return { slowLinks: /** @type {any[]} */ (q.slowLinks.filter((/** @type {any} */ r) => r.t >= after)), programs: /** @type {any[]} */ (q.programs.filter((/** @type {any} */ r) => r.t >= after)), frames: /** @type {number[][]} */ (q.frames.filter((/** @type {number[]} */ r) => (r[0] ?? 0) >= after)), samples: /** @type {any[]} */ (q.samples.filter((/** @type {any} */ r) => r.err === undefined && r.t >= after)) }; }, fromT);
158
+ const leaving = name.startsWith('out'), line = samples.find((s, i) => i > 0 && (leaving ? s.inside === null && samples[i - 1].inside !== null : s.inside === home.slug && samples[i - 1].inside !== home.slug));
159
+ if (line === undefined) return { name, crossed: false };
160
+ const span = frames.filter(r => (r[0] ?? 0) >= line.t - 1000 && (r[0] ?? 0) <= line.t + 3000).map(r => r[1] ?? 0), sorted = [...span].sort((a, b) => a - b);
161
+ const cards = samples.filter(s => s.t >= line.t - 1000 && s.t <= line.t + 3000 && s.card !== null);
162
+ // the road bar's stop: ground speed under 90 % of the approach's median, counted only while the key is held
163
+ let stop = 0, worstStop = 0;
164
+ const near = samples.filter(s => s.t >= line.t - 1000 && s.t <= line.t + 3000), held = near.filter(s => s.t <= heldUntil);
165
+ const speed = (/** @type {number} */ i) => Math.hypot(held[i].x - held[i - 1].x, held[i].z - held[i - 1].z) / Math.max(1, held[i].t - held[i - 1].t);
166
+ const approach = held.map((_, i) => i > 0 && held[i].t < line.t - 200 ? speed(i) : Number.NaN).filter(v => Number.isFinite(v)).sort((a, b) => a - b), cruise = approach[Math.floor(approach.length / 2)] ?? 0;
167
+ let stopAt = null;
168
+ // a walk that starts within the window starts from rest: count only once the feet first reach the approach's speed
169
+ for (let i = 1, moving = false; i < held.length; i++) { const slow = speed(i) < cruise * 0.9; moving ||= !slow; if (!moving) continue; stop = slow ? stop + (held[i].t - held[i - 1].t) : 0; if (stop > worstStop) { worstStop = stop; stopAt = { endsMs: held[i].t - line.t, x: held[i].x, z: held[i].z }; } }
170
+ return { name, crossed: true, lineAt: line.t, frames: span.length, worstFrameMs: sorted.at(-1) ?? 0, p95Ms: sorted[Math.floor(sorted.length * 0.95)] ?? 0, medianMs: sorted[Math.floor(sorted.length / 2)] ?? 0,
171
+ over33: span.filter(ms => ms > 33.4).length, over50: span.filter(ms => ms > 50).length, over100: span.filter(ms => ms > 100).length,
172
+ trace: near.filter((_, i) => i % 2 === 0).map(s => [s.t - line.t, s.x, s.z, s.inside, s.cur, s.cx, s.phase, s.card, s.stage, s.res, s.hy, s.hook]), cardMs: cards.length * 50, cards: [...new Set(cards.map(s => `${String(s.card)}:${String(s.stage)}`))], worstStopMs: worstStop, stopAt, cruiseMps: Number((cruise * 1000).toFixed(2)), phases: [...new Set(near.map(s => s.phase))],
173
+ programs: programs.filter(r => r.t >= line.t - 1000 && r.t <= line.t + 3000).map(r => programRow(r, line.t)),
174
+ releasedBefore: programs.filter(r => r.released === true && r.t < line.t - 1000).map(r => ({ t: r.t - line.t, name: r.name, key: r.key })),
175
+ slowLinks: slowLinks.filter(r => r.t >= line.t - 1000 && r.t <= line.t + 3000).map(r => shifted(r, line.t)) };
176
+ };
177
+ const cdp = profile && engineName === 'chromium' ? await context.newCDPSession(page) : undefined;
178
+ let profileAt = 0;
179
+ // --profile-lap=<n>: the profile covers that lap (default the first; a later lap shows what a warm page still pays)
180
+ const profileLap = Number(flag('profile-lap', '1'));
181
+ if (cdp !== undefined) await cdp.send('Profiler.enable');
182
+ for (let rep = 1; rep <= reps; rep++) {
183
+ if (cdp !== undefined && rep === profileLap) { await cdp.send('Profiler.setSamplingInterval', { interval: 250 }); await cdp.send('Profiler.start'); profileAt = await t(); }
184
+ let from = await t();
185
+ await walk(outward, s => s.inside === null && Math.abs(local(s)) >= edge + 12);
186
+ await sleep(2500);
187
+ result.crossings.push({ rep, ...await measure('out (cell to road)', from) });
188
+ from = await t();
189
+ await walk(outward + Math.PI, s => s.inside === home.slug && Math.abs(local(s)) <= edge - 12);
190
+ await sleep(2500);
191
+ result.crossings.push({ rep, ...await measure('back (road to cell)', from) });
192
+ if (cdp !== undefined && rep === profileLap) {
193
+ const { profile: taken } = await cdp.send('Profiler.stop');
194
+ writeFileSync(join(out, `${engineName}${device === '' ? '' : '-phone'}${run ? '-run' : ''}-${homeName}-lap${String(profileLap)}.cpuprofile.json`), JSON.stringify({ at: profileAt, base, profile: taken }));
195
+ }
196
+ for (const row of result.crossings.slice(-2)) console.log(`${row.crossed === true ? 'ok ' : 'FAIL'} ${homeName} rep ${String(rep)} ${String(row.name)} ${JSON.stringify({ worst: row.worstFrameMs, p95: row.p95Ms, over50: row.over50, over100: row.over100, card: row.cardMs, stop: row.worstStopMs })}`);
197
+ }
198
+ await page.screenshot({ path: join(out, `${engineName}${device === '' ? '' : '-phone'}${run ? '-run' : ''}-${homeName}-road-lag.png`) });
199
+ // ZE2d: every road program the run linked or released, by page time (the crossings' `lineAt` place them)
200
+ /** @type {any} */ (result).roadPrograms = await page.evaluate(() => /** @type {any[]} */ (/** @type {any} */ (window).__road.programs).filter(p => String(p.name).startsWith('grid-') || p.name === '').map(p => { const f = String(p.key).split(','); return `${String(p.t)} ${String(p.name)} ${f[3] ?? ''} ${f[4] ?? ''} ${f[51] ?? ''} ${f[52] ?? ''}${p.released === undefined ? '' : ' released'}`; }));
201
+ result.crossingTiming = await page.evaluate(() => /** @type {any} */ (window).__wildshard.shard.grid.state().live?.crossingTiming ?? null);
202
+ await context.close();
203
+ code = result.crossings.every(row => row.crossed === true) && result.errors.length === 0 ? 0 : 1;
204
+ } catch (error) { result.note = String(error).slice(0, 400); console.log(`FAIL ${result.note}`); }
205
+ finally {
206
+ writeFileSync(join(out, `${engineName}${device === '' ? '' : '-phone'}${run ? '-run' : ''}-${homeName}-road-lag.json`), `${JSON.stringify(result, null, 2)}\n`);
207
+ await browser.close();
208
+ }
209
+ process.exit(code);