@wildshard/engine 0.1.18 → 0.1.20

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 (334) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/budgets/shard-size-baseline.json +10 -4
  3. package/index.html +6 -4
  4. package/lint/engine-sides.json +18 -0
  5. package/lint/ratchet.json +0 -68
  6. package/lint/ratchet.mjs +1 -4
  7. package/package.json +19 -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 +33 -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 +83 -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 +284 -0
  51. package/scripts/grid-crossing-walk-proof.mjs +126 -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/land.mjs +2 -1
  56. package/scripts/live-prepush.py +3 -5
  57. package/scripts/loading-flow/benchmax.mjs +37 -12
  58. package/scripts/loading-flow/deskbench.mjs +276 -0
  59. package/scripts/loading-flow/stalls.d.mts +17 -3
  60. package/scripts/loading-flow/stalls.mjs +82 -3
  61. package/scripts/look-loop/test_look_loop.py +1 -38
  62. package/scripts/memory-proof.mjs +61 -6
  63. package/scripts/mmo-bots.mjs +8 -2
  64. package/scripts/net-lag-proof.mjs +219 -0
  65. package/scripts/night-market-kit-budget.mjs +2 -2
  66. package/scripts/nightly-model.ts +9 -6
  67. package/scripts/offline-proof-rules.d.mts +2 -2
  68. package/scripts/offline-proof-rules.mjs +15 -4
  69. package/scripts/offline-proof.mjs +80 -13
  70. package/scripts/{shard-platform-output.mjs → output-reader.mjs} +1 -1
  71. package/scripts/page-release/content.d.mts +9 -1
  72. package/scripts/page-release/content.mjs +131 -17
  73. package/scripts/page-release/flow.mjs +36 -10
  74. package/scripts/page-release/stamp-content.mjs +24 -0
  75. package/scripts/page-release.mjs +28 -6
  76. package/scripts/page-size.mjs +2 -1
  77. package/scripts/parity/boot-smoke.mjs +13 -2
  78. package/scripts/pin-format.ts +5 -2
  79. package/scripts/pin-packs.ts +1 -1
  80. package/scripts/pins-reuse.d.mts +1 -0
  81. package/scripts/pins-reuse.mjs +22 -0
  82. package/scripts/pins.ts +4 -4
  83. package/scripts/precommit-checks.mjs +1 -7
  84. package/scripts/precommit-jobs.mjs +0 -1
  85. package/scripts/precommit-source.py +1 -9
  86. package/scripts/program-discovery.mjs +1 -1
  87. package/scripts/ring-cook.mjs +2 -1
  88. package/scripts/ring-step.ts +1 -1
  89. package/scripts/scratch-dir.mjs +95 -0
  90. package/scripts/scratch-sweep.mjs +182 -0
  91. package/scripts/script-scenario-metrics.mjs +1 -1
  92. package/scripts/shard-output-content.d.mts +1 -1
  93. package/scripts/shard-output-content.mjs +2 -2
  94. package/scripts/shard-outputs.mjs +1 -1
  95. package/scripts/shard-public.mjs +1 -1
  96. package/scripts/shard-wire-meter.mjs +24 -9
  97. package/scripts/side-parity.mjs +4 -2
  98. package/scripts/standalone-smoke.mjs +8 -3
  99. package/scripts/tier-textures.mjs +22 -4
  100. package/scripts/tile-bake-report.mjs +1 -1
  101. package/scripts/tile-bakes.mjs +1 -1
  102. package/scripts/title-assets.generated.json +2 -0
  103. package/scripts/tsconfig.json +2 -14
  104. package/scripts/vendor/basisu/LICENSE +201 -0
  105. package/scripts/vendor/basisu/basis_encoder.cjs +2 -0
  106. package/scripts/vendor/basisu/basis_encoder.wasm +0 -0
  107. package/scripts/vitest-push-guards.config.ts +1 -1
  108. package/scripts/vps/harden-apply.sh +4 -1
  109. package/scripts/vps/harden-prometheus.sh +179 -0
  110. package/scripts/vps/harden.sh +16 -0
  111. package/scripts/vps/rebuild.sh +18 -0
  112. package/scripts/vps/wildshard-config +6 -2
  113. package/scripts/worker-client-play.mjs +6 -2
  114. package/scripts/worktree-reap.mjs +59 -13
  115. package/scripts/worktree.mjs +19 -5
  116. package/src/.oxlintrc.json +3 -182
  117. package/src/client/app/entry.ts +10 -2
  118. package/src/client/engine/anim/rigParser.ts +2 -2
  119. package/src/client/engine/boot/bootCache.ts +2 -2
  120. package/src/client/engine/boot/bootTrace.ts +12 -4
  121. package/src/client/engine/boot/browserChunkRecovery.ts +4 -0
  122. package/src/client/engine/boot/clearDownloads.ts +5 -2
  123. package/src/client/engine/boot/contentRead.ts +11 -0
  124. package/src/client/engine/boot/gpuFiles.ts +4 -2
  125. package/src/client/engine/boot/lastEnd.ts +99 -12
  126. package/src/client/engine/boot/texturePack.ts +2 -2
  127. package/src/client/engine/core/Game.ts +63 -19
  128. package/src/client/engine/core/gpuOnly.ts +10 -0
  129. package/src/client/engine/core/renderBudget.ts +134 -0
  130. package/src/client/engine/net/netPlayer.ts +19 -2
  131. package/src/client/engine/net/otherPlayers.ts +55 -8
  132. package/src/client/engine/net/predictor.ts +33 -9
  133. package/src/client/engine/net/redial.ts +68 -10
  134. package/src/client/engine/pwa/cacheNames.ts +58 -1
  135. package/src/client/engine/pwa/sw.js +41 -11
  136. package/src/client/engine/render/dataLook.ts +219 -44
  137. package/src/client/engine/render/families/detail.ts +89 -0
  138. package/src/client/engine/render/families/pbr.ts +9 -1
  139. package/src/client/engine/render/families/registry.ts +11 -2
  140. package/src/client/engine/render/families/sceneSurface.ts +116 -0
  141. package/src/client/engine/render/look.ts +12 -0
  142. package/src/client/engine/render/lookLight.ts +103 -11
  143. package/src/client/engine/render/lookRender.ts +105 -0
  144. package/src/client/engine/render/precompile.ts +4 -2
  145. package/src/client/engine/render/tiers.ts +4 -1
  146. package/src/client/engine/saves/indexed.ts +2 -2
  147. package/src/client/engine/telemetry/browserErrors.ts +24 -3
  148. package/src/client/engine/telemetry/staleBuildReport.ts +22 -1
  149. package/src/client/engine/ui/debugOptions.ts +1 -1
  150. package/src/client/engine/ui/lookLightOption.ts +10 -6
  151. package/src/client/engine/ui/namePrompt.ts +7 -0
  152. package/src/client/engine/world/declaredProps.ts +5 -1
  153. package/src/client/engine/world/skyRig.ts +4 -1
  154. package/src/client/engine/world/terrainTileView.ts +64 -23
  155. package/src/client/game/boot/audio.generated.ts +114 -114
  156. package/src/client/game/boot/bytes.generated.ts +118 -220
  157. package/src/client/game/boot/placedSpawn.ts +35 -0
  158. package/src/client/game/boot/spawnDownload.ts +25 -6
  159. package/src/client/game/boot/versions.generated.ts +7 -5
  160. package/src/client/game/devScene/hook.ts +428 -0
  161. package/src/client/game/devScene/liveLook.ts +21 -0
  162. package/src/client/game/grid/cellLoading.ts +12 -2
  163. package/src/client/game/grid/live.ts +152 -19
  164. package/src/client/game/grid/liveSession.ts +53 -3
  165. package/src/client/game/grid/mapAtlas.ts +18 -4
  166. package/src/client/game/grid/minimapBlend.ts +15 -5
  167. package/src/client/game/grid/oneWayIn.ts +5 -1
  168. package/src/client/game/grid/pageEntry.ts +12 -1
  169. package/src/client/game/grid/placedCells.ts +114 -12
  170. package/src/client/game/grid/placedContent.ts +85 -0
  171. package/src/client/game/grid/prefetch.ts +9 -1
  172. package/src/client/game/grid/productInputs.ts +23 -10
  173. package/src/client/game/grid/productLeases.ts +4 -1
  174. package/src/client/game/grid/products.ts +8 -4
  175. package/src/client/game/grid/roadLook.ts +24 -15
  176. package/src/client/game/grid/roadLookPlatform.ts +4 -2
  177. package/src/client/game/grid/roadResources.ts +24 -0
  178. package/src/client/game/grid/roadSign.worker.ts +4 -3
  179. package/src/client/game/grid/roadSignPaint.ts +16 -5
  180. package/src/client/game/grid/roadSignPreparation.ts +4 -3
  181. package/src/client/game/grid/roadSignScale.ts +8 -0
  182. package/src/client/game/grid/roadTileCapture.worker.ts +3 -1
  183. package/src/client/game/grid/roadTileCaptureWorker.ts +2 -1
  184. package/src/client/game/grid/roadTileWrite.worker.ts +4 -2
  185. package/src/client/game/grid/roadTileWriter.ts +2 -1
  186. package/src/client/game/grid/screenReports.ts +39 -0
  187. package/src/client/game/grid/session.ts +32 -7
  188. package/src/client/game/grid/softWallLook.ts +25 -8
  189. package/src/client/game/mainMenu.ts +6 -2
  190. package/src/client/game/plugin/context.ts +2 -1
  191. package/src/client/game/plugin/followedMovers.ts +7 -1
  192. package/src/client/game/quest/figures.ts +2 -0
  193. package/src/client/game/session/finish.ts +9 -0
  194. package/src/client/game/shardfile/assetCache.ts +4 -4
  195. package/src/client/game/shardfile/client.ts +28 -8
  196. package/src/client/game/shardfile/clientAssets.ts +9 -5
  197. package/src/client/game/shardfile/clientLibrary.ts +1 -1
  198. package/src/client/game/shardfile/clientPropMaterials.ts +4 -1
  199. package/src/client/game/shardfile/clientViews.ts +36 -8
  200. package/src/client/game/shardfile/clientWater.ts +51 -9
  201. package/src/client/game/shardfile/clientWorker.ts +19 -7
  202. package/src/client/game/shardfile/constructionCheckpoint.ts +2 -2
  203. package/src/client/game/shardfile/groundMerge.ts +57 -5
  204. package/src/client/game/shardfile/hybrid.ts +2 -0
  205. package/src/client/game/shardfile/look.ts +8 -3
  206. package/src/client/game/shardfile/product.ts +34 -7
  207. package/src/client/game/shardfile/productChecks.ts +2 -2
  208. package/src/client/game/shardfile/productCost.ts +2 -2
  209. package/src/client/game/shardfile/readAsset.ts +2 -2
  210. package/src/client/game/shardfile/reflectingWater.ts +73 -0
  211. package/src/client/game/shardfile/seatGrace.ts +9 -0
  212. package/src/client/game/shardfile/skinPlayback.ts +1 -1
  213. package/src/client/game/shardfile/slabLibrary.ts +115 -49
  214. package/src/client/game/shardfile/tileContent.ts +1 -1
  215. package/src/client/game/shardfile/tileDriver.ts +38 -11
  216. package/src/client/game/shardfile/wirePage.ts +7 -3
  217. package/src/client/game/shardfile/worldScenes.ts +17 -10
  218. package/src/client/game/systems/npc/figureRows.ts +9 -0
  219. package/src/client/host/online/doctor.ts +22 -7
  220. package/src/client/host/online/doctorView.ts +2 -0
  221. package/src/client/host/online/linkScreens.ts +109 -5
  222. package/src/client/host/online/shell.ts +13 -4
  223. package/src/client/host/standalone/shell.ts +40 -0
  224. package/src/cook/game/astc6Encode.ts +55 -0
  225. package/src/cook/game/astc6Wasm.ts +176 -0
  226. package/src/cook/game/cookJob.ts +30 -6
  227. package/src/cook/game/cookWorker.ts +38 -11
  228. package/src/cook/game/entryTotals.ts +51 -24
  229. package/src/cook/game/shardCook.ts +35 -7
  230. package/src/cook/game/spawnParts.ts +33 -8
  231. package/src/cook/game/tierTextures.ts +87 -14
  232. package/src/server/engine/ai/bossContenders.ts +27 -3
  233. package/src/server/engine/ai/phases.ts +1 -1
  234. package/src/server/engine/entities/creatureRefill.ts +9 -2
  235. package/src/server/engine/net/ledgerBook.ts +2 -0
  236. package/src/server/engine/net/room.ts +15 -0
  237. package/src/server/engine/sim/respawn.ts +8 -0
  238. package/src/server/game/boss/arenaRoomEntry.ts +5 -1
  239. package/src/server/game/boss/arenaRoomNative.ts +2 -0
  240. package/src/server/game/boss/native.ts +2 -1
  241. package/src/server/game/boss/nativeWake.ts +9 -5
  242. package/src/server/game/boss/openArenaNative.ts +2 -2
  243. package/src/server/game/boss/openArenaRoom.ts +3 -1
  244. package/src/server/game/grid/room.ts +44 -3
  245. package/src/server/game/grid/simulation.ts +23 -0
  246. package/src/server/game/population/mixedRoster.ts +11 -3
  247. package/src/server/game/population/nativeBake.ts +8 -3
  248. package/src/server/game/population/nativeReturns.ts +6 -3
  249. package/src/server/game/population/roster.ts +5 -3
  250. package/src/server/game/quest/eliteDrops.ts +18 -3
  251. package/src/server/game/quest/nativeChapter.ts +1 -1
  252. package/src/server/game/quest/nativeComposition.ts +5 -1
  253. package/src/server/game/riding/nativeTaming.ts +22 -7
  254. package/src/server/game/riding/wildRefill.ts +3 -2
  255. package/src/server/game/shardfile/bossRow.ts +4 -2
  256. package/src/server/game/shardfile/homeKeeper.ts +4 -2
  257. package/src/server/host/bake/headlessWorker.ts +1 -1
  258. package/src/server/host/dedicated/cellHost.ts +112 -18
  259. package/src/server/host/dedicated/cellProtocol.ts +18 -1
  260. package/src/server/host/dedicated/cellWorker.ts +8 -5
  261. package/src/server/host/dedicated/dedicatedRoom.ts +38 -11
  262. package/src/server/host/dedicated/gridCells.ts +15 -6
  263. package/src/server/host/dedicated/loopLag.ts +21 -0
  264. package/src/server/host/dedicated/main.ts +13 -5
  265. package/src/server/host/dedicated/packReader.ts +3 -3
  266. package/src/server/host/dedicated/placementFile.ts +3 -2
  267. package/src/server/host/dedicated/roadRoom.ts +34 -4
  268. package/src/server/host/dedicated/serverMetrics.ts +135 -0
  269. package/src/server/host/dedicated/socketPump.ts +21 -4
  270. package/src/server/host/dedicated/workerTable.ts +32 -14
  271. package/src/server/host/dedicated/world.ts +65 -7
  272. package/src/server/host/headless.ts +1 -1
  273. package/src/server/host/headlessRuntime.ts +1 -1
  274. package/src/server/host/standalone/roadWorld.ts +15 -3
  275. package/src/server/host/standalone/serverHost.ts +57 -8
  276. package/src/server/host/standalone/serverProduct.ts +48 -16
  277. package/src/server/host/standalone/serverRuntime.ts +1 -1
  278. package/src/shared/engine/ai/BossBrain.ts +8 -0
  279. package/src/shared/engine/core/framePacing.ts +12 -1
  280. package/src/shared/engine/physics/terrainTiles.ts +20 -4
  281. package/src/shared/game/boss/wake.ts +6 -0
  282. package/src/shared/game/devColliders.ts +107 -0
  283. package/src/shared/game/devGameplay.ts +41 -0
  284. package/src/shared/game/eliteSystem.ts +8 -0
  285. package/src/shared/game/grid/allocator.ts +3 -0
  286. package/src/shared/game/grid/placementRows.ts +5 -2
  287. package/src/shared/game/plugin/bossRecord.ts +3 -2
  288. package/src/shared/game/shardfile/ktx2Targets.ts +23 -3
  289. package/src/shared/game/shardfile/outputDescriptor.ts +9 -5
  290. package/src/shared/game/shardfile/packReads.ts +28 -3
  291. package/src/shared/game/shardfile/serverPack.ts +9 -0
  292. package/src/shared/game/systems/looks/trampleField.ts +2 -0
  293. package/src/shared/host/formatJsonSchema.ts +2 -2
  294. package/src/tsconfig.json +1 -27
  295. package/lint/host-reviews.json +0 -14
  296. package/lint/listed-view-code.json +0 -13
  297. package/lint/platform-pending-users.json +0 -2520
  298. package/lint/platform-pending-users.md +0 -18
  299. package/scripts/cell-mem/metrics-preload.mjs +0 -65
  300. package/scripts/check-closed-components.d.mts +0 -7
  301. package/scripts/check-closed-components.mjs +0 -87
  302. package/scripts/g571-hosts.d.mts +0 -3
  303. package/scripts/g571-hosts.mjs +0 -54
  304. package/scripts/host-ruler/register-migrate.mjs +0 -242
  305. package/scripts/listed-view-code.d.mts +0 -7
  306. package/scripts/listed-view-code.mjs +0 -93
  307. package/scripts/look-loop/fit-lut.py +0 -142
  308. package/scripts/look-loop/palette-delta.py +0 -183
  309. package/scripts/look-loop/regions/driftwood-isle.json +0 -25
  310. package/scripts/look-loop/regions/far-reach.json +0 -225
  311. package/scripts/look-loop/regions/open-plot-night-market.json +0 -855
  312. package/scripts/look-loop/regions/pine-hollow.json +0 -22
  313. package/scripts/look-loop/regions/sunscar-dunes.json +0 -281
  314. package/scripts/platform-chargebacks.d.mts +0 -9
  315. package/scripts/platform-chargebacks.mjs +0 -135
  316. package/scripts/shard-component-spans.d.mts +0 -15
  317. package/scripts/shard-component-spans.mjs +0 -18
  318. package/scripts/shard-components.d.mts +0 -16
  319. package/scripts/shard-components.mjs +0 -363
  320. package/scripts/shard-platform-hosts.d.mts +0 -2
  321. package/scripts/shard-platform-hosts.mjs +0 -93
  322. package/scripts/shard-platform-sections.d.mts +0 -2
  323. package/scripts/shard-platform-sections.mjs +0 -9
  324. package/scripts/shard-platform.d.mts +0 -76
  325. package/scripts/shard-platform.mjs +0 -1072
  326. package/src/.oxfmtrc.json +0 -48
  327. package/src/scripts/ask-new.sh +0 -29
  328. package/src/scripts/asks.mjs +0 -142
  329. package/src/scripts/herdr-prompt.sh +0 -34
  330. package/src/scripts/herdr-question-open.sh +0 -67
  331. package/src/scripts/md-wrap.mjs +0 -229
  332. /package/scripts/{shard-platform-format.d.mts → node-format.d.mts} +0 -0
  333. /package/scripts/{shard-platform-format.mjs → node-format.mjs} +0 -0
  334. /package/scripts/{shard-platform-output.d.mts → output-reader.d.mts} +0 -0
