@wildshard/engine 0.1.17 → 0.1.18

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 (83) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lint/engine-sides.json +7 -0
  3. package/lint/host-callback-syntax.mjs +2 -1
  4. package/lint/host-callbacks.mjs +3 -3
  5. package/lint/host-files.mjs +5 -4
  6. package/lint/no-base64.mjs +3 -1
  7. package/lint/shard-imports.mjs +6 -7
  8. package/lint/shard-source.d.mts +9 -0
  9. package/lint/shard-source.mjs +91 -0
  10. package/lint/shardfile-boundaries.mjs +10 -8
  11. package/lint/sim-closure.mjs +6 -3
  12. package/lint/wildshard-plugin.d.ts +4 -0
  13. package/lint/wildshard-plugin.js +22 -23
  14. package/package.json +9 -2
  15. package/scripts/app-build/outputProducts.d.mts +3 -0
  16. package/scripts/app-build/outputProducts.mjs +31 -0
  17. package/scripts/app-build-pipeline.mjs +3 -0
  18. package/scripts/check-devserver.mjs +1 -1
  19. package/scripts/chromium-keychain-check.mjs +4 -2
  20. package/scripts/chromium-keychain.mjs +3 -1
  21. package/scripts/cook.mjs +7 -3
  22. package/scripts/devices.d.mts +4 -0
  23. package/scripts/devices.mjs +39 -0
  24. package/scripts/devserver-client.d.mts +4 -2
  25. package/scripts/devserver-client.mjs +25 -8
  26. package/scripts/doctor-proof.mjs +1 -1
  27. package/scripts/e2e-faults.mjs +159 -0
  28. package/scripts/grid-crossing-walk-proof.mjs +14 -3
  29. package/scripts/memory-proof.mjs +158 -0
  30. package/scripts/offline-proof-rules.d.mts +4 -2
  31. package/scripts/offline-proof-rules.mjs +21 -5
  32. package/scripts/offline-proof.mjs +15 -6
  33. package/scripts/tier-textures-proof.mjs +101 -0
  34. package/scripts/tier-textures.mjs +60 -0
  35. package/scripts/tsconfig.json +1 -0
  36. package/scripts/vps/wildshard-config +79 -23
  37. package/scripts/worker-client-play.mjs +1 -0
  38. package/scripts/worker-client-proof.mjs +1 -1
  39. package/scripts/worker-client-slug.mjs +44 -0
  40. package/src/client/app/entry.ts +37 -10
  41. package/src/client/engine/boot/parsedPages.ts +127 -58
  42. package/src/client/engine/build.d.ts +2 -0
  43. package/src/client/engine/core/Game.ts +18 -0
  44. package/src/client/engine/core/bootstrap.ts +4 -1
  45. package/src/client/engine/debug/probe.ts +18 -1
  46. package/src/client/engine/fx/LightPool.ts +41 -1
  47. package/src/client/engine/pwa/sw.js +12 -3
  48. package/src/client/engine/render/precompile.ts +20 -14
  49. package/src/client/engine/telemetry/browserErrors.ts +4 -1
  50. package/src/client/engine/telemetry/deviceSnapshot.ts +155 -0
  51. package/src/client/game/boot/audio.generated.ts +0 -102
  52. package/src/client/game/boot/bytes.generated.ts +42 -60
  53. package/src/client/game/boot/versions.generated.ts +0 -2
  54. package/src/client/game/grid/area.ts +38 -0
  55. package/src/client/game/grid/live.ts +28 -2
  56. package/src/client/game/grid/liveSession.ts +14 -3
  57. package/src/client/game/grid/menu.ts +4 -0
  58. package/src/client/game/grid/neighbourPanels.ts +10 -1
  59. package/src/client/game/grid/placedCards.ts +55 -0
  60. package/src/client/game/grid/placedCells.ts +131 -0
  61. package/src/client/game/grid/regionalRuntime.ts +6 -0
  62. package/src/client/game/grid/regionalWorld.ts +15 -2
  63. package/src/client/game/grid/roadCull.ts +44 -14
  64. package/src/client/game/grid/roadTileBacking.ts +13 -3
  65. package/src/client/game/grid/session.ts +9 -0
  66. package/src/client/game/grid/shardfileFar.ts +9 -3
  67. package/src/client/game/session/finish.ts +5 -1
  68. package/src/client/game/shard/titleList.ts +6 -2
  69. package/src/client/game/shardfile/clientWorker.ts +2 -1
  70. package/src/client/game/titleDeck.ts +4 -3
  71. package/src/client/host/online/shell.ts +14 -0
  72. package/src/cook/game/shardCook.ts +38 -8
  73. package/src/cook/game/tierTextures.ts +276 -0
  74. package/src/e2e/smoke/game.ts +19 -14
  75. package/src/e2e/smoke/page-globals.d.ts +9 -8
  76. package/src/e2e/smoke/template2.spec.ts +8 -7
  77. package/src/server/host/dedicated/placementFile.ts +1 -17
  78. package/src/server/host/dedicated/socketTransport.ts +2 -1
  79. package/src/server/host/dedicated/world.ts +30 -1
  80. package/src/shared/engine/net/deviceWord.ts +138 -0
  81. package/src/shared/engine/net/socketFrames.ts +7 -4
  82. package/src/shared/game/grid/catalogueSlot.ts +7 -0
  83. package/src/shared/game/grid/placementRows.ts +33 -0
