@wildshard/engine 0.1.18 → 0.1.19

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 (293) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/budgets/shard-size-baseline.json +10 -4
  3. package/index.html +6 -4
  4. package/lint/engine-sides.json +14 -0
  5. package/lint/ratchet.json +0 -68
  6. package/lint/ratchet.mjs +1 -4
  7. package/package.json +17 -15
  8. package/scripts/agent-sync.mjs +27 -8
  9. package/scripts/app-build/appCook.ts +8 -2
  10. package/scripts/app-build/catalogue.ts +10 -7
  11. package/scripts/app-build/gen.ts +22 -2
  12. package/scripts/app-build/isolation.d.mts +10 -0
  13. package/scripts/app-build/isolation.mjs +47 -0
  14. package/scripts/app-build/outputProducts.mjs +4 -0
  15. package/scripts/app-build/previousDeploy.d.mts +2 -0
  16. package/scripts/app-build/previousDeploy.mjs +10 -1
  17. package/scripts/app-build/serviceWorker.ts +10 -3
  18. package/scripts/app-build/splitOutput.mjs +4 -2
  19. package/scripts/app-build/standaloneOutput.d.mts +1 -1
  20. package/scripts/app-build/standaloneOutput.mjs +5 -3
  21. package/scripts/app-build/titlePreloads.d.mts +8 -0
  22. package/scripts/app-build/titlePreloads.mjs +69 -0
  23. package/scripts/app-build/worldMapAtlas.ts +10 -6
  24. package/scripts/app-build-pipeline.mjs +31 -3
  25. package/scripts/built-product.mjs +1 -1
  26. package/scripts/cell-mem-bench.mjs +81 -23
  27. package/scripts/check-custom-sections-zero.mjs +1 -1
  28. package/scripts/check-devserver.mjs +2 -0
  29. package/scripts/check-models.mjs +2 -0
  30. package/scripts/check-paths.allow.json +0 -115
  31. package/scripts/check-paths.mjs +2 -2
  32. package/scripts/check-platform-ratchets.mjs +2 -3
  33. package/scripts/chromium-keychain.d.mts +1 -1
  34. package/scripts/ci-static.sh +1 -1
  35. package/scripts/committed-fast-checks.mjs +0 -2
  36. package/scripts/content-sw-proof.mjs +2 -1
  37. package/scripts/cook-worker.mjs +9 -3
  38. package/scripts/cook.mjs +18 -5
  39. package/scripts/docs-inputs-proof.mjs +6 -6
  40. package/scripts/e7-voice-staging-proof.mjs +1 -1
  41. package/scripts/gate-related-tests.mjs +1 -1
  42. package/scripts/git-source-view.mjs +1 -1
  43. package/scripts/goldens/capture.mjs +17 -5
  44. package/scripts/grid-crossing-nightly.mjs +59 -0
  45. package/scripts/grid-crossing-qa.mjs +44 -0
  46. package/scripts/grid-crossing-ratchet.d.mts +6 -0
  47. package/scripts/grid-crossing-ratchet.mjs +52 -0
  48. package/scripts/grid-crossing-report.mjs +122 -0
  49. package/scripts/grid-crossing-stages.mjs +47 -0
  50. package/scripts/grid-crossing-tour.mjs +277 -0
  51. package/scripts/grid-crossing-walk-proof.mjs +124 -17
  52. package/scripts/host-ruler/roots.mjs +2 -2
  53. package/scripts/host-ruler.d.mts +91 -0
  54. package/scripts/host-ruler.mjs +565 -0
  55. package/scripts/live-prepush.py +3 -5
  56. package/scripts/loading-flow/benchmax.mjs +3 -1
  57. package/scripts/look-loop/test_look_loop.py +1 -38
  58. package/scripts/memory-proof.mjs +61 -6
  59. package/scripts/mmo-bots.mjs +8 -2
  60. package/scripts/net-lag-proof.mjs +219 -0
  61. package/scripts/night-market-kit-budget.mjs +2 -2
  62. package/scripts/offline-proof-rules.d.mts +2 -2
  63. package/scripts/offline-proof-rules.mjs +15 -4
  64. package/scripts/offline-proof.mjs +74 -13
  65. package/scripts/{shard-platform-output.mjs → output-reader.mjs} +1 -1
  66. package/scripts/page-release/content.d.mts +9 -1
  67. package/scripts/page-release/content.mjs +131 -17
  68. package/scripts/page-release/flow.mjs +36 -10
  69. package/scripts/page-release/stamp-content.mjs +24 -0
  70. package/scripts/page-release.mjs +28 -6
  71. package/scripts/page-size.mjs +2 -1
  72. package/scripts/pin-packs.ts +1 -1
  73. package/scripts/pins.ts +4 -4
  74. package/scripts/precommit-checks.mjs +1 -7
  75. package/scripts/precommit-jobs.mjs +0 -1
  76. package/scripts/precommit-source.py +1 -9
  77. package/scripts/program-discovery.mjs +1 -1
  78. package/scripts/ring-cook.mjs +2 -1
  79. package/scripts/ring-step.ts +1 -1
  80. package/scripts/script-scenario-metrics.mjs +1 -1
  81. package/scripts/shard-output-content.d.mts +1 -1
  82. package/scripts/shard-output-content.mjs +2 -2
  83. package/scripts/shard-outputs.mjs +1 -1
  84. package/scripts/shard-public.mjs +1 -1
  85. package/scripts/shard-wire-meter.mjs +24 -9
  86. package/scripts/side-parity.mjs +4 -2
  87. package/scripts/standalone-smoke.mjs +8 -3
  88. package/scripts/tier-textures.mjs +22 -4
  89. package/scripts/tile-bake-report.mjs +1 -1
  90. package/scripts/tile-bakes.mjs +1 -1
  91. package/scripts/title-assets.generated.json +2 -0
  92. package/scripts/tsconfig.json +0 -2
  93. package/scripts/vendor/basisu/LICENSE +201 -0
  94. package/scripts/vendor/basisu/basis_encoder.cjs +2 -0
  95. package/scripts/vendor/basisu/basis_encoder.wasm +0 -0
  96. package/scripts/vitest-push-guards.config.ts +1 -1
  97. package/scripts/vps/harden-apply.sh +4 -1
  98. package/scripts/vps/harden-prometheus.sh +176 -0
  99. package/scripts/vps/harden.sh +16 -0
  100. package/scripts/vps/rebuild.sh +18 -0
  101. package/scripts/vps/wildshard-config +6 -2
  102. package/scripts/worker-client-play.mjs +6 -2
  103. package/scripts/worktree-reap.mjs +5 -5
  104. package/src/.oxlintrc.json +3 -182
  105. package/src/client/app/entry.ts +10 -2
  106. package/src/client/engine/boot/bootCache.ts +2 -2
  107. package/src/client/engine/boot/bootTrace.ts +12 -4
  108. package/src/client/engine/boot/browserChunkRecovery.ts +4 -0
  109. package/src/client/engine/boot/clearDownloads.ts +5 -2
  110. package/src/client/engine/boot/contentRead.ts +11 -0
  111. package/src/client/engine/boot/gpuFiles.ts +4 -2
  112. package/src/client/engine/boot/lastEnd.ts +99 -12
  113. package/src/client/engine/boot/texturePack.ts +2 -2
  114. package/src/client/engine/net/netPlayer.ts +19 -2
  115. package/src/client/engine/net/otherPlayers.ts +55 -8
  116. package/src/client/engine/net/predictor.ts +33 -9
  117. package/src/client/engine/net/redial.ts +29 -6
  118. package/src/client/engine/pwa/cacheNames.ts +58 -1
  119. package/src/client/engine/pwa/sw.js +41 -11
  120. package/src/client/engine/render/dataLook.ts +152 -40
  121. package/src/client/engine/render/families/detail.ts +89 -0
  122. package/src/client/engine/render/families/pbr.ts +7 -1
  123. package/src/client/engine/render/look.ts +6 -0
  124. package/src/client/engine/render/lookLight.ts +103 -11
  125. package/src/client/engine/render/lookRender.ts +105 -0
  126. package/src/client/engine/saves/indexed.ts +2 -2
  127. package/src/client/engine/telemetry/browserErrors.ts +24 -3
  128. package/src/client/engine/telemetry/staleBuildReport.ts +22 -1
  129. package/src/client/engine/ui/debugOptions.ts +1 -1
  130. package/src/client/engine/ui/lookLightOption.ts +10 -6
  131. package/src/client/engine/ui/namePrompt.ts +7 -0
  132. package/src/client/game/boot/audio.generated.ts +114 -114
  133. package/src/client/game/boot/bytes.generated.ts +118 -220
  134. package/src/client/game/boot/placedSpawn.ts +35 -0
  135. package/src/client/game/boot/spawnDownload.ts +25 -6
  136. package/src/client/game/boot/versions.generated.ts +7 -5
  137. package/src/client/game/devScene/hook.ts +291 -0
  138. package/src/client/game/grid/cellLoading.ts +12 -2
  139. package/src/client/game/grid/live.ts +112 -16
  140. package/src/client/game/grid/liveSession.ts +33 -2
  141. package/src/client/game/grid/mapAtlas.ts +18 -4
  142. package/src/client/game/grid/minimapBlend.ts +15 -5
  143. package/src/client/game/grid/oneWayIn.ts +5 -1
  144. package/src/client/game/grid/placedCells.ts +114 -12
  145. package/src/client/game/grid/placedContent.ts +85 -0
  146. package/src/client/game/grid/prefetch.ts +9 -1
  147. package/src/client/game/grid/productInputs.ts +3 -1
  148. package/src/client/game/grid/productLeases.ts +4 -1
  149. package/src/client/game/grid/products.ts +8 -4
  150. package/src/client/game/grid/roadLook.ts +24 -15
  151. package/src/client/game/grid/roadLookPlatform.ts +4 -2
  152. package/src/client/game/grid/roadResources.ts +24 -0
  153. package/src/client/game/grid/roadSign.worker.ts +4 -3
  154. package/src/client/game/grid/roadSignPaint.ts +16 -5
  155. package/src/client/game/grid/roadSignPreparation.ts +4 -3
  156. package/src/client/game/grid/roadSignScale.ts +8 -0
  157. package/src/client/game/grid/roadTileCapture.worker.ts +3 -1
  158. package/src/client/game/grid/roadTileCaptureWorker.ts +2 -1
  159. package/src/client/game/grid/roadTileWrite.worker.ts +4 -2
  160. package/src/client/game/grid/roadTileWriter.ts +2 -1
  161. package/src/client/game/grid/screenReports.ts +39 -0
  162. package/src/client/game/grid/session.ts +20 -4
  163. package/src/client/game/grid/softWallLook.ts +25 -8
  164. package/src/client/game/mainMenu.ts +6 -2
  165. package/src/client/game/plugin/context.ts +2 -1
  166. package/src/client/game/plugin/followedMovers.ts +7 -1
  167. package/src/client/game/quest/figures.ts +2 -0
  168. package/src/client/game/session/finish.ts +6 -0
  169. package/src/client/game/shardfile/assetCache.ts +4 -4
  170. package/src/client/game/shardfile/client.ts +4 -1
  171. package/src/client/game/shardfile/clientAssets.ts +9 -5
  172. package/src/client/game/shardfile/clientLibrary.ts +1 -1
  173. package/src/client/game/shardfile/clientWater.ts +51 -9
  174. package/src/client/game/shardfile/clientWorker.ts +19 -7
  175. package/src/client/game/shardfile/look.ts +8 -3
  176. package/src/client/game/shardfile/product.ts +34 -7
  177. package/src/client/game/shardfile/productChecks.ts +2 -2
  178. package/src/client/game/shardfile/productCost.ts +2 -2
  179. package/src/client/game/shardfile/readAsset.ts +2 -2
  180. package/src/client/game/shardfile/reflectingWater.ts +73 -0
  181. package/src/client/game/shardfile/seatGrace.ts +9 -0
  182. package/src/client/game/shardfile/skinPlayback.ts +1 -1
  183. package/src/client/game/systems/npc/figureRows.ts +9 -0
  184. package/src/client/host/online/doctor.ts +2 -0
  185. package/src/client/host/online/linkScreens.ts +30 -4
  186. package/src/client/host/standalone/shell.ts +4 -0
  187. package/src/cook/game/astc6Encode.ts +55 -0
  188. package/src/cook/game/astc6Wasm.ts +176 -0
  189. package/src/cook/game/cookJob.ts +30 -6
  190. package/src/cook/game/cookWorker.ts +38 -11
  191. package/src/cook/game/entryTotals.ts +51 -24
  192. package/src/cook/game/shardCook.ts +35 -7
  193. package/src/cook/game/spawnParts.ts +33 -8
  194. package/src/cook/game/tierTextures.ts +87 -14
  195. package/src/server/engine/ai/bossContenders.ts +27 -3
  196. package/src/server/engine/ai/phases.ts +1 -1
  197. package/src/server/engine/entities/creatureRefill.ts +9 -2
  198. package/src/server/engine/net/ledgerBook.ts +2 -0
  199. package/src/server/engine/net/room.ts +15 -0
  200. package/src/server/engine/sim/respawn.ts +8 -0
  201. package/src/server/game/boss/arenaRoomEntry.ts +5 -1
  202. package/src/server/game/boss/arenaRoomNative.ts +2 -0
  203. package/src/server/game/boss/native.ts +2 -1
  204. package/src/server/game/boss/nativeWake.ts +9 -5
  205. package/src/server/game/boss/openArenaNative.ts +2 -2
  206. package/src/server/game/boss/openArenaRoom.ts +3 -1
  207. package/src/server/game/grid/room.ts +44 -3
  208. package/src/server/game/grid/simulation.ts +23 -0
  209. package/src/server/game/population/mixedRoster.ts +11 -3
  210. package/src/server/game/population/nativeBake.ts +8 -3
  211. package/src/server/game/population/nativeReturns.ts +6 -3
  212. package/src/server/game/population/roster.ts +5 -3
  213. package/src/server/game/quest/eliteDrops.ts +15 -4
  214. package/src/server/game/quest/nativeChapter.ts +1 -1
  215. package/src/server/game/quest/nativeComposition.ts +5 -1
  216. package/src/server/game/riding/nativeTaming.ts +10 -6
  217. package/src/server/game/riding/wildRefill.ts +3 -2
  218. package/src/server/game/shardfile/bossRow.ts +4 -2
  219. package/src/server/game/shardfile/homeKeeper.ts +4 -2
  220. package/src/server/host/bake/headlessWorker.ts +1 -1
  221. package/src/server/host/dedicated/cellHost.ts +98 -16
  222. package/src/server/host/dedicated/cellProtocol.ts +16 -1
  223. package/src/server/host/dedicated/cellWorker.ts +8 -5
  224. package/src/server/host/dedicated/dedicatedRoom.ts +16 -6
  225. package/src/server/host/dedicated/gridCells.ts +15 -6
  226. package/src/server/host/dedicated/loopLag.ts +21 -0
  227. package/src/server/host/dedicated/main.ts +13 -5
  228. package/src/server/host/dedicated/packReader.ts +3 -3
  229. package/src/server/host/dedicated/placementFile.ts +3 -2
  230. package/src/server/host/dedicated/roadRoom.ts +34 -4
  231. package/src/server/host/dedicated/serverMetrics.ts +126 -0
  232. package/src/server/host/dedicated/socketPump.ts +21 -4
  233. package/src/server/host/dedicated/workerTable.ts +15 -4
  234. package/src/server/host/dedicated/world.ts +65 -7
  235. package/src/server/host/headless.ts +1 -1
  236. package/src/server/host/headlessRuntime.ts +1 -1
  237. package/src/server/host/standalone/roadWorld.ts +15 -3
  238. package/src/server/host/standalone/serverHost.ts +4 -1
  239. package/src/server/host/standalone/serverProduct.ts +41 -11
  240. package/src/shared/engine/ai/BossBrain.ts +8 -0
  241. package/src/shared/game/boss/wake.ts +6 -0
  242. package/src/shared/game/devColliders.ts +47 -0
  243. package/src/shared/game/eliteSystem.ts +8 -0
  244. package/src/shared/game/grid/allocator.ts +3 -0
  245. package/src/shared/game/grid/placementRows.ts +5 -2
  246. package/src/shared/game/plugin/bossRecord.ts +3 -2
  247. package/src/shared/game/shardfile/ktx2Targets.ts +23 -3
  248. package/src/shared/game/shardfile/outputDescriptor.ts +9 -5
  249. package/src/shared/game/shardfile/packReads.ts +28 -3
  250. package/src/shared/game/shardfile/serverPack.ts +9 -0
  251. package/src/shared/game/systems/looks/trampleField.ts +2 -0
  252. package/src/shared/host/formatJsonSchema.ts +2 -2
  253. package/src/tsconfig.json +1 -27
  254. package/lint/host-reviews.json +0 -14
  255. package/lint/listed-view-code.json +0 -13
  256. package/lint/platform-pending-users.json +0 -2520
  257. package/lint/platform-pending-users.md +0 -18
  258. package/scripts/cell-mem/metrics-preload.mjs +0 -65
  259. package/scripts/check-closed-components.d.mts +0 -7
  260. package/scripts/check-closed-components.mjs +0 -87
  261. package/scripts/g571-hosts.d.mts +0 -3
  262. package/scripts/g571-hosts.mjs +0 -54
  263. package/scripts/host-ruler/register-migrate.mjs +0 -242
  264. package/scripts/listed-view-code.d.mts +0 -7
  265. package/scripts/listed-view-code.mjs +0 -93
  266. package/scripts/look-loop/fit-lut.py +0 -142
  267. package/scripts/look-loop/palette-delta.py +0 -183
  268. package/scripts/look-loop/regions/driftwood-isle.json +0 -25
  269. package/scripts/look-loop/regions/far-reach.json +0 -225
  270. package/scripts/look-loop/regions/open-plot-night-market.json +0 -855
  271. package/scripts/look-loop/regions/pine-hollow.json +0 -22
  272. package/scripts/look-loop/regions/sunscar-dunes.json +0 -281
  273. package/scripts/platform-chargebacks.d.mts +0 -9
  274. package/scripts/platform-chargebacks.mjs +0 -135
  275. package/scripts/shard-component-spans.d.mts +0 -15
  276. package/scripts/shard-component-spans.mjs +0 -18
  277. package/scripts/shard-components.d.mts +0 -16
  278. package/scripts/shard-components.mjs +0 -363
  279. package/scripts/shard-platform-hosts.d.mts +0 -2
  280. package/scripts/shard-platform-hosts.mjs +0 -93
  281. package/scripts/shard-platform-sections.d.mts +0 -2
  282. package/scripts/shard-platform-sections.mjs +0 -9
  283. package/scripts/shard-platform.d.mts +0 -76
  284. package/scripts/shard-platform.mjs +0 -1072
  285. package/src/.oxfmtrc.json +0 -48
  286. package/src/scripts/ask-new.sh +0 -29
  287. package/src/scripts/asks.mjs +0 -142
  288. package/src/scripts/herdr-prompt.sh +0 -34
  289. package/src/scripts/herdr-question-open.sh +0 -67
  290. package/src/scripts/md-wrap.mjs +0 -229
  291. /package/scripts/{shard-platform-format.d.mts → node-format.d.mts} +0 -0
  292. /package/scripts/{shard-platform-format.mjs → node-format.mjs} +0 -0
  293. /package/scripts/{shard-platform-output.d.mts → output-reader.d.mts} +0 -0