@@ -20,14 +20,18 @@ import type { HeadlessRuntimeInput } from '../headlessRuntime';
20
20
  import { StandaloneGrid } from './gridServer';
21
21
  import { isHarnessFlag, isHarnessGod, isHarnessHits, isHarnessJoin, isHarnessMove, isHarnessPlace } from '../../../shared/host/standalone/harnessPlace';
22
22
  import { WorkerLoopback } from '../../../shared/host/standalone/workerLoopback';
23
+ import { isDevColliders, isDevGround, swapDevBoxes, swapDevGround } from '@wildshard/engine/game/devColliders';
24
+ import { isDevRestart, withDevGameplay, type DevGameplay, type DevPlace, type DevRestarted } from '@wildshard/engine/game/devGameplay';
25
+ import type { Shardfile } from '@wildshard/format/shardSchema';
23
26
  import { ProgressSaves, ProgressWatch } from './progressWatch';
24
27
 
25
28
  type Boot = Extract<ShellMessage, { kind: 'boot' }>;
26
29
  /** How the composition reaches what a worker and a Node test get differently. */
27
30
  export interface StandaloneServerOptions {
28
31
  readonly control: MessagePort; readonly game: MessagePort;
29
- /** Read and verify a shard's server inputs: the home cell's, and each cell's as the grid admits it. */
30
- readonly load: (boot: Boot, slug: string) => Promise<HeadlessRuntimeInput>;
32
+ /** Read and verify a shard's server inputs: the home cell's, and each cell's as the grid admits it. `patch` (DEVSERVER, SHARD-SOURCE
33
+ * AP19) changes the read shardfile before the input is made of it. */
34
+ readonly load: (boot: Boot, slug: string, patch?: (shard: Shardfile) => Shardfile) => Promise<HeadlessRuntimeInput>;
31
35
  /** The road's collision, read once a grid session boots. A lone cell has no road and never asks; a proof that stays in a cell needs none. */
32
36
  readonly strips?: (boot: Boot) => Promise<readonly GridCollisionStrip[]>;
33
37
  /** A save read back but would not restore, and boot moved to the one before it. */
@@ -83,24 +87,69 @@ export function runStandaloneServer(options: StandaloneServerOptions): { dispose
83
87
  changed.poll(now);
84
88
  };
85
89
 
90
+ /** The grid's boot options for `message`; `patch` changes the watched shard's read shardfile (AP19's restart), never a neighbour's. */
91
+ const gridOptions = (message: Boot, local: ForwardedStorage, patch?: (shard: Shardfile) => Shardfile): Parameters<typeof StandaloneGrid.boot>[0] => {
92
+ const { arrival, residents } = options.proof ?? {}, watched = new Set([message.slug]);
93
+ return { slug: message.slug, build: message.build, book, saves, storage: local, savePrefix: message.savePrefix, now: diagnosticNow, ...(message.lone === true ? { lone: true } : {}),
94
+ load: slug => options.load(message, slug, watched.has(slug) ? patch : undefined), strips: () => options.strips?.(message) ?? Promise.resolve([]), stepped, ...(options.onSaveRefused === undefined ? {} : { refused: options.onSaveRefused }), ...(options.reports === undefined ? {} : { reports: options.reports }),
95
+ ...(arrival === undefined ? {} : { arrival }), ...(residents === undefined ? {} : { residents }), ...(options.goto === undefined ? {} : { goto: options.goto }) };
96
+ };
97
+
86
98
  const boot = async (message: Boot): Promise<void> => {
87
99
  bootMark('server:boot-configuration');
88
100
  storage = new ForwardedStorage(message.saves, write => { post({ kind: 'write', ...write }); });
89
- const local = storage, { arrival, residents } = options.proof ?? {};
101
+ const local = storage;
90
102
  installWorkerIdentity(message.savePrefix);
91
103
  allowDeveloperBoost(); // this server is the player's own device; a page only sends the button with Developer on
92
104
  installSaveEnvironment({ storage: saveScope => saveScope === 'session' ? null : local, persistent: () => true, persist: () => Promise.resolve(false) });
93
- const server = await bootTask('server:world-boot', () => StandaloneGrid.boot({ slug: message.slug, build: message.build, book, saves, storage: local, savePrefix: message.savePrefix, now: diagnosticNow, ...(message.lone === true ? { lone: true } : {}),
94
- load: slug => options.load(message, slug), strips: () => options.strips?.(message) ?? Promise.resolve([]), stepped, ...(options.onSaveRefused === undefined ? {} : { refused: options.onSaveRefused }), ...(options.reports === undefined ? {} : { reports: options.reports }),
95
- ...(arrival === undefined ? {} : { arrival }), ...(residents === undefined ? {} : { residents }), ...(options.goto === undefined ? {} : { goto: options.goto }) }));
105
+ const server = await bootTask('server:world-boot', () => StandaloneGrid.boot(gridOptions(message, local)));
96
106
  grid = server;
97
107
  const { restored } = server;
98
108
  if (restored?.ledger !== undefined) book.restore(restored.ledger);
99
109
  server.connect(new WorkerLoopback(game));
100
110
  watch.look(server.host, book.filed); // where the world stands before its first tick: what that tick moves is progress
101
- if (options.harness !== undefined) options.harness.onmessage = (event: MessageEvent<unknown>): void => { const [port] = event.ports; if (isHarnessJoin(event.data) && port !== undefined) server.join(event.data, new WorkerLoopback(port)); else if (isHarnessFlag(event.data)) server.raise(event.data.flag); else if (isHarnessMove(event.data)) server.place(event.data, event.data.move); else if (isHarnessPlace(event.data)) server.place(event.data); else if (isHarnessHits(event.data)) server.hardHits(event.data.hits); else if (isHarnessGod(event.data)) server.bossGod(); };
111
+ // SHARD-SOURCE AP5: `wildshard watch`'s part colliders, in this world as in the page's (DEVSERVER only: the define folds it away)
112
+ // and (AP18) its ground: the heightfield, the height query, and the players lifted out of a hill raised under them
113
+ const devBoxes = new Map<string, Scope>(), devGround: { scope: Scope | null } = { scope: null };
114
+ const groundPorts = { heightQuery: (heightAt: (x: number, z: number) => number) => { grid?.host.setHeightQuery(heightAt); }, players: () => (grid ?? server).host.players.entries(),
115
+ place: (at: { x: number; y: number; z: number; yaw: number }, player: string) => { try { grid?.place(at, player); } catch (cause) { console.warn('[devGround] a player stays where it was', cause); } } };
116
+ // AP19: `wildshard watch`'s soft restart. Save, put the world down, boot it again on the new sections from that save (its
117
+ // progress and its player's place), give the page its new link and put the player where the page says it stands. The page
118
+ // sends its held boxes and ground again once this answers.
119
+ let restarting = false;
120
+ const restart = typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ ? async (gameplay: DevGameplay, at: DevPlace | null, link: MessagePort, reply: MessagePort): Promise<void> => {
121
+ const started = diagnosticNow(), old = grid;
122
+ const answer = (ok: boolean, reason?: string): void => { reply.postMessage({ ok, ms: Math.round(diagnosticNow() - started), ...(reason === undefined ? {} : { reason }) } satisfies DevRestarted, []); reply.close(); };
123
+ if (old === undefined || restarting) { answer(false, 'no world to restart'); return; }
124
+ // the clock comes back only as it was: a hidden tab's or a failed world's server stays paused
125
+ const running = clock?.running ?? false;
126
+ restarting = true; clock?.pause();
127
+ try {
128
+ await saveWorld();
129
+ old.dispose(); grid = undefined;
130
+ for (const held of devBoxes.values()) held.dispose();
131
+ devBoxes.clear(); devGround.scope?.dispose(); devGround.scope = null;
132
+ const next = await StandaloneGrid.boot(gridOptions(message, local, shard => withDevGameplay(shard, gameplay)));
133
+ grid = next;
134
+ next.connect(new WorkerLoopback(link));
135
+ if (at !== null) next.place(at);
136
+ watch.look(next.host, book.filed);
137
+ next.open();
138
+ answer(true);
139
+ } catch (cause) { answer(false, cause instanceof Error ? cause.message : String(cause)); }
140
+ finally { restarting = false; if (running) clock?.start(); }
141
+ } : null;
142
+ if (options.harness !== undefined) options.harness.onmessage = (event: MessageEvent<unknown>): void => {
143
+ const [port, reply] = event.ports, live = grid;
144
+ if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ && restart !== null && isDevRestart(event.data) && port !== undefined && reply !== undefined) { void restart(event.data.wildshardDevRestart, event.data.at, port, reply); return; }
145
+ // while a restart runs there is no world: the page sends its boxes and ground again once it answers
146
+ if (live === undefined) return;
147
+ if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ && isDevColliders(event.data)) swapDevBoxes(live.host.physics, live.host.scope, devBoxes, event.data.wildshardDevColliders, event.data.boxes);
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();
150
+ };
102
151
  clock = new ServerClock({ now: diagnosticNow, wait: (ms, run) => { const timer = scope.timeout(ms, run); return () => { scope.cancelTimer(timer); }; },
103
- step: () => { try { server.tick(); progress(server); } catch (error) { fail(error); } } });
152
+ step: () => { const live = grid; if (live === undefined) return; try { live.tick(); progress(live); } catch (error) { fail(error); } } });
104
153
  options.proof?.booted?.(server);
