@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
@@ -0,0 +1,9 @@
1
+ /* ZE8: the gate card, in Shard Select's card language (glass, cyan line, mono), standing on the gate's face */
2
+ .ws-gate-card { position: fixed; left: 0; top: 0; z-index: calc(var(--ws-layer-hud) + 30); pointer-events: none; width: 220px; padding: 14px 16px 16px; text-align: center; transform-origin: 50% 100%;
3
+ background: var(--ws-glass-deep, rgba(9, 22, 36, 0.88)); border: 1px solid var(--ws-cyan-line, rgba(143, 227, 255, 0.4)); color: var(--ws-text, #e8f6ff);
4
+ font-family: var(--ws-mono, ui-monospace, monospace); box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.35), 0 12px 40px rgba(0, 0, 0, 0.45);
5
+ -webkit-backdrop-filter: blur(10px) saturate(1.2); backdrop-filter: blur(10px) saturate(1.2); }
6
+ .ws-gate-card[hidden] { display: none; }
7
+ .ws-gate-card .ws-gate-name { font-size: 15px; letter-spacing: 0.08em; text-transform: uppercase; }
8
+ .ws-gate-card .ws-gate-line { margin-top: 6px; font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; opacity: 0.75; }
9
+ .ws-gate-card .ws-gate-count { margin-top: 8px; font-size: 44px; line-height: 1; color: var(--ws-cyan, #38e6ff); }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * ZONE-ENTRY ZE8 (J352): the gate card. Feet in a walled cell's buffer show it on that buffer's gate: the shard's name, "Preparing
3
+ * to enter" and the count (`GateCount`). It is a crisp DOM card in Shard Select's card style, pinned each frame to the gate's face
4
+ * through the camera and scaled with distance, so it reads as standing in the world (board pick A), never G578's blurry canvas
5
+ * panel. A cell the device can't enter shows its reason in place of the count (ZE14). No button: standing there is the yes.
6
+ */
7
+ import { Vector3, type Camera } from 'three';
8
+ import type { Scope } from '@wildshard/engine/app/scope';
9
+ import { CHUNK_HALF } from '@wildshard/engine/core/config';
10
+ import { GAME_STRINGS } from '../../../shared/game/strings';
11
+ import { BUFFER_DEPTH } from '../../../shared/game/grid/zoneWalls';
12
+ import './gateCard.css';
13
+
14
+ /** The card's height on the gate (metres above the road) and the distance it is drawn at its full size. */
15
+ const LIFT = 2.6, FULL_AT = 9;
16
+
17
+ export interface GateCardView {
18
+ /** the gate's cell centre in the render frame, and the feet there: the gate faced is the side nearest the feet */
19
+ readonly centre: { readonly x: number; readonly z: number };
20
+ readonly feet: { readonly x: number; readonly z: number };
21
+ readonly name: string;
22
+ readonly count: number;
23
+ /** why the cell can't be entered from here, shown in place of the count */
24
+ readonly reason?: string | null;
25
+ }
26
+
27
+ export class GateCard {
28
+ readonly root: HTMLElement;
29
+ private readonly name: HTMLElement;
30
+ private readonly count: HTMLElement;
31
+ private readonly at = new Vector3();
32
+ private shown: string | null = null;
33
+
34
+ constructor(scope: Scope, parent: HTMLElement = document.body) {
35
+ const root = this.root = document.createElement('div');
36
+ root.className = 'ws-gate-card'; root.hidden = true; root.setAttribute('role', 'status');
37
+ this.name = document.createElement('div'); this.name.className = 'ws-gate-name';
38
+ const line = document.createElement('div'); line.className = 'ws-gate-line'; line.textContent = GAME_STRINGS.grid.gatePreparing;
39
+ this.count = document.createElement('div'); this.count.className = 'ws-gate-count';
40
+ root.append(this.name, line, this.count); parent.append(root);
41
+ scope.onDispose(() => { root.remove(); });
42
+ }
43
+
44
+ /** Pin the card to its gate, or hide it with `null`. */
45
+ show(view: GateCardView | null, camera: Camera | undefined, width: number, height: number): void {
46
+ if (view === null || camera === undefined) { this.hide(); return; }
47
+ const dx = view.feet.x - view.centre.x, dz = view.feet.z - view.centre.z, alongX = Math.abs(dx) >= Math.abs(dz);
48
+ const face = CHUNK_HALF - BUFFER_DEPTH - 0.3;
49
+ this.at.set(view.centre.x + (alongX ? Math.sign(dx) * face : 0), LIFT, view.centre.z + (alongX ? 0 : Math.sign(dz) * face));
50
+ const distance = Math.max(0.5, this.at.distanceTo(camera.position));
51
+ this.at.project(camera);
52
+ if (this.at.z > 1 || Math.abs(this.at.x) > 1.4 || Math.abs(this.at.y) > 1.4) { this.hide(); return; }
53
+ const key = `${view.name}|${String(view.count)}|${view.reason ?? ''}`;
54
+ if (key !== this.shown) {
55
+ this.shown = key; this.name.textContent = view.name;
56
+ this.count.textContent = view.reason ?? String(Math.max(1, view.count));
57
+ }
58
+ const scale = Math.min(1.2, Math.max(0.45, FULL_AT / distance));
59
+ const x = (this.at.x * 0.5 + 0.5) * width, y = (-this.at.y * 0.5 + 0.5) * height;
60
+ this.root.style.transform = `translate(${x.toFixed(1)}px, ${y.toFixed(1)}px) translate(-50%, -100%) scale(${scale.toFixed(3)})`;
61
+ this.root.hidden = false;
62
+ }
63
+
64
+ hide(): void { if (this.root.hidden !== true) this.root.hidden = true; this.shown = null; }
65
+ /** the card's text while shown (proofs read it) */
66
+ get text(): string | null { return this.root.hidden === true ? null : `${this.name.textContent ?? ''} ${this.count.textContent ?? ''}`; }
67
+ }
@@ -72,6 +72,10 @@ export interface LiveGridPorts {
72
72
  /** Keep only the last departed isolated world on the road. Its original
73
73
  * full claim stays unneeded/evictable; no new world may overlap it. */
74
74
  lastCell?: { readonly windowMs: number; readonly playingBytes: number;
75
+ /** ZE3 / ZE21 (J352): the owned home, once departed onto the road, has no time expiry: it stays resident, and needed (never
76
+ * a pressure eviction), while the traveller is within this many metres of it (the page passes Infinity: the whole road),
77
+ * and is retired before any other cell's allocation. Absent: every cell expires. */
78
+ readonly keepHome?: number;
75
79
  readonly schedule: (expire: () => void, delayMs: number) => () => void };
76
80
  /** G580 T2: told once before a resident's retirement or unload disposes its world, so its compiled programs can be kept
77
81
  * for the next world; never refuses a retirement. Absent keeps nothing. */
@@ -142,7 +146,9 @@ export class LiveGridHost {
142
146
  private readonly highway: LiveGridHighway;
143
147
  private sequence: Promise<void> = Promise.resolve();
144
148
  private active: string | null;
145
- private lastCell: { readonly instance: string; readonly until: number; cancel: () => void } | null = null;
149
+ /** `pinned`: the owned home kept on the road (ZE21): needed while kept, so allocator pressure (a neighbour's tiles or
150
+ * products) is refused rather than evicting it. */
151
+ private lastCell: { readonly instance: string; readonly until: number; readonly pinned: boolean; cancel: () => void } | null = null;
146
152
  private disposed = false;
147
153
  /** Each checkpoint of an instance takes a generation; a staged one still waiting is superseded by any later one. */
148
154
  private highwayDisposed = false;
@@ -388,8 +394,13 @@ export class LiveGridHost {
388
394
  } catch { return false; }
389
395
  }
390
396
  this.forgetLastCell();
391
- const last = { instance, until: diagnosticNow() + policy.windowMs, cancel: (): void => undefined };
397
+ const kept = policy.keepHome !== undefined && instance === this.ports.home.instance && this.distance(this.assembly.cell(instance)) <= policy.keepHome;
398
+ const last = { instance, until: kept ? Number.POSITIVE_INFINITY : diagnosticNow() + policy.windowMs, pinned: kept, cancel: (): void => undefined };
392
399
  this.lastCell = last;
400
+ if (kept) {
401
+ resident.lease.update({ needed: true, distance: this.distance(this.assembly.cell(instance)) });
402
+ return true;
403
+ }
393
404
  try {
394
405
  last.cancel = policy.schedule(() => {
395
406
  if (this.lastCell !== last) return;
@@ -406,11 +417,14 @@ export class LiveGridHost {
406
417
  * A different actual entry retires the departure before any new allocation. */
407
418
  private retireInactiveRegions(destination?: string): boolean {
408
419
  const last = this.lastCell;
420
+ const keep = this.ports.lastCell?.keepHome;
409
421
  if (last !== null && (diagnosticNow() >= last.until || !this.retainedFits(last.instance)
422
+ || keep !== undefined && last.instance === this.ports.home.instance && this.distance(this.assembly.cell(last.instance)) > keep
410
423
  || this.active !== null || destination !== undefined && destination !== last.instance)) this.forgetLastCell();
411
424
  let released = true;
412
425
  for (const [instance, resident] of this.residents) {
413
- const needed = instance === this.active || instance === destination || instance === this.ahead || this.requests.has(instance) || resident.reservations > 0;
426
+ const needed = instance === this.active || instance === destination || instance === this.ahead || this.requests.has(instance) || resident.reservations > 0
427
+ || this.lastCell?.instance === instance && this.lastCell.pinned;
414
428
  resident.lease.update({ distance: this.distance(this.assembly.cell(instance)), needed: needed || resident.disposalFailed === true });
415
429
  if (needed || this.lastCell?.instance === instance) continue;
416
430
  if (resident.disposalFailed === true || resident.evicting || this.coldUnloadRefused.has(instance)) { released = false; continue; }
@@ -50,7 +50,7 @@ import type { ResidencyAllocator } from '../../../shared/game/grid/allocator';
50
50
  import type { HomeResidencyClaim } from './pageResidency';
51
51
  import { LiveGridHost, type LiveGridAdmission, type LiveGridFrame, type LiveGridRegion, type LiveGridState } from './live';
52
52
  import { installGridCrossing, type GridCheckpointResult, type GridCrossingSession, type GridCrossingState } from '../../../shared/game/grid/crossing';
53
- import { GridWallet, stowGridMount } from '../../../shared/game/grid/wallet';
53
+ import { GridWallet, stowGridMount, type GridLoadout } from '../../../shared/game/grid/wallet';
54
54
  import type { LedgerCatalogueItem } from '../../../shared/game/ledger';
55
55
  import { installGridHoverSpeed } from '../../../shared/game/grid/rules';
56
56
  import { installGridTravellerCombat } from '../../../shared/game/grid/travellerCombat';
@@ -194,6 +194,11 @@ const HIGHWAY_QUERIES: PlayerFrameQueries = { heightAt: () => 0, waterSurfaceAt:
194
194
  export interface LiveGridSpawn { readonly x: number; readonly y: number | undefined; readonly z: number; readonly yaw: number }
195
195
 
196
196
  /** The platform travel envelope at the deck's 30 m/s; a shardfile's critical bundle is its declared compressed sim. */
197
+ /** ZE21 (Jake, 2026-11-15 ~16:50 Cancún: "Having the home cell in memory when your 10m away 100m or 300m away shouldnt
198
+ * matter, 1000m away shouldnt matter"): the owned home stays resident for the whole road. Measured on the laptop (desktop,
199
+ * 2992x1434@2), the home is ~216 MB of real GPU and RAM; the envelope was filled by neighbours' tile products and the cost
200
+ * model's fixed shares, which now yield to it (`keepHome`). */
201
+ const HOME_KEEP_METRES = Number.POSITIVE_INFINITY;
197
202
  const LINK: ReadinessLink = { speed: 30, linkBitsPerSecond: 5_000_000, requestLatencySeconds: 0.25, maxStallSeconds: 10 };
198
203
 
199
204
  /** G598: a preparation that fails (or a road approach abandoned for another crossing, T7) frees its half-built region as a
@@ -297,7 +302,7 @@ export class LiveGridSession {
297
302
  const highwayBytes = (ports.initialStripBytes ?? ports.strips.reduce((sum, strip) => sum + strip.mesh.positions.byteLength + strip.mesh.indices.byteLength, 0))
298
303
  + assembly.cells.length * TRANSFER_WALL_BYTES;
299
304
  try { this.live = new LiveGridHost(assembly, {
300
- lastCell: { windowMs: 30_000, playingBytes: ports.allocator.envelope(), schedule: (expire, ms) => {
305
+ lastCell: { windowMs: 30_000, playingBytes: ports.allocator.envelope(), keepHome: HOME_KEEP_METRES, schedule: (expire, ms) => {
301
306
  const timer = scope.child('grid.last-cell-expiry');
302
307
  timer.timeout(ms, () => { timer.dispose(); scope.run(expire); });
303
308
  return () => { timer.dispose(); };
@@ -407,12 +412,17 @@ export class LiveGridSession {
407
412
  }, target: (feet) => this.wire === null ? this.live.target(feet) : this.wireTarget() },
408
413
  this.ports.assembly, (instance) => {
409
414
  const runtime = this.runtimeRegions.get(instance), flush = (): boolean => true;
410
- if (runtime === undefined) return { checkpoint: flush, stow: () => { stowGridMount(this.page.traveller); }, interior: () => undefined };
411
- if (this.wire !== null) return { ...runtime.loadout, checkpoint: flush };
415
+ if (runtime === undefined) return { checkpoint: flush, stow: () => { this.keepPrograms('home-edge:cell'); stowGridMount(this.page.traveller); }, interior: () => { this.keepPrograms('home-edge:road'); } };
416
+ // ZE2: the home edge swaps the lights, shadows and kit drawn, so three moves every material to another program key
417
+ // and releases the old one; walking back linked it again on the edge frame (Pine 133 to 650 ms, every lap). Each side's
418
+ // programs are pinned as the feet leave it, so the way back finds them compiled.
419
+ const edge = (loadout: GridLoadout): GridLoadout => ({ ...loadout, stow: () => { this.keepPrograms('home-edge:cell'); loadout.stow(); },
420
+ interior: () => { this.keepPrograms('home-edge:road'); loadout.interior(); } });
421
+ if (this.wire !== null) return edge({ ...runtime.loadout, checkpoint: flush });
412
422
  // rt3-crossing2: a committed runtime the traveller never entered never ran its hooks and never played: it saves as
413
423
  // the stored resident. Its own checkpoint refuses until its hooks restore, so turning back on the strip after the
414
424
  // commit held the crossing in save-failed for good.
415
- return this.startedRuntimes.has(instance) ? runtime.loadout : { ...runtime.loadout, checkpoint: flush };
425
+ return edge(this.startedRuntimes.has(instance) ? runtime.loadout : { ...runtime.loadout, checkpoint: flush });
416
426
  }, this.ports.scope, (from, to) => {
417
427
  if (to !== null || from === null) return;
418
428
  const leaveStart = diagnosticNow();
@@ -93,6 +93,10 @@ export class NeighbourLife {
93
93
  const { mesh, bones } = skinMesh(skin), driver = new SkinDriver(skin, bones);
94
94
  const view: CreatureView = { id, mesh, driver, spawn: { at: spawn.at, yaw: spawn.yaw, scale: spawn.scale }, bodyY: species.dims.bodyY * spawn.scale, t: (spawn.seed % 97) / 13, phase: 0 };
95
95
  mesh.position.set(spawn.at[0], spawn.at[1], spawn.at[2]); mesh.rotation.set(0, spawn.yaw, 0, 'YXZ'); mesh.scale.setScalar(spawn.scale);
96
+ // ZE3a: hidden from birth unless its cell is the active one: an admission that resolves between the late phase (which
97
+ // hides a frozen cell's creatures) and the draw drew them once, and that draw linked their programs on the frame (a
98
+ // neighbour's barrow warden, 114 ms, on the laptop's whole-road drive past an open plot, 2026-11-15)
99
+ mesh.visible = this.ports.active(cell.instance);
96
100
  root.add(mesh); creatures.set(id, view);
97
101
  }
98
102
  const instance = cell.instance;
@@ -130,7 +134,11 @@ export class NeighbourLife {
130
134
  const object: Object3D | null = view?.mesh ?? null;
131
135
  return { entity, object, anchor, emitters };
132
136
  });
133
- return { scripts, views: new ClientScriptViews(scripts.lane, targets, { root, scope: this.ports.scope }) };
137
+ const views = new ClientScriptViews(scripts.lane, targets, { root, scope: this.ports.scope });
138
+ // ZE3a: its particles too, hidden from birth unless its cell is active (ink-cel-valley's pool linked its program for 65 ms
139
+ // on the road, 2026-11-15)
140
+ views.show(this.ports.active(instance));
141
+ return { scripts, views };
134
142
  } catch (error) { scripts.dispose(); throw error; }
135
143
  }
136
144
 
@@ -150,6 +158,7 @@ export class NeighbourLife {
150
158
  life.lane?.views.restore();
151
159
  const region = this.ports.simulation(life.cell.instance), live = this.ports.active(life.cell.instance);
152
160
  // G663: a frozen cell draws none of its creatures and composes no lane
161
+ life.lane?.views.show(live);
153
162
  if (!live) { for (const view of life.creatures.values()) view.mesh.visible = false; continue; }
154
163
  for (const view of life.creatures.values()) {
155
164
  const sim = region?.host.entities.get(view.id);
@@ -8,11 +8,13 @@
8
8
  *
9
9
  * Presentation only: nothing here writes a simulation, a field or a collider.
10
10
  */
11
- import type { Group, Object3D } from 'three';
11
+ import { Euler, Matrix4, Quaternion, Vector3, type Group, type Object3D } from 'three';
12
+ import type { MoverPose } from '@wildshard/engine/physics/mover';
12
13
  import type { ClientTileViews } from '../shardfile/clientViews';
13
14
  import type { Shardfile } from '@wildshard/format/shardSchema';
14
15
  import type { GridCell } from '../../../shared/game/grid/assembly';
15
16
  import type { ProbeAreaTarget } from '@wildshard/engine/debug/probe';
17
+ import { wirePage } from '../shardfile/wirePage';
16
18
 
17
19
  /** What the panels read of a cell the live host has admitted: the solids of its world, and a field's row where this page has one. */
18
20
  export interface PanelRegion { readonly colliders: ReadonlyMap<string, { readonly active: () => boolean; readonly setActive: (active: boolean) => void }>; readonly field: (name: string) => number | undefined }
@@ -38,6 +40,23 @@ export function targetMatched(row: TargetRow, fallback: number, region: PanelReg
38
40
  return ((field === undefined ? undefined : region?.field(field.name)) ?? fallback) === row.equals;
39
41
  }
40
42
 
43
+ /** TEMPLATE-E2E TC-E5b: pose a mover's panel. The panel was baked where the mover rests (its `at` and `euler`), so each
44
+ * pose sets the panel to (pose) x (rest)^-1 x (its baked transform): it turns about the mover's own origin, as the server's
45
+ * body does. Presentation only: the mover's collider is the server's. */
46
+ export function moverPanelPose(panel: Object3D, rest: { readonly at: { x: number; y: number; z: number }; readonly euler: { x: number; y: number; z: number } }): (pose: MoverPose) => void {
47
+ const one = new Vector3(1, 1, 1), euler = new Euler(0, 0, 0, 'YXZ'), q = new Quaternion(), at = new Vector3();
48
+ panel.updateMatrix();
49
+ const baked = panel.matrix.clone(), restInverse = new Matrix4().compose(new Vector3(rest.at.x, rest.at.y, rest.at.z),
50
+ q.setFromEuler(euler.set(rest.euler.x, rest.euler.y, rest.euler.z, 'YXZ')).clone(), one).invert();
51
+ const now = new Matrix4();
52
+ return (pose) => {
53
+ now.compose(at.set(pose.position.x, pose.position.y, pose.position.z), q.setFromEuler(euler.set(pose.euler.x, pose.euler.y, pose.euler.z, 'YXZ')), one)
54
+ .multiply(restInverse).multiply(baked);
55
+ now.decompose(panel.position, panel.quaternion, panel.scale); panel.updateMatrix(); // a frame-floored root walks no matrices
56
+ panel.visible = pose.enabled;
57
+ };
58
+ }
59
+
41
60
  /** The page's neighbour panels: one set per shardfile neighbour whose targets show or hide a panel; disposed with the scope. */
42
61
  export class NeighbourPanels {
43
62
  private readonly ports: NeighbourPanelPorts;
@@ -47,7 +66,7 @@ export class NeighbourPanels {
47
66
  /** Draw one neighbour's declared panels in its cell root (the session's shared per-slug load supplies views and bytes). */
48
67
  async admit(cell: GridCell, root: Group, source: Shardfile, assets: ReadonlyMap<string, Uint8Array>, views: ClientTileViews): Promise<void> {
49
68
  const props = source.props;
50
- if (props === null || props.panels.length === 0 || source.targets.panels.length === 0 || this.cells.has(cell.instance)) return;
69
+ if (props === null || props.panels.length === 0 || source.targets.panels.length === 0 && source.movers.length === 0 || this.cells.has(cell.instance)) return;
51
70
  const panels = await views.panels(props, assets, root, this.ports.scope);
52
71
  if (this.ports.scope.disposed) return;
53
72
  // a panel's programs compile in the page's warm-up, off the drive's frames: hidden until then, then shown by sync
@@ -63,6 +82,14 @@ export class NeighbourPanels {
63
82
  });
64
83
  const cellPanels: CellPanels = { instance: cell.instance, source, bindings };
65
84
  this.cells.set(cell.instance, cellPanels);
85
+ // TEMPLATE-E2E TC-E5b: a mover's look is the props panel with its id; the wire's pose for it moves that panel
86
+ for (const row of source.movers) {
87
+ const panel = panels.get(row.id); if (panel === undefined) continue;
88
+ const view = { pose: moverPanelPose(panel, row) };
89
+ panel.visible = row.enabled; // drawn at rest until the wire poses it (review SHOULD)
90
+ wirePage.movers.set(row.id, view);
91
+ this.ports.scope.onDispose(() => { if (wirePage.movers.get(row.id) === view) wirePage.movers.delete(row.id); });
92
+ }
66
93
  this.sync(cellPanels);
67
94
  }
68
95
 
@@ -140,6 +140,27 @@ export function enterGrid(): void {
140
140
 
141
141
 
142
142
 
143
+ /** ZONE-ENTRY ZE10 (J352, Jake 2026-11-15: "you pop up the full loading screen, the same loading screen that you get in shard select
144
+ * [...] you've evicted the previous zone from memory, you've loaded a new zone into memory"): a gate's count reached 0. The page
145
+ * enters that cell as Shard select enters it: the full loading screen at once, then a fresh page whose home is the target (so its
146
+ * walls move), with a goto asking the world (or the in-page server, J311) to seat it there. The plan's marked-reload form: one world
147
+ * in memory by construction, the old home released with its document. */
148
+ export function enterZone(instance: string): void {
149
+ if (navigating !== null && !navigating.disposed) return;
150
+ const cell = new GridAssembly(gridMode(DEVSERVER)).cells.find(row => row.instance === instance), target = cell === undefined ? undefined : findTitleManifest(cell.slug);
151
+ if (cell === undefined || target === undefined) return; // a cell this build can't open stays behind its gate
152
+ const shown = gridDestination({ slug: target.slug }, target);
153
+ document.documentElement.style.setProperty('--ws-load-portrait', shown.art === '' ? 'none' : `url("${shown.art}")`);
154
+ startEntryDownload(target.slug, 'grid');
155
+ startGridStripDownload(gridMode(DEVSERVER), cell.instance, 'metadata');
156
+ navigating = beginNavigationShell(shown.name, pageScope, () => {
157
+ if (!gridRecovery(saves).clearLoop()) throw new Error('Grid recovery guard could not be cleared');
158
+ clearGridRecovery();
159
+ pageGridIntents().set({ instance: cell.instance, slug: target.slug, goto: true });
160
+ travel({ to: target.slug, mode: 'enter', shown });
161
+ }, null);
162
+ }
163
+
143
164
  /** The grid page's address: its path, and only the harness flags skipintro, mute and nolock, none of which selects a level, and `skipintro` dropped here sent a
144
165
  * `?chunk=<slug>&skipintro` link on a world build back under the title (OFFLINE OF18: every Open Plot in the offline proof). */
145
166
  export function gridPageUrl(href: string): URL {
@@ -533,6 +533,11 @@ export function createRegionalWorldFoundation(ports: RegionalWorldPorts): (reque
533
533
  const animals = frame.run(app, () => new RowBodies(new AnimalHerdView(scene, sky, { physics: host.physics }), app, host.physics));
534
534
  await animals.build(ports.pause, frame);
535
535
  if (left()) throw new Error('Regional world left while building creatures');
536
+ // ZE2d (DL24 on the grid): one hidden rig of every model a row can bring, parked in this region's scene, so its
537
+ // warm-up builds the programs its creatures draw with: the region's look patch and its own factory's bodies. The
538
+ // page's warm rigs sit outside the region (no `|look:`, another factory's hulls): Driftwood's glowing creature
539
+ // linked 149 to 198 ms on the first walk back in from the road, Pine's wildlife three programs
540
+ frame.run(app, () => { animals.stageWarmRigs(); });
536
541
  return { animals, wearSkin: (equipment: EquipmentService, skin: SkinDef): void => {
537
542
  const model = equipment.get(skin.weapon).model;
538
543
  if (model instanceof Group) applySkin(model, skin, sky);
@@ -0,0 +1,69 @@
1
+ import {type CompressedTexture, LinearFilter, LinearMipmapLinearFilter, RepeatWrapping, RGBA_ASTC_6x6_Format, SRGBColorSpace} from 'three';
2
+ import {TIER} from '@wildshard/engine/core/tier';
3
+ import {contentURL} from '@wildshard/engine/boot/contentBase';
4
+ import {nativeCompressedFormatSupported} from '@wildshard/engine/core/ktx2';
5
+ import {ROAD_GRAIN_PLANES} from './roadGrain';
6
+ import {PlatformRenderAdmissionError, type PlatformRenderAdmission} from './renderResidency';
7
+ import type {RoadMapShare} from './roadResources';
8
+
9
+ const KINDS = ['asphalt', 'junction'] as const;
10
+ const IDS = {asphalt: 'road.asphalt', junction: 'road.junctions'} as const;
11
+ /** Native ASTC must have sampled correctly at every mip; unsupported phones keep the procedural maps. */
12
+ export function compressedRoadSupport(tier: string, nativeSupported: boolean): boolean {
13
+ return tier === 'phone' && nativeSupported;
14
+ }
15
+ /** Exact ASTC 6x6 allocation, including the small padded levels at the end of the chain. */
16
+ export function roadSurfaceBytes(width: number, height: number): number {
17
+ let bytes = 0;
18
+ for (let w = width, h = height; ; w = Math.max(1, w >> 1), h = Math.max(1, h >> 1)) {
19
+ bytes += Math.ceil(w / 6) * Math.ceil(h / 6) * 16;
20
+ if (w === 1 && h === 1) return bytes;
21
+ }
22
+ }
23
+ interface SurfaceLoader {
24
+ readonly supported?: boolean;
25
+ readonly read?: (url: string, signal: AbortSignal) => Promise<CompressedTexture>;
26
+ readonly upload?: (texture: CompressedTexture, current: () => boolean) => Promise<void>;
27
+ }
28
+
29
+ /** Admit the pair before loading, publish both atomically, and retain one counted owner across road halves. */
30
+ export async function prepareRoadSurfaceMaps(admission: PlatformRenderAdmission, maps: RoadMapShare, loader: SurfaceLoader = {}): Promise<boolean> {
31
+ if (!(loader.supported ?? compressedRoadSupport(TIER, nativeCompressedFormatSupported('SRGB8_ALPHA8_ASTC_6x6'))) || KINDS.some(kind => maps.has(IDS[kind]))) return false;
32
+ const gpuBytes = KINDS.reduce((bytes, kind) => bytes + roadSurfaceBytes(ROAD_GRAIN_PLANES[kind].width, ROAD_GRAIN_PLANES[kind].height), 0);
33
+ let owner;
34
+ try { owner = admission.allocate({id: 'road.surface-maps', jsBytes: gpuBytes, gpuBytes}, scope => scope); }
35
+ catch (error) { if (error instanceof PlatformRenderAdmissionError) return false; throw error; }
36
+ const textures = new Map<string, CompressedTexture>();
37
+ const controller = new AbortController(), loading = owner.child('surface-loading');
38
+ const retired = new Promise<false>(resolve => { owner.onDispose(() => { controller.abort(); resolve(false); }); });
39
+ loading.timeout(5000, () => { owner.dispose(); });
40
+ let shared = false;
41
+ owner.onDispose(() => { for (const [id, texture] of textures) { if (shared) maps.release(id, texture); else texture.dispose(); } });
42
+ const read = loader.read ?? (async (url: string, signal: AbortSignal) => (await import('@wildshard/engine/core/ktx2')).ktx2File(url, signal));
43
+ const upload = loader.upload ?? (async (texture: CompressedTexture, current: () => boolean): Promise<void> => {
44
+ await (await import('@wildshard/engine/core/ktx2')).prepareCompressedTexture(texture, undefined, current);
45
+ });
46
+ try {
47
+ const results = await Promise.race([retired, Promise.allSettled(KINDS.map(async kind => {
48
+ const texture = await read(contentURL(`/assets/grid-road/road-${kind}-phone.ktx2`), controller.signal);
49
+ if (owner.disposed || owner.disposing) { texture.dispose(); throw new Error('Road surface owner retired'); }
50
+ textures.set(IDS[kind], texture);
51
+ const image: unknown = texture.image, expected = ROAD_GRAIN_PLANES[kind];
52
+ if (texture.format !== RGBA_ASTC_6x6_Format || texture.colorSpace !== SRGBColorSpace || typeof image !== 'object' || image === null
53
+ || Reflect.get(image, 'width') !== expected.width || Reflect.get(image, 'height') !== expected.height
54
+ || texture.mipmaps.length !== 11 || texture.mipmaps.reduce((bytes, mip) => bytes + mip.data.byteLength, 0) !== roadSurfaceBytes(expected.width, expected.height)) {
55
+ throw new Error('Road surface texture differs from its admitted format');
56
+ }
57
+ if (kind === 'asphalt') { texture.wrapS = RepeatWrapping; texture.wrapT = RepeatWrapping; }
58
+ texture.anisotropy = 8; texture.minFilter = LinearMipmapLinearFilter; texture.magFilter = LinearFilter;
59
+ texture.needsUpdate = true;
60
+ await upload(texture, () => !owner.disposed && !owner.disposing);
61
+ }))]);
62
+ if (results === false || results.some(result => result.status === 'rejected') || owner.disposed || owner.disposing) { owner.dispose(); return false; }
63
+ for (const [id, texture] of textures) maps.hold(id, texture);
64
+ shared = true;
65
+ admission.shrink?.('road.surface-maps', gpuBytes);
66
+ return true;
67
+ } catch (error) { owner.dispose(); throw error; }
68
+ finally { loading.dispose(); }
69
+ }
@@ -8,11 +8,12 @@
8
8
  * The layout is `roadLayout.ts`; sign text comes from the catalogue's slugs through the shard registry.
9
9
  */
10
10
  import {
11
- BufferAttribute, BufferGeometry, CanvasTexture, Color, DataTexture, Group, LinearFilter, LinearMipmapLinearFilter, Matrix4, Mesh,
12
- MeshLambertMaterial, NoColorSpace, type Object3D, Quaternion, RepeatWrapping, RGFormat, SRGBColorSpace, type Texture, UnsignedByteType, Vector3,
11
+ BufferAttribute, BufferGeometry, Color, DataTexture, Group, LinearFilter, LinearMipmapLinearFilter, Matrix4, Mesh,
12
+ MeshLambertMaterial, NoColorSpace, type Object3D, Quaternion, RGFormat, type Texture, UnsignedByteType, Vector3,
13
13
  } from 'three';
14
14
  import type { GridCell } from '../../../shared/game/grid/assembly';
15
- import { putRoadGrain, roadGrainSteps, type RoadGrainSource } from './roadGrain';
15
+ import type { RoadGrainSource } from './roadGrain';
16
+ import { junctionTextureSteps, roadTextureSteps, ROAD_PERIOD, WHITE } from './roadSurfaceMaps';
16
17
  import { packRoadSignPixels } from './roadSignPixels';
17
18
  import { paintRoadSignCanvas, roadSignPaintLayout, roadSignLineKey as lineKey, SIGN_LINE_W as LINE_W, SIGN_LINE_H as LINE_H, type RoadSignSource } from './roadSignPaint';
18
19
  import { ownRoadMesh, type RoadMapShare } from './roadResources';
@@ -95,7 +96,7 @@ export class RoadOverlayLight {
95
96
  export interface RoadLookState { readonly segments: number; readonly junctions: number; readonly roundabouts: number; readonly signs: number; readonly lights: number; readonly draws: number }
96
97
 
97
98
  const LIFT = 0.02; // the overlay's height over the deck's road band (polygon offset does the rest)
98
- const YELLOW = '#e0b23a', WHITE = '#e9ebe6', KERB = new Color(0x9a9c98), ISLAND = new Color(0x4f6a35), SIGN_GREEN = '#0d6b3c';
99
+ const KERB = new Color(0x9a9c98), ISLAND = new Color(0x4f6a35), SIGN_GREEN = '#0d6b3c';
99
100
 
100
101
  /** A tiny triangle builder: positions, normals, uvs, colours, one index buffer. */
101
102
  class Mesher {
@@ -148,75 +149,6 @@ function canvas(w: number, h: number): { el: HTMLCanvasElement; g: CanvasRenderi
148
149
  const g = el.getContext('2d'); if (g === null) throw new Error('No 2D canvas for the road look');
149
150
  return { el, g };
150
151
  }
151
- function texture(el: HTMLCanvasElement, repeat: boolean): CanvasTexture {
152
- const t = new CanvasTexture(el); t.colorSpace = SRGBColorSpace; t.anisotropy = 8; t.minFilter = LinearMipmapLinearFilter;
153
- if (repeat) { t.wrapS = RepeatWrapping; t.wrapT = RepeatWrapping; }
154
- return t;
155
- }
156
-
157
- /** The road canvas: u [0, 0.5) the normal section, [0.5, 1) the turn-in section; v one 12 m period of dashes. */
158
- const ROAD_PERIOD = 12;
159
- function* roadTextureSteps(grain?: RoadGrainSource): Generator<void, CanvasTexture> {
160
- const W = 1024, H = 512, { el, g } = canvas(W, H);
161
- const plane = grain?.('asphalt');
162
- if (plane === undefined) yield* roadGrainSteps(g, W, H, 1); else putRoadGrain(g, 'asphalt', plane);
163
- const half = W / 2, px = (t: number, base: number): number => base + (t + ROAD_HALF) / (2 * ROAD_HALF) * half, pm = half / (2 * ROAD_HALF);
164
- for (const base of [0, half]) {
165
- const turnIn = base > 0;
166
- // wheel paths: faint darker wear in each lane
167
- g.fillStyle = 'rgba(20,22,26,0.07)';
168
- for (const t of [-5.9, -4.3, -2.6, -1.0, 1.0, 2.6, 4.3, 5.9]) g.fillRect(px(t, base) - 0.45 * pm, 0, 0.9 * pm, H);
169
- g.fillStyle = YELLOW; // the double yellow centre line (G80)
170
- for (const t of [-0.17, 0.17]) g.fillRect(px(t, base) - 0.06 * pm, 0, 0.12 * pm, H);
171
- g.fillStyle = WHITE; // lane dividers: 3 m dash in a 12 m period
172
- for (const t of [-3.55, 3.55]) g.fillRect(px(t, base) - 0.06 * pm, 0, 0.12 * pm, H * 3 / ROAD_PERIOD);
173
- for (const t of [-7.0, 7.0]) { // edge lines; at a turn-in, short dashes so the opening reads
174
- if (!turnIn) g.fillRect(px(t, base) - 0.075 * pm, 0, 0.15 * pm, H);
175
- else for (let k = 0; k < 6; k++) g.fillRect(px(t, base) - 0.075 * pm, k * H / 6, 0.15 * pm, H / 12);
176
- }
177
- }
178
- return texture(el, true);
179
- }
180
-
181
- /** The junction canvas: 62.5 m square; the roundabout's markings in the middle, plain asphalt in the corners. */
182
- function* junctionTextureSteps(grain?: RoadGrainSource): Generator<void, CanvasTexture> {
183
- const W = 1024, { el, g } = canvas(W, W), k = W / (2 * GAP_HALF);
184
- const plane = grain?.('junction');
185
- if (plane === undefined) yield* roadGrainSteps(g, W, W, 2); else putRoadGrain(g, 'junction', plane);
186
- const P = (x: number, z: number): [number, number] => [(x + GAP_HALF) * k, (GAP_HALF - z) * k];
187
- const arc = (r: number, a0: number, a1: number, width: number, colour: string, dash?: readonly [number, number]): void => {
188
- g.strokeStyle = colour; g.lineWidth = width * k; g.setLineDash(dash === undefined ? [] : [dash[0] * k, dash[1] * k]);
189
- const [cx, cy] = P(0, 0); g.beginPath(); g.arc(cx, cy, r * k, -a1, -a0); g.stroke(); g.setLineDash([]);
190
- };
191
- const open = Math.asin((ROAD_HALF + 0.3) / (RING_OUTER - 0.5));
192
- for (let q = 0; q < 4; q++) arc(RING_OUTER - 0.5, q * Math.PI / 2 + open, (q + 1) * Math.PI / 2 - open, 0.15, WHITE); // outer edge line between the arms
193
- arc(RING_ISLAND + 0.45, 0, Math.PI * 2, 0.15, WHITE); // inner edge line
194
- arc((RING_ISLAND + RING_OUTER) / 2, 0, Math.PI * 2, 0.12, WHITE, [3, 3]); // the circulating lane divider
195
- const sides: readonly { x: number; z: number }[] = [{ x: 1, z: 0 }, { x: 0, z: 1 }, { x: -1, z: 0 }, { x: 0, z: -1 }];
196
- for (const d of sides) {
197
- const rx = -d.z, rz = d.x; // the across unit
198
- const line = (t: number, r0: number, r1: number, width: number, colour: string, dash = 0): void => {
199
- g.fillStyle = colour;
200
- for (let r = r0; r < r1; r += dash > 0 ? dash * 4 : r1 - r0) {
201
- const e = Math.min(r1, r + (dash > 0 ? dash : r1 - r0)), [ax, ay] = P(d.x * r + rx * (t - width / 2), d.z * r + rz * (t - width / 2)), [bx, by] = P(d.x * e + rx * (t + width / 2), d.z * e + rz * (t + width / 2));
202
- g.fillRect(Math.min(ax, bx), Math.min(ay, by), Math.abs(bx - ax), Math.abs(by - ay));
203
- }
204
- };
205
- for (const t of [-0.17, 0.17]) line(t, RING_OUTER + 3, GAP_HALF, 0.12, YELLOW);
206
- for (const t of [-3.55, 3.55]) line(t, RING_OUTER + 3, GAP_HALF, 0.12, WHITE, 3);
207
- for (const t of [-7.0, 7.0]) line(t, RING_OUTER + 0.5, GAP_HALF, 0.15, WHITE);
208
- // give way: the entry half is on the inbound traveller's right (three's mirrored frame: −across), dashed, a triangle per lane
209
- const entry = -1;
210
- for (let t = 0.4; t < 6.9; t += 0.9) line(entry * (t + 0.3), RING_OUTER + 0.9, RING_OUTER + 1.2, 0.6, WHITE);
211
- for (const t of [1.8, 5.3]) {
212
- const tip = RING_OUTER + 2.2, base = tip + 2.6, [ax, ay] = P(d.x * tip + rx * t * entry, d.z * tip + rz * t * entry);
213
- const [bx, by] = P(d.x * base + rx * (t * entry + 0.7), d.z * base + rz * (t * entry + 0.7)), [cx, cy] = P(d.x * base + rx * (t * entry - 0.7), d.z * base + rz * (t * entry - 0.7));
214
- g.strokeStyle = WHITE; g.lineWidth = 0.15 * k; g.beginPath(); g.moveTo(ax, ay); g.lineTo(bx, by); g.lineTo(cx, cy); g.closePath(); g.stroke();
215
- }
216
- }
217
- return texture(el, false);
218
- }
219
-
220
152
  /** The asphalt over every segment: three quads each (the middle one the turn-in section), UVs into the road canvas. */
221
153
  function asphalt(layout: RoadLayout, home: GridCell): Mesher {
222
154
  const m = new Mesher();
@@ -14,7 +14,7 @@ import type { RoadSignSource } from './roadSignPaint';
14
14
  * before the deck's and the boulevard's claims and dropped after; the curtain's split arrays become its geometry without a
15
15
  * copy (they are counted in `road.curtain`).
16
16
  */
17
- import { Mesh, type Camera, type Object3D } from 'three';
17
+ import { DataArrayTexture, Mesh, type Camera, type Object3D } from 'three';
18
18
  import { CONTENT_CAPS } from '@wildshard/engine/core/config';
19
19
  import { ownRoadMesh, type RoadMapShare } from './roadResources';
20
20
  import type { RoadTileBacking } from './roadTileBacking';
@@ -57,7 +57,7 @@ export interface PlatformRoadInput {
57
57
  readonly within?: (x: number, z: number) => boolean;
58
58
  /** build the void floor and its rail (default true; one build of a split road draws it) */
59
59
  readonly voidFloor?: boolean;
60
- /** PZ24: one asphalt and one junction map for every build of this road (a split road's halves pass the same share) */
60
+ /** PZ24: one asphalt, junction and deck-grain upload for every build of this road (a split road's halves pass the same share) */
61
61
  readonly maps?: RoadMapShare;
62
62
  }
63
63
  /** The readouts and the roots the road budget measures. */
@@ -162,18 +162,23 @@ function* platformRoadSteps(input: PlatformRoadInput): Generator<void, PlatformR
162
162
  const meshes: Mesh[] = [];
163
163
  yield;
164
164
  const deckBytes = yield* meshBytesSteps(parts.map(solidSource), SOLID_FLOATS, { pitch, ...(tileSize === undefined ? {} : { tileSize }), lod: ROAD_LOD }, true);
165
- const grainBytes = gpuOnlyTextureBytes(GRAIN_SIZE, GRAIN_SIZE, GRAIN_LAYERS.length, 'data');
165
+ const maps = input.maps, grainId = 'road.deck-grain';
166
+ const grainBytes = maps?.has(grainId) === true ? { jsBytes: 0, gpuBytes: 0 } : gpuOnlyTextureBytes(GRAIN_SIZE, GRAIN_SIZE, GRAIN_LAYERS.length, 'data');
166
167
  const deckAdmission = bytePlan('road.deck', deckBytes, grainBytes);
167
168
  const builtDeck = yield* allocateRenderSteps(admission, deckAdmission, function* buildDeck(owner) {
168
169
  yield;
169
- const grain = grainArray({ gravel, stone, strata, riprap }), material = solidMaterial(grain);
170
+ const held = maps?.take(grainId);
171
+ if (held !== undefined && !(held instanceof DataArrayTexture)) throw new Error('Road deck grain must be an array texture');
172
+ const grain = held ?? grainArray({ gravel, stone, strata, riprap }), material = solidMaterial(grain);
173
+ if (maps !== undefined && held === undefined) maps.hold(grainId, grain);
170
174
  yield;
171
175
  const deck = new Mesh(yield* solidGeometrySteps(parts), material);
172
- ownRoadMesh(owner, deck, [grain]);
176
+ ownRoadMesh(owner, deck, maps === undefined ? [grain] : []);
177
+ if (maps !== undefined) owner.onDispose(() => { maps.release(grainId, grain); });
173
178
  deck.name = 'grid-deck'; deck.receiveShadow = true;
174
179
  deck.castShadow = false; deck.matrixAutoUpdate = false; deck.updateMatrix();
175
180
  yield* cullIntoSteps(culler, deck, ROAD_LOD); scene.add(deck); meshes.push(deck);
176
- gpuOnlyRoad(deck, [grain]); // G144: admitted, its JS copies go on upload (the plan counts them gone)
181
+ gpuOnlyRoad(deck, held === undefined ? [grain] : []); // G144: admitted, its JS copies go on upload (the plan counts them gone)
177
182
  return deck;
178
183
  });
179
184
  if (builtDeck === undefined) throw new Error('Road construction cancelled');
@@ -0,0 +1,80 @@
1
+ /** The unchanged procedural road painters, shared by runtime fallback and the reproducible phone bake. */
2
+ import {CanvasTexture, LinearMipmapLinearFilter, RepeatWrapping, SRGBColorSpace} from 'three';
3
+ import {GAP_HALF, RING_ISLAND, RING_OUTER, ROAD_HALF} from '../../../shared/game/grid/roadLayout';
4
+ import {putRoadGrain, roadGrainSteps, type RoadGrainSource} from './roadGrain';
5
+
6
+ export const WHITE = '#e9ebe6';
7
+ const YELLOW = '#e0b23a';
8
+ function canvas(w: number, h: number): {el: HTMLCanvasElement; g: CanvasRenderingContext2D} {
9
+ const el = document.createElement('canvas'); el.width = w; el.height = h;
10
+ const g = el.getContext('2d'); if (g === null) throw new Error('No 2D canvas for the road look');
11
+ return {el, g};
12
+ }
13
+ function texture(el: HTMLCanvasElement, repeat: boolean): CanvasTexture {
14
+ const t = new CanvasTexture(el); t.colorSpace = SRGBColorSpace; t.anisotropy = 8; t.minFilter = LinearMipmapLinearFilter;
15
+ if (repeat) { t.wrapS = RepeatWrapping; t.wrapT = RepeatWrapping; }
16
+ return t;
17
+ }
18
+
19
+ /** The road canvas: u [0, 0.5) the normal section, [0.5, 1) the turn-in section; v one 12 m period of dashes. */
20
+ export const ROAD_PERIOD = 12;
21
+ export function* roadTextureSteps(grain?: RoadGrainSource): Generator<void, CanvasTexture> {
22
+ const W = 1024, H = 512, { el, g } = canvas(W, H);
23
+ const plane = grain?.('asphalt');
24
+ if (plane === undefined) yield* roadGrainSteps(g, W, H, 1); else putRoadGrain(g, 'asphalt', plane);
25
+ const half = W / 2, px = (t: number, base: number): number => base + (t + ROAD_HALF) / (2 * ROAD_HALF) * half, pm = half / (2 * ROAD_HALF);
26
+ for (const base of [0, half]) {
27
+ const turnIn = base > 0;
28
+ // wheel paths: faint darker wear in each lane
29
+ g.fillStyle = 'rgba(20,22,26,0.07)';
30
+ for (const t of [-5.9, -4.3, -2.6, -1.0, 1.0, 2.6, 4.3, 5.9]) g.fillRect(px(t, base) - 0.45 * pm, 0, 0.9 * pm, H);
31
+ g.fillStyle = YELLOW; // the double yellow centre line (G80)
32
+ for (const t of [-0.17, 0.17]) g.fillRect(px(t, base) - 0.06 * pm, 0, 0.12 * pm, H);
33
+ g.fillStyle = WHITE; // lane dividers: 3 m dash in a 12 m period
34
+ for (const t of [-3.55, 3.55]) g.fillRect(px(t, base) - 0.06 * pm, 0, 0.12 * pm, H * 3 / ROAD_PERIOD);
35
+ for (const t of [-7.0, 7.0]) { // edge lines; at a turn-in, short dashes so the opening reads
36
+ if (!turnIn) g.fillRect(px(t, base) - 0.075 * pm, 0, 0.15 * pm, H);
37
+ else for (let k = 0; k < 6; k++) g.fillRect(px(t, base) - 0.075 * pm, k * H / 6, 0.15 * pm, H / 12);
38
+ }
39
+ }
40
+ return texture(el, true);
41
+ }
42
+
43
+ /** The junction canvas: 62.5 m square; the roundabout's markings in the middle, plain asphalt in the corners. */
44
+ export function* junctionTextureSteps(grain?: RoadGrainSource): Generator<void, CanvasTexture> {
45
+ const W = 1024, { el, g } = canvas(W, W), k = W / (2 * GAP_HALF);
46
+ const plane = grain?.('junction');
47
+ if (plane === undefined) yield* roadGrainSteps(g, W, W, 2); else putRoadGrain(g, 'junction', plane);
48
+ const P = (x: number, z: number): [number, number] => [(x + GAP_HALF) * k, (GAP_HALF - z) * k];
49
+ const arc = (r: number, a0: number, a1: number, width: number, colour: string, dash?: readonly [number, number]): void => {
50
+ g.strokeStyle = colour; g.lineWidth = width * k; g.setLineDash(dash === undefined ? [] : [dash[0] * k, dash[1] * k]);
51
+ const [cx, cy] = P(0, 0); g.beginPath(); g.arc(cx, cy, r * k, -a1, -a0); g.stroke(); g.setLineDash([]);
52
+ };
53
+ const open = Math.asin((ROAD_HALF + 0.3) / (RING_OUTER - 0.5));
54
+ for (let q = 0; q < 4; q++) arc(RING_OUTER - 0.5, q * Math.PI / 2 + open, (q + 1) * Math.PI / 2 - open, 0.15, WHITE); // outer edge line between the arms
55
+ arc(RING_ISLAND + 0.45, 0, Math.PI * 2, 0.15, WHITE); // inner edge line
56
+ arc((RING_ISLAND + RING_OUTER) / 2, 0, Math.PI * 2, 0.12, WHITE, [3, 3]); // the circulating lane divider
57
+ const sides: readonly { x: number; z: number }[] = [{ x: 1, z: 0 }, { x: 0, z: 1 }, { x: -1, z: 0 }, { x: 0, z: -1 }];
58
+ for (const d of sides) {
59
+ const rx = -d.z, rz = d.x; // the across unit
60
+ const line = (t: number, r0: number, r1: number, width: number, colour: string, dash = 0): void => {
61
+ g.fillStyle = colour;
62
+ for (let r = r0; r < r1; r += dash > 0 ? dash * 4 : r1 - r0) {
63
+ const e = Math.min(r1, r + (dash > 0 ? dash : r1 - r0)), [ax, ay] = P(d.x * r + rx * (t - width / 2), d.z * r + rz * (t - width / 2)), [bx, by] = P(d.x * e + rx * (t + width / 2), d.z * e + rz * (t + width / 2));
64
+ g.fillRect(Math.min(ax, bx), Math.min(ay, by), Math.abs(bx - ax), Math.abs(by - ay));
65
+ }
66
+ };
67
+ for (const t of [-0.17, 0.17]) line(t, RING_OUTER + 3, GAP_HALF, 0.12, YELLOW);
68
+ for (const t of [-3.55, 3.55]) line(t, RING_OUTER + 3, GAP_HALF, 0.12, WHITE, 3);
69
+ for (const t of [-7.0, 7.0]) line(t, RING_OUTER + 0.5, GAP_HALF, 0.15, WHITE);
70
+ // give way: the entry half is on the inbound traveller's right (three's mirrored frame: −across), dashed, a triangle per lane
71
+ const entry = -1;
72
+ for (let t = 0.4; t < 6.9; t += 0.9) line(entry * (t + 0.3), RING_OUTER + 0.9, RING_OUTER + 1.2, 0.6, WHITE);
73
+ for (const t of [1.8, 5.3]) {
74
+ const tip = RING_OUTER + 2.2, base = tip + 2.6, [ax, ay] = P(d.x * tip + rx * t * entry, d.z * tip + rz * t * entry);
75
+ const [bx, by] = P(d.x * base + rx * (t * entry + 0.7), d.z * base + rz * (t * entry + 0.7)), [cx, cy] = P(d.x * base + rx * (t * entry - 0.7), d.z * base + rz * (t * entry - 0.7));
76
+ g.strokeStyle = WHITE; g.lineWidth = 0.15 * k; g.beginPath(); g.moveTo(ax, ay); g.lineTo(bx, by); g.lineTo(cx, cy); g.closePath(); g.stroke();
77
+ }
78
+ }
79
+ return texture(el, false);
80
+ }