@@ -0,0 +1,291 @@
1
+ import * as THREE from 'three';
2
+ import type { Scope } from '@wildshard/engine/app/scope';
3
+ import type { Physics } from '@wildshard/engine/physics/Physics';
4
+ import type { LookKey } from '@wildshard/engine/render/dataLook';
5
+ import type { LookStrategy } from '@wildshard/engine/render/look';
6
+ import { lampLights } from '@wildshard/engine/render/lookLight';
7
+ import type { LookLamp } from '@wildshard/format/look-light';
8
+ import type { ShardWater } from '@wildshard/format/water';
9
+ import { installClientWater } from '../shardfile/clientWater';
10
+ import { isDevColliders, swapDevBoxes, type DevBox } from '@wildshard/engine/game/devColliders';
11
+
12
+ /**
13
+ * SHARD-SOURCE AP5 (J347: engine is the deployed client and server; dev tooling is sharddev's). The dev hook: the one thing
14
+ * a DEVSERVER page carries for `wildshard watch`. sharddev owns the rest, its WebSocket server and protocol, the part diff
15
+ * and a page script `watch` injects into the page it serves; that script owns one scope per part and the swap order, and
16
+ * calls these five functions on `window.__wildshardDevHook`:
17
+ *
18
+ * addPart(name, part) draw a new part: meshes, sprites, lamps (the look's lamp lights) and water (the client's water)
19
+ * replacePart(name, part) build the new part first, then dispose the old part's scope, in one call: no frame shows neither
20
+ * removePart(name) dispose the part's scope (its boxes stay: the page script calls swapColliders(name, []))
21
+ * setLook(look) the data look's day keys (sky, fog, sun, ambient) in place: true, or false when the page's look
22
+ * can't take them live and the page must reload
23
+ * swapColliders(name, boxes) the part's solid boxes, in the page's world and the in-page server's (the worker, by its
24
+ * harness port), new set first, then the old one goes
25
+ *
26
+ * `version` is `DEV_HOOK_VERSION`; sharddev refuses a page with another (its page script) and a client whose build flags
27
+ * say another (`build-flags.json` `devHook`, written by `scripts/app-build-pipeline.mjs`). Bump it on any change to these
28
+ * signatures or to `DevPart`. A production build has none of this: `finish.ts` imports it only behind `__DEVSERVER__`, and
29
+ * `scripts/check-devserver.mjs` refuses a bundle that holds `DEV_HOOK_GLOBAL`.
30
+ */
31
+ export const DEV_HOOK_VERSION = 1;
32
+ export const DEV_HOOK_GLOBAL = '__wildshardDevHook';
33
+
34
+ export type Rgb = readonly [number, number, number];
35
+
36
+ export interface DevMaterial {
37
+ readonly key: string;
38
+ readonly name: string;
39
+ readonly kind: 'standard' | 'basic' | 'sprite';
40
+ readonly colour: Rgb;
41
+ readonly roughness: number;
42
+ readonly metalness: number;
43
+ readonly emissive: Rgb;
44
+ readonly emissiveIntensity: number;
45
+ /** a `DevTexture` key */
46
+ readonly map: string | null;
47
+ readonly repeat: readonly [number, number];
48
+ readonly offset: readonly [number, number];
49
+ readonly alphaTest: number;
50
+ readonly side: 'front' | 'back' | 'double';
51
+ readonly vertexColours: boolean;
52
+ readonly transparent: boolean;
53
+ readonly opacity: number;
54
+ readonly blending: 'normal' | 'additive';
55
+ readonly depthWrite: boolean;
56
+ readonly fog: boolean;
57
+ }
58
+
59
+ /** One RGBA8 raster, row 0 at v = 0. Immutable by key: a key the hook holds is not uploaded again. */
60
+ export interface DevTexture { readonly key: string; readonly width: number; readonly height: number; readonly colourSpace: 'srgb' | 'linear'; readonly rgba: Uint8Array }
61
+
62
+ /** One geometry in its own frame. Immutable by key, like a texture. */
63
+ export interface DevGeometry {
64
+ readonly key: string;
65
+ readonly position: Float32Array;
66
+ readonly normal: Float32Array;
67
+ readonly uv: Float32Array | null;
68
+ readonly colour: Float32Array | null;
69
+ readonly index: Uint32Array | null;
70
+ }
71
+
72
+ export interface DevDraw {
73
+ readonly geometry: string;
74
+ readonly material: string;
75
+ /** column-major world matrix */
76
+ readonly matrix: readonly number[];
77
+ readonly instances: { readonly count: number; readonly matrices: ArrayLike<number>; readonly colours: ArrayLike<number> | null } | null;
78
+ readonly castShadow: boolean;
79
+ readonly receiveShadow: boolean;
80
+ }
81
+
82
+ export interface DevSprite { readonly material: string; readonly position: readonly [number, number, number]; readonly scale: readonly [number, number]; readonly center: readonly [number, number] }
83
+
84
+ /** One part, decoded: every colour linear, every matrix column-major in world metres. Colliders come by `swapColliders`. */
85
+ export interface DevPart {
86
+ readonly materials: readonly DevMaterial[];
87
+ readonly textures: readonly DevTexture[];
88
+ readonly geometries: readonly DevGeometry[];
89
+ readonly draws: readonly DevDraw[];
90
+ readonly sprites: readonly DevSprite[];
91
+ /** the shardfile's lamp rows (`look.light.lamps`), drawn as the look's lamps are */
92
+ readonly lamps: readonly LookLamp[];
93
+ /** the shardfile's water rows, drawn as the client draws a shard's water */
94
+ readonly water: ShardWater;
95
+ }
96
+
97
+ /** The part of a shardfile look a watched page takes live. */
98
+ export interface DevLook { readonly keys: readonly LookKey[] }
99
+
100
+ export interface DevHook {
101
+ readonly version: number;
102
+ addPart: (name: string, part: DevPart) => void;
103
+ replacePart: (name: string, part: DevPart) => void;
104
+ removePart: (name: string) => void;
105
+ setLook: (look: DevLook) => boolean;
106
+ swapColliders: (name: string, boxes: readonly DevBox[]) => void;
107
+ }
108
+
109
+ export interface DevHookPorts {
110
+ readonly scope: Scope;
111
+ readonly scene: THREE.Object3D;
112
+ /** the page's physics world now (the player's prediction): a grid crossing swaps it, so the hook reads it per call;
113
+ * null on a page without one */
114
+ readonly physics: () => Physics | null;
115
+ /** the page's look now */
116
+ readonly look: () => LookStrategy | null;
117
+ /** the in-page server's half of `swapColliders` (the worker page's harness port); null when the page has none */
118
+ readonly server: () => ((name: string, boxes: readonly DevBox[]) => void) | null;
119
+ readonly watchFrames: (fn: (dt: number) => void) => () => void;
120
+ }
121
+
122
+ interface Held<T extends { dispose: () => void }> { readonly value: T; users: number }
123
+ interface LivePart { readonly scope: Scope; readonly geometries: readonly string[]; readonly textures: readonly string[] }
124
+
125
+ /** Build the hook over the page's scene and world; `installDevHook` puts it on the window. */
126
+ export function createDevHook(ports: DevHookPorts): DevHook & { readonly root: THREE.Group; held: () => { geometries: number; textures: number } } {
127
+ const { scope } = ports, root = new THREE.Group(), parts = new Map<string, LivePart>(), colliders = new Map<string, Scope>();
128
+ const boxesOf = new Map<string, readonly DevBox[]>();
129
+ let collidersIn: Physics | null = null;
130
+ const geometries = new Map<string, Held<THREE.BufferGeometry>>(), textures = new Map<string, Held<THREE.DataTexture>>();
131
+ root.name = 'devScene';
132
+ ports.scene.add(root);
133
+ scope.onDispose(() => {
134
+ for (const name of Array.from(parts.keys())) removePart(name);
135
+ root.removeFromParent();
136
+ });
137
+
138
+ const acquire = <T extends { dispose: () => void }>(map: Map<string, Held<T>>, key: string, make: () => T): T => {
139
+ const held = map.get(key);
140
+ if (held !== undefined) { held.users++; return held.value; }
141
+ const value = make();
142
+ map.set(key, { value, users: 1 });
143
+ return value;
144
+ };
145
+ const drop = <T extends { dispose: () => void }>(map: Map<string, Held<T>>, keys: readonly string[]): void => {
146
+ for (const key of keys) {
147
+ const held = map.get(key);
148
+ if (held !== undefined && --held.users === 0) { held.value.dispose(); map.delete(key); }
149
+ }
150
+ };
151
+ const release = (live: LivePart): void => { live.scope.dispose(); drop(geometries, live.geometries); drop(textures, live.textures); };
152
+
153
+ /** One part under its own scope, not yet in the scene; on a throw, everything it took is given back first. */
154
+ const build = (name: string, part: DevPart): { live: LivePart; group: THREE.Group } => {
155
+ const partScope = scope.child(`devScene.${name}`), group = new THREE.Group(), owned: { dispose: () => void }[] = [];
156
+ const geometryKeys: string[] = [], textureKeys: string[] = [], live: LivePart = { scope: partScope, geometries: geometryKeys, textures: textureKeys };
157
+ group.name = `devScene.${name}`;
158
+ partScope.onDispose(() => { group.removeFromParent(); for (const resource of owned) resource.dispose(); });
159
+ try {
160
+ const maps = new Map<string, THREE.DataTexture>(), shapes = new Map<string, THREE.BufferGeometry>();
161
+ for (const row of part.textures) { maps.set(row.key, acquire(textures, row.key, () => makeTexture(row))); textureKeys.push(row.key); }
162
+ for (const row of part.geometries) { shapes.set(row.key, acquire(geometries, row.key, () => makeGeometry(row))); geometryKeys.push(row.key); }
163
+ const need = <T>(map: Map<string, T>, key: string, what: string): T => { const value = map.get(key); if (value === undefined) throw new Error(`dev hook: part ${name} names ${what} ${key} it does not carry`); return value; };
164
+ const materials = new Map<string, THREE.Material>();
165
+ for (const row of part.materials) {
166
+ const material = makeMaterial(row, row.map === null ? null : need(maps, row.map, 'texture'), owned);
167
+ materials.set(row.key, material); owned.push(material);
168
+ }
169
+ for (const draw of part.draws) {
170
+ const material = need(materials, draw.material, 'material'), geometry = need(shapes, draw.geometry, 'geometry');
171
+ let mesh: THREE.Mesh;
172
+ if (draw.instances === null) mesh = new THREE.Mesh(geometry, material);
173
+ else {
174
+ if (draw.instances.matrices.length !== draw.instances.count * 16) throw new Error(`dev hook: part ${name} has ${draw.instances.matrices.length} instance matrix floats for ${draw.instances.count} instances`);
175
+ const instanced = new THREE.InstancedMesh(geometry, material, draw.instances.count);
176
+ owned.push(instanced);
177
+ instanced.instanceMatrix.array.set(draw.instances.matrices);
178
+ if (draw.instances.colours !== null) instanced.instanceColor = new THREE.InstancedBufferAttribute(Float32Array.from(draw.instances.colours), 3);
179
+ instanced.computeBoundingSphere();
180
+ mesh = instanced;
181
+ }
182
+ mesh.matrixAutoUpdate = false;
183
+ mesh.matrix.fromArray(draw.matrix);
184
+ mesh.castShadow = draw.castShadow; mesh.receiveShadow = draw.receiveShadow;
185
+ group.add(mesh);
186
+ }
187
+ for (const sprite of part.sprites) {
188
+ const card = new THREE.Sprite(need(materials, sprite.material, 'material') as THREE.SpriteMaterial);
189
+ card.position.set(...sprite.position); card.scale.set(sprite.scale[0], sprite.scale[1], 1); card.center.set(...sprite.center);
190
+ group.add(card);
191
+ }
192
+ if (part.lamps.length > 0) {
193
+ // the look's own lamp lights (B2, M4.3): what a baked shard's `look.light.lamps` draws
194
+ const lamps = lampLights(part.lamps);
195
+ group.add(lamps);
196
+ owned.push({ dispose: () => { for (const light of lamps.children) if (light instanceof THREE.Light) light.dispose(); } });
197
+ const { update } = lamps;
198
+ if (update !== null) { let time = 0; partScope.onDispose(ports.watchFrames(dt => { time += dt; update(time); })); }
199
+ }
200
+ // the client's own water surfaces, under this part's scope
201
+ installClientWater(part.water, { root: group, scope: partScope, frame: run => { partScope.onDispose(ports.watchFrames(run)); } });
202
+ group.updateMatrixWorld(true);
203
+ } catch (cause) { release(live); throw cause; }
204
+ return { live, group };
205
+ };
206
+
207
+ const replacePart = (name: string, part: DevPart): void => {
208
+ const { live, group } = build(name, part), old = parts.get(name);
209
+ root.add(group);
210
+ parts.set(name, live);
211
+ if (old !== undefined) release(old);
212
+ };
213
+ const addPart = (name: string, part: DevPart): void => {
214
+ if (parts.has(name)) throw new Error(`dev hook: part ${name} is already drawn (replacePart swaps it)`);
215
+ replacePart(name, part);
216
+ };
217
+ function removePart(name: string): void {
218
+ const live = parts.get(name);
219
+ if (live === undefined) return;
220
+ parts.delete(name);
221
+ release(live);
222
+ }
223
+ const setLook = (look: DevLook): boolean => {
224
+ const current = ports.look();
225
+ return current !== null && 'liveKeys' in current && current.liveKeys !== undefined && current.liveKeys(look.keys);
226
+ };
227
+ // The boxes go into the page's world as it is now. After a grid crossing that is a new world: every held part's boxes
228
+ // are made again in it, and the old world's sets are disposed (Physics skips removal from a freed world).
229
+ const swapColliders = (name: string, boxes: readonly DevBox[]): void => {
230
+ const message = { wildshardDevColliders: name, boxes };
231
+ if (!isDevColliders(message)) throw new Error(`dev hook: part ${name} has a malformed collider box`);
232
+ if (boxes.length === 0) boxesOf.delete(name); else boxesOf.set(name, boxes);
233
+ const physics = ports.physics();
234
+ if (physics !== collidersIn) {
235
+ for (const held of colliders.values()) held.dispose();
236
+ colliders.clear();
237
+ collidersIn = physics;
238
+ if (physics !== null) for (const [part, held] of boxesOf) if (part !== name) swapDevBoxes(physics, scope, colliders, part, held);
239
+ }
240
+ if (physics !== null) swapDevBoxes(physics, scope, colliders, name, boxes);
241
+ ports.server()?.(name, boxes);
242
+ };
243
+ scope.onDispose(() => { for (const held of colliders.values()) held.dispose(); colliders.clear(); });
244
+ return { version: DEV_HOOK_VERSION, root, addPart, replacePart, removePart, setLook, swapColliders,
245
+ held: () => ({ geometries: geometries.size, textures: textures.size }) };
246
+ }
247
+
248
+ /** Put the hook on the window for sharddev's page script, for the page's level. */
249
+ export function installDevHook(ports: DevHookPorts): DevHook {
250
+ const hook = createDevHook(ports), { version, addPart, replacePart, removePart, setLook, swapColliders } = hook;
251
+ ports.scope.expose(window, DEV_HOOK_GLOBAL, Object.freeze({ version, addPart, replacePart, removePart, setLook, swapColliders } satisfies DevHook));
252
+ return hook;
253
+ }
254
+
255
+ function makeMaterial(row: DevMaterial, shared: THREE.DataTexture | null, owned: { dispose: () => void }[]): THREE.Material {
256
+ let map: THREE.Texture | null = null;
257
+ if (shared !== null) {
258
+ // a clone shares the raster (one upload) and keeps its own repeat and offset, as an author's `clone()` does
259
+ map = shared.clone(); owned.push(map); map.repeat.set(...row.repeat); map.offset.set(...row.offset); map.version++;
260
+ }
261
+ const colour = new THREE.Color().setRGB(...row.colour);
262
+ const common = { name: row.name, color: colour, map, alphaTest: row.alphaTest, transparent: row.transparent, opacity: row.opacity, depthWrite: row.depthWrite, fog: row.fog,
263
+ blending: row.blending === 'additive' ? THREE.AdditiveBlending : THREE.NormalBlending };
264
+ if (row.kind === 'sprite') return new THREE.SpriteMaterial(common);
265
+ const side = row.side === 'double' ? THREE.DoubleSide : row.side === 'back' ? THREE.BackSide : THREE.FrontSide;
266
+ if (row.kind === 'basic') return new THREE.MeshBasicMaterial({ ...common, side, vertexColors: row.vertexColours });
267
+ return new THREE.MeshStandardMaterial({ ...common, side, vertexColors: row.vertexColours, roughness: row.roughness, metalness: row.metalness,
268
+ emissive: new THREE.Color().setRGB(...row.emissive), emissiveIntensity: row.emissiveIntensity });
269
+ }
270
+
271
+ function makeGeometry(source: DevGeometry): THREE.BufferGeometry {
272
+ const geometry = new THREE.BufferGeometry();
273
+ geometry.setAttribute('position', new THREE.BufferAttribute(source.position, 3));
274
+ geometry.setAttribute('normal', new THREE.BufferAttribute(source.normal, 3));
275
+ if (source.uv !== null) geometry.setAttribute('uv', new THREE.BufferAttribute(source.uv, 2));
276
+ if (source.colour !== null) geometry.setAttribute('color', new THREE.BufferAttribute(source.colour, 3));
277
+ if (source.index !== null) geometry.setIndex(new THREE.BufferAttribute(source.index, 1));
278
+ geometry.computeBoundingSphere();
279
+ return geometry;
280
+ }
281
+
282
+ function makeTexture(row: DevTexture): THREE.DataTexture {
283
+ if (row.rgba.byteLength !== row.width * row.height * 4) throw new Error(`dev hook: texture ${row.key} is ${row.rgba.byteLength} bytes, not ${row.width}x${row.height} RGBA8`);
284
+ const texture = new THREE.DataTexture(row.rgba, row.width, row.height);
285
+ texture.colorSpace = row.colourSpace === 'linear' ? THREE.LinearSRGBColorSpace : THREE.SRGBColorSpace;
286
+ texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
287
+ texture.magFilter = THREE.LinearFilter; texture.minFilter = THREE.LinearMipmapLinearFilter; texture.generateMipmaps = true;
288
+ texture.anisotropy = 4;
289
+ texture.needsUpdate = true;
290
+ return texture;
291
+ }
@@ -49,6 +49,9 @@ export function cellLoadingStep(input: CellLoadingInput): CellLoadingStep {
49
49
  }