105
154
  bootMark('server:booted-send');
106
155
  post({ kind: 'booted', tick: server.host.state.tick, restored: restored !== undefined });
@@ -1,13 +1,13 @@
1
1
  import type { Rapier } from '@wildshard/engine/physics/rapier';
2
2
  import { bootTask, bootProgress, bootTiming } from '@wildshard/engine/boot/timing';
3
3
  import { isOutputIndex } from '@wildshard/format/outputAddress';
4
- import { parseShardfile } from '@wildshard/format/shardSchema';
4
+ import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
5
5
  import { contentHash } from '@wildshard/engine/game/shardfile/contentHash';
6
6
  import { nodeNamedJsonCheck, nodeOutputDescriptorChecks } from '@wildshard/engine/game/shardfile/outputChecksNode';
7
7
  import { carryOutputDescriptor, isBuildValidatedOutput, outputDescriptor, resolveOutputDescriptor, serverReadsFile } from '@wildshard/engine/game/shardfile/outputDescriptor';
8
8
  import { shardProductData } from '@wildshard/engine/game/shardfile/productData';
9
9
  import { GRID_COLLISION_BODY, GRID_COLLISION_HEADER, readGridCollision, type GridCollisionStrip } from '@wildshard/engine/game/grid/gridCollision';
10
- import { readServerPackBook, serverPackBookPath, serverPackFile, serverPackPart, type ServerPackBook, type ServerPackPart } from '@wildshard/engine/game/shardfile/serverPack';
10
+ import { cookIndexPath, readCookedServerIndex, readServerPack, readServerPackBook, serverPackBookPath, serverPackFile, serverPackPart, type ServerPack, type ServerPackBook, type ServerPackPart } from '@wildshard/engine/game/shardfile/serverPack';
11
11
  import type { HeadlessRuntimeInput } from '../headlessRuntime';