@@ -240,6 +240,12 @@ async function slicedTerrainGrid(run: (rows: () => number) => number, left: () =
240
240
 
241
241
  const regionLevel = ({ id, spawn }: LevelSpec): RegionLevel => ({ id, player: { at: { x: spawn.x, y: spawn.y ?? 0, z: spawn.z }, yaw: spawn.yaw } });
242
242
 
243
+ /** PZ22: install the shard's KTX2 table (once per manifest) before its texture policy resolves: Auto reads KTX2 from
244
+ * the registered table (gpuFiles.ts, DL17), so a choice made first stays on images for the resident's whole life. */
245
+ export function registerRegionalTextureTable(manifest: ShardManifest): Promise<void> {
246
+ return prepareShardAssets(manifest, registerGpuFiles);
247
+ }
248
+
243
249
  /** Resolve the existing texture policy once before memory admission. The resident enters this SAME policy for
244
250
  * asynchronous construction and each frame, so a capability-probe image fallback cannot retain a compressed claim. */
245
251
  export function resolveRegionalRuntimeTextures(manifest: Pick<ShardManifest, 'slug' | 'tiers' | 'runtimeCost'>, residents?: Parameters<typeof imagesFirstPlayingBytes>[1]): RegionalRuntimeTextures {
@@ -263,6 +269,8 @@ export function createRegionalWorldFoundation(ports: RegionalWorldPorts): (reque
263
269
  const level = ports.level === undefined ? toLevelSpec(hasDeclaredClientPage(request.admitted.source) ? { ...request.manifest, ground: clientPageGround(request.admitted.source, request.admitted.assets) } : request.manifest, product) : ports.level(request.manifest);
264
270
  const { slug: identity } = request.manifest;
265
271
  if (level.id !== identity) throw new Error('Regional level identity differs from its trusted manifest');
272
+ // PZ22: the table goes in before Auto resolves, and before the resident's scope exists to leak on a refusal
273
+ if (request.textures === undefined) await registerRegionalTextureTable(request.manifest);
266
274
  const resident = request.scope.child(`grid.world:${cell.instance}`), left = (): boolean => resident.disposed;
267
275
  const pausePoint = regionalBuildCheckpoint(resident, ports.pause);
268
276
  let pauses = clientPreparationBatch(identity, 'native.checkpoints', ['pause']);
@@ -280,7 +288,7 @@ export function createRegionalWorldFoundation(ports: RegionalWorldPorts): (reque
280
288
  let rendering: Promise<[PromiseSettledResult<void>]> | undefined;
281
289
  ownSceneTree(scene, resident, app.assets);
282
290
  try {
283
- await timeClientPreparation(identity, 'native.shard-assets', () => prepareShardAssets(request.manifest, registerGpuFiles));
291
+ await timeClientPreparation(identity, 'native.shard-assets', () => registerRegionalTextureTable(request.manifest));
284
292
  if (left()) throw new Error('Regional world left while registering its texture stand-ins');
285
293
  // M3 tiles-swap: the admitted product's reader for the resident runtime (a painter that binds its compiled tiles reads
286
294
  // it), handed over first: the level's declared navigation and a required manifest ground are that product's own files
@@ -534,7 +542,9 @@ export function createRegionalWorldFoundation(ports: RegionalWorldPorts): (reque
534
542
  // The world-only inventory can link while kit/play continue, with the exact destination sky and look.
535
543
  prepareWorldMaterials: async () => {
536
544
  await skyReady;
537
- if (!resident.disposed) regionLook?.sweep();
545
+ if (resident.disposed) return;
546
+ regionLook?.sweep();
547
+ LightPool.for(scene).adopt(scene);
538
548
  },
539
549
  precompileEnvironment: () => scene.environment,
540
550
  // rt3-crossing2: the look's per-frame sweep never ran on what the entered hooks added (no frame draws while they
@@ -543,6 +553,9 @@ export function createRegionalWorldFoundation(ports: RegionalWorldPorts): (reque
543
553
  await skyReady;
544
554
  if (resident.disposed) return;
545
555
  regionLook?.sweep();
556
+ // RP4: its content's own point lights (Sunscar's site and signal lights) show through the page's reserved lights,
557
+ // taken before the warm-up compiles, so showing the region never moves the page's light count
558
+ LightPool.for(scene).adopt(scene);
546
559
  // op-frame21: its own composite, once its world hook has run and before the warm-up compiles the page's passes
547
560
  const place = framePort?.composite;
548
561
  if (cellComposite !== null && place !== undefined && viewRoot !== null && !composited) {
@@ -42,6 +42,25 @@ function binGrid(pitch: number, tileSize?: number): { size: number; offset: numb
42
42
  /** A cell edge's distance from its cell centre (the seam's outer row meets the shard's own ground there). */
43
43
  const CELL_EDGE = CHUNK_HALF;
44
44
 
45
+ /** IOSMEM (WILDSHARD-GAME-8G): the clip's and bin sort's working lists, growing typed storage off the JS heap. As
46
+ * number[] they held ~40-90 bytes a triangle of short-lived heap through an install (hundreds of MB on Driftwood's road),
47
+ * which an iPhone counts against the page until it collects. */
48
+ class Grow<A extends Uint32Array | Float64Array> {
49
+ length = 0;
50
+ constructor(private array: A, private readonly make: (size: number) => A) {}
51
+ push(value: number): void {
52
+ if (this.length === this.array.length) { const next = this.make(Math.max(64, this.array.length * 2)); next.set(this.array); this.array = next; }
53
+ this.array[this.length++] = value;
54
+ }
55
+ /** The filled part; `exact` copies it out so a long-kept result never pins the spare capacity. */
56
+ view(exact = false): A {
57
+ if (!exact) return this.array.subarray(0, this.length) as A;
58
+ return (this.length === this.array.length ? this.array : this.array.slice(0, this.length)) as A;
59
+ }
60
+ }
61
+ const growU32 = (size: number): Grow<Uint32Array> => new Grow(new Uint32Array(size), (n) => new Uint32Array(n));
62
+ const growF64 = (size: number): Grow<Float64Array> => new Grow(new Float64Array(size), (n) => new Float64Array(n));
63
+
45
64
 
46
65
  /** The same attribute interpolation and index order, yielding between bounded triangle/copy batches. */
47
66
  export function* clipToBinsSteps(geometry: BufferGeometry, pitch: number, tileSize?: number): Generator<void> {
@@ -70,7 +89,7 @@ export function* clipToBinsSteps(geometry: BufferGeometry, pitch: number, tileSi
70
89
  for (let n = 0; n < extra.length / stride; n++) { if (n % 256 === 0) yield; for (let c = 0; c < size; c++) array[(count + n) * size + c] = extra[n * stride + o + c] ?? 0; }
71
90
  geometry.setAttribute(name, new BufferAttribute(array, size)); o += size;
72
91
  }
73
- geometry.setIndex(new BufferAttribute(Uint32Array.from(out), 1));
92
+ geometry.setIndex(new BufferAttribute(out.slice(), 1));
74
93
  }
75
94
 
76
95
  /**
@@ -78,8 +97,9 @@ export function* clipToBinsSteps(geometry: BufferGeometry, pitch: number, tileSi
78
97
  * x then z, a new vertex interpolating all `stride` values linearly (position at `px`). A plan that reads only positions
79
98
  * gets exactly the builder's positions, new vertices and triangles: every value interpolates on its own.
80
99
  */
81
- function* clipCore(triangles: number, indexAt: (i: number) => number, count: number, stride: number, px: number, read: (n: number) => Float64Array, coordinate: (n: number, axis: number) => number, pitch: number, tileSize?: number, retain = true): Generator<void, { extra: number[]; out: number[]; added: number; corners: number }> {
82
- const { size: s, offset } = binGrid(pitch, tileSize), extra: number[] = [], out: number[] = [];
100
+ function* clipCore(triangles: number, indexAt: (i: number) => number, count: number, stride: number, px: number, read: (n: number) => Float64Array, coordinate: (n: number, axis: number) => number, pitch: number, tileSize?: number, retain = true): Generator<void, { extra: Float64Array; out: Uint32Array; added: number; corners: number }> {
101
+ // Most triangles fit one bin, so the index is about three corners a triangle; cut triangles grow it.
102
+ const { size: s, offset } = binGrid(pitch, tileSize), extra = growF64(retain ? stride * 64 : 0), out = growU32(retain ? triangles * 3 + 64 : 0);
83
103
  let added = 0, corners = 0;
84
104
  // Count-only admission needs no final index or copied interpolation channels.
85
105
  // Polygon vertices still retain every value used by the original split.
@@ -107,7 +127,7 @@ function* clipCore(triangles: number, indexAt: (i: number) => number, count: num
107
127
  // polygons or copying attributes; only an interior cut needs interpolation.
108
128
  if (!crossesBin(coordinate(a, 0), coordinate(b, 0), coordinate(third, 0), s, offset)
109
129
  && !crossesBin(coordinate(a, 2), coordinate(b, 2), coordinate(third, 2), s, offset)) {
110
- corners += 3; if (retain) out.push(a, b, third); continue;
130
+ corners += 3; if (retain) { out.push(a); out.push(b); out.push(third); } continue;
111
131
  }
112
132
  const tri: V[] = [a, b, third].map((n) => ({ n, v: read(n) }));
113
133
  let polys: V[][] = [tri];
@@ -127,10 +147,10 @@ function* clipCore(triangles: number, indexAt: (i: number) => number, count: num
127
147
  }
128
148
  for (const poly of polys) for (let k = 1; k + 1 < poly.length; k++) {
129
149
  corners += 3;
130
- if (retain) out.push(poly[0]?.n ?? 0, poly[k]?.n ?? 0, poly[k + 1]?.n ?? 0);
150
+ if (retain) { out.push(poly[0]?.n ?? 0); out.push(poly[k]?.n ?? 0); out.push(poly[k + 1]?.n ?? 0); }
131
151
  }
132
152
  }
133
- return { extra, out, added, corners };
153
+ return { extra: extra.view(), out: out.view(), added, corners };
134
154
  }
135
155
 
136
156
 
@@ -147,26 +167,36 @@ export function* cullPlanSteps(geometry: BufferGeometry, pitch: number, lod: rea
147
167
  if (index === null) throw new Error('A culled road mesh needs an index');
148
168
  // each triangle's bin (`cullBin` of its centroid) as two numbers; a bin's string key, made once, orders the bins
149
169
  const { size, offset } = binGrid(pitch, tileSize);
150
- const triangles = index.count / 3, byBin = new Map<number, Map<number, { readonly key: string; readonly x: number; readonly z: number; readonly list: number[] }>>();
170
+ // Each triangle's bin id in one typed pass, then a counting sort keeps every bin's triangles in index order (IOSMEM:
171
+ // no number[] list per bin on the JS heap).
172
+ interface BinRow { readonly key: string; readonly x: number; readonly z: number; readonly id: number; count: number }
173
+ const triangles = index.count / 3, byBin = new Map<number, Map<number, BinRow>>(), binOf = new Uint32Array(triangles);
174
+ let binCount = 0;
151
175
  for (let t = 0; t < triangles; t++) {
152
176
  if (t % 256 === 0) yield;
153
177
  let x = 0, z = 0;
154
178
  for (let c = 0; c < 3; c++) { const n = index.getX(t * 3 + c); x += position.getX(n); z += position.getZ(n); }
155
179
  const bx = Math.floor(x / 3 / size + offset), bz = Math.floor(z / 3 / size + offset);
156
180
  let row = byBin.get(bx); if (row === undefined) { row = new Map(); byBin.set(bx, row); }
157
- const bin = row.get(bz);
158
- if (bin === undefined) row.set(bz, { key: `${String(bx)},${String(bz)}`, x: bx, z: bz, list: [t] }); else bin.list.push(t);
181
+ let bin = row.get(bz);
182
+ if (bin === undefined) { bin = { key: `${String(bx)},${String(bz)}`, x: bx, z: bz, id: binCount++, count: 0 }; row.set(bz, bin); }
183
+ bin.count++; binOf[t] = bin.id;
159
184
  }
160
- const out: number[] = [], bins: CullBin[] = [];
185
+ const firsts = new Uint32Array(binCount + 1), members = new Uint32Array(triangles);
186
+ for (const row of byBin.values()) for (const bin of row.values()) firsts[bin.id + 1] = bin.count;
187
+ for (let b = 0; b < binCount; b++) firsts[b + 1] = (firsts[b + 1] ?? 0) + (firsts[b] ?? 0);
188
+ { const cursor = firsts.slice(0, binCount); for (let t = 0; t < triangles; t++) { if (t % 4096 === 0) yield; const b = binOf[t] ?? 0; members[cursor[b] ?? 0] = t; cursor[b] = (cursor[b] ?? 0) + 1; } }
189
+ const out = growU32(triangles * 3 + 64), bins: CullBin[] = [];
161
190
  const clusters = lod.map((tier) => clusterer(geometry, pitch, tier.cell, tileSize));
162
- const ordered: { readonly key: string; readonly x: number; readonly z: number; readonly list: number[] }[] = [];
191
+ const ordered: BinRow[] = [];
163
192
  for (const row of byBin.values()) for (const bin of row.values()) ordered.push(bin);
164
193
  ordered.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
165
194
  // A shared indexed vertex contributes once per bin to both bounds scans.
166
195
  // Keep triangle publication and LOD representative order unchanged.
167
196
  const boundedIn = new Uint32Array(position.count);
168
197
  let binId = 0;
169
- for (const { list, x: tileX, z: tileZ } of ordered) {
198
+ for (const { id, x: tileX, z: tileZ } of ordered) {
199
+ const list = members.subarray(firsts[id] ?? 0, firsts[id + 1] ?? 0);
170
200
  const start = out.length, unique: number[] = [];
171
201
  binId++;
172
202
  let minX = Infinity, minY = Infinity, minZ = Infinity, maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
@@ -198,13 +228,13 @@ export function* cullPlanSteps(geometry: BufferGeometry, pitch: number, lod: rea
198
228
  if (i % 256 === 0) yield;
199
229
  const t = list[i] ?? 0;
200
230
  const a = cluster(index.getX(t * 3)), b = cluster(index.getX(t * 3 + 1)), c = cluster(index.getX(t * 3 + 2));
201
- if (a !== b && b !== c && a !== c) out.push(a, b, c);
231
+ if (a !== b && b !== c && a !== c) { out.push(a); out.push(b); out.push(c); }
202
232
  }
203
233
  levels.push({ start: from, count: out.length - from });
204
234
  }
205
235
  bins.push({ sphere, start, count, levels, ...(tileSize === undefined ? {} : { tile: { x: tileX, z: tileZ } }) });
206
236
  }
207
- return { source: Uint32Array.from(out), bins, lod: lod.map((tier) => tier.distance) };
237
+ return { source: out.view(true), bins, lod: lod.map((tier) => tier.distance) };
208
238
  }
209
239
 
210
240
  /**
@@ -53,6 +53,18 @@ function archiveScratch(mesh: Mesh, indices: number): number {
53
53
  const bytes = 4 * (indices * (stride + 8) + header) + 2 * (indices * (stride + 64) + header);
54
54
  return Number.isSafeInteger(bytes) ? bytes : Infinity;
55
55
  }
56
+ /** Retire a whole-road mesh once its tile pool (a child) draws instead; returns the geometry it drew, for disposal. It stays
57
+ * as the pool's parent but draws in no view (no camera's layers, shadow pass included). RP4: three links a program in
58
+ * `setProgram` before it reads the draw count, so the empty mesh linked a flat-shaded, position-less variant of each road
59
+ * material the first frame it drew (Driftwood's west edge, 3 links, 386 ms in Chromium) and again at every light-count move. */
60
+ export function retireWholeRoadMesh(mesh: Mesh): BufferGeometry {
61
+ const previous = mesh.geometry;
62
+ mesh.geometry = new BufferGeometry(); mesh.geometry.setDrawRange(0, 0);
63
+ mesh.onBeforeRender = () => { /* Original cull buffers are retired. */ };
64
+ mesh.layers.disableAll();
65
+ return previous;
66
+ }
67
+
56
68
  export class RoadTileBacking {
57
69
  private readonly sources = new Map<Mesh, Source>();
58
70
  private readonly pending: PendingArchive[] = [];
@@ -284,9 +296,7 @@ export class RoadTileBacking {
284
296
  // hidden. Geometry disposal precedes each corresponding lease shrink.
285
297
  for (const source of this.sources.values()) if (source.pool !== null) source.pool.root.visible = true;
286
298
  for (const source of this.sources.values()) {
287
- const previous = source.mesh.geometry;
288
- source.mesh.geometry = new BufferGeometry(); source.mesh.geometry.setDrawRange(0, 0);
289
- source.mesh.onBeforeRender = () => { /* Original cull buffers are retired. */ };
299
+ const previous = retireWholeRoadMesh(source.mesh);
290
300
  this.culler.plans.delete(source.mesh); previous.dispose(); source.retire?.();
291
301
  }
292
302
  this.committed = true;
@@ -116,6 +116,8 @@ import { startRoadSigns } from './roadSignPreparation';
116
116
  import { clientPreparationBatch } from '../shardfile/preparationTiming';
117
117
 
118
118
  import { admittedRuntimeProduct } from '../shardfile/runtimeProduct';
119
+ import { gridArea } from './area';
120
+ import type { ProbeArea } from '@wildshard/engine/debug/probe';
119
121
 
120
122
  /** D12: the A1 outer ring's share of a drawn frame (ms). On the phone tier its strips, colliders and road stop 4 ms after
121
123
  * the last drawn frame (every other build keeps WORK_SLICE_MS): streamed at the shared 8 ms it held the grid's spawn
@@ -1208,6 +1210,13 @@ export class GridSession {
1208
1210
  * This runs only the presentation frame; no neighbour tick, input, physics or simulation is advanced. */
1209
1211
  prepareFrame(): void { this.frame?.frame(); }
1210
1212
 
1213
+ /** T2E-1b: the cell the player is in, as the test probe reads it (its shard, door panels and the server's flags there).
1214
+ * Without a live host no region is admitted, so no panel reads solid. */
1215
+ area(): ProbeArea | null {
1216
+ return gridArea({ current: this.live === null ? this.home.instance : this.live.live.current(), cells: this.assembly.cells,
1217
+ targets: id => this.panels.targets(id), flags: id => this.live?.areaFlags(id) ?? [] });
1218
+ }
1219
+
1211
1220
  /** The readout: what each cell shows, the rings and the allocator. */
1212
1221
  state(): GridSessionState {
1213
1222
  const pending = bootWaits();
@@ -1,5 +1,6 @@
1
1
  import { Mesh, type BufferGeometry, type Object3D } from 'three';
2
2
  import { prepareRigLoader } from '@wildshard/engine/anim/rig';
3
+ import { workSlice } from '@wildshard/engine/core/workSlice';
3
4
  import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
4
5
  import { NEAR_COLOUR, NEAR_LIGHT, nearPlaceholderCost, type NearPlaceholder } from '@wildshard/format/nearPlaceholder';
5
6
  import type { Shardfile } from '@wildshard/format/shardSchema';
@@ -63,16 +64,21 @@ export async function loadShardfileNear(rows: ShardfileNearRows, read: (ref: str
63
64
  const near = rows.near;
64
65
  if (near.content.length === 0) throw new Error('Shardfile declares no near content');
65
66
  const cost = nearPlaceholderCost(near, rows.inventory), loader = (await prepareRigLoader()).createRigLoader(), parts: BufferGeometry[] = [], lights: BufferGeometry[] = [], colours: BufferGeometry[] = [];
67
+ // GC36 / RP4: a neighbour's near placeholder loads while the traveller walks to its edge. Baking every mesh's pose in one
68
+ // go held the frame 60 to 170 ms per content file (Chromium, Driftwood to Sunscar); it now lets a frame through between meshes.
69
+ const slice = workSlice();
66
70
  try {
67
71
  for (const ref of near.content) {
68
72
  const gltf = await loader.parseAsync((await read(ref)).slice().buffer, '');
69
73
  gltf.scene.updateMatrixWorld(true);
70
- gltf.scene.traverse(node => {
71
- if (!isMesh(node)) return;
74
+ const meshes: Mesh[] = [];
75
+ gltf.scene.traverse(node => { if (isMesh(node)) meshes.push(node); });
76
+ for (const node of meshes) {
77
+ await slice.check();
72
78
  for (const material of Array.isArray(node.material) ? node.material : [node.material]) material.dispose();
73
79
  // NM13: the light layer stays apart from the lit draw (drawn additively, unlit)
74
80
  (node.name === NEAR_LIGHT ? lights : node.name === NEAR_COLOUR ? colours : parts).push(node.geometry.applyMatrix4(node.matrixWorld));
75
- });
81
+ }
76
82
  }
77
83
  } catch (error) { for (const part of [...parts, ...lights, ...colours]) part.dispose(); throw error; }
78
84
  const [first] = parts;
@@ -29,6 +29,7 @@ import { textureBytes } from '@wildshard/engine/render/textureBytes';
29
29
  import { setPoseProvider } from '@wildshard/engine/ui/ReloadPrompt';
30
30
  import { lastEnd, registerBeforeReload } from '@wildshard/engine/boot/lastEnd';
31
31
  import { gridPrefetchOrder, startGridPrefetch } from '../grid/prefetch';
32
+ import { shardArea } from '../grid/area';
32
33
  import { admittedRuntimeProduct, completeManifestCache, releaseManifestTransport } from '../shardfile/runtimeProduct';
33
34
  import { enterSkyClock } from './clockSettings';
34
35
  import { settleEntryPrograms } from './settlePrograms';
@@ -392,7 +393,10 @@ export async function finishStage(ctx: Awaited<ReturnType<typeof playStage>>): P
392
393
  ctx.session.residency?.bindComposer(game, game.engineScope, TIER);
393
394
  game.captureLevelResources();
394
395
  game.levelScope.onDispose(() => { windupWarn?.dispose(); weapons.setEnabled(false); boot.runtime.hooks.dispose?.(); audio.unloadLevel(); });
395
- installProbe(handle, { leakPhysics, health: () => playerHealth.attributes.health, quest: () => ({ adventure: boot.runtime.hooks.adventureFlags?.() ?? [], quest: boot.runtime.hooks.questFlags?.() ?? [] }) });
396
+ const grid = ctx.grid;
397
+ installProbe(handle, { leakPhysics, health: () => playerHealth.attributes.health, quest: () => ({ adventure: boot.runtime.hooks.adventureFlags?.() ?? [], quest: boot.runtime.hooks.questFlags?.() ?? [] }),
398
+ // T2E-1b: a grid page's area is the cell the player is in, not the shell
399
+ area: () => grid === null ? shardArea(slug, app.debug.snapshot()['shardfile'], boot.runtime.hooks.questFlags?.() ?? []) : grid.area() });
396
400
  ctx.startExplore?.();
397
401
  document.dispatchEvent(new Event('ws:ready')); // booted to the title
398
402
  const completeOfflineCopy = async (): Promise<void> => {
@@ -58,6 +58,11 @@ export function catalogueManifests():readonly (ShardManifest|TitleManifest)[]{
58
58
  return [...rows.values()];
59
59
  }
60
60
  const NO_ART = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 3 4"%3E%3Crect width="3" height="4" fill="%23273340"/%3E%3C/svg%3E';
61
+ /** C3, SA46: the plain row of a shard this build has no card for, from what the catalogue says of it (its name). Its art is the
62
+ * plain card until its product is admitted: the API hosts no uploaded shard's images. */
63
+ export function catalogueTitleRow(slug: string, name: string, order: number): TitleManifest {
64
+ return { slug, name, biome: '', status: 'live', order, shardfile: `/shardfiles/${slug}/shard.json`, card: { thumb: NO_ART, portrait: NO_ART, landscape: NO_ART } };
65
+ }
61
66
  /** C3: a head with a placement and no card in this build: a shard added to the catalogue after the build. Its name is all
62
67
  * the catalogue says, so it wears a plain card until its product is admitted. */
63
68
  export function withCatalogueHeads(rows: readonly TitleManifest[]): readonly TitleManifest[] {
@@ -68,8 +73,7 @@ export function withCatalogueHeads(rows: readonly TitleManifest[]): readonly Tit
68
73
  const added = heads.filter(head => !known.has(head.slug)).flatMap(head => {
69
74
  const placement = placed.get(head.slug);
70
75
  if (placement === undefined) return [];
71
- const row: TitleManifest = { slug: placement.slug, name: head.name, biome: '', status: 'live', order: placement.order ?? rows.length, shardfile: `/shardfiles/${placement.slug}/shard.json`, card: { thumb: NO_ART, portrait: NO_ART, landscape: NO_ART } };
72
- return [row];
76
+ return [catalogueTitleRow(placement.slug, head.name, placement.order ?? rows.length)];
73
77
  });
74
78
  return added.length === 0 ? rows : [...rows, ...added];
75
79
  }
@@ -433,7 +433,8 @@ async function startWorkerClient(ports: WorkerClientPorts, card: ReturnType<type
433
433
  let opened: number | undefined, renderTick = 0;
434
434
  if (grid === null) net.inCell = cell => (opened ??= cell) === cell;
435
435
  else {
436
- grid.bindWire({ site: () => { const cell = client.latest?.cell; return cell === undefined ? undefined : siteOf(cell); }, rebound: next => { net.world.rebind(next); }, rows: netNeighbourRegion(client, () => renderTick) });
436
+ grid.bindWire({ site: () => { const cell = client.latest?.cell; return cell === undefined ? undefined : siteOf(cell); }, rebound: next => { net.world.rebind(next); }, rows: netNeighbourRegion(client, () => renderTick),
437
+ flags: () => [...client.phased, ...client.flags()] });
437
438
  net.inCell = cell => siteOf(cell) === grid.frame();
438
439
  }
439
440
  scope.onDispose(() => { player.link = null; ports.weapons.bindWire(null); net.dispose(); });
@@ -36,7 +36,7 @@ import { readSummary, summaryView } from './summary';
36
36
  import { GAME_STRINGS } from '../../shared/game/strings';
37
37
  import { menuMode, selectEnters, selectExplores, type MenuMode } from './grid/menu';
38
38
  import { pageShardRefusals, refusalReason, type ShardRefusal } from './grid/refusal';
39
- import { autoPlaced, playerHidden, titleStatus } from '../../shared/game/grid/catalogueSlot';
39
+ import { autoPlaced, placedByFile, playerHidden, titleStatus } from '../../shared/game/grid/catalogueSlot';
40
40
  import { worldOpens } from './grid/oneWayIn';
41
41
  import './summary.css';
42
42
  import './upgrade.css';
@@ -82,8 +82,9 @@ const buildWorld = (): OpensShard => worldOpens((globalThis as { __WS_WORLD__?:
82
82
  export function titleCards(showHidden: boolean = isDev(), upgradeNeeded: UpgradeNeeded = noUpgrades, refused: RefusedShard = sessionRefusals, opens: OpensShard = buildWorld()): readonly TitleCard[] {
83
83
  // a `_` prototype stays Developer only unless its catalogue placement opens it (J313: Mossgate)
84
84
  const hidden = (m: TitleManifest): boolean => playerHidden(m);
85
- // SA34 (Q12): an auto-placed shard has no card, even for Developer: you cross in from a neighbour
86
- const ordinary = titleManifests().filter(m => m.shardSelect !== false && !autoPlaced(m));
85
+ // SA34 (Q12): an auto-placed shard has no card, even for Developer: you cross in from a neighbour. A cell the page learned from its
86
+ // channel's placement file (`placedCells.ts`) has one: with crossing off, its card and `?chunk=` are the only ways in
87
+ const ordinary = titleManifests().filter(m => (m.shardSelect !== false && !autoPlaced(m)) || placedByFile(m));
87
88
  const visible = ordinary.filter((m) => !hidden(m));
88
89
  const manifests = showHidden ? [...visible, ...ordinary.filter(hidden)] : visible;
89
90
  return manifests.map((m): TitleCard => titleCard(m, upgradeNeeded, refused, opens));
@@ -7,6 +7,7 @@ import { NetClient } from '@wildshard/engine/net/client';
7
7
  import type { NetIdentity } from '@wildshard/engine/net/identity';
8
8
  import { Redial, type LinkCause, type LinkProgress, type LinkState } from '@wildshard/engine/net/redial';
9
9
  import { decodeCountdown, type Countdown } from '@wildshard/engine/net/socketFrames';
10
+ import { encodeDeviceWord, worldReadsDevice } from '@wildshard/engine/net/deviceWord';
10
11
  import { WebSocketTransport } from '@wildshard/engine/net/webSocketTransport';
11
12
  import {NetRecords} from '@wildshard/engine/net/netRecord';
12
13
  import {onlineTelemetry} from '@wildshard/engine/telemetry/runtime';
@@ -90,6 +91,17 @@ export interface OnlineShell {
90
91
  dispose: () => void;
91
92
  }
92
93
 
94
+ /** DT3: how long a socket's device word waits for the renderer to name its GPU before it goes without it. */
95
+ const DEVICE_GPU_WAIT_MS = 10_000;
96
+ /** DT3: this page's device snapshot on `transport` (a closed one drops it). Telemetry: never throws, never holds the link. */
97
+ function sendDevice(transport: WebSocketTransport, build: string): void {
98
+ const send = async (): Promise<void> => {
99
+ const { deviceSnapshot } = await import('@wildshard/engine/telemetry/deviceSnapshot');
100
+ transport.control('device', encodeDeviceWord({ ...await deviceSnapshot(DEVICE_GPU_WAIT_MS), build }));
101
+ };
102
+ void send().catch(() => undefined);
103
+ }
104
+
93
105
  /** The link alone, with no page around it. `startOnline` is this with the strips. */
94
106
  export function connectOnline(config: OnlineConfig, view: OnlineView): OnlineShell {
95
107
  let playtest=false;
@@ -103,6 +115,8 @@ export function connectOnline(config: OnlineConfig, view: OnlineView): OnlineShe
103
115
  transport.onClose(() => { if (link === transport) down = true; });
104
116
  transport.onControl((control, bytes) => {
105
117
  if(control==='playtest'){playtest=true;return;}
118
+ // DEVICE-TELEMETRY DT3: a door whose first word says it reads the device word hears this page's snapshot, once per socket
119
+ if (control === 'world') { if (worldReadsDevice(bytes)) sendDevice(transport, config.build); return; }
106
120
  if (control === 'voice') {
107
121
  let word: VoiceHeard;
108
122
  try { word = JSON.parse(decoder.decode(bytes)) as VoiceHeard; } catch { return; }
@@ -23,6 +23,7 @@ import {readTar} from '@wildshard/format/tar';
23
23
  import type {ServerPack, ServerPackPart} from '../../shared/game/shardfile/serverPack';
24
24
  import {serverReadsFile} from '../../shared/game/shardfile/outputDescriptor';
25
25
  import {entryReadSet} from './entryReadSet';
26
+ import {phoneTier} from './tierTextures';
26
27
  import {createPartEncoder, packable, writeSpawnParts, type CookedMember, type PartEncoder} from './spawnParts';
27
28
 
28
29
  export type CookTier = 'phone' | 'desktop';
@@ -160,11 +161,18 @@ export interface ShardHalf {
160
161
  readonly mountRows: (tier: CookTier, set: CookSet) => readonly SpawnFile[];
161
162
  readonly read: (url: string) => Uint8Array;
162
163
  readonly stableKey: (url: string) => string | undefined;
164
+ /** A mount's bytes as this cook serves it: the discovery document carries the phone tier's table (S12b). */
165
+ readonly mountBytes: (row: CookMount) => Uint8Array;
163
166
  }
164
167
 
168
+ /** S12b: what the cook does with a shard's textures per tier. `phone`: give each phone row of the KTX2 table its own
169
+ * trimmed file (`phoneTier`), listed in the phone manifests in place of the file it stands in for. Off by default until
170
+ * the cook's own 6×6 encode (S12c) can replace the hand-made sets. */
171
+ export interface CookTiers {readonly phone?: boolean}
172
+
165
173
  /** The shard half of every manifest: what the app build's `write` and the standalone cook share. `folder` is where the
166
174
  * product is served; a catalogue names it by slug, and today's `_template` folder is the one that differs (`template`). */
167
- export function shardHalf(shard: OpenShardfile, wireBytes: WireBytes, warn: (line: string) => void = () => undefined, folder: string = shard.slug): ShardHalf {
175
+ export function shardHalf(shard: OpenShardfile, wireBytes: WireBytes, warn: (line: string) => void = () => undefined, folder: string = shard.slug, tiers: CookTiers = {}): ShardHalf {
168
176
  const prefix = `/shardfiles/${folder}/`, {index, source, sections} = shard, named = namedPlaces(sections);
169
177
  // D5-4: a preparation-only preview lists the default set alone (no stored fence), so `wildshard prepare` sees the boot's
170
178
  // own reads beyond it. Listing the whole level there made every recorded fence the whole level (Pine, Nalati).
@@ -187,17 +195,31 @@ export function shardHalf(shard: OpenShardfile, wireBytes: WireBytes, warn: (lin
187
195
  sources.set(headerURL, () => shard.header);
188
196
  const header = {url: headerURL, bytes: shard.header.length, hash: headerHash, wireBytes: wireBytes(`${prefix}shard.json`, shard.header, headerHash)};
189
197
  // C3: a page reads this before it knows the product, and a cold offline entry reads it too.
190
- const document = shard.cook?.mounts.find(row => row.url === `${prefix}discovery.json`), discovery: readonly SpawnFile[] = document === undefined ? [] : [{
191
- url: `${document.url}?v=${document.hash.slice(0, 8)}`, bytes: document.bytes, hash: document.hash, wireBytes: wireBytes(document.url, shard.read(document.path), document.hash)}];
192
- for (const row of discovery) if (document !== undefined) sources.set(row.url, () => shard.read(document.path));
193
- const mounts = downloaded(shard), mountURLs = new Set(mounts.map(row => row.url)), onTier = mountTiers(mountURLs);
198
+ const document = shard.cook?.mounts.find(row => row.url === `${prefix}discovery.json`), mounts = downloaded(shard);
199
+ // S12b: the phone tier's files, made from the KTX2 table's own targets; the discovery document names them.
200
+ const onTier = mountTiers(new Set(mounts.map(row => row.url))), mountByURL = new Map(mounts.map(row => [row.url, row])), mountOf = (url: string): Uint8Array | undefined => { const row = mountByURL.get(url); return row === undefined ? undefined : shard.read(row.path); };
201
+ const phone = tiers.phone === true && document !== undefined ? phoneTier(shard.read(document.path), mountOf) : undefined;
202
+ const documentBytes = phone?.discovery ?? (document === undefined ? undefined : shard.read(document.path));
203
+ const discovery: readonly SpawnFile[] = document === undefined || documentBytes === undefined ? [] : [(() => {
204
+ const hash = phone === undefined ? document.hash : sha256(documentBytes);
205
+ return {url: `${document.url}?v=${hash.slice(0, 8)}`, bytes: documentBytes.length, hash, wireBytes: wireBytes(document.url, documentBytes, hash)};
206
+ })()];
207
+ for (const row of discovery) if (documentBytes !== undefined) sources.set(row.url, () => documentBytes);
194
208
  const mountRow = new Map(mounts.map(row => {
195
209
  const url = CONTENT_NAMED.test(row.url) || /-[a-f0-9]{8}\.[a-z0-9]+$/u.test(row.url) ? row.url : `${row.url}?v=${row.hash.slice(0, 8)}`;
196
210
  sources.set(url, () => shard.read(row.path));
197
211
  return [row.url, () => ({url, bytes: row.bytes, hash: row.hash, wireBytes: wireBytes(row.url, shard.read(row.path), row.hash)})] as const;
198
212
  }));
213
+ const tierRows = new Map([...phone?.files ?? []].map(([from, files]) => [from, files.map(file => {
214
+ const hash = sha256(file.bytes);
215
+ sources.set(file.url, () => file.bytes);
216
+ return {url: file.url, bytes: file.bytes.length, hash, wireBytes: wireBytes(file.url, file.bytes, hash)};
217
+ })]));
218
+ /** A phone list names each trimmed target's phone files in its place, and the target too while a kept row still reads it. */
219
+ const tiered = (tier: CookTier, url: string): readonly string[] => tier !== 'phone' || !tierRows.has(url) ? [url] : phone?.kept.has(url) === true ? [url, `tier:${url}`] : [`tier:${url}`];
199
220
  return {shard, header, read: url => { const read = sources.get(url); if (read === undefined) throw new Error(`Spawn file has no source: ${url}`); return read(); },
200
221
  stableKey: url => stableKeys.get(url),
222
+ mountBytes: row => (row.url === document?.url && documentBytes !== undefined ? documentBytes : shard.read(row.path)),
201
223
  productRows: (tier, set) => {
202
224
  const selected: SpawnFile[] = [header, ...discovery];
203
225
  for (const row of index.sections) selected.push(productFile(row.path, row.bytes, row.hash, `section:${row.name}`));
@@ -208,7 +230,13 @@ export function shardHalf(shard: OpenShardfile, wireBytes: WireBytes, warn: (lin
208
230
  },
209
231
  mountRows: (tier, set) => {
210
232
  const urls = wholeSet(tier, set) ? mounts.map(row => row.url).filter(url => onTier(url, tier)) : fence.mounts;
211
- return urls.flatMap(url => { const row = mountRow.get(url); return row === undefined ? [] : [row()]; });
233
+ // A phone file whose target no phone list names (a fence shard's file read past its fence) rides in the phone's whole
234
+ // set: no other tier's part holds it, and it costs less than the target a phone read from a desktop part before.
235
+ const listed = new Set(urls), unlisted = tier === 'phone' && set === 'whole' ? [...tierRows.keys()].filter(url => !listed.has(url)).map(url => `tier:${url}`) : [];
236
+ return [...urls.flatMap(url => tiered(tier, url)), ...unlisted].flatMap(url => {
237
+ if (url.startsWith('tier:')) return tierRows.get(url.slice(5)) ?? [];
238
+ const row = mountRow.get(url); return row === undefined ? [] : [row()];
239
+ });
212
240
  }};
213
241
  }
214
242
 
@@ -300,6 +328,8 @@ export interface CookShardOptions {
300
328
  readonly warn?: (line: string) => void;
301
329
  /** The renderer fingerprint to cook for; this engine's own unless a build names it. */
302
330
  readonly renderer?: string;
331
+ /** S12b: per-tier texture files; off unless a cook asks. */
332
+ readonly tiers?: CookTiers;
303
333
  }
304
334
 
305
335
  /** `cook <shardfile> → <packs>`: the shard's half of every manifest, its parts, and its loose mounts at their URLs. */
@@ -313,7 +343,7 @@ export async function cookShard(tarball: Uint8Array, out: string, options: CookS
313
343
  async function cookWith(tarball: Uint8Array, out: string, options: CookShardOptions, encoder: PartEncoder): Promise<CookReport> {
314
344
  const started = options.now(), shard = openShardfile(tarball, options.renderer === undefined ? {} : {renderer: options.renderer});
315
345
  if (shard.preparation === 'stale') options.warn?.(stalePreparationLine(shard.slug));
316
- const half = shardHalf(shard, options.wireBytes, options.warn);
346
+ const half = shardHalf(shard, options.wireBytes, options.warn, shard.slug, options.tiers);
317
347
  const before = encoder.stats();
318
348
  const table = COOK_TIERS.flatMap(tier => COOK_SETS.map(set => ({tier, set, rows: [...half.productRows(tier, set), ...half.mountRows(tier, set)]})));
319
349
  const whole = table.filter(row => row.set === 'whole');
@@ -337,7 +367,7 @@ async function cookWith(tarball: Uint8Array, out: string, options: CookShardOpti
337
367
  const loose = (half.shard.cook?.mounts ?? []).filter(row => !packable(row.url) || !row.url.startsWith('/assets/'));
338
368
  for (const row of loose) {
339
369
  const file = join(out, row.url.slice(1));
340
- mkdirSync(dirname(file), {recursive: true}); writeFileSync(file, half.shard.read(row.path));
370
+ mkdirSync(dirname(file), {recursive: true}); writeFileSync(file, half.mountBytes(row));
341
371
  }
342
372
  // C3: a title or menu `<img>` reads a shard's images by the URLs its level manifest names, before any fetch layer exists.
343
373
  const images = half.shard.index.files.flatMap(row => row.name?.startsWith('ui/images/') === true ? [row.path] : []);