@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
@@ -20,12 +20,18 @@ export interface GridSimulationPorts {
20
20
  /** The session's owning seat; older standalone callers use actor.player. */
21
21
  readonly owner?: string;
22
22
  readonly highway: GridResident;
23
+ /** ZE11 (J352): the cells a walker crosses into from the road (the session's home); absent, every cell. Any other cell is entered
24
+ * only by its gate's zone entry. */
25
+ readonly enterable?: (instance: string) => boolean;
23
26
  load: (cell: GridCell, saved: SimSnapshot | undefined) => Promise<GridResident>;
24
27
  save?: (instance: string, snapshot: SimSnapshot) => boolean;
25
28
  /**
26
29
  * An owner that keeps every continuation itself, and reloads them in `load` (E5.2b, a phone's worker). It captures an occupied
27
30
  * world when told to, in whatever form it stores. Nothing is captured on admission or packed in memory: capturing a whole
28
- * physics world grows a wasm heap that never gives it back, and a world nobody entered has nothing to keep.
31
+ * physics world grows a wasm heap that never gives it back, and a world nobody entered has nothing to keep. ZONE-ENTRY ZE2:
32
+ * it is not told at a leave. The world left stays resident with everything it held, so its capture is owed until its
33
+ * eviction, the only time it is lost: a whole world's capture stood the in-page server's tick for 122 to 134 ms
34
+ * (Driftwood) on the step onto the road. What a reload in between loses is only what moved since its last progress save.
29
35
  */
30
36
  durable?: (instance: string, host: SimHost) => boolean;
31
37
  read?: (instance: string) => SimSnapshot | undefined;
@@ -97,6 +103,8 @@ export class GridSimulation {
97
103
  private readonly requests = new Map<string, Promise<void>>();
98
104
  private readonly cancelFrames = new Set<() => void>();
99
105
  private readonly cleanupIssues: string[] = [];
106
+ /** Worlds left with their `durable` capture not yet taken (ZE2): it is taken at their eviction. */
107
+ private readonly owed = new Set<string>();
100
108
  private sequence: Promise<void> = Promise.resolve();
101
109
  private used = 0;
102
110
  private disposed = false;
@@ -163,7 +171,7 @@ export class GridSimulation {
163
171
  const distance = (cell: GridCell): number => Math.max(Math.abs(feet.x - cell.origin.x), Math.abs(feet.z - cell.origin.z)) - CHUNK_HALF;
164
172
  const active = this.current(player);
165
173
  if (active !== null && distance(this.assembly.cell(active)) <= 10) return active;
166
- return [...this.assembly.cells].sort((a, b) => a.instance.localeCompare(b.instance)).find((cell) => distance(cell) <= 6)?.instance ?? null;
174
+ return [...this.assembly.cells].sort((a, b) => a.instance.localeCompare(b.instance)).find((cell) => distance(cell) <= 6 && (this.ports.enterable?.(cell.instance) ?? true))?.instance ?? null;
167
175
  }
168
176
  /** Physics construction is not enough when the runtime/admitted closure has an additional readiness fence. */
169
177
  ready(instance: string | null): boolean { return !this.disposed && (instance === null || (this.residents.has(instance) && !this.resident(instance).evicting && (this.ports.admitted?.(instance) ?? true))); }
@@ -230,13 +238,28 @@ export class GridSimulation {
230
238
  /** Snapshot before leaving the active region. Failure keeps both its world and the traveller authoritative. */
231
239
  checkpoint(instance: string): boolean {
232
240
  const resident = this.residents.get(instance); if (resident === undefined || this.disposed) return false;
233
- if (this.ports.durable !== undefined) return !this.occupied(instance) || this.ports.durable(instance, resident.value.host);
241
+ if (this.ports.durable !== undefined) {
242
+ if (this.occupied(instance)) { this.owed.add(instance); return true; }
243
+ if (!this.owed.has(instance)) return true;
244
+ // Nobody stands here, so the owner's seat holds no capsule; a capture reads one, as a parked seat holds.
245
+ const { host } = resident.value, parked = !this.seat(host, this.owner).hasMotor;
246
+ if (parked) this.parkOwner(host);
247
+ try { if (!this.ports.durable(instance, host)) return false; } finally { if (parked) this.unparkOwner(host); }
248
+ this.owed.delete(instance); return true;
249
+ }
234
250
  const snapshot = this.occupied(instance) ? snapshotSimHost(resident.value.host) : this.snapshots.read(instance);
235
251
  if (snapshot === undefined) throw new Error('Missing admitted grid continuation');
236
252
  const packed = this.snapshots.pack(instance, snapshot); if (packed === null) return false;
237
253
  if (this.ports.save?.(instance, snapshot) !== true) return false;
238
254
  this.snapshots.store(instance, packed); return true;
239
255
  }
256
+ /** Take every capture a step out left owed whose world nobody stands in now (a save on the road: a reload there must not lose
257
+ * the world left behind). False when one fails; the rest are still tried, and a failed one stays owed. */
258
+ flushOwed(): boolean {
259
+ let ok = true;
260
+ for (const instance of this.owed) if (!this.occupied(instance) && !this.checkpoint(instance)) ok = false;
261
+ return ok;
262
+ }
240
263
  /** Readiness keeps a frozen destination resident; unneeded neighbours may be evicted by the shared allocator. */
241
264
  retain(instance: string, needed: boolean, distance: number): void {
242
265
  if (!Number.isFinite(distance) || distance < 0) throw new RangeError('Invalid sim residency distance');
@@ -261,7 +284,7 @@ export class GridSimulation {
261
284
  commit: () => {
262
285
  if (closed) return; closed = true;
263
286
  if (this.disposed || this.residents.get(instance) !== resident) return;
264
- this.residents.delete(instance);
287
+ this.residents.delete(instance); this.owed.delete(instance);
265
288
  if (this.ports.read !== undefined) this.snapshots.drop(instance);
266
289
  // Each cleanup runs even if another fails. The infallible allocator commit exposes failures for the session owner.
267
290
  for (const dispose of [() => { this.ports.invalidated?.(instance); }, () => { resident.value.dispose(); }, () => { resident.lease?.release(); }]) {
@@ -64,6 +64,7 @@ import type { Shardfile } from "@wildshard/format/shardSchema";
64
64
  import { speciesResolver, simStrikes } from "./brain";
65
65
  import { createShardfileScriptLane, verifiedScriptModules, type ScriptModuleAssets, type ShardScriptPorts } from "../shardfile/scripts";
66
66
  import { installDeclaredBrains, type DeclaredBrainPorts } from "../shardfile/brainRuntime";
67
+ import { installDataRespawns } from "../shardfile/dataRespawn";
67
68
  import { createShardfileComposedLane, type DeclaredScriptBrainPorts } from "../shardfile/scriptComposition";
68
69
  import { bindPlayerColumns, dataCreaturePorts } from "../../../shared/game/shardfile/dataCreaturePorts";
69
70
  import { prepareDeclaredGroupBrains, type DeclaredGroupPorts, type DeclaredGroupPolicy } from "../shardfile/groupRuntime";
@@ -644,6 +645,7 @@ export function bindShardfileSim(host: SimHost, shard: Shardfile, assets: Readon
644
645
  } });
645
646
  }
646
647
  installDeclaredBrains(host, shard.creatures.spawns.filter((spawn) => spawn.brain === null || (!custom.has(spawn.brain) && !groupIds.has(spawn.brain))), shard.creatures.brains.filter((brain) => brain.kind !== 'script'), ports.brains ?? dataPorts?.brains);
648
+ installDataRespawns(host, shard.creatures.spawns);
647
649
  dataPorts?.install();
648
650
  const decisionRows = decisionScriptsFromSections(ports.sections);
649
651
  const decisionActors = new Set(decisionRows.flatMap(row => Object.values(row.actors)));
@@ -0,0 +1,47 @@
1
+ // TEMPLATE-E2E TC-E2 (J361, meta TEMPLATE-E2E-PLAN): a data shard's creatures respawn. A `creatures.spawns` row's optional
2
+ // `respawn` (seconds, 1 to 3600, shard-format 0.5.8) brings its body back at its `at`, whole, that long after it dies: the
3
+ // declared brain and group skip a dead actor and resume once it is alive again, so reviving the body restores them. The
4
+ // waits are the host's state (one adapter), so a save keeps the clock; a cell asleep spends it (SC10, as declared homes do).
5
+ import * as v from 'valibot';
6
+ import type { SimHost } from '@wildshard/engine/sim';
7
+
8
+ /** One spawn row's revive inputs (the format's `creatures.spawns` row). */
9
+ export interface RespawnRow { readonly id: string; readonly at: readonly [number, number, number]; readonly yaw: number; readonly respawn?: number | undefined }
10
+
11
+ const finite = v.pipe(v.number(), v.finite());
12
+ const Saved = v.strictObject({ version: v.literal(1), waits: v.array(v.tuple([v.string(), finite])) });
13
+ export const DATA_RESPAWN_STEP = 'data.respawn';
14
+
15
+ /** Install the respawn clocks for the rows that declare one; nothing when none does (no adapter, so old saves restore). */
16
+ export function installDataRespawns(host: SimHost, rows: readonly RespawnRow[]): { readonly waits: () => ReadonlyMap<string, number> } | null {
17
+ const timed = new Map(rows.flatMap((row) => (row.respawn === undefined ? [] : [[row.id, row] as const])));
18
+ if (timed.size === 0) return null;
19
+ for (const id of timed.keys()) if (!host.entities.has(id)) throw new Error(`Respawn row ${id} names no body`);
20
+ const waits = new Map<string, number>();
21
+ host.events.on('actor.died', ({ actor }) => { const row = timed.get(actor.id); if (row?.respawn !== undefined) waits.set(row.id, row.respawn); }, host.scope);
22
+ host.events.on('world.slept', ({ seconds }) => { for (const [id, left] of waits) waits.set(id, Math.max(Number.MIN_VALUE, left - seconds)); }, host.scope);
23
+ const revive = (row: RespawnRow): void => {
24
+ const body = host.entities.get(row.id); if (body === undefined) return;
25
+ body.place(row.at[0], row.at[2], row.yaw, row.at[1]);
26
+ body.revive();
27
+ // A data cell keeps a dead body's motor (no body bands drop it): stand its capsule at the spawn, no sweep. Under body
28
+ // bands a dead body has none, and the next sync makes one where it now stands.
29
+ body.motor?.resetAt?.(body.position);
30
+ };
31
+ host.onStep(DATA_RESPAWN_STEP, (dt) => {
32
+ for (const [id, left] of waits) {
33
+ const next = left - dt;
34
+ if (next > 0) { waits.set(id, next); continue; }
35
+ waits.delete(id);
36
+ const row = timed.get(id); if (row !== undefined) revive(row);
37
+ }
38
+ }, {
39
+ snapshot: () => ({ version: 1, waits: [...waits].sort(([a], [b]) => a.localeCompare(b)) }),
40
+ restore: (value) => {
41
+ const state = v.parse(Saved, value);
42
+ waits.clear();
43
+ for (const [id, left] of state.waits) { if (!timed.has(id)) throw new Error(`Incompatible respawn continuation: ${id}`); waits.set(id, left); }
44
+ },
45
+ });
46
+ return { waits: () => waits };
47
+ }
@@ -145,7 +145,7 @@ const PLACE_RADIUS = 8;
145
145
  export async function dataCellPlaces(input: Pick<HeadlessRuntimeInput, 'shard' | 'product'>): Promise<readonly PlaceArea[]> {
146
146
  const published = input.product === undefined ? [] : await serverPlaces(input.product);
147
147
  if (published.length > 0) return published;
148
- return (input.shard.manifest?.pois ?? []).map(poi => ({ id: poi.id, label: poi.name, x: poi.x, z: poi.z, r: poi.r ?? PLACE_RADIUS }));
148
+ return (input.shard.manifest?.pois ?? []).filter(poi => poi.respawn !== false).map(poi => ({ id: poi.id, label: poi.name, x: poi.x, z: poi.z, r: poi.r ?? PLACE_RADIUS }));
149
149
  }
150
150
 
151
151
  /** Whether this output runs on the trusted headless owner. */
@@ -33,7 +33,7 @@ import { landedBy } from '@wildshard/engine/combat/damageBook';
33
33
  import type { HeadlessRuntimeInput } from '../headlessRuntime';
34
34
  import { actRoutes } from '@wildshard/engine/sim/actRoutes';
35
35
  import { openCellWorld, type CellWorld, type CellWorldOptions } from './cellWorld';
36
- import { addCellWalls, addVoidFloor, installRoadCombat, renewVoidFloor, ROAD } from './roadWorld';
36
+ import { addVoidFloor, addZoneWalls, dropCellWalls, installRoadCombat, renewVoidFloor, ROAD } from './roadWorld';
37
37
  import { netBuys, netWorldInput } from '../../../shared/host/standalone/netInput';
38
38
  import { cellDocuments, CONTINUATION, ContinuationSlots, SITE, siteDocuments, type SavedContinuation, type SavedSite } from './continuation';
39
39
  import { ledgerFilings } from './ledgerFilings';
@@ -171,8 +171,11 @@ export class StandaloneGrid {
171
171
  return world;
172
172
  };
173
173
  const strips = options.lone === true ? [] : await bootTask('server:road-collision-inputs', options.strips);
174
- const road = bootWork('server:road-physics-and-collision', () => StandaloneGrid.road(rapier, assembly.cells, strips, site === null ? candidate?.saved.road : undefined, arrival, options.refused));
174
+ // ZE11 (J352): the session's home is the cell it opens in (a Shard select pick, a gate's zone entry or its save), else its slug's
175
+ const homeCell = site ?? home.instance;
176
+ const road = bootWork('server:road-physics-and-collision', () => StandaloneGrid.road(rapier, assembly.cells, strips, site === null ? candidate?.saved.road : undefined, arrival, options.refused, homeCell));
175
177
  const grid: GridSimulation = new GridSimulation(assembly, { highway: { host: road, dispose: () => { road.dispose(); } }, maxResidents: options.residents ?? STANDALONE_RESIDENTS,
178
+ enterable: instance => options.lone === true || instance === homeCell,
176
179
  load: async (cell, cached) => {
177
180
  const world = await open(cell, cached);
178
181
  holdStrips(world.host, strips.flatMap(strip => strip.duplicates.filter(row => row.instance === cell.instance).map(row => row.mesh)));
@@ -193,19 +196,20 @@ export class StandaloneGrid {
193
196
  return server;
194
197
  }
195
198
 
196
- private static road(rapier: Rapier, cells: readonly GridCell[], strips: readonly GridCollisionStrip[], saved: string | undefined, arrival: Readonly<GridPoint> | undefined, refused: GridServerOptions['refused']): SimHost {
199
+ private static road(rapier: Rapier, cells: readonly GridCell[], strips: readonly GridCollisionStrip[], saved: string | undefined, arrival: Readonly<GridPoint> | undefined, refused: GridServerOptions['refused'], home: string): SimHost {
197
200
  if (saved !== undefined) {
198
201
  try {
199
202
  const restored = restoreSimHost(ROAD, { rapier }, decodeSimSnapshot(saved)), player = sessionPlayer(restored);
200
203
  if (renewVoidFloor(restored, cells, player.position, ROAD_SKIN)) player.motor.resetAt(player.position);
201
204
  installRoadCombat(restored);
205
+ dropCellWalls(restored); addZoneWalls(restored, cells, home);
202
206
  holdStrips(restored, strips.map(strip => strip.mesh));
203
207
  return restored;
204
208
  } catch (error) { refused?.(error); } // a road holds no progress but where the player stood
205
209
  }
206
210
  const road = createSimHost(ROAD, { rapier }), [x, y, z] = readableSnapshot(saved ?? '')?.players[0]?.position ?? [], stood = arrival ?? (x === undefined || y === undefined || z === undefined ? undefined : { x, y, z });
207
211
  installRoadCombat(road);
208
- addCellWalls(road, cells);
212
+ addZoneWalls(road, cells, home);
209
213
  addVoidFloor(road, cells);
210
214
  holdStrips(road, strips.map(strip => strip.mesh));
211
215
  const player = sessionPlayer(road);
@@ -269,8 +273,14 @@ export class StandaloneGrid {
269
273
  }
270
274
  /** A Developer's `?bossGod`, on the pipeline that now lands the blow, and a lair's script, whose contact wears no fight's tag. */
271
275
  bossGod(): void { this.host.combat.playerRules(this.host.scope, { bossGod: true }); actRoutes(this.host).god = true; }
276
+ /** A golden camera's spectator (`HarnessStill`): from now on every creature in the world the player stands in holds where it is. */
277
+ still(): void { this.stilled = true; }
278
+ private stilled = false;
272
279
  open(): void { this.rooms.open(); }
273
- tick(): void { this.rooms.tick(); }
280
+ tick(): void {
281
+ if (this.stilled) for (const actor of this.host.entities.values()) actor.harnessHold = true; // each tick: a creature that streams in later holds too
282
+ this.rooms.tick();
283
+ }
274
284
  /** Resolves true when every write so far reached the real storage, and tells `held` which of its saves that makes good. */
275
285
  private settle(held: readonly { settled: (durable: boolean) => void }[]): Promise<boolean> {
276
286
  this.settling = this.settling.then(() => this.options.storage.settled()).then(durable => { for (const slots of held) slots.settled(durable); return durable; });
@@ -278,10 +288,12 @@ export class StandaloneGrid {
278
288
  }
279
289
  /** Save where the session stands. The document for that place first, then the site that names it. */
280
290
  async save(): Promise<{ readonly tick: number; readonly durable: boolean }> {
291
+ // a world left for the road owes its capture until evicted: a save takes it, so a reload on the road keeps it
292
+ const owed = this.grid.flushOwed();
281
293
  const site = this.grid.current(), { host } = this, { tick } = host.state, wire = capture(host), ledger = this.options.book.snapshot();
282
294
  const cell = site === null ? undefined : this.slots(site);
283
295
  const wrote = (cell?.write({ tick, snapshot: wire, ledger }) ?? true) && this.sites.write({ tick: ++this.saved, site, ...(site === null ? { road: wire, ledger } : {}) });
284
- return { tick, durable: await this.settle(cell === undefined ? [this.sites] : [cell, this.sites]) && wrote };
296
+ return { tick, durable: await this.settle(cell === undefined ? [this.sites] : [cell, this.sites]) && wrote && owed };
285
297
  }
286
298
  dispose(): void { this.rooms.dispose(); this.room.dispose(); this.grid.dispose(); }
287
299
  }
@@ -14,6 +14,9 @@ import type { GridCollisionStrip } from '@wildshard/engine/game/grid/gridCollisi
14
14
  import { HOST_PROBE } from '@wildshard/engine/game/plugin/simulation';
15
15
  import { installVoidFloor, voidFloorBoxes } from '@wildshard/engine/game/grid/voidFloor';
16
16
  import { FALL_FLOOR } from './fallFloor';
17
+ import { installEntrySockets } from '@wildshard/engine/physics/entrySockets';
18
+ import { ReadinessWalls } from '@wildshard/engine/physics/readinessWalls';
19
+ import { walledCells, zoneWallEdges } from '@wildshard/engine/game/grid/zoneWalls';
17
20
 
18
21
  /** Ground under the whole grid, far below the road's strips, and a player's pace on them. */
19
22
  const ROAD_HALF_SIZE = 2000, ROAD_SPEED = 8;
@@ -42,6 +45,33 @@ export function addCellWalls(road: SimHost, cells: readonly (Pick<GridCell, 'ori
42
45
  }
43
46
  });
44
47
  }
48
+ /**
49
+ * ZONE-ENTRY ZE11 (J352): the in-page server's road walls every cell but the session's home on the page's own lines (`zoneWallEdges`:
50
+ * the edge line, open only at each entryway's buffer, the gate 10 m in) and floors each buffer with its entry socket, so the feet
51
+ * reach a gate on the server's road as they do on the page, and no further. The home has only its 2 m hold. A restored road first loses the
52
+ * walls an older build saved (`dropCellWalls`); its platform-tagged pieces are renewed with its void floor (`renewVoidFloor`).
53
+ */
54
+ export function addZoneWalls(road: SimHost, cells: readonly GridCell[], home: string): void {
55
+ const walled = walledCells({ cells }, { instance: home });
56
+ withOwner(road.scope, () => {
57
+ installEntrySockets(road.physics, road.scope, walled.map(cell => cell.origin));
58
+ new ReadinessWalls(road.physics, walled.flatMap(cell => zoneWallEdges(cell, { origin: { x: 0, z: 0 } })), road.scope);
59
+ });
60
+ // the home keeps the 2 m hold (`addCellWalls`): its crossing, 6 m out, takes a walker past it; but this server keeps one world, so
61
+ // after a reload on the road a walker who reaches the home before it loads stops there, never walking on under its hills
62
+ addCellWalls(road, cells.filter(cell => cell.instance === home));
63
+ }
64
+ /** ZE11: take out the 2 m plain walls (`addCellWalls`) a road saved by an older build holds: the only cuboids of that size. */
65
+ export function dropCellWalls(road: SimHost): number {
66
+ const { world } = road.physics, found: Collider[] = [];
67
+ world.forEachCollider(collider => {
68
+ if (tagOf(collider) !== undefined) return;
69
+ const half = collider.halfExtents?.();
70
+ if (half !== undefined && half !== null && Math.abs(half.y - WALL_HEIGHT) < 1e-3 && Math.abs(Math.min(half.x, half.z) - WALL / 2) < 1e-3) found.push(collider);
71
+ });
72
+ for (const collider of found) world.removeCollider(collider, false);
73
+ return found.length;
74
+ }
45
75
  /** GC15 (3): take down the walls round these cells (on another worker, their entryways standing): the road crosses into them now. */
46
76
  export function openCellWalls(road: SimHost, instances: readonly string[]): void {
47
77
  const kept = walls.get(road);
@@ -18,7 +18,7 @@ import type { GridPoint } from '@wildshard/engine/game/grid/assembly';
18
18
  import type { GridCollisionStrip } from '@wildshard/engine/game/grid/gridCollision';
19
19
  import type { HeadlessRuntimeInput } from '../headlessRuntime';
20
20
  import { StandaloneGrid } from './gridServer';
21
- import { isHarnessFlag, isHarnessGod, isHarnessHits, isHarnessJoin, isHarnessMove, isHarnessPlace } from '../../../shared/host/standalone/harnessPlace';
21
+ import { isHarnessFlag, isHarnessGod, isHarnessHits, isHarnessJoin, isHarnessMove, isHarnessPlace, isHarnessStill } from '../../../shared/host/standalone/harnessPlace';
22
22
  import { WorkerLoopback } from '../../../shared/host/standalone/workerLoopback';
23
23
  import { isDevColliders, isDevGround, swapDevBoxes, swapDevGround } from '@wildshard/engine/game/devColliders';
24
24
  import { isDevRestart, withDevGameplay, type DevGameplay, type DevPlace, type DevRestarted } from '@wildshard/engine/game/devGameplay';
@@ -146,7 +146,7 @@ export function runStandaloneServer(options: StandaloneServerOptions): { dispose
146
146
  if (live === undefined) return;
147
147
  if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ && isDevColliders(event.data)) swapDevBoxes(live.host.physics, live.host.scope, devBoxes, event.data.wildshardDevColliders, event.data.boxes);
148
148
  else if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ && isDevGround(event.data)) swapDevGround(live.host.physics, live.host.scope, devGround, event.data.wildshardDevGround, groundPorts);
149
- else if (isHarnessJoin(event.data) && port !== undefined) live.join(event.data, new WorkerLoopback(port)); else if (isHarnessFlag(event.data)) live.raise(event.data.flag); else if (isHarnessMove(event.data)) live.place(event.data, event.data.move); else if (isHarnessPlace(event.data)) live.place(event.data); else if (isHarnessHits(event.data)) live.hardHits(event.data.hits); else if (isHarnessGod(event.data)) live.bossGod();
149
+ else if (isHarnessJoin(event.data) && port !== undefined) live.join(event.data, new WorkerLoopback(port)); else if (isHarnessFlag(event.data)) live.raise(event.data.flag); else if (isHarnessMove(event.data)) live.place(event.data, event.data.move); else if (isHarnessPlace(event.data)) live.place(event.data); else if (isHarnessHits(event.data)) live.hardHits(event.data.hits); else if (isHarnessGod(event.data)) live.bossGod(); else if (isHarnessStill(event.data)) live.still();
150
150
  };
151
151
  clock = new ServerClock({ now: diagnosticNow, wait: (ms, run) => { const timer = scope.timeout(ms, run); return () => { scope.cancelTimer(timer); }; },
152
152
  step: () => { const live = grid; if (live === undefined) return; try { live.tick(); progress(live); } catch (error) { fail(error); } } });
@@ -17,6 +17,8 @@ export interface AnimalSimSpec {
17
17
  export interface AnimalMotor {
18
18
  move: (feet: Vector3, want: { x: number; y: number; z: number }, ignoreGround: boolean) => void;
19
19
  dispose: () => void;
20
+ /** Stand the capsule at `feet` without a sweep (a revived body back at its spawn, TEMPLATE-E2E TC-E2). */
21
+ resetAt?: (feet: Vector3) => void;
20
22
  }
21
23
  /** Trusted collision-pose owner. It reads only the last published joints, never advances a body or pose.
22
24
  * The installer snapshots/restores its publication history through the host adapter alongside this actor. */
@@ -174,6 +176,14 @@ export class AnimalSim {
174
176
  get flying(): boolean { return this.flight !== null; }
175
177
  get lockable(): boolean { return this.simSpec.lockable ?? this.flying; }
176
178
  get lockRange(): number | undefined { return this.simSpec.flight?.lockRange; }
179
+ /** TEMPLATE-E2E TC-E2: a dead body stands again, whole (a data spawn's `respawn`); `place` it first. */
180
+ revive(): void {
181
+ if (this.alive) return;
182
+ this.alive = true; this.hp = this.maxHp; this.state = 'idle'; this.deathT = -1; this.lastHitT = -Infinity;
183
+ this.flinch = 0; this.flinchRoll = 0; this.flinchPitch = 0; this.stunT = 0; this.pushT = 0; this.brace = 0;
184
+ this.speed = 0; this.desiredSpeed = 0; this.strafe = 0; this.desiredStrafe = 0; this.attackT = -1;
185
+ this.impulseVelocity.set(0, 0, 0);
186
+ }
177
187
  place(x: number, z: number, yaw: number, y?: number): void {
178
188
  this.position.set(x, y ?? this.simPorts.heightAt(x, z), z);
179
189
  const flight = this.simSpec.flight;
@@ -8,10 +8,15 @@ import { PLATFORM_COLLIDER_OWNER } from './stripColliders';
8
8
 
9
9
  /** Conservative native wall/handle allowance per four-sided cell, reserved before construction. */
10
10
  export const TRANSFER_WALL_BYTES = 65_536;
11
- /** Outgoing feet may reach the >10 m target threshold, but never pass this solid hold line before a durable commit. */
12
- export const TRANSFER_EXIT_LIMIT = 10.1;
13
- /** Incoming contact reaches the <=6 m target threshold without crossing the cell boundary in the highway frame. */
14
- export const TRANSFER_ENTER_LIMIT = 5.9;
11
+ /**
12
+ * Outgoing feet pass the >10 m target threshold and walk on over the cell's own strip (23.75 m wide) while the commit
13
+ * lands: a fixed step or two on the page's own law, a round trip when the server says when (ZONE-ENTRY ZE2; at 10.1 m
14
+ * the feet stood at the line for that round trip). They never pass this solid hold line before a durable commit.
15
+ */
16
+ export const TRANSFER_EXIT_LIMIT = 20;
17
+ /** Incoming feet pass the <=6 m target threshold and walk on to 1 m short of the cell boundary in the highway frame
18
+ * while the commit lands (ZE2: at 5.9 m they stood at the line for the server's round trip). */
19
+ export const TRANSFER_ENTER_LIMIT = 1;
15
20
  /** Cell centres in this physics frame; entry walls enclose highway destinations, exit walls enclose the active region. */
16
21
  export interface TransferWallCell { readonly x: number; readonly z: number }
17
22
 
@@ -100,16 +100,23 @@ export class ResidencyAllocator {
100
100
  private evictableCredit = 0;
101
101
 
102
102
  private readonly playing: number;
103
+ /** GC13: the most two worlds may hold at once while one is built beside another (`canPrepareAlongside`'s caller) */
104
+ private readonly loading: number;
103
105
  private generation = 0;
104
106
  private evicting = false;
105
- constructor(options: { playing?: number; memory?: MemoryAdmission } = {}) {
107
+ constructor(options: { playing?: number; loading?: number; memory?: MemoryAdmission } = {}) {
106
108
  this.memory = options.memory ?? new MemoryAdmission();
107
109
  this.playing = options.playing ?? CONTENT_CAPS.playing;
110
+ this.loading = options.loading ?? Math.max(CONTENT_CAPS.loading, this.playing);
108
111
  if (!Number.isFinite(this.playing) || this.playing <= 0) throw new RangeError('Invalid residency envelope');
112
+ if (!Number.isFinite(this.loading) || this.loading < this.playing) throw new RangeError('Invalid residency loading envelope');
109
113
  }
110
114
 
111
115
  /** The playing envelope this allocator admits against (the tier's, else §3.2's). */
112
116
  envelope(): number { return this.playing; }
117
+ /** GC13: the transient envelope a world built beside the kept one may reach (§3.2's loading cap; a phone's is its playing
118
+ * envelope, so the world left is released before the next is built). */
119
+ loadingEnvelope(): number { return this.loading; }
113
120
 
114
121
  /** Admit a claim, or share one already held under the same id; null when it cannot fit even after eviction. */
115
122
  reserve(claim: ResidencyClaim): ResidencyLease | null { return this.reserveClaim(claim, 0); }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * ZONE-ENTRY ZE8 (J352, Jake 2026-11-15: "it's gonna count down 5, 4, 3, 2, 1. If you back away, if you move away from it, it's
3
+ * gonna disappear. It's gonna reset the counter to 5"): the gate card's count. Feet in a walled cell's buffer start it at 5; it
4
+ * steps once a second; at 0 it fires that cell's zone entry, once. Feet out of the buffer hide it and reset it; back in starts
5
+ * at 5 again. No button: standing there is the yes. Pure, so the page and a test drive it the same way.
6
+ */
7
+ /** The count a buffer starts at, in whole seconds. */
8
+ export const GATE_COUNT = 5;
9
+
10
+ /** What the card shows: the cell counted for and the number on it, or nothing. `fire` is set on the one step the count hits 0. */
11
+ export interface GateCountState { readonly cell: string | null; readonly count: number; readonly fire: string | null }
12
+
13
+ export class GateCount {
14
+ private cell: string | null = null;
15
+ private since = 0;
16
+ private fired = false;
17
+
18
+ /** One step: the buffer the feet stand in (a cell instance, or null) at `now` (ms). */
19
+ step(buffer: string | null, now: number): GateCountState {
20
+ if (buffer !== this.cell) { this.cell = buffer; this.since = now; this.fired = false; }
21
+ if (buffer === null) return { cell: null, count: GATE_COUNT, fire: null };
22
+ const count = Math.max(0, GATE_COUNT - Math.floor((now - this.since) / 1000));
23
+ const fire = count === 0 && !this.fired ? buffer : null;
24
+ if (fire !== null) this.fired = true;
25
+ return { cell: buffer, count, fire };
26
+ }
27
+ }
@@ -0,0 +1,64 @@
1
+ import { CHUNK_HALF, ENTRY_WIDTH } from '@wildshard/engine/core/config';
2
+ import type { ReadinessEdge } from '@wildshard/engine/physics/readinessWalls';
3
+ import type { GridCell } from './assembly';
4
+
5
+ /**
6
+ * ZONE-ENTRY ZE5 (J352, Jake 2026-11-15: "high walls, impermeable walls. The only places you can enter a cell are the four road
7
+ * entrances [...] a 10-meter buffer going into the zone. So the actual physical wall is going to be 10 meters in"): the wall round
8
+ * every cell but the home. It stands on the cell's edge line, open only at its four entryways, where it steps 10 m in: two side
9
+ * walls along the entry asphalt's sides and the gate across its inner end. The pocket between them is the buffer, floored by the
10
+ * entry socket. Each piece is a readiness edge (`ReadinessWalls`), as tall as a cell (`CELL_ABOVE` over `CELL_BELOW`), so no jump,
11
+ * boost or fall clears it. The page and the server's road (ZE6) lay the same lines; the home is never walled.
12
+ */
13
+ /** How far the gate stands inside the cell's edge: the buffer's depth. */
14
+ export const BUFFER_DEPTH = 10;
15
+ /** A wall's half thickness, as `ReadinessWalls` builds it. */
16
+ const HALF_THICK = 0.25;
17
+
18
+ /** Which piece of a cell's wall an edge is. */
19
+ export type ZoneWallPart = 'edge' | 'side' | 'gate';
20
+ /** A wall piece with its part and its side of the cell. */
21
+ export interface ZoneWallEdge extends ReadinessEdge { readonly part: ZoneWallPart; readonly side: 'north' | 'east' | 'south' | 'west' }
22
+
23
+ const SIDES = [{ side: 'north', x: 0, z: 1 }, { side: 'east', x: 1, z: 0 }, { side: 'south', x: 0, z: -1 }, { side: 'west', x: -1, z: 0 }] as const;
24
+
25
+ /** The wall round `cell`, in the frame whose origin is `home.origin`: per side two edge runs either side of the entryway, two
26
+ * buffer sides and the gate. Every piece's inner face is on the cell's line (the edge) or the buffer's (sides, gate). */
27
+ export function zoneWallEdges(cell: GridCell, home: Readonly<{ origin: Readonly<{ x: number; z: number }> }>): ZoneWallEdge[] {
28
+ const cx = cell.origin.x - home.origin.x, cz = cell.origin.z - home.origin.z, open = ENTRY_WIDTH / 2;
29
+ const edges: ZoneWallEdge[] = [];
30
+ for (const { side, x: nx, z: nz } of SIDES) {
31
+ // `across` runs out of the cell through this side, `along` runs along it; a wall facing x (axis 'x') is thin in x
32
+ const facing: 'x' | 'z' = nx !== 0 ? 'x' : 'z', running: 'x' | 'z' = facing === 'x' ? 'z' : 'x';
33
+ const at = (across: number, along: number): { x: number; z: number } => facing === 'x' ? { x: cx + nx * across, z: cz + along } : { x: cx + along, z: cz + nz * across };
34
+ const piece = (part: ZoneWallPart, axis: 'x' | 'z', across: number, along: number, halfLength: number): ZoneWallEdge =>
35
+ ({ instance: cell.instance, ...at(across, along), axis, halfLength, floor: 0, part, side });
36
+ // the edge line either side of the opening, past the corner by a wall's thickness so two sides meet with no gap
37
+ const run = (CHUNK_HALF + 2 * HALF_THICK - open) / 2, mid = open + run;
38
+ edges.push(piece('edge', facing, CHUNK_HALF + HALF_THICK, mid, run), piece('edge', facing, CHUNK_HALF + HALF_THICK, -mid, run));
39
+ // the buffer's two sides, from the gate's back face out to the edge line's outer face, just outside the 8 m asphalt
40
+ const depth = (BUFFER_DEPTH + 4 * HALF_THICK) / 2, centre = CHUNK_HALF + 2 * HALF_THICK - depth;
41
+ edges.push(piece('side', running, centre, open + HALF_THICK, depth), piece('side', running, centre, -(open + HALF_THICK), depth));
42
+ // the gate across the buffer's inner end, its face BUFFER_DEPTH in from the edge
43
+ edges.push(piece('gate', facing, CHUNK_HALF - BUFFER_DEPTH - HALF_THICK, 0, open + 2 * HALF_THICK));
44
+ }
45
+ return edges;
46
+ }
47
+
48
+ /** The cells a page walls: every cell but its home. */
49
+ export function walledCells<Cell extends Readonly<{ instance: string }>>(assembly: Readonly<{ cells: readonly Cell[] }>, home: Readonly<{ instance: string }>): Cell[] {
50
+ return assembly.cells.filter(cell => cell.instance !== home.instance);
51
+ }
52
+
53
+ /** ZE8: the walled cell whose buffer the feet (grid metres) stand in, or null. The buffer is the 8 m wide pocket from an entryway's
54
+ * edge line to its gate, in the cell's own frame; the home has none. */
55
+ export function bufferAt<Cell extends Readonly<{ instance: string; origin: Readonly<{ x: number; z: number }> }>>(cells: readonly Cell[], home: Readonly<{ instance: string }>, feet: Readonly<{ x: number; z: number }>): Cell | null {
56
+ const open = ENTRY_WIDTH / 2;
57
+ for (const cell of cells) {
58
+ if (cell.instance === home.instance) continue;
59
+ const x = feet.x - cell.origin.x, z = feet.z - cell.origin.z;
60
+ const across = Math.max(Math.abs(x), Math.abs(z)), along = Math.abs(x) >= Math.abs(z) ? z : x;
61
+ if (across <= CHUNK_HALF && across >= CHUNK_HALF - BUFFER_DEPTH && Math.abs(along) <= open) return cell;
62
+ }
63
+ return null;
64
+ }
@@ -92,6 +92,8 @@ export const GAME_STRINGS = {
92
92
  /** G119: on the border shimmer while a crossing waits for its durable save, and when that save fails (the crossing retries) */
93
93
  saving: 'SAVING…',
94
94
  saveFailed: 'SAVE FAILED, RETRY',
95
+ /** ZE8: the gate card's line under a walled cell's name, over its count */
96
+ gatePreparing: 'Preparing to enter',
95
97
  off: 'Off',
96
98
  on: 'On',
97
99
  },
@@ -8,6 +8,10 @@ export interface HarnessHits { readonly hits: number }
8
8
  /** A Developer's `?bossGod`: a fight's blows stop reaching a player, as the page's own rule stops them on a page. */
9
9
  export interface HarnessGod { readonly god: true }
10
10
  export const isHarnessGod = (value: unknown): value is HarnessGod => typeof value === 'object' && value !== null && 'god' in value && value.god === true;
11
+ /** A golden camera's spectator: every creature in the world the player stands in holds where it is, from now on, so none
12
+ * wakes, charges or bites the player the camera streams round (Pine's bear den killed it, and the shot streamed round spawn). */
13
+ export interface HarnessStill { readonly still: true }
14
+ export const isHarnessStill = (value: unknown): value is HarnessStill => typeof value === 'object' && value !== null && 'still' in value && value.still === true;
11
15
  /** Raise one of this player's flags, for a door whose quest step a proof can't reach in its minutes (a thrall hunt at night). */
12
16
  export interface HarnessFlag { readonly flag: string }
13
17
  export const isHarnessFlag = (value: unknown): value is HarnessFlag => typeof value === 'object' && value !== null && 'flag' in value && typeof value.flag === 'string';
@@ -0,0 +1,134 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- A witness's continuation hash is a sha256 of the canonical state.
2
+ import { createHash } from 'node:crypto';
3
+ import RAPIER, { RigidBodyType, type Collider, type World } from '@dimforge/rapier3d-simd';
4
+ import { Physics } from '../../shared/engine/physics/Physics';
5
+ import { decodeSimSnapshot, type SimSnapshot, type SimSnapshotBytes } from '../../shared/engine/sim/snapshot';
6
+
7
+ /**
8
+ * A sim snapshot's native physics as restored world state, the one canonical form of "the same world" (SF72, E435).
9
+ *
10
+ * Rapier's snapshot bytes are not canonical: `takeSnapshot(restoreSnapshot(x))` can differ from `x` by a few records
11
+ * (Driftwood's quest checkpoint: two 13-byte records swapped near offset 194 k of 3.3 MB, the broad phase's pair order),
12
+ * and repeated round trips keep permuting them, with no step in between and every body, collider and contact the same.
13
+ * Whether it shows hangs on where a dynamic body rests, so a byte check of a restore flakes about one run in two on the
14
+ * wrong checkpoint. So a restore or a replay is judged on the world the bytes restore to: every rigid body (type,
15
+ * enabled, asleep, pose, velocities, mass, damping, gravity scale, CCD, dominance), every collider (parent, enabled,
16
+ * collision and solver groups, sensor, shape type, pose, friction, restitution, density) in the arenas' own order, and
17
+ * every contact of a dynamic body's collider (partners by handle; per manifold its contacts' distances and impulses, the
18
+ * solver's warm start). Numbers compare exactly: a 1-ULP pose difference still fails. Identical bytes need no restore.
19
+ */
20
+ export interface PhysicsState {
21
+ /** the state, flattened (booleans as 0 / 1, a missing parent as -1) */
22
+ readonly values: number[];
23
+ /** [index of a record's first value, what the record is], ascending: names the first difference */
24
+ readonly marks: [number, string][];
25
+ }
26
+
27
+ const bodyType = (t: RigidBodyType): number => t === RigidBodyType.Dynamic ? 0 : t === RigidBodyType.Fixed ? 1 : t === RigidBodyType.KinematicPositionBased ? 2 : 3;
28
+
29
+ function contacts(world: World, collider: Collider, out: number[]): void {
30
+ const partners: Collider[] = [];
31
+ world.contactPairsWith(collider, other => { partners.push(other); });
32
+ partners.sort((a, b) => a.handle - b.handle);
33
+ out.push(partners.length);
34
+ for (const other of partners) {
35
+ out.push(other.handle);
36
+ world.contactPair(collider, other, (manifold, flipped) => {
37
+ const n = manifold.numContacts();
38
+ out.push(flipped ? 1 : 0, n);
39
+ for (let i = 0; i < n; i++) out.push(manifold.contactDist(i), manifold.contactImpulse(i));
40
+ });
41
+ }
42
+ }
43
+
44
+ /** The world `bytes` restore to, as state. */
45
+ export function physicsState(bytes: ArrayLike<number>): PhysicsState {
46
+ const physics = new Physics(RAPIER, Uint8Array.from(bytes)), world = physics.world, values: number[] = [], marks: [number, string][] = [];
47
+ try {
48
+ world.forEachRigidBody(rb => {
49
+ marks.push([values.length, `rigid body ${String(rb.handle)}`]);
50
+ const t = rb.translation(), r = rb.rotation(), v = rb.linvel(), w = rb.angvel();
51
+ values.push(rb.handle, bodyType(rb.bodyType()), rb.isEnabled() ? 1 : 0, rb.isSleeping() ? 1 : 0, t.x, t.y, t.z, r.x, r.y, r.z, r.w,
52
+ v.x, v.y, v.z, w.x, w.y, w.z, rb.mass(), rb.linearDamping(), rb.angularDamping(), rb.gravityScale(), rb.isCcdEnabled() ? 1 : 0, rb.dominanceGroup());
53
+ });
54
+ world.forEachCollider(c => {
55
+ marks.push([values.length, `collider ${String(c.handle)}`]);
56
+ const t = c.translation(), r = c.rotation(), parent = c.parent();
57
+ values.push(c.handle, parent?.handle ?? -1, c.isEnabled() ? 1 : 0, c.collisionGroups(), c.solverGroups(), c.isSensor() ? 1 : 0, c.shapeType(),
58
+ t.x, t.y, t.z, r.x, r.y, r.z, r.w, c.friction(), c.restitution(), c.density());
59
+ if (parent?.bodyType() === RigidBodyType.Dynamic) { marks.push([values.length, `contacts of collider ${String(c.handle)}`]); contacts(world, c, values); }
60
+ });
61
+ } finally { physics.dispose(); }
62
+ return { values, marks };
63
+ }
64
+
65
+ /** Do two byte arrays hold the same bytes? */
66
+ export function sameBytes(a: ArrayLike<number>, b: ArrayLike<number>): boolean {
67
+ if (a.length !== b.length) return false;
68
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
69
+ return true;
70
+ }
71
+
72
+ /** Where two physics states first differ (`null`: the same world, exactly). */
73
+ export function physicsDifference(a: PhysicsState, b: PhysicsState): string | null {
74
+ const n = Math.max(a.values.length, b.values.length);
75
+ for (let i = 0; i < n; i++) {
76
+ const x = a.values[i], y = b.values[i];
77
+ if (x !== undefined && y !== undefined && Object.is(x, y)) continue;
78
+ let at = '';
79
+ for (const [start, label] of a.marks) { if (start > i) break; at = label; }
80
+ return `${at || 'the world'}: value ${String(i)} is ${String(x)}, expected ${String(y)}`;
81
+ }
82
+ return null;
83
+ }
84
+
85
+ /** Version 1's field order for a player. */
86
+ const V1_PLAYER_FIELDS = ['id', 'position', 'yaw', 'health', 'motor', 'walk', 'moveScale', 'impulse', 'fall', 'shove', 'board', 'swim', 'jump', 'dash', 'dodge', 'traversals'] as const;
87
+ /** A player in the version 1 shape: one velocity back out into each mode's. Footing never was a version 1 field. */
88
+ function versionOnePlayer(player: Readonly<Record<string, unknown>>): Record<string, unknown> {
89
+ const velocity = (player['velocity'] ?? [0, 0, 0]) as readonly [number, number, number], [x, y, z] = velocity;
90
+ const board = player['board'] as Record<string, unknown> | undefined, swim = player['swim'] as ({ on: boolean } & Record<string, unknown>) | undefined;
91
+ const riding = board !== undefined || swim?.on === true, airborne = player['airborne'] === true, vy = riding ? 0 : y;
92
+ const mapped: Record<string, unknown> = { ...player,
93
+ ...(riding || (x === 0 && z === 0) ? {} : { walk: { x, z } }),
94
+ ...(board === undefined && (airborne || vy !== 0) ? { fall: { vy, grounded: !airborne } } : {}),
95
+ ...(board === undefined ? {} : { board: { velocity: [...velocity], ...board, ground: !airborne } }),
96
+ ...(swim === undefined ? {} : { swim: { on: swim.on, velocity: swim.on ? [...velocity] : [0, 0, 0], diving: swim['diving'], climbTo: swim['climbTo'], climbCooldown: swim['climbCooldown'], stroke: swim['stroke'], stood: swim['stood'] } }) };
97
+ const out: Record<string, unknown> = {};
98
+ for (const key of V1_PLAYER_FIELDS) if (mapped[key] !== undefined) out[key] = mapped[key];
99
+ return out;
100
+ }
101
+ /** A one-player snapshot's fields in the version 1 shape, in order: the form every recorded digest and checkpoint hash was
102
+ * taken in. Comparing there is what proves the version 3 engine reaches exactly the state version 1 did. A room keeps
103
+ * its `players`: no version 1 record of one exists. */
104
+ function versionOneFields(fields: Readonly<Record<string, unknown>>): Record<string, unknown> {
105
+ const players = fields['players'], out: Record<string, unknown> = {};
106
+ if (!Array.isArray(players) || players.length !== 1) return { ...fields };
107
+ for (const [key, value] of Object.entries(fields)) {
108
+ if (key === 'version' || key === 'apiVersion') out[key] = 1;
109
+ else if (key === 'players') out['player'] = versionOnePlayer((players as readonly Record<string, unknown>[])[0] ?? {});
110
+ else out[key] = value;
111
+ }
112
+ return out;
113
+ }
114
+ // The wire's number form: JSON.stringify would lose a -0.
115
+ function wireText(value: unknown): string {
116
+ if (typeof value === 'number' && Object.is(value, -0)) return '-0';
117
+ if (Array.isArray(value)) return `[${value.map(wireText).join(',')}]`;
118
+ if (value !== null && typeof value === 'object') return `{${Object.entries(value).map(([key, item]) => `${JSON.stringify(key)}:${wireText(item)}`).join(',')}}`;
119
+ return JSON.stringify(value);
120
+ }
121
+ /** A one-player wire as the version 1 writer left it, byte for byte: what a witness records, so its checkpoints stay real
122
+ * version 1 saves that every continuation proof loads through the migration. */
123
+ export function simWireV1(wire: string): string {
124
+ const { format, snapshot } = JSON.parse(wire) as { format: string; snapshot: Record<string, unknown> };
125
+ return wireText({ format, version: 1, snapshot: versionOneFields(snapshot) });
126
+ }
127
+ /**
128
+ * The sha256 of a snapshot in canonical form, a witness's continuation hash: every field but the physics bytes as JSON,
129
+ * then the physics as restored world state, each value's exact float64 bits (so -0, NaN payloads and 1 ULP all count).
130
+ */
131
+ export function canonicalSimDigest(snapshot: SimSnapshot | SimSnapshotBytes | string): string {
132
+ const { physics, ...rest } = typeof snapshot === 'string' ? decodeSimSnapshot(snapshot) : snapshot;
133
+ return createHash('sha256').update(JSON.stringify(versionOneFields(rest))).update('\0').update(new Uint8Array(Float64Array.from(physicsState(physics).values).buffer)).digest('hex');
134
+ }