12
12
  import type { HeldRead } from '../../../shared/host/standalone/heldReads';
13
13
 
@@ -51,10 +51,29 @@ function besideShard(path: string, root: string): URL {
51
51
  if (!path.startsWith('/') || path.startsWith('//') || at === -1) return new URL(path, base);
52
52
  return new URL(`.${path}`, new URL(base.pathname.slice(0, at + 1), base));
53
53
  }
54
+ /** A JSON file beside a shard's base, by its path from the origin's root. `fresh` asks past any cache with a query of its own: a CDN keeps a
55
+ * 404 for a while, and a cook index that is missing now may be written a minute later. A `file:` origin reads `path` and ignores it. */
56
+ async function originJson(root: string, path: string, read: ServerRead, fresh = false): Promise<unknown> {
57
+ const url = besideShard(`/${path}`, root);
58
+ if (fresh) url.search = `?t=${String(Date.now())}`;
59
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await read(url, path)));
60
+ }
54
61
  /** This build's server book. */
55
62
  async function serverBook(root: string, build: string, read: ServerRead): Promise<ServerPackBook> {
56
- const path = serverPackBookPath(build);
57
- return readServerPackBook(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await read(besideShard(`/${path}`, root), path))));
63
+ return readServerPackBook(await originJson(root, serverPackBookPath(build), read));
64
+ }
65
+ /** The leading `_` a grid slug may carry is not the shard's (shard-format `shardSlugOf`). */
66
+ const shardOf = (slug: string): string => slug.replace(/^_/u, '');
67
+ /**
68
+ * SA47: a placed slug this build's book has no row for (a new author's, uploaded after the build), from the cook's index for this build
69
+ * and these bytes (MMO-SERVER MS2.4): `index/<build>/<hash>.json` names the pack the cook wrote beside its parts. The parts are read by
70
+ * their hash as a book's are, so the index only says where they are. A missing index throws, as a missing row does.
71
+ */
72
+ async function cookedPack(root: string, slug: string, cooked: Readonly<{ build: string; hash: string }>, read: ServerRead): Promise<ServerPack> {
73
+ const { build, hash } = cooked, path = cookIndexPath(build, hash), index = readCookedServerIndex(await originJson(root, path, read, true));
74
+ if (index.build !== build || index.hash !== hash || shardOf(index.slug) !== shardOf(slug)) throw new Error(`The cook's ${path} is not ${slug}'s`);
75
+ if (index.serverPack === undefined) throw new Error(`No server pack for ${slug} in the cook's ${path}`);
76
+ return readServerPack(await originJson(root, index.serverPack.index.slice(1), read));
58
77
  }
59
78
 
60
79
  /** C2: the road's collision from this build's grid pack: nothing a page reads, and no shard's. */