50
50
  const hooksDone = (last: string): boolean => !input.hybrid || input.hooks.has(last);
51
51
  if (!input.product) return { kind: 'step', key: 'world', detail: input.requested ? 'reading its region files' : 'requested as you approach' };
52
+ // QA 11-13 row 43: a resident product but no readiness request is a world nobody is building yet; its hooks are a past
53
+ // visit's, not progress (a return visit read "saved state and its systems" for 11 s while nothing built it)
54
+ if (!input.requested) return { kind: 'step', key: 'world', detail: 'waiting for its world to start' };
52
55
  const running = input.hook === null ? '' : ` · ${input.hook}`;
53
56
  if (!hooksDone('afterWorld')) return { kind: 'step', key: 'world', detail: `${input.claimedMB.toFixed(0)} MB admitted${running}` };
54
57
  if (!hooksDone('afterKit')) return { kind: 'step', key: 'loadout', detail: `weapons, held items and HUD${running}` };
@@ -71,6 +74,8 @@ export class CellLoading {
71
74
  /** the step shown: a running hook's own step, else the furthest reached (a region learns it has hooks only when they
72
75
  * start, so between hooks a row never goes back) */
73
76
  private reached = -1;
77
+ /** GC8: the step the screen shows now and its detail, for a harness to time each step (null while closed). */
78
+ private shown: { readonly step: string; readonly detail: string } | null = null;
74
79
  /** `known`: whether the waiting cell is one of this session's neighbours (no screen for one that is not) */
75
80
  constructor(private readonly screen: CellLoadingScreen, private readonly known: (instance: string) => boolean) {}
76
81
  /** Show, step or hide the screen from this cell's live state (null: no cell is waiting). */
@@ -87,14 +92,19 @@ export class CellLoading {
87
92
  }
88
93
  const rows = path.map((row, i): CellLoadingRow => ({ label: row.label, state: i < this.reached ? 'done' : i === this.reached ? 'now' : 'next' }));
89
94
  const detail = step.kind === 'step' ? step.detail : '';
90
- this.screen.show({ instance: input.instance, name: input.name, step: path[Math.max(0, this.reached)]?.key ?? '', rows, detail,
95
+ this.shown = { step: path[Math.max(0, this.reached)]?.key ?? '', detail };
96
+ this.screen.show({ instance: input.instance, name: input.name, step: this.shown.step, rows, detail,
91
97
  failed: step.kind === 'failed' ? step.reason : null });
92
98
  }
93
99
  /** The screen's cell (null: none shown). */
94
100
  get open(): string | null { return this.instance; }
101
+ /** NET-LAG NL7: the row the screen shows running now (its label), null when none is shown: a proof times each stage. */
102
+ get stage(): string | null { return this.instance === null || this.reached < 0 ? null : loadingPath('cell').steps[this.reached]?.label ?? null; }
103
+ /** GC8: the step shown now and its detail, or null. */
104
+ get now(): { readonly step: string; readonly detail: string } | null { return this.instance === null ? null : this.shown; }
95
105
  /** Hide the screen: `entered`, the cell is ready (the card completes and fades); else it was left or cancelled. */
96
106
  close(entered = false): void {
97
- const was = this.instance; this.instance = null; this.reached = -1;
107
+ const was = this.instance; this.instance = null; this.reached = -1; this.shown = null;
98
108
  if (was !== null) this.screen.hide(entered);
99
109
  }
100
110
  }
@@ -13,6 +13,7 @@ import type { ResidencyAllocator, ResidencyLease, ResidencyEviction } from '../.
13
13
  import type { PreparedGridCrossing } from '../../../shared/game/grid/crossing';
14
14
  import type { HomeResidencyClaim } from './pageResidency';
15
15
  import { ApproachInputsDeferredError } from './productInputs';
16
+ import { PRODUCT_DEFERRED } from './productLeases';
16
17
  import { clientPreparationBatch } from '../shardfile/preparationTiming';
17
18
  import { tileOf, type CellTile } from '../../../shared/game/shardfile/tileOrder';
18
19
  import type { RegionShell } from './regionShell';
@@ -88,6 +89,8 @@ export interface LiveGridPorts {
88
89
  /** Crossing telemetry is a production port: the harness verifies real fixed-boundary commits, never a page/debug probe. */
89
90
  export interface LiveGridState {
90
91
  current: string | null; worldFeet: GridPoint; crossings: number;
92
+ /** GC5: the world built ahead of the traveller (on the road or pre-warmed inside the source), and how many pre-warms began */
93
+ ahead?: { readonly instance: string | null; readonly warms: number; readonly refused?: string | null };
91
94
  /** Last complete world remains fully charged and pressure-evictable on the road. */
92
95
  retainedCell?: { readonly instance: string; readonly remainingMs: number; readonly playingBytes: number; readonly capBytes: number } | null;
93
96
  transitions: readonly { from: string | null; to: string | null }[];
@@ -115,6 +118,10 @@ interface Resident { region: LiveGridRegion; lease: ResidencyLease; reservations
115
118
  // Contact corrections at a closed readiness wall are not a U-turn. Accumulate real horizontal travel
116
119
  // before selecting another approach, so sub-centimetre capsule recoil cannot evict the world just prepared.
117
120
  const APPROACH_TRAVEL_METRES = 0.1;
121
+ // GC5: the page pre-warms a neighbour's world from inside the source, at the distance the traveller covers at its speed in that
122
+ // world's last measured build time (2 s at least; before it is measured, the slowest build so far or 14 s, capped at 16 s), times a margin. Kept while the traveller stays within
123
+ // WARM_KEEP_METRES of it; the lead is capped below that, so a pre-warm never starts where it would be dropped.
124
+ const DEMAND_METRES = 80, HELD_RETRY_MS = 5000, HEADING_HOLD_MS = 600, FIXED_HZ = 60, WARM_DEFAULT_SECONDS = 14, WARM_MIN_SECONDS = 2, WARM_MAX_SECONDS = 16, WARM_MARGIN = 1.25, WARM_LEAD_METRES = 8, WARM_LEAD_CAP_METRES = 200, WARM_KEEP_METRES = 240;
118
125
  const entryAxes = [['x', 'z'], ['z', 'x']] as const;
119
126
  // Distance can decrease while passing parallel to a cell. Only a ray into its first boundary's midpoint mouth
120
127
  // predicts entry; product downloads remain radial, but an unrelated native world must not block the real turn-in.
@@ -177,7 +184,18 @@ export class LiveGridHost {
177
184
  private frameGeneration = 0;
178
185
  private readonly transitions: { from: string | null; to: string | null }[] = [];
179
186
  private crossings = 0;
187
+ private warms = 0;
188
+ /** QA row 43: when a traveller held at a cell's wall may next retry its failed build */
189
+ private readonly heldRetryAt = new Map<string, number>();
190
+ /** the other mouth the traveller inside the source turned to, and since when (HEADING_HOLD_MS) */
191
+ private turnedSince: { instance: string; at: number } | null = null;
192
+ /** GC5: why the last pre-warm the heading asked for did not start (its product still reading, an exclusive runtime, or the budget) */
193
+ private warmRefusal: string | null = null;
180
194
  private previousFeet: GridPoint | undefined;
195
+ /** fixed steps since `previousFeet` moved, for the traveller's speed (GC5) */
196
+ private stepsSincePrevious = 0;
197
+ /** GC5: each cell's last measured world build, in seconds (product to colliders and sim ready) */
198
+ private readonly builtSeconds = new Map<string, number>();
181
199
  private readonly candidateDistances = new Map<GridCell,number>();
182
200
  private readonly approachWork:{candidates:GridCell[];boulevard:GridCell[]}[]=[];
183
201
  /** This host already owns the assembly and its frozen cells for its whole lifetime. */
@@ -243,18 +261,21 @@ export class LiveGridHost {
243
261
  }
244
262
  /** Submit whole-shard requests in stable order. Failed attempts remain closed until an explicit retry. */
245
263
  prefetch(instances: readonly string[], trigger: 'explicit' | 'radial' | 'boulevard' = 'explicit'): Promise<void> { return Promise.all([...new Set(instances)].sort().map((id) => this.residents.has(id) || (!this.disposed && this.constructing.has(id)) || this.deferredProducts.get(id) === this.ports.allocator.revision ? Promise.resolve() : this.prefetchProduct(id, false, trigger))).then(() => undefined); }
246
- private async requireProduct(instance: string, pending: Promise<LiveGridAdmission>): Promise<LiveGridAdmission> {
264
+ private async requireProduct(instance: string, pending: Promise<LiveGridAdmission>, trigger: 'entry' | 'explicit' | 'radial' | 'boulevard' = 'entry', speculative = false): Promise<LiveGridAdmission> {
247
265
  try { return await pending; }
248
266
  catch (error) {
249
- if (!(error instanceof ApproachInputsDeferredError)) throw error;
250
- return this.prefetchProduct(instance, true);
267
+ // the optional read's budget deferral says nothing of a required one: read it again as required
268
+ if (!(error instanceof ApproachInputsDeferredError) && !(error instanceof Error && error.message.includes(PRODUCT_DEFERRED))) throw error;
269
+ return this.prefetchProduct(instance, true, trigger, speculative);
251
270
  }
252
271
  }
253
- private prefetchProduct(instance: string, required = false, trigger: 'entry' | 'explicit' | 'radial' | 'boulevard' = 'entry'): Promise<LiveGridAdmission> {
272
+ /** `speculative`: a demand read nobody waits on yet (GC5's near neighbour and pre-warm). Its budget refusal is deferred
273
+ * until the budget changes, as a radial read's is, not a failed cell that closes the radial read, the pre-warm and the road. */
274
+ private prefetchProduct(instance: string, required = false, trigger: 'entry' | 'explicit' | 'radial' | 'boulevard' = 'entry', speculative = false): Promise<LiveGridAdmission> {
254
275
  this.assertAlive(); const cell = this.assembly.cell(instance);
255
276
  const product = this.products.get(instance); if (product !== undefined) return Promise.resolve(product);
256
277
  const pending = this.productRequests.get(instance);
257
- if (pending !== undefined) return !required || pending.required ? pending.work : this.requireProduct(instance, pending.work);
278
+ if (pending !== undefined) return !required || pending.required ? pending.work : this.requireProduct(instance, pending.work, trigger, speculative);
258
279
  const issue = this.issues.get(instance); if (issue !== undefined) return Promise.reject(new Error(issue));
259
280
  const timing = clientPreparationBatch(cell.slug, `grid.product:${instance}`, ['admission', 'runtime']);
260
281
  const request = (async (): Promise<LiveGridAdmission> => {
@@ -272,7 +293,8 @@ export class LiveGridHost {
272
293
  } catch (error) {
273
294
  this.tileMetadata.delete(instance);
274
295
  if (this.tileApproach?.instance === instance) { this.tileApproach.controller.abort(); this.tileApproach = null; }
275
- if (!required && error instanceof ApproachInputsDeferredError) this.deferredProducts.set(instance, this.ports.allocator.revision);
296
+ const refused = error instanceof ApproachInputsDeferredError || (error instanceof Error && error.message.includes(PRODUCT_DEFERRED));
297
+ if ((!required || speculative) && refused) this.deferredProducts.set(instance, this.ports.allocator.revision);
276
298
  else { this.issues.set(instance, error instanceof Error ? error.message : String(error)); this.refusals.set(instance, error); }
277
299
  try { admission?.cancel?.(); }
278
300
  catch (cleanup) { throw new AggregateError([error, cleanup], 'Live product admission and cancellation failed', { cause: cleanup }); }
@@ -284,6 +306,8 @@ export class LiveGridHost {
284
306
  /** GC5 / GC36: the cell whose world the road is building or built ahead of its line (`buildAhead`), kept until the
285
307
  * traveller enters a cell or heads into another's mouth. */
286
308
  private ahead: string | null = null;
309
+ /** GC9: the optional read last raised to demand, so a pending radial read is raised once, not every tick */
310
+ private raised: Promise<LiveGridAdmission> | null = null;
287
311
  private tileApproach: { instance: string; tile: CellTile; controller: AbortController } | null = null;
288
312
  private transportApproach: { instance: string; controller: AbortController; work: Promise<void> } | null = null;
289
313
  private retiredTransport: Promise<void> = Promise.resolve();
@@ -352,6 +376,7 @@ export class LiveGridHost {
352
376
  await (timing === undefined ? previous : timing.run('queue', () => previous));
353
377
  await this.retiredTransport;
354
378
  this.assertAlive();
379
+ const buildStart = diagnosticNow();
355
380
  const admitted = timing === undefined ? await this.prefetchProduct(instance, true) : await timing.run('metadata', () => this.prefetchProduct(instance, true));
356
381
  admission = admitted;
357
382
  this.assertAlive();
@@ -386,6 +411,7 @@ export class LiveGridHost {
386
411
  this.assertAlive();
387
412
  this.residents.set(instance, { region, lease, reservations: 0, evicting: false, retainable: admitted.isolatedPreparation === true });
388
413
  this.readiness.complete(ticket, 'colliders'); this.readiness.complete(ticket, 'sim');
414
+ this.builtSeconds.set(instance, (diagnosticNow() - buildStart) / 1000);
389
415
  lease.update({ needed: false, distance: this.distance(cell) });
390
416
  } catch (error) {
391
417
  try { region?.dispose(); }
@@ -457,6 +483,13 @@ export class LiveGridHost {
457
483
  resident.lease.update({ needed: false, distance: this.distance(this.assembly.cell(instance)) });
458
484
  return this.lastCell === last;
459
485
  }
486
+ /** GC5: how far from a neighbour's square its world starts building at `speed` (m/s): its measured build time, or the
487
+ * slowest measured so far or the default, at least WARM_MIN_SECONDS, with a margin; capped below the keep distance. */
488
+ private warmLead(instance: string, speed: number): number {
489
+ const measured = this.builtSeconds.get(instance) ?? Math.max(WARM_DEFAULT_SECONDS, ...this.builtSeconds.values());
490
+ const seconds = Math.min(WARM_MAX_SECONDS, Math.max(WARM_MIN_SECONDS, measured));
491
+ return Math.min(WARM_LEAD_CAP_METRES, WARM_LEAD_METRES + speed * seconds * WARM_MARGIN);
492
+ }
460
493
  private distance(cell: GridCell, p = this.worldFeet()): number { return Math.hypot(Math.max(0, Math.abs(p.x - cell.origin.x) - CHUNK_HALF), Math.max(0, Math.abs(p.z - cell.origin.z) - CHUNK_HALF)); }
461
494
  /** Only the active/reserved world and one bounded departed world can remain.
462
495
  * A different actual entry retires the departure before any new allocation. */
@@ -500,7 +533,8 @@ export class LiveGridHost {
500
533
  // More than a second of modeled travel between fixed samples is a pose/portal jump.
501
534
  // Establish a new origin instead of spending a constructor on its accidental direction.
502
535
  const travelled = previous !== undefined && travelledDistance >= APPROACH_TRAVEL_METRES && travelledDistance <= this.ports.readiness.link.speed;
503
- if (previous === undefined || travelledDistance >= APPROACH_TRAVEL_METRES) this.previousFeet = feet;
536
+ const steps = ++this.stepsSincePrevious, speed = travelled ? travelledDistance * FIXED_HZ / steps : 0;
537
+ if (previous === undefined || travelledDistance >= APPROACH_TRAVEL_METRES) { this.previousFeet = feet; this.stepsSincePrevious = 0; }
504
538
  // Prefetch the closest cells' products (never their worlds: G663). Unsupported far proxies do not consume the count
505
539
  // before enterable cells inside the cold readiness bound.
506
540
  const candidates=work.candidates,cells=this.assembly.cells;
@@ -513,13 +547,30 @@ export class LiveGridHost {
513
547
  // Immutable products are selected by distance, without a whole-world count cap.
514
548
  const nearby = candidates;
515
549
  // The frame-transfer reservation protects an actual entry; inactive whole worlds retire in steps. A world built ahead
516
- // (`buildAhead`) stays while the traveller is on the road and has not turned into another mouth (below).
517
- if (this.active !== null) this.ahead = null;
550
+ // (`buildAhead`) stays while the traveller is on the road and has not turned into another mouth (below); one pre-warmed
551
+ // from inside the source (GC5) stays while the traveller is within WARM_KEEP_METRES of it.
552
+ if (this.active !== null && this.ahead !== null && (this.ahead === this.active
553
+ || this.distance(this.assembly.cell(this.ahead), feet) > WARM_KEEP_METRES)) this.ahead = null;
518
554
  this.retireInactiveRegions();
519
555
  for (const cell of nearby) {
520
556
  const estimate = readinessModel(this.ports.readiness.bundle(cell), this.ports.readiness.link), distance = this.distance(cell, feet);
521
557
  if (this.assembly.approaching(distance, estimate.distance) && !this.issues.has(cell.instance) && this.ports.backgroundReady?.() !== false) void background(cell.instance, this.prefetch([cell.instance], 'radial'), () => !this.disposed);
522
558
  }
559
+ // GC5: the neighbour across the source's nearest edge, within DEMAND_METRES, has its product read as demand, standing or
560
+ // moving: a player at a cell's edge reaches it in seconds at a boost, and the radial read above is only a guess the shared
561
+ // budget declines while every neighbour competes for it (Pine's read alone is 6 to 8 s). One at a time, the nearest.
562
+ if (this.active !== null && this.ports.buildAhead === true) {
563
+ const near = candidates[0];
564
+ // GC9: a radial read already pending for it is raised to demand once (the budget declined Pine's radial read again and
565
+ // again while it stood pending, so the demand read never started inside Driftwood and Pine's world was built on the road)
566
+ const pending = near === undefined ? undefined : this.productRequests.get(near.instance);
567
+ if (near !== undefined && this.distance(near, feet) <= DEMAND_METRES && !this.products.has(near.instance) && !this.residents.has(near.instance)
568
+ && (pending === undefined || !pending.required && this.raised !== pending.work) && !this.issues.has(near.instance) && !this.constructing.has(near.instance)
569
+ && this.deferredProducts.get(near.instance) !== this.ports.allocator.revision && this.ports.backgroundReady?.() !== false) {
570
+ if (pending !== undefined) this.raised = pending.work;
571
+ void background(near.instance, this.prefetchProduct(near.instance, true, 'explicit', true), () => !this.disposed);
572
+ }
573
+ }
523
574
  // Approach preparation owns render tiles only, never a regional world or gameplay hooks.
524
575
  const moving = !travelled ? undefined : candidates.find(cell => headsToEntry(cell, feet, previous)
525
576
  && this.distance(cell, feet) < this.distance(cell, previous) - 0.000001);
@@ -542,11 +593,21 @@ export class LiveGridHost {
542
593
  }
543
594
  // The world built ahead goes once the traveller is a pitch from it, or heads from the road into another mouth (a stop
544
595
  // keeps it). Checked while a build runs too, which the gate below skips.
596
+ const wallReach = 6 + this.ports.player.motor.opts.radius + 0.5 + this.ports.readiness.link.speed / 60;
597
+ const departed = this.transitions.at(-1)?.from;
598
+ // QA 11-13 row 43: on the road within a cell's wall reach the traveller is at that cell's wall, whatever the heading: a
599
+ // jump or a recoil off the wall reads as a heading back into the cell just left, which let the world built ahead go.
600
+ const held = this.ports.buildAhead === true && this.active === null && this.assembly.at(feet.x, feet.z) === undefined
601
+ ? nearby.find(cell => cell.instance !== departed && this.distance(cell, feet) <= wallReach) : undefined;
602
+ // Inside the source a new heading must hold HEADING_HOLD_MS before it retires the world built ahead: steering that
603
+ // wobbles near a corner would otherwise build and dispose a whole world per flip.
604
+ const turned = moving !== undefined && moving.instance !== this.ahead;
605
+ if (!turned || this.active === null) this.turnedSince = null;
606
+ else if (this.turnedSince?.instance !== moving.instance) this.turnedSince = { instance: moving.instance, at: diagnosticNow() };
607
+ const settledTurn = turned && (this.active === null || diagnosticNow() - (this.turnedSince?.at ?? 0) >= HEADING_HOLD_MS);
545
608
  if (this.ahead !== null && (this.distance(this.assembly.cell(this.ahead), feet) >= this.assembly.pitch
546
- || moving !== undefined && moving.instance !== this.ahead && this.assembly.at(feet.x, feet.z) === undefined)) this.ahead = null;
609
+ || held === undefined && settledTurn && (this.assembly.at(feet.x, feet.z) === undefined || this.active !== null))) this.ahead = null;
547
610
  if (this.requests.size === 0) {
548
- const wallReach = 6 + this.ports.player.motor.opts.radius + 0.5 + this.ports.readiness.link.speed / 60;
549
- const departed = this.transitions.at(-1)?.from;
550
611
  const boulevard=work.boulevard;
551
612
  if(travelled&&moving===undefined)for(let i=0,length=candidates.length;i<length;i++){
552
613
  const cell=candidates[i];if(cell!==undefined&&cell.instance!==departed
@@ -579,12 +640,46 @@ export class LiveGridHost {
579
640
  // cell retires first, as the entry would retire it; a U-turn builds it again, as any entry does.
580
641
  // Only from the road itself: past a cell's line (inside its square, before the 6 m entry) the heading names the cell
581
642
  // beyond it, which would retire the world just built for the one underfoot.
582
- if (this.ports.buildAhead === true && moving !== undefined && this.active === null && this.assembly.at(feet.x, feet.z) === undefined
643
+ // QA 11-13 row 43 (Jake on staging: 11 s at Template's wall, "saved state and its systems", no progress): a traveller
644
+ // standing at a neighbour's closed wall makes no heading (under 0.1 m a sample), so a world built ahead and then let go
645
+ // was never asked for again, and online the server crosses only past the line the wall holds them short of. Held at
646
+ // a closed wall on the road, that cell's world is always building.
647
+ // A failed build is tried again while they stand there, at most every HELD_RETRY_MS (never on a cleanup failure).
648
+ if (held !== undefined && this.issues.has(held.instance) && !this.residents.has(held.instance) && !this.requests.has(held.instance) && !this.productRequests.has(held.instance)
649
+ && diagnosticNow() >= (this.heldRetryAt.get(held.instance) ?? 0)) { this.heldRetryAt.set(held.instance, diagnosticNow() + HELD_RETRY_MS); this.retry(held.instance); }
650
+ if (held !== undefined && !this.residents.has(held.instance) && !this.issues.has(held.instance)) {
651
+ this.ahead = held.instance;
652
+ if (this.retireInactiveRegions(held.instance)) void background(held.instance, this.ensure(held.instance), () => !this.disposed);
653
+ }
654
+ else if (held === undefined && this.ports.buildAhead === true && moving !== undefined && this.active === null && this.assembly.at(feet.x, feet.z) === undefined
583
655
  && !this.residents.has(moving.instance) && !this.issues.has(moving.instance)
584
656
  && this.distance(moving, feet) < this.assembly.pitch && this.retireInactiveRegions(moving.instance)) {
585
657
  this.ahead = moving.instance;
586
658
  void background(moving.instance, this.ensure(moving.instance), () => !this.disposed);
587
659
  }
660
+ // GC5 (QA 11-13 row 39: boosts held 4 to 7.6 s at the neighbour's loading wall, the road being under 3 s at 18 m/s):
661
+ // inside the source, heading into a neighbour's mouth, its world is built once the traveller is its measured build
662
+ // time away at this speed. Only beside an isolated source and for an isolated product (opaque runtimes stay exclusive,
663
+ // built only on the road), and only when both fit beside each other (G723); else the road builds it as before.
664
+ if (this.ports.buildAhead === true && moving !== undefined && this.active !== null && this.ahead === null
665
+ && this.residents.get(this.active)?.retainable === true && !this.residents.has(moving.instance) && !this.issues.has(moving.instance)
666
+ && this.distance(moving, feet) <= this.warmLead(moving.instance, speed)) {
667
+ const product = this.products.get(moving.instance);
668
+ // The heading names it: its product is read as demand (it may evict speculative neighbours' products), not as a radial
669
+ // guess, which the shared budget declines while the page's other neighbours compete for the same headroom.
670
+ if (product === undefined) {
671
+ this.warmRefusal = 'product';
672
+ if (!this.productRequests.has(moving.instance) && this.deferredProducts.get(moving.instance) !== this.ports.allocator.revision)
673
+ void background(moving.instance, this.prefetchProduct(moving.instance, true, 'explicit', true), () => !this.disposed);
674
+ }
675
+ else if (product.isolatedPreparation !== true) this.warmRefusal = 'exclusive';
676
+ else if (!this.ports.allocator.canPrepareAlongside(this.active, moving.instance, product.bytes,
677
+ { playing: this.ports.allocator.envelope(), loading: CONTENT_CAPS.loading })) this.warmRefusal = 'budget';
678
+ else {
679
+ this.ahead = moving.instance; this.warms++; this.warmRefusal = null;
680
+ void background(moving.instance, this.ensure(moving.instance), () => !this.disposed);
681
+ }
682
+ }
588
683
  if (approach !== undefined && this.ports.prepareNeighbour !== undefined && this.tileMetadata.has(approach.instance)
589
684
  && !this.residents.has(approach.instance) && !this.issues.has(approach.instance)
590
685
  && (this.active === null || moving === approach)
@@ -710,8 +805,9 @@ export class LiveGridHost {
710
805
  /** Prepare disabled replacement controllers while the existing page stays authoritative; no entered runtime hooks run here. */
711
806
  async prepare(from: string | null, to: string | null): Promise<PreparedGridCrossing> {
712
807
  if (this.disposed || this.active !== from || from === to) throw new Error('Stale live frame preparation');
713
- // An entry anywhere but the world built ahead lets that world go, so it retires before this one allocates.
714
- if (this.ahead !== to) this.ahead = null;
808
+ // An entry anywhere but the world built ahead lets that world go, so it retires before this one allocates. Stepping out
809
+ // onto the road keeps one pre-warmed from inside the source (GC5).
810
+ if (to !== null && this.ahead !== to) this.ahead = null;
715
811
  if (from !== null && to !== null) throw new Error('Owned runtime crossing must commit onto the neutral road first');
716
812
  // Protect a ready return before yielding: expiry/pressure cannot free it
717
813
  // between its selection and the final prepared-frame reservation.
@@ -767,7 +863,7 @@ export class LiveGridHost {
767
863
  playingBytes: this.ports.allocator.ownerCost(last.instance).playing, capBytes: Math.min(CONTENT_CAPS.playing, policy.playingBytes) };
768
864
  }
769
865
  /** Read-only crossing evidence and failures for the real grid physics harness. */
770
- state(): LiveGridState { return { current: this.active, worldFeet: this.worldFeet(), crossings: this.crossings, transitions: this.transitions.map((row) => ({ ...row })), residents: [...this.residents.keys()].sort(), pending: [...new Set([...this.requests.keys(), ...this.productRequests.keys()])].sort(), pendingWork: [
866
+ state(): LiveGridState { return { current: this.active, worldFeet: this.worldFeet(), crossings: this.crossings, ahead: { instance: this.ahead, warms: this.warms, refused: this.warmRefusal }, transitions: this.transitions.map((row) => ({ ...row })), residents: [...this.residents.keys()].sort(), pending: [...new Set([...this.requests.keys(), ...this.productRequests.keys()])].sort(), pendingWork: [
771
867
  ...[...this.requests.keys()].sort().map(instance => ({ instance, kind: 'world' as const, trigger: 'entry' as const })),
772
868
  ...[...this.productRequests].sort(([a], [b]) => a.localeCompare(b)).map(([instance, request]) => ({ instance, kind: request.required ? 'required-metadata' as const : 'optional-metadata' as const, trigger: request.trigger })),
773
869
  ], issues: Object.fromEntries(this.issues), gameplayReady: this.active === null || this.ports.gameplayReady(this.active), ...(this.ports.lastCell === undefined ? {} : { retainedCell: this.retainedState() }), retirements: this.retirements.map(row => ({ ...row })), retiring: [...this.retiring.keys()], ghosts: { count: this.ghosts.count(), regions: this.ghosts.regions() } }; }