@@ -79,9 +98,21 @@ export async function readGridCollisionPack(root: string, build: string, read: S
79
98
  /** C2: reads a server file from its product's pack, fetching the book once and a part only for a file it holds. The browser
80
99
  * undoes `br`. A read file is copied out and its part left to the collector: a phone's worker shouldn't hold a level's worth
81
100
  * of them, and reading one again is a cache hit. */
82
- function serverPackReader(root: string, slug: string, build: () => string, source: ServerRead): (path: string) => Promise<Uint8Array> {
101
+ function serverPackReader(root: string, slug: string, build: () => string, source: ServerRead, hash?: string): (path: string) => Promise<Uint8Array> {
83
102
  const opening = new Map<string, Promise<Uint8Array>>(), opened = new Map<string, WeakRef<Uint8Array>>();
84
- let book: Promise<ServerPackBook> | undefined;
103
+ let pack: Promise<ServerPack> | undefined, book: Promise<ServerPackBook> | undefined;
104
+ // SA47: the book wins; only a slug it has no row for, with the shardfile hash its placement names, reads the cook's index. The book
105
+ // is read once, as before SA47; only a refused index is asked again (review)
106
+ const packOf = async (): Promise<ServerPack> => {
107
+ const row = (await (book ??= serverBook(root, build(), source))).shards[slug];
108
+ if (row !== undefined) return row;
109
+ if (hash === undefined) throw new Error(`No server pack for ${slug}`);
110
+ return cookedPack(root, slug, { build: build(), hash }, source);
111
+ };
112
+ // A refusal is not kept: the next read (the next look, SA33) asks again.
113
+ const packOnce = async (): Promise<ServerPack> => {
114
+ try { return await packOf(); } catch (error) { pack = undefined; throw error; }
115
+ };
85
116
  const body = (part: ServerPackPart): Promise<Uint8Array> => {
86
117
  const kept = opened.get(part.url)?.deref();
87
118
  if (kept !== undefined) return Promise.resolve(kept);
@@ -92,9 +123,7 @@ function serverPackReader(root: string, slug: string, build: () => string, sourc
92
123
  return read;
93
124
  };
94
125
  return async path => {
95
- const pack = (await (book ??= serverBook(root, build(), source))).shards[slug];
96
- if (pack === undefined) throw new Error(`No server pack for ${slug}`);
97
- const part = serverPackPart(pack, path), bytes = part === undefined ? undefined : serverPackFile(part, await body(part), path);
126
+ const part = serverPackPart(await (pack ??= packOnce()), path), bytes = part === undefined ? undefined : serverPackFile(part, await body(part), path);
98
127
  if (bytes === undefined) throw new Error(`Missing server input ${path}`);
99
128
  return bytes.slice();
100
129
  };
@@ -104,15 +133,17 @@ function serverPackReader(root: string, slug: string, build: () => string, sourc
104
133
  * P1-E5.2: the worker's product reader, loadHeadlessProduct over `fetch`. It verifies the same index, sizes and SHA-256
105
134
  * addresses with the same checks; only where the bytes come from differs.
106
135
  */
107
- export function fetchServerProduct(base: string, rapier: Rapier, held?: HeldRead): Promise<HeadlessRuntimeInput> {
108
- return readServerProduct(new URL(base, globalThis.location.href).href, workerBuild, serverBytes, rapier, held);
136
+ export function fetchServerProduct(base: string, rapier: Rapier, held?: HeldRead, patch?: (shard: Shardfile) => Shardfile): Promise<HeadlessRuntimeInput> {
137
+ return readServerProduct(new URL(base, globalThis.location.href).href, workerBuild, serverBytes, rapier, held, undefined, patch);
109
138
  }
110
- /** A shard's server inputs under `root`, whichever server is reading: `source` is what differs. */
111
- export async function readServerProduct(root: string, build: () => string, source: ServerRead, rapier: Rapier, held?: HeldRead): Promise<HeadlessRuntimeInput> {
139
+ /** A shard's server inputs under `root`, whichever server is reading: `source` is what differs. `hash`, a placed slug's shardfile (SA47),
140
+ * lets a slug the build's book lacks open from the cook's index. `patch` (DEVSERVER, SHARD-SOURCE AP19: `withDevGameplay`) changes
141
+ * the read shardfile before the product is made of it. */
142
+ export async function readServerProduct(root: string, build: () => string, source: ServerRead, rapier: Rapier, held?: HeldRead, hash?: string, patch?: (shard: Shardfile) => Shardfile): Promise<HeadlessRuntimeInput> {
112
143
  const slug = new URL('.', root).pathname.split('/').at(-2) ?? '';
113
144
  // C2: all of it is in the pack this build's book names, the server class only there (J91). The page lends what it holds
114
145
  // (DL25), so that moves no bytes. A host with no book, or one offline after a new build, reads what the device kept.
115
- const serverFile = serverPackReader(root, slug, build, source);
146
+ const serverFile = serverPackReader(root, slug, build, source, hash);
116
147
  const read = async (path: string): Promise<Uint8Array> => {
117
148
  if (path.startsWith('server/')) return serverFile(path);
118
149
  const url = new URL(path, root), lent = await held?.(url.href);
@@ -125,8 +156,9 @@ export async function readServerProduct(root: string, build: () => string, sourc
125
156
  // on bytes its build has already checked and the page has just read without checking. As on the page, only a build's own verdict
126
157
  // for exactly these bytes spares the checks. A product with none, an outside one, keeps them.
127
158
  const assembled = await bootTask('server:descriptor-read-and-verification', () => resolveOutputDescriptor(input, { offline: false, firstParty: true, hash: contentHash, read, checks: nodeOutputDescriptorChecks }));
128
- const built = isBuildValidatedOutput(assembled), shard = built ? assembled : parseShardfile(assembled);
129
- if (!built) carryOutputDescriptor(assembled, shard);
159
+ const built = isBuildValidatedOutput(assembled), parsed = built ? assembled : parseShardfile(assembled);
160
+ if (!built) carryOutputDescriptor(assembled, parsed);
161
+ const shard = patch === undefined ? parsed : patch(parsed);
130
162
  const descriptor = outputDescriptor(shard);
131
163
  if (descriptor === undefined) throw new Error('Standalone output has no verified index');
132
164
  const files = new Map<string, { readonly path: string; readonly hash: string; readonly bytes: number }>();
@@ -37,7 +37,7 @@ export function runServerWorker(event: MessageEvent<unknown>): void {
37
37
  const [control, game, harness, reads] = event.ports;
38
38
  if (control === undefined || game === undefined) return;
39
39
  const held = reads === undefined ? undefined : askHeldReads(reads);
40
- runStandaloneServer({ control, game, ...harness === undefined ? {} : { harness }, ...typeof start.goto === 'string' ? { goto: start.goto } : {}, load: async (boot, slug) => fetchServerProduct(new URL(`../${slug}/`, new URL(boot.base, globalThis.location.href)).href, await rapierOf(held), held),
40
+ runStandaloneServer({ control, game, ...harness === undefined ? {} : { harness }, ...typeof start.goto === 'string' ? { goto: start.goto } : {}, load: async (boot, slug, patch) => fetchServerProduct(new URL(`../${slug}/`, new URL(boot.base, globalThis.location.href)).href, await rapierOf(held), held, patch),
41
41
  strips: boot => fetchGridCollision(boot.base),
42
42
  onSaveRefused: error => { console.warn('Standalone save refused, falling back', error); } });
43
43
  }
@@ -156,6 +156,14 @@ export class BossBrain {
156
156
  this.state = 'dormant';
157
157
  }
158
158
 
159
+ /** SERVER-CELLS SC5 (J328): a served world's beaten boss comes back (its world is never rebuilt): forgotten as `disarm` does, and its
160
+ * record is a fresh world's (SC10: not beaten, so a record's world flags clear; its reward stands again for the next win). Who is
161
+ * paid stays the bounty's, once per player. */
162
+ returnBeaten(): void {
163
+ this.disarm();
164
+ this.saved.defeated = false; this.saved.rewardTaken = false; this.save();
165
+ }
166
+
159
167
  /** the player died. In this fight → back at the checkpoint (true); anywhere else → not ours (false) */
160
168
  onPlayerDeath(): boolean {
161
169
  if (!this.engaged) return false;
@@ -50,6 +50,16 @@ const HELD_SLICE_MIN_MS = 4;
50
50
  let heldSliceAt = Number.NEGATIVE_INFINITY;
51
51
  /** Frames drawn while held, for `heldFrameTurn`. */
52
52
  let heldFrames = 0;
53
+ /** GRID-CROSSING GC6 (QA 11-14 row 6, Jake on staging: a 37 s card crossing into Nalati at 2992x1434@2): a build the traveller
54
+ * is about to need (the world of the cell ahead, its entry on the road) is on the crossing's critical path. Its slices then
55
+ * get URGENT_BUILD_MS after each drawn frame, whatever the display's rate and whether the next vsync is due: the ordinary
56
+ * quarter of the fastest display interval gave a 120 Hz screen 2 ms a frame, and at 30 fps that is 6% of the wall clock, so
57
+ * an 11 s world took 30 s. The grid sets it while such a build runs; off by default. */
58
+ export const URGENT_BUILD_MS = 8;
59
+ let urgent = false;
60
+ export function setBuildUrgent(on: boolean): void { urgent = on; }
61
+ /** Whether a build the traveller is about to need is running (`setBuildUrgent`). */
62
+ export function buildUrgent(): boolean { return urgent; }
53
63
  /** Whether the traveller waits for the build (a grid cell's loading screen shows); the grid sets it, off by default.
54
64
  * The page sets it through `setBuildHeldTimed` (`heldTiming.ts`), which also times each held interval on Developer pages. */
55
65
  export function setBuildHeld(on: boolean): void {
@@ -104,6 +114,7 @@ export function frameBudgetSpent(budgetMs: number, now: number = diagnosticNow()
104
114
  // D110: a frame that overran its interval (drawn after the next was due: a phone at 4x CPU) is due the moment it lands,
105
115
  // so the due rule would end every slice before it starts and no sliced build would run again; after such a frame the
106
116
  // builds get their ordinary slice instead
117
+ if (urgent) return presenting(now) && now - lastDrawn >= Math.min(budgetMs, URGENT_BUILD_MS);
107
118
  const overran = lastDrawn - lastFrameAt >= interval - DUE_SLACK_MS;
108
119
  return presenting(now) && (now - lastDrawn >= Math.min(budgetMs, interval / 4, BUILD_FRAME_MS / 2) || (!overran && frameDue(now)));
109
120
  }
@@ -175,5 +186,5 @@ export function paceYield(plain: () => Promise<void>, owner?: Scope, budgetMs?:
175
186
  }
176
187
 
177
188
  function yieldDue(budgetMs: number | undefined, now: number): boolean {
178
- return !held && frameDue(now) || (budgetMs !== undefined && frameBudgetSpent(budgetMs, now));
189
+ return !held && (!urgent || budgetMs === undefined) && frameDue(now) || (budgetMs !== undefined && frameBudgetSpent(budgetMs, now));
179
190
  }
@@ -1,16 +1,21 @@
1
1
  import type { Collider } from '@dimforge/rapier3d-simd';
2
2
  import type { Scope } from '../app/scope';
3
3
  import { withOwner } from '../app/ownership';
4
- import { decodeTerrainTile } from '@wildshard/format/terrainTileBytes';
4
+ import { decodeTerrainTile, type TerrainTileData } from '@wildshard/format/terrainTileBytes';
5
5
  import type { Physics } from './Physics';
6
6
  import { groups } from './groups';
7
- import { tagCollider } from './surface';
7
+ import { isTerrainCollider, tagCollider } from './surface';
8
8
 
9
9
  /** Install the baked critical heightfield in the local physics world; the owning scope removes it on unload. */
10
10
  export function addBakedTerrainCollider(physics: Physics, bytes: Uint8Array, scope: Scope): Collider {
11
- const data = decodeTerrainTile(bytes), r = data.resolution;
11
+ const data = decodeTerrainTile(bytes);
12
12
  if (data.colours !== undefined) throw new Error('Collider terrain must contain heights only');
13
- const heights = new Float32Array(r * r);
13
+ return addTerrainTileCollider(physics, data, scope);
14
+ }
15
+
16
+ /** A heights lattice (row-major, as the wire carries it) as the world's ground heightfield, owned by `scope`. */
17
+ export function addTerrainTileCollider(physics: Physics, data: Pick<TerrainTileData, 'resolution' | 'x' | 'z' | 'size' | 'heights'>, scope: Scope): Collider {
18
+ const r = data.resolution, heights = new Float32Array(r * r);
14
19
  for (let z = 0; z < r; z++) for (let x = 0; x < r; x++) heights[x * r + z] = data.heights[z * r + x] ?? 0;
15
20
  const collider = withOwner(scope, () => physics.world.createCollider(physics.R.ColliderDesc.heightfield(r - 1, r - 1, heights, { x: data.size, y: 1, z: data.size })
16
21
  .setTranslation(data.x + data.size / 2, 0, data.z + data.size / 2).setCollisionGroups(groups('WORLD')).setFriction(0.9)));
@@ -18,3 +23,14 @@ export function addBakedTerrainCollider(physics: Physics, bytes: Uint8Array, sco
18
23
  // Physics already owns the scoped handle and forgets its capture before freeing a replaced world.
19
24
  return collider;
20
25
  }
26
+
27
+ /**
28
+ * SHARD-SOURCE AP18 (DEVSERVER): `wildshard watch`'s new ground. The lattice goes in as the world's heightfield under
29
+ * `scope`, then every other terrain heightfield leaves the world (the boot's, or the last swap's). Returns how many went.
30
+ */
31
+ export function swapTerrainCollider(physics: Physics, data: Pick<TerrainTileData, 'resolution' | 'x' | 'z' | 'size' | 'heights'>, scope: Scope): number {
32
+ const fresh = addTerrainTileCollider(physics, data, scope), old: Collider[] = [];
33
+ physics.world.forEachCollider(collider => { if (collider !== fresh && isTerrainCollider(collider)) old.push(collider); });
34
+ for (const collider of old) physics.world.removeCollider(collider, true);
35
+ return old.length;
36
+ }
@@ -43,6 +43,12 @@ export class WakeBossEncounter {
43
43
  private near(player: { readonly x: number; readonly z: number }): boolean { return Math.hypot(player.x - this.center.x, player.z - this.center.z) < this.row.arena.radius; }
44
44
  private finish(outcome: 'won' | 'lost' | 'left'): void { if (this.attempt) { this.attempt = false; this.effects.push({ kind: 'outcome', outcome }); } }
45
45
  arm(observation: WakeBossObservation): void { this.wake(observation); }
46
+ /** SERVER-CELLS SC10 (J328): a served world's beaten fight stands again, as a fresh world's would: no attempt, nobody waited for. */
47
+ returnBeaten(): void {
48
+ this.attempt = false; this.waitForReturn = false; this.state = 'dormant'; this.phase = 0;
49
+ this.boss = { ...this.boss, state: 'dormant', phase: 0, checkpoint: 0, attempts: 1, t: 0, skipT: 0 };
50
+ this.effects.push({ kind: 'hide' });
51
+ }
46
52
  disarm(): void { this.finish('left'); this.effects.push({ kind: 'hide' }); this.state = 'dormant'; }
47
53
  onPlayerDeath(player: { readonly x: number; readonly z: number }): false {
48
54
  if (this.attempt && this.near(player)) { this.finish('lost'); this.waitForReturn = true; this.effects.push({ kind: 'hide' }); this.state = 'dormant'; }
@@ -0,0 +1,107 @@
1
+ import type { Scope } from '@wildshard/engine/app/scope';
2
+ import { withOwner } from '@wildshard/engine/app/ownership';
3
+ import type { Physics } from '@wildshard/engine/physics/Physics';
4
+ import { groups } from '@wildshard/engine/physics/groups';
5
+ import { swapTerrainCollider } from '@wildshard/engine/physics/terrainTiles';
6
+ import { terrainTileHeight, type TerrainTileData } from '@wildshard/format/terrainTileBytes';
7
+
8
+ /**
9
+ * SHARD-SOURCE AP5 (J347): a watched part's solid boxes, as the dev hook's `swapColliders` hands them to a physics world.
10
+ * The page's world (the player's prediction) and the in-page server's world (the worker, over the harness port) both take
11
+ * them through `swapDevBoxes`, so the two sets never differ. DEVSERVER-only on both sides: each caller reaches this module
12
+ * behind the `__DEVSERVER__` define, so a production bundle drops it (engine `scripts/check-devserver.mjs`).
13
+ */
14
+ export interface DevBox {
15
+ readonly centre: readonly [number, number, number];
16
+ readonly half: readonly [number, number, number];
17
+ /** world rotation quaternion (x, y, z, w) */
18
+ readonly rotation: readonly [number, number, number, number];
19
+ }
20
+
21
+ /** The harness-port message that carries one part's boxes to the in-page server. */
22
+ export interface DevCollidersMessage { readonly wildshardDevColliders: string; readonly boxes: readonly DevBox[] }
23
+
24
+ const numbers = (value: unknown, length: number, above = -Infinity): boolean => Array.isArray(value) && value.length === length
25
+ && value.every(n => typeof n === 'number' && Number.isFinite(n) && n > above);
26
+ const isBox = (value: unknown): value is DevBox => typeof value === 'object' && value !== null && 'centre' in value && numbers(value.centre, 3)
27
+ && 'half' in value && numbers(value.half, 3, 0) && 'rotation' in value && numbers(value.rotation, 4);
28
+
29
+ export const isDevColliders = (value: unknown): value is DevCollidersMessage => typeof value === 'object' && value !== null
30
+ && 'wildshardDevColliders' in value && typeof value.wildshardDevColliders === 'string' && 'boxes' in value && Array.isArray(value.boxes) && value.boxes.every(isBox);
31
+
32
+ /**
33
+ * Replace part `name`'s boxes in `physics`: the new set is made under a fresh child of `owner` first, then the old set's
34
+ * scope is disposed (its colliders leave the world with it). An empty set removes the part's boxes.
35
+ */
36
+ export function swapDevBoxes(physics: Physics, owner: Scope, held: Map<string, Scope>, name: string, boxes: readonly DevBox[]): void {
37
+ const old = held.get(name);
38
+ if (boxes.length === 0) held.delete(name);
39
+ else {
40
+ const scope = owner.child(`devColliders.${name}`);
41
+ withOwner(scope, () => {
42
+ for (const box of boxes) physics.world.createCollider(physics.R.ColliderDesc.cuboid(...box.half)
43
+ .setTranslation(...box.centre).setRotation({ x: box.rotation[0], y: box.rotation[1], z: box.rotation[2], w: box.rotation[3] })
44
+ .setCollisionGroups(groups('WORLD')));
45
+ });
46
+ held.set(name, scope);
47
+ }
48
+ old?.dispose();
49
+ }
50
+
51
+ /** SHARD-SOURCE AP18: a watched shard's whole ground, heights only (row-major, as the wire carries a terrain tile). */
52
+ export type DevGround = Pick<TerrainTileData, 'resolution' | 'x' | 'z' | 'size' | 'heights'>;
53
+ /** The harness-port message that carries the new ground to the in-page server. */
54
+ export interface DevGroundMessage { readonly wildshardDevGround: DevGround }
55
+
56
+ export const isDevGround = (value: unknown): value is DevGroundMessage => {
57
+ if (typeof value !== 'object' || value === null || !('wildshardDevGround' in value)) return false;
58
+ const ground = value.wildshardDevGround;
59
+ if (typeof ground !== 'object' || ground === null || !('resolution' in ground) || !('x' in ground) || !('z' in ground) || !('size' in ground) || !('heights' in ground)) return false;
60
+ const { resolution, x, z, size, heights } = ground;
61
+ return typeof resolution === 'number' && Number.isInteger(resolution) && resolution >= 2 && resolution <= 257 && [x, z, size].every(n => typeof n === 'number' && Number.isFinite(n))
62
+ && (size as number) > 0 && heights instanceof Float32Array && heights.length === resolution * resolution && heights.every(Number.isFinite);
63
+ };
64
+
65
+ /**
66
+ * Where feet at (x, y, z) stand once new solids are in: on the ground when they are under it, or on top of a box they are
67
+ * inside. Null when they are in neither (nothing to lift). A box's top is its highest point, a fair floor for a dev swap.
68
+ */
69
+ export function liftedFeet(x: number, y: number, z: number, heightAt: ((x: number, z: number) => number) | null, boxes: readonly DevBox[]): number | null {
70
+ let lifted: number | null = null;
71
+ if (heightAt !== null) { const ground = heightAt(x, z); if (y < ground - 0.02) lifted = ground; }
72
+ for (const box of boxes) {
73
+ const [qx, qy, qz, qw] = box.rotation, dx = x - box.centre[0], dy = (lifted ?? y) + 0.05 - box.centre[1], dz = z - box.centre[2];
74
+ // into the box's frame: the conjugate rotation, v + 2w(-q x v) + 2(-q x (-q x v))
75
+ const cx = -qy * dz + qz * dy, cy = -qz * dx + qx * dz, cz = -qx * dy + qy * dx;
76
+ const lx = dx + 2 * (qw * cx + (-qy * cz + qz * cy)), ly = dy + 2 * (qw * cy + (-qz * cx + qx * cz)), lz = dz + 2 * (qw * cz + (-qx * cy + qy * cx));
77
+ if (Math.abs(lx) > box.half[0] || Math.abs(ly) > box.half[1] || Math.abs(lz) > box.half[2]) continue;
78
+ // the box's world y extent: |R row y| . half
79
+ const r1 = 2 * (qx * qy + qw * qz), r2 = 1 - 2 * (qx * qx + qz * qz), r3 = 2 * (qy * qz - qw * qx);
80
+ const top = box.centre[1] + Math.abs(r1) * box.half[0] + Math.abs(r2) * box.half[1] + Math.abs(r3) * box.half[2];
81
+ if (top > (lifted ?? y)) lifted = top;
82
+ }
83
+ return lifted;
84
+ }
85
+
86
+ /** The new ground's height law, as the page's terrain field (`clientGround`) reads a collider: 0 off the lattice. */
87
+ export const devGroundHeight = (ground: DevGround): ((x: number, z: number) => number) => (x, z) => x < ground.x || z < ground.z || x > ground.x + ground.size || z > ground.z + ground.size ? 0 : terrainTileHeight(ground, x, z);
88
+
89
+ /**
90
+ * The in-page server's half of a ground swap: the new heightfield (in `held`'s scope, the last swap's going), the new
91
+ * height query, and every player under it lifted onto it (`place`: the wire counts it and the client snaps).
92
+ */
93
+ export function swapDevGround(physics: Physics, owner: Scope, held: { scope: Scope | null }, ground: DevGround, ports: {
94
+ readonly heightQuery: (heightAt: (x: number, z: number) => number) => void;
95
+ readonly players: () => Iterable<readonly [string, { readonly position: { readonly x: number; readonly y: number; readonly z: number }; readonly yaw: number }]>;
96
+ readonly place: (at: { x: number; y: number; z: number; yaw: number }, player: string) => void;
97
+ }): void {
98
+ const old = held.scope, scope = owner.child('devGround');
99
+ swapTerrainCollider(physics, ground, scope);
100
+ held.scope = scope; old?.dispose();
101
+ const heightAt = (x: number, z: number): number => terrainTileHeight(ground, x, z, { boundary: 'clamp' });
102
+ ports.heightQuery(heightAt);
103
+ for (const [id, player] of ports.players()) {
104
+ const y = liftedFeet(player.position.x, player.position.y, player.position.z, heightAt, []);
105
+ if (y !== null) ports.place({ x: player.position.x, y, z: player.position.z, yaw: player.yaw }, id);
106
+ }
107
+ }
@@ -0,0 +1,41 @@
1
+ import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
2
+ import { carryOutputDescriptor } from '@wildshard/engine/game/shardfile/outputDescriptor';
3
+
4
+ /**
5
+ * SHARD-SOURCE AP19 (J347): `wildshard watch`'s soft restart. A watched shard's quests, encounters, spawns or scripts
6
+ * changed: the in-page server restarts its world on the new sections, from a save it takes first (so progress and the
7
+ * player's place carry over), and the page rebuilds its quest views. These are the sections it takes; anything else (the
8
+ * state schema, the look, the ground) is a new shell or the hook's other calls. DEVSERVER-only on both sides, as
9
+ * `devColliders.ts` is (engine `scripts/check-devserver.mjs` refuses `wildshardDevRestart` in a production bundle).
10
+ */
11
+ // `questNpcs` and `clientScripts` are not here: only the page reads them and the hook rebuilds only the quest views, so a change
12
+ // to either is a new shell.
13
+ export const DEV_GAMEPLAY_SECTIONS = ['quests', 'questHost', 'encounters', 'directors', 'creatures', 'crowds', 'hooks', 'ledger', 'sim'] as const;
14
+ export type DevGameplaySection = typeof DEV_GAMEPLAY_SECTIONS[number];
15
+ /** The new rows of each section the watched source declares now; a section left out keeps the shell's. */
16
+ export type DevGameplay = Partial<Pick<Shardfile, DevGameplaySection>>;
17
+ /** Where the page's player stands: the restarted world puts its player there. */
18
+ export interface DevPlace { readonly x: number; readonly y: number; readonly z: number; readonly yaw: number }
19
+ /** The harness-port message that restarts the in-page server; its ports are the new game link and the reply's. */
20
+ export interface DevRestartMessage { readonly wildshardDevRestart: DevGameplay; readonly at: DevPlace | null }
21
+ /** The worker's answer on the reply port. */
22
+ export interface DevRestarted { readonly ok: boolean; readonly ms: number; readonly reason?: string }
23
+
24
+ const SECTIONS: ReadonlySet<string> = new Set(DEV_GAMEPLAY_SECTIONS);
25
+
26
+ export const isDevRestart = (value: unknown): value is DevRestartMessage => {
27
+ if (typeof value !== 'object' || value === null || !('wildshardDevRestart' in value) || !('at' in value)) return false;
28
+ const { wildshardDevRestart: gameplay, at } = value;
29
+ if (typeof gameplay !== 'object' || gameplay === null || Array.isArray(gameplay) || !Object.keys(gameplay).every(key => SECTIONS.has(key))) return false;
30
+ return at === null || (typeof at === 'object' && 'x' in at && 'y' in at && 'z' in at && 'yaw' in at && [at.x, at.y, at.z, at.yaw].every(n => typeof n === 'number' && Number.isFinite(n)));
31
+ };
32
+
33
+ /** `shard` with `gameplay`'s sections in place of its own, checked as a whole shardfile; the output descriptor carries over. */
34
+ export function withDevGameplay(shard: Shardfile, gameplay: DevGameplay): Shardfile {
35
+ const merged: Record<string, unknown> = { ...shard };
36
+ for (const section of DEV_GAMEPLAY_SECTIONS) if (gameplay[section] !== undefined) merged[section] = gameplay[section];
37
+ // oxlint-disable-next-line unicorn/prefer-structured-clone -- JSON wire normalization, as the product reader parses it
38
+ const next = parseShardfile(JSON.parse(JSON.stringify(merged)));
39
+ carryOutputDescriptor(shard, next);
40
+ return next;
41
+ }
@@ -313,6 +313,14 @@ export class EliteCore<S extends EliteCoreScript> {
313
313
  this.save();
314
314
  }
315
315
 
316
+ /** SERVER-CELLS SC10: a served cell slept this long with nobody in it: a fallen lair's timer spends it (a dusk lair still waits for dusk). */
317
+ slept(seconds: number): void {
318
+ for (const e of this.entries) if ((e.state === 'dead' || e.state === 'absent') && e.timer > 0) {
319
+ e.timer = Math.max(0, e.timer - seconds);
320
+ if (e.timer === 0 && (e.script.def.rule === 'dusk' || e.script.def.rule === 'night')) e.waitDusk = true;
321
+ }
322
+ }
323
+
316
324
  /** Copy the lair rules only, preserving their historical wire field order and null last-hit sentinel. */
317
325
  snapshot(): EliteCoreContinuation {
318
326
  // A page's save can hold a lair this world has no row for: its record rides along, for the world that has one.
@@ -108,6 +108,9 @@ export class ResidencyAllocator {
108
108
  if (!Number.isFinite(this.playing) || this.playing <= 0) throw new RangeError('Invalid residency envelope');
109
109
  }
110
110
 
111
+ /** The playing envelope this allocator admits against (the tier's, else §3.2's). */
112
+ envelope(): number { return this.playing; }
113
+
111
114
  /** Admit a claim, or share one already held under the same id; null when it cannot fit even after eviction. */
112
115
  reserve(claim: ResidencyClaim): ResidencyLease | null { return this.reserveClaim(claim, 0); }
113
116
  /** Speculative IO may use existing headroom, never evict another owner's ready world. */
@@ -10,13 +10,16 @@ export interface PlacementFile {
10
10
  readonly channel: 'production' | 'staging';
11
11
  /** Rises with every write; an older file is never believed (J179). */
12
12
  readonly serial: number;
13
- readonly cells: readonly { readonly instance: string; readonly slug: string; readonly cell: readonly [number, number] }[];
13
+ /** SA47: `hash` is the channel pointer's shardfile (the raw upload), so a box whose build's book lacks the slug opens it from the
14
+ * cook's `index/<build>/<hash>.json`. A file from before SA47 names none. */
15
+ readonly cells: readonly { readonly instance: string; readonly slug: string; readonly cell: readonly [number, number]; readonly hash?: string }[];
14
16
  }
15
17
  const placedId = v.pipe(v.string(), v.regex(/^_?[a-z0-9]+(?:-[a-z0-9]+)*$/u), v.maxLength(64));
16
18
  const placedSpot = v.pipe(v.number(), v.integer());
19
+ const placedHash = v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/u));
17
20
  /** A placement file's body, once its signature has held. The spot's bounds are `placeCell`'s. */
18
21
  export const PlacementSchema: v.GenericSchema<PlacementFile> = v.object({ kind: v.literal('placement'), channel: v.picklist(['production', 'staging']), serial: v.pipe(v.number(), v.integer(), v.minValue(0)),
19
- cells: v.pipe(v.array(v.object({ instance: placedId, slug: placedId, cell: v.tuple([placedSpot, placedSpot]) })), v.maxLength(49)) });
22
+ cells: v.pipe(v.array(v.object({ instance: placedId, slug: placedId, cell: v.tuple([placedSpot, placedSpot]), hash: v.exactOptional(placedHash) })), v.maxLength(49)) });
20
23
  /** The file on R2: the body as signed, and its signature in hex (as the release file's, `releaseRows.ts`). */
21
24
  export const SignedPlacementSchema: v.GenericSchema<{ readonly body: string; readonly signature: string }> = v.object({ body: v.string(), signature: v.string() });
22
25
  /** The API's placement key (SA33a, `~/.config/wildshard/placement-signing-key.pub.pem`), SPKI DER in hex: the box's PLACEMENT_PUBLIC_KEY. */
@@ -5,13 +5,14 @@ import { pageStateOf } from '../shardfile/runtimeState';
5
5
  /** A boss row's two durable flags: beaten (its record's `defeated`) and paid (its record's `rewardTaken`). */
6
6
  export interface BossRowFlagNames { readonly defeated: string; readonly paid: string }
7
7
  /** The shard flags a boss record reads and writes. */
8
- export interface BossRowFlags { has: (flag: string) => boolean; set: (flag: string) => void }
8
+ export interface BossRowFlags { has: (flag: string) => boolean; set: (flag: string, on?: boolean) => void }
9
9
 
10
10
  /** A boss row's record kept on the shard's own flags (no save of its own): `saved` to start from, `persist` to write. */
11
11
  export function bossFlagRecord(flags: BossRowFlags, names: BossRowFlagNames): { saved: BossSaved; persist: (value: BossSaved) => void } {
12
12
  const defeated = flags.has(names.defeated);
13
13
  return { saved: { defeated, rewardTaken: flags.has(names.paid), kills: defeated ? 1 : 0 },
14
- persist: (value) => { if (value.defeated) flags.set(names.defeated); if (value.rewardTaken) flags.set(names.paid); } };
14
+ // SC10: a record goes back to not beaten only when a served world's boss stands again (`returnBeaten`), and both flags clear with it
15
+ persist: (value) => { if (!value.defeated) { flags.set(names.defeated, false); flags.set(names.paid, false); return; } flags.set(names.defeated); if (value.rewardTaken) flags.set(names.paid); } };
15
16
  }
16
17
 
17
18
  const finite = v.pipe(v.number(), v.finite());
@@ -5,7 +5,9 @@
5
5
  * missing target in the table's own order.
6
6
  *
7
7
  * A target is served when it is a file under `mounts/`, a `cook.json` mount row over a file the product holds, a product
8
- * file at `/shardfiles/<slug>/<path>`, or an engine file: the caller says which URLs its host serves itself. */
8
+ * file at `/shardfiles/<slug>/<path>`, or an engine file: the caller says which URLs its host serves itself. A `phone` row's
9
+ * target is also served when its source is (SHARD-SIZE S12d): the cook makes that phone file from the source, as a shard that
10
+ * dropped its hand-made phone set (Sky Reach rev 2 on) expects. */
9
11
 
10
12
  /** Read access to one product: the paths it holds and the bytes of one of them. */
11
13
  export interface Ktx2TableProduct {
@@ -34,13 +36,30 @@ export function ktx2TableTargets(table: unknown): readonly string[] {
34
36
  return targets;
35
37
  }
36
38
 
39
+ /** Each `phone` row's target and the source the cook makes it from when the product lacks it (`phoneTier`, S12d): a row whose
40
+ * source and target are the same kind of file (GLB or KTX2). */
41
+ export function phoneRowSources(table: unknown): ReadonlyMap<string, string> {
42
+ const rows = new Map<string, string>(), kind = (url: string): string | undefined => /\.(glb|ktx2)$/u.exec(url)?.[1];
43
+ const walk = (value: unknown): void => {
44
+ if (Array.isArray(value)) { for (const child of value) walk(child); return; }
45
+ if (!isRow(value)) return;
46
+ for (const [key, child] of Object.entries(value)) {
47
+ if (key === 'phone' && isRow(child)) {
48
+ for (const [source, target] of Object.entries(child)) if (typeof target === 'string' && kind(target) !== undefined && kind(source) === kind(target) && !rows.has(target)) rows.set(target, source);
49
+ } else walk(child);
50
+ }
51
+ };
52
+ walk(table);
53
+ return rows;
54
+ }
55
+
37
56
  /** The table's targets nothing serves, each once, first missing first. */
38
57
  export function missingKtx2Targets(product: Ktx2TableProduct, engineFile: (url: string) => boolean = () => false): { readonly total: number; readonly missing: readonly string[] } {
39
58
  const paths = new Set(product.paths());
40
59
  const discovery = [...paths].find(path => DISCOVERY.test(path));
41
60
  if (discovery === undefined) return { total: 0, missing: [] };
42
61
  const document = parse(product.read(discovery), discovery);
43
- const targets = ktx2TableTargets(isRow(document) && isRow(document['native']) ? document['native']['ktx2'] : undefined);
62
+ const table = isRow(document) && isRow(document['native']) ? document['native']['ktx2'] : undefined, targets = ktx2TableTargets(table);
44
63
  if (targets.length === 0) return { total: 0, missing: [] };
45
64
  const mounted = new Set<string>();
46
65
  if (paths.has('cook.json')) {
@@ -51,7 +70,8 @@ export function missingKtx2Targets(product: Ktx2TableProduct, engineFile: (url:
51
70
  const home = `/shardfiles/${DISCOVERY.exec(discovery)?.[1] ?? ''}/`;
52
71
  const served = (url: string): boolean => paths.has(`mounts${url}`) || mounted.has(url)
53
72
  || (url.startsWith(home) && paths.has(url.slice(home.length))) || engineFile(url);
54
- return { total: targets.length, missing: [...new Set(targets.filter(url => !served(url)))] };
73
+ const cooked = phoneRowSources(table), made = (url: string): boolean => { const source = cooked.get(url); return source !== undefined && served(source); };
74
+ return { total: targets.length, missing: [...new Set(targets.filter(url => !served(url) && !made(url)))] };
55
75
  }
56
76
 
57
77
  /** Refuse a product whose KTX2 table names a file nothing serves. */