threedog 1.1.0 → 1.3.0

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 (370) hide show
  1. package/CHANGELOG.md +893 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +187 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +17 -7
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +8 -7
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +50 -28
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +36 -15
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +47 -4
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +17 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +30 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +24 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +7 -2
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +75 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +10 -9
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +72 -79
  180. package/docs/recipes/63-third-person-start.md +48 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/.threedog/content-index.json +1 -1
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/.threedog/content-index.json +1 -1
  189. package/examples/perf-island/GAMEMAP.md +3 -3
  190. package/examples/perf-island/picture/lights.js +2 -1
  191. package/examples/plain-picture/GAMEMAP.md +1 -1
  192. package/examples/rc2d/GAMEMAP.md +1 -1
  193. package/examples/styletest/.threedog/content-index.json +1 -1
  194. package/examples/styletest/GAMEMAP.md +2 -2
  195. package/examples/styletest/main.js +1 -1
  196. package/examples/techniques/interior-light/README.md +3 -3
  197. package/examples/techniques/interior-light/interiorLight.js +2 -4
  198. package/examples/techniques/interior-light/picture/lights.js +2 -1
  199. package/examples/techniques/modular-building/picture/lights.js +3 -1
  200. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  201. package/examples/techniques/procedural-animation/README.md +1 -1
  202. package/examples/techniques/procedural-animation/main.js +1 -1
  203. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  204. package/examples/world/.threedog/content-index.json +1 -1
  205. package/examples/world/GAMEMAP.md +2 -3
  206. package/examples/world/art/humanoid.js +1 -1
  207. package/examples/world/main.js +6 -3
  208. package/index.d.ts +2 -2
  209. package/llms.txt +101 -0
  210. package/modules/ambience/Ambience.js +21 -5
  211. package/modules/calendar/index.js +9 -5
  212. package/modules/calendar/schedule.js +23 -8
  213. package/modules/camera/FirstPersonCamera.js +3 -1
  214. package/modules/camera/FollowCamera.js +10 -5
  215. package/modules/camera/RtsCamera.js +4 -3
  216. package/modules/camera/common.js +70 -8
  217. package/modules/camera/contract.js +1 -1
  218. package/modules/characters/Character.js +16 -10
  219. package/modules/characters/NPC.js +31 -19
  220. package/modules/characters/assetModel.js +14 -9
  221. package/modules/characters/astar.js +6 -1
  222. package/modules/characters/contract.js +2 -2
  223. package/modules/characters/index.js +34 -22
  224. package/modules/characters/movers/manual.js +1 -1
  225. package/modules/characters/movers/rapier.js +17 -2
  226. package/modules/characters/movers/simple.js +1 -1
  227. package/modules/characters/movers/support.js +16 -7
  228. package/modules/characters/npcAvoid.js +2 -2
  229. package/modules/characters/npcSim.js +3 -2
  230. package/modules/characters/pathAsync.js +24 -8
  231. package/modules/characters/pathJob.js +1 -1
  232. package/modules/characters/player.js +10 -9
  233. package/modules/characters/playerStrings.js +5 -5
  234. package/modules/characters/proceduralRig.js +5 -5
  235. package/modules/characters/useModel.js +6 -0
  236. package/modules/characters/walkTo.js +1 -1
  237. package/modules/collision/Collision.js +29 -18
  238. package/modules/collision/grid.js +22 -4
  239. package/modules/content/index.js +3 -1
  240. package/modules/content/loader.js +1 -1
  241. package/modules/content/models.js +82 -33
  242. package/modules/content/props.js +2 -1
  243. package/modules/content/rules.js +11 -5
  244. package/modules/content/templates.js +3 -3
  245. package/modules/content/words.js +2 -2
  246. package/modules/debug/DebugPanel.js +9 -9
  247. package/modules/flow/index.js +9 -6
  248. package/modules/gameplay/Dialogue.js +34 -20
  249. package/modules/gameplay/Interactions.js +19 -15
  250. package/modules/gameplay/Inventory.js +9 -4
  251. package/modules/gameplay/Quests.js +12 -10
  252. package/modules/gameplay/pickups.js +23 -11
  253. package/modules/grid/index.js +1 -1
  254. package/modules/grid/preview.js +2 -2
  255. package/modules/grid/tiles.js +1 -1
  256. package/modules/hlod/index.js +4 -1
  257. package/modules/hud/index.js +47 -10
  258. package/modules/hud/parts.js +28 -9
  259. package/modules/level/geometry.js +8 -3
  260. package/modules/level/index.js +10 -5
  261. package/modules/level/load.js +4 -2
  262. package/modules/lights/sources.js +1 -1
  263. package/modules/music/Music.js +22 -4
  264. package/modules/nav/index.js +20 -10
  265. package/modules/particles/Particles.js +31 -14
  266. package/modules/particles/effect.js +20 -5
  267. package/modules/particles/lit.js +72 -0
  268. package/modules/photo/Photo.js +72 -28
  269. package/modules/photo/pathTrace.js +106 -0
  270. package/modules/rigid/RigidBodies.js +23 -14
  271. package/modules/rigid/Vehicles.js +3 -13
  272. package/modules/rigid/sync.js +2 -1
  273. package/modules/settings/Settings.js +52 -20
  274. package/modules/settings/apply.js +23 -9
  275. package/modules/settings/sections.js +39 -6
  276. package/modules/settings/strings.js +2 -0
  277. package/modules/settings/view.js +19 -3
  278. package/modules/sky/dome.js +15 -3
  279. package/modules/sky/environment.js +28 -12
  280. package/modules/sky/fog.js +1 -1
  281. package/modules/sky/frame.js +6 -1
  282. package/modules/sky/shader.js +4 -3
  283. package/modules/sky/skyModule.js +8 -4
  284. package/modules/swarm/Swarm.js +1 -1
  285. package/modules/terrain/ChunkManager.js +61 -15
  286. package/modules/terrain/chunkJob.js +2 -2
  287. package/modules/terrain/index.js +20 -5
  288. package/modules/terrain/terrainEdit.js +8 -4
  289. package/modules/terrain/terrainTexture.js +4 -2
  290. package/modules/timeline/Timeline.js +4 -3
  291. package/modules/timeline/Tween.js +3 -0
  292. package/modules/timeline/letterbox.js +1 -0
  293. package/modules/triggers/index.js +36 -17
  294. package/modules/vegetation/Vegetation.js +81 -19
  295. package/modules/vegetation/densityMap.js +13 -8
  296. package/modules/vegetation/draw.js +147 -24
  297. package/modules/vegetation/groundChunks.js +20 -5
  298. package/modules/vegetation/index.js +3 -3
  299. package/modules/vegetation/modelGeometry.js +9 -4
  300. package/modules/water/Water.js +11 -8
  301. package/modules/weather/Weather.js +7 -2
  302. package/modules/weather/shaders.js +25 -5
  303. package/modules/weather/weatherDraw.js +20 -6
  304. package/modules/world/World.js +2 -1
  305. package/modules/world/index.js +2 -2
  306. package/modules/world/persist.js +6 -2
  307. package/modules/world/views.js +15 -2
  308. package/package.json +5 -1
  309. package/presets.js +5 -5
  310. package/render/PostFX.js +102 -42
  311. package/render/backend.js +142 -16
  312. package/render/bindingLimits.js +59 -0
  313. package/render/cascades.js +3 -1
  314. package/render/cascades.tsl.js +2 -0
  315. package/render/daylight.js +7 -1
  316. package/render/detail.js +7 -4
  317. package/render/effects.js +27 -8
  318. package/render/fogLook.js +24 -0
  319. package/render/fuse.js +5 -2
  320. package/render/fx/compareLevel.tsl.js +23 -0
  321. package/render/fx/detail.tsl.js +9 -7
  322. package/render/fx/index.js +9 -2
  323. package/render/fx/library.tsl.js +1 -0
  324. package/render/fx/lightShaft.tsl.js +114 -0
  325. package/render/fx/noise.tsl.js +25 -8
  326. package/render/fx/objectOrigin.tsl.js +39 -10
  327. package/render/fx/particles.tsl.js +23 -6
  328. package/render/fx/patchNodes.tsl.js +17 -12
  329. package/render/fx/pcss.tsl.js +51 -0
  330. package/render/fx/postWebGPU.tsl.js +104 -29
  331. package/render/fx/sky.tsl.js +3 -9
  332. package/render/fxNumbers.js +10 -4
  333. package/render/impostor.tsl.js +107 -0
  334. package/render/lighting.js +33 -1
  335. package/render/lightmap.js +42 -28
  336. package/render/lights.js +19 -3
  337. package/render/materials.js +6 -4
  338. package/render/mergeCommon.js +4 -1
  339. package/render/occlusion.js +14 -4
  340. package/render/patches.js +79 -41
  341. package/render/postRuns.js +32 -0
  342. package/render/postWebGL.js +97 -10
  343. package/render/probes.js +10 -14
  344. package/render/shaderErrors.js +44 -7
  345. package/render/shadowCache.tsl.js +33 -5
  346. package/render/shadows.js +42 -16
  347. package/render/slots.js +8 -5
  348. package/render/vertexInputs.js +52 -0
  349. package/types/core.d.ts +115 -47
  350. package/types/gameplay.d.ts +56 -23
  351. package/types/generated/core/audio/Audio.d.ts +27 -1
  352. package/types/generated/core/base/Random.d.ts +1 -1
  353. package/types/generated/core/input/Input.d.ts +6 -8
  354. package/types/generated/core/input/inputSeat.d.ts +1 -1
  355. package/types/generated/core/inspect/Budget.d.ts +26 -0
  356. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  357. package/types/generated/core/saves/Saves.d.ts +10 -7
  358. package/types/generated/core/saves/session.d.ts +8 -2
  359. package/types/generated/core/scene/Rays.d.ts +1 -3
  360. package/types/generated/core/scene/Views.d.ts +17 -3
  361. package/types/generated/modules/particles/Particles.d.ts +1 -1
  362. package/types/generated/modules/world/World.d.ts +2 -1
  363. package/types/generated/render/PostFX.d.ts +35 -9
  364. package/types/physics.d.ts +796 -764
  365. package/types/pixel.d.ts +1 -1
  366. package/types/tsl.d.ts +62 -1
  367. package/types/world.d.ts +12 -3
  368. package/ui/Focus.js +7 -5
  369. package/ui/Parts.js +1 -1
  370. package/ui/touchPart.js +6 -3
@@ -12,7 +12,7 @@
12
12
  // The rollback point is a copy (structuredClone of every part's save()): save() may return the live object, which load() then writes into.
13
13
  // A part about to load whose save() gives nothing to copy (null, or it threw) goes back to its new-game state; with none of that either it cannot go back, and a failed load says so.
14
14
  import { toast } from '../../ui/UI.js';
15
- import { fmt, warnOnce } from '../base/validate.js';
15
+ import { fmt, warnOnce, isThenable, syncOnly } from '../base/validate.js';
16
16
  import { reportError } from '../base/errors.js';
17
17
  import { codedError, coded } from '../base/errorHints.js';
18
18
  import { FORMAT, readSave, parseSave, upgradePart, partVersion } from './saveVersions.js';
@@ -23,6 +23,7 @@ const DEV_STRINGS = {
23
23
  partAt: "load() of save part '{k}'", adoptAt: "load() of save part '{k}' (registered after the save was loaded)",
24
24
  rollback: "rollback of save part '{k}' after a failed load (that part may be half-loaded; the other parts rolled back)",
25
25
  noRollback: "save part '{k}' keeps what the failed load gave it: its save() gave nothing before the load and it has no new-game state to go back to (the other parts rolled back)",
26
+ changed: "save part '{k}' was unloaded or replaced while '{slot}' was loading, so its data had nobody to take it; the load failed and rolled back (the data stays in the save)",
26
27
  notData: "save() of save part '{k}' returned {got}, which a save cannot hold; return plain data, or null when there is nothing to save",
27
28
  notNumber: "save() of save part '{k}' holds {got} at {path}, which a save cannot hold (it would come back as null); save a finite number, or leave the field out",
28
29
  listener: 'a listener of event {name} threw while the part loaded: {msg}',
@@ -44,45 +45,57 @@ const loadError = (k, err, slot) => Object.assign(codedError('save-load-threw',
44
45
  * @internal
45
46
  */
46
47
  export function applySave(s, data, slot) {
48
+ return marked(s, () => {
49
+ const r = readSave(data, s.providers, slot);
50
+ if ('reason' in r) {
51
+ if (r.reason !== 'missing') { warnOnce(coded('save-refused', r.dev)); // handled: the player is told, nothing changed
52
+ toast(s.engine, s.engine.t('saves.' + r.reason), { kind: 'error', ms: 5000 }); }
53
+ return false;
54
+ }
55
+ return applyRead(s, r, slot, false);
56
+ });
57
+ }
58
+
59
+ /** fn under the marker, from its first line until what it returned settled (top of stateReplace.js) */
60
+ function marked(s, fn) {
47
61
  const q = s._replace, job = q.job;
48
62
  q.begin();
49
63
  let out;
50
- try { out = checkAndApply(s, data, slot); } catch (err) { q.end(); throw err; }
64
+ try { out = fn(); } catch (err) { q.end(); throw err; }
51
65
  if (typeof out !== 'boolean') return out.finally(() => q.endOf(job));
52
66
  q.end();
53
67
  return out;
54
68
  }
55
69
 
56
- /** The body of applySave, under the marker */
57
- function checkAndApply(s, data, slot) {
58
- const r = readSave(data, s.providers, slot);
59
- if ('reason' in r) {
60
- if (r.reason !== 'missing') { warnOnce(coded('save-refused', r.dev)); // handled: the player is told, nothing changed
61
- toast(s.engine, s.engine.t('saves.' + r.reason), { kind: 'error', ms: 5000 }); }
62
- return false;
63
- }
70
+ /** Apply parts already read and migrated (r.list): the one part-application protocol. late: one part registered after its save was loaded (adoptPart);
71
+ * it adds to the state instead of replacing it, so the parts nobody owns, background results and the saved-state generation stay, and only that part rolls back */
72
+ function applyRead(s, r, slot, late) {
64
73
  const e = s.engine, foreign0 = s._foreign;
65
74
  let before; // the rollback point, a copy (rollbackPoint)
66
- try { before = rollbackPoint(s, slot, r.list); } catch (err) { reportError(e, err, `saves.apply('${slot}')`); return false; }
75
+ try { before = rollbackPoint(s, slot, r.list, late); } catch (err) { reportError(e, err, `saves.apply('${slot}')`); return false; }
67
76
  const ev = e.events, scope = []; // this load's capture scope: listener errors from now until the load settled (top of the file)
68
77
  ev._scopes.push(scope);
69
78
  const settled = () => { const i = ev._scopes.lastIndexOf(scope); if (i >= 0) ev._scopes.splice(i, 1); };
70
79
  let out;
71
- try { out = applyParts(s, e, r, slot, before, foreign0, scope); } catch (err) { settled(); throw err; }
80
+ try { out = applyParts(s, e, r, slot, before, foreign0, scope, late); } catch (err) { settled(); throw err; }
72
81
  if (typeof out !== 'boolean') return out.finally(settled);
73
82
  settled();
74
83
  return out;
75
84
  }
76
85
 
77
86
  /** The rest of applySave, under the load's capture scope */
78
- function applyParts(s, e, r, slot, before, foreign0, scope) {
79
- const q = s._replace;
80
- const keepResults = e.commits.invalidate(); e.ops._mark('(load)'); // old background results die with the old world; the op log shows where the load cut in
81
- const generation = q.generation++;
82
- q.changed();
83
- s._foreign = r.foreign;
87
+ function applyParts(s, e, r, slot, before, foreign0, scope, late) {
88
+ const q = s._replace, turn = q.job.turn, generation = q.generation;
89
+ let keepResults = () => {};
90
+ if (!late) {
91
+ keepResults = e.commits.invalidate(); e.ops._mark('(load)'); // old background results die with the old world; the op log shows where the load cut in
92
+ q.generation++; q.changed();
93
+ s._foreign = r.foreign;
94
+ }
95
+ const reached = new Set();
84
96
  const fail = err => {
85
- keepResults(); q.generation = generation; q.changed(true); // the old world stays, and what it was waiting for with it
97
+ keepResults();
98
+ if (!late) { q.generation = generation; q.changed(true); } // the old world stays, and what it was waiting for with it
86
99
  // a malformed save (refuseSave, save-bad-record) is the save's fault, not the game's: refused like a corrupt save (warning + toast), so it
87
100
  // does not freeze gameplay as a code error would; a load() / listener / afterLoad that throws is a bug and goes through the error tiers
88
101
  const refused = err?.cause?.code === 'save-bad-record';
@@ -91,12 +104,11 @@ function applyParts(s, e, r, slot, before, foreign0, scope) {
91
104
  s._foreign = foreign0;
92
105
  const back = readSave(before, s.providers, '(rollback)');
93
106
  // every part reloads its pre-load state; a part that throws again is reported (once) and the rest still roll back
94
- const onPart = er => reportError(e, er, fmt(DEV_STRINGS.rollback, { k: er.part }), { soft: true });
95
- const undone = 'list' in back ? e.ops.allow(() => runParts(s, back.list, '(rollback)', scope, onPart)) : true;
107
+ const undone = 'list' in back ? e.ops.allow(() => runParts(s, back.list, '(rollback)', scope, onRollback(e), turn)) : true;
96
108
  // a part that refused its data took none of it: it has nothing to go back from
97
- for (const [k] of r.list) if (!Object.hasOwn(before.parts, k) && !(refused && k === err.part)) reportError(e, codedError('save-load-threw', fmt(DEV_STRINGS.noRollback, { k })), `saves.apply('${slot}')`, { soft: true });
109
+ for (const [k] of r.list) if (reached.has(k) && !Object.hasOwn(before.parts, k) && !(refused && k === err.part)) reportError(e, codedError('rollback-incomplete', fmt(DEV_STRINGS.noRollback, { k })), `saves.apply('${slot}')`);
98
110
  // a session door announces its own failure, after its clocks came back
99
- const failed = () => { if (!e.session._busy) e.events.emit('session:failed', { kind: 'quick', slot }); return false; };
111
+ const failed = () => { if (!e.session._busy && !late) e.events.emit('session:failed', { kind: 'quick', slot }); return false; };
100
112
  if (undone === true) return failed();
101
113
  q.hold(); // a rollback that waits on an async part holds gameplay too, whichever way the load failed
102
114
  return undone.then(failed);
@@ -109,7 +121,7 @@ function applyParts(s, e, r, slot, before, foreign0, scope) {
109
121
  return hooks === true ? true : hooks.then(() => true, fail);
110
122
  };
111
123
  let out;
112
- try { out = e.ops.allow(() => runParts(s, r.list, slot, scope)); } catch (err) { return fail(err); } // loading writes state outside ops on purpose (guard allows it)
124
+ try { out = e.ops.allow(() => runParts(s, r.list, slot, scope, null, turn, reached)); } catch (err) { return fail(err); } // loading writes state outside ops on purpose (guard allows it)
113
125
  if (out === true) return partsDone();
114
126
  q.hold(); // a part still loading (its load() returned a Promise): gameplay waits until every part is applied. A fully sync load never takes it
115
127
  return out.then(partsDone, fail);
@@ -118,8 +130,9 @@ function applyParts(s, e, r, slot, before, foreign0, scope) {
118
130
  /** The rollback point: every part's save(), copied so a load() writing into the object its save() returned cannot change it.
119
131
  * A part whose data cannot be copied throws (save-part-threw): without a true copy a failed load could not be undone.
120
132
  * list: the parts about to load; those with nothing to copy take their new-game data (top of the file) */
121
- function rollbackPoint(s, slot, list) {
133
+ function rollbackPoint(s, slot, list, late) {
122
134
  const data = s._collect().data, S = s.engine.session, base = S._base ? S._baseData() : { parts: {}, versions: {} };
135
+ if (late) for (const k of Object.keys(data.parts)) if (!list.some(([n]) => n === k)) { delete data.parts[k]; delete data.versions[k]; } // only the late part loads, so only it goes back
123
136
  for (const [k] of list) if (!Object.hasOwn(data.parts, k) && Object.hasOwn(base.parts, k)) { data.parts[k] = base.parts[k]; data.versions[k] = base.versions[k]; }
124
137
  for (const k of Object.keys(data.parts)) {
125
138
  try { data.parts[k] = structuredClone(data.parts[k]); }
@@ -149,23 +162,44 @@ function callLoad(s, fn, scope) {
149
162
  }
150
163
 
151
164
  /**
152
- * Load parts in order; a part returning a Promise makes the rest wait for it. A failing part throws (or rejects) with the part named,
153
- * unless onFail is given (rollback): then onFail(err) is called and the next part loads anyway.
165
+ * The one loop that calls a part's load(): a load, its rollback, a late part, an atomic op's rollback. Parts load in order; a part returning a Promise makes
166
+ * the rest wait for it, except with sync (an atomic op's rollback): there a Promise is refused as at the other sync-only sites (syncOnly), reported, and the
167
+ * next part loads at once. That rollback has to be whole before the op returns: the outer op of a nested failure goes on, commits and runs its after hooks
168
+ * right after, and a part load still pending would then write the old value over it, its change events past the mute. A failing part throws (or rejects) with the part named, unless onFail is given (rollback): then onFail(err) is called and the next
169
+ * part loads anyway. A part whose provider is no longer the one registered under its key (its module unloaded or replaced while an earlier part awaited)
170
+ * cannot take the data read for that provider (review l2 #4): the load fails with save-provider-changed and rolls back, a rollback reports it and goes on. turn: the replacement's identity for load(); none outside one (an atomic op's rollback).
154
171
  */
155
- function runParts(s, list, slot, scope, onFail = null) {
156
- const failed = (k, err) => { const er = loadError(k, err, slot); if (!onFail) throw er; onFail(er); }, { turn } = s._replace.job;
172
+ function runParts(s, list, slot, scope, onFail, turn, reached, sync = false) {
173
+ const failed = (k, err, own) => { const er = own ? Object.assign(own, { part: k }) : loadError(k, err, slot); if (!onFail) throw er; onFail(er); };
157
174
  const step = i => {
158
175
  for (; i < list.length; i++) {
159
176
  const [k, p, d] = list[i];
177
+ if (s.providers.get(k) !== p) { failed(k, null, codedError('save-provider-changed', fmt(DEV_STRINGS.changed, { k, slot }))); continue; } // a rollback reports it and goes on; a load fails and rolls back
160
178
  let r;
179
+ reached?.add(k); // a part that started loading may hold half of the new data; one never reached holds nothing of it
161
180
  try { r = callLoad(s, () => p.load(d, turn), scope); } catch (err) { failed(k, err); continue; }
162
- if (r && typeof r.then === 'function') return r.then(() => step(i + 1), err => { failed(k, err); return step(i + 1); });
181
+ if (!isThenable(r)) continue;
182
+ if (sync) { try { syncOnly(r, `save part '${k}' load() in ${slot}`, true); } catch (err) { failed(k, null, err); } continue; }
183
+ return r.then(() => step(i + 1), err => { failed(k, err); return step(i + 1); });
163
184
  }
164
185
  return true;
165
186
  };
166
187
  return step(0);
167
188
  }
168
189
 
190
+ /** A rollback goes past a part that throws again: reported once (a gameplay error: engine.error / engine:error, not soft, an incomplete rollback is a broken state), and the rest still go back */
191
+ const onRollback = e => er => reportError(e, er, fmt(DEV_STRINGS.rollback, { k: er.part }));
192
+
193
+ /**
194
+ * Put plain part data back outside a load (an atomic op's rollback, core/ops/opsAtomic.js): the same loop, past a part that throws, synchronous only:
195
+ * a part whose load() returns a Promise is reported (engine-misuse) and not waited for. A normal load keeps waiting for async parts.
196
+ * @param {any} s the Saves instance
197
+ * @param {[string, any, any][]} list
198
+ * @param {string} where
199
+ * @internal
200
+ */
201
+ export const restoreParts = (s, list, where) => { runParts(s, list, where, [], onRollback(s.engine), undefined, undefined, true); };
202
+
169
203
  /**
170
204
  * A part registered after a save was loaded (a module installed later): hand it its data from that save in a turn of its own. Idle that is now. During a
171
205
  * replacement it is after it, whole: its first line would write into a half-loaded state, and a newer load waits for it instead of having this older data
@@ -174,21 +208,34 @@ function runParts(s, list, slot, scope, onFail = null) {
174
208
  * @param {string} key
175
209
  * @internal
176
210
  */
177
- export function adoptPart(s, key) {
178
- const f = s._foreign, q = s._replace, where = fmt(DEV_STRINGS.adoptAt, { k: key });
179
- q.run(null, () => {
180
- const p = s.providers.get(key);
181
- if (s._foreign !== f || !p || !Object.hasOwn(f.parts, key)) return;
211
+ export function adoptPart(s, key, part) {
212
+ const f = s._foreign, q = s._replace, where = fmt(DEV_STRINGS.adoptAt, { k: key }), L = s.engine.loading;
213
+ // engine.loading.settled() waits for it: use(mod); await loading.settled() says the module runs with its data back, and gameplay is no longer held for it.
214
+ // Its own set, not the inits': a failed replaces tells module:restored once the inits are done, and its content must land on the line after use() threw
215
+ L._track(q.run(null, () => {
216
+ // the provider this data was kept for: one removed meanwhile, or another under the same key, does not get it (review l2 #4)
217
+ if (s._foreign !== f || s.providers.get(key) !== part || !Object.hasOwn(f.parts, key)) return;
182
218
  const d = f.parts[key], v = f.versions[key] ?? 1;
183
219
  delete f.parts[key]; delete f.versions[key];
184
220
  // data the part could not take stays unattached, and collectParts writes it instead of the part's empty state: the next save must not lose it
185
- const refused = err => { if (s._foreign === f) { f.parts[key] = d; f.versions[key] = v; } reportError(s.engine, err, where); };
221
+ const back = () => { if (s._foreign === f && !Object.hasOwn(f.parts, key)) { f.parts[key] = d; f.versions[key] = v; } };
222
+ let list;
186
223
  try {
187
- if (v > p.version) throw codedError('save-refused', `save part '${key}' is version ${v}, this build reads up to ${p.version}`);
188
- const r = s.engine.ops.allow(() => p.load(upgradePart(key, p, d, v, f.whole), q.job.turn));
189
- if (r && typeof r.then === 'function') return r.catch(refused);
190
- } catch (err) { refused(err); }
191
- }, true);
224
+ if (v > part.version) throw codedError('save-refused', `save part '${key}' is version ${v}, this build reads up to ${part.version}`);
225
+ list = [[key, part, upgradePart(key, part, d, v, f.whole)]];
226
+ } catch (err) {
227
+ back();
228
+ if (err?.code === 'save-refused') warnOnce(err.message); // handled like an ordinary load's version refusal: newer data kept, nothing reported as an engine error
229
+ else reportError(s.engine, err, where);
230
+ return;
231
+ }
232
+ // the protocol of a load: marker, freeze while it waits, a rollback point of this part, afterLoad. Called bare, ops and fixed steps would read a half-loaded part
233
+ part.adopting = true; // a remove() meanwhile keeps this data, not the half-loaded state (Saves.define)
234
+ const done = ok => { part.adopting = false; if (!ok) back(); return ok; };
235
+ let out;
236
+ try { out = marked(s, () => applyRead(s, { list }, `(late part '${key}')`, true)); } catch (err) { done(false); throw err; }
237
+ return typeof out === 'boolean' ? done(out) : out.then(done);
238
+ }, { behind: true }), L._parts);
192
239
  }
193
240
 
194
241
 
@@ -244,12 +291,17 @@ export function applyAnnounced(s, data, slot, done) {
244
291
  * Returns true when no module has a hook (nothing waited), else a Promise. The hooks start a microtask after the parts, and the marker and the
245
292
  * freeze with them: the lines right after an unawaited apply can still step, run ops and apply again (stateReplace.js, pause). */
246
293
  function afterLoad(s, e, slot, scope) {
247
- const hooks = [...e.modules.values()].filter(m => m.afterLoad), q = s._replace;
248
- if (!hooks.length) { takeListenerError(scope, 0); return true; }
294
+ const has = [...e.modules.values()].filter(m => m.afterLoad), q = s._replace;
295
+ if (!has.length) { takeListenerError(scope, 0); return true; }
249
296
  const job = q.pause();
250
- const run = () => {
297
+ let hooks = [];
298
+ const run = async () => {
251
299
  if (!q.resume(job)) return null;
252
300
  q.hold();
301
+ // the loop hooks' gate (_runsHooks): a failed, blocked, disabled or still initializing module rebuilds nothing, so no afterLoad reads what its init has not
302
+ // built (review l2 #10). Not waited for: an init that defines a save part (a late job holding the turn) and then awaits a load would wait for this very job.
303
+ // Its init builds for the state that stands when it runs
304
+ hooks = has.filter(m => e._runsHooks(m.name));
253
305
  return Promise.allSettled(hooks.map(m => Promise.resolve().then(() => m.afterLoad(e, job.turn))));
254
306
  };
255
307
  return Promise.resolve().then(run).then(res => {
@@ -1,4 +1,4 @@
1
- // Record ids inside save data, for upgrade steps (saves.register migrate). Shared by the world part and every part that keys data by a record id
1
+ // Record ids inside save data, for upgrade steps (saves.define migrate). Shared by the world part and every part that keys data by a record id
2
2
  // (containers): when the world part renames ids, those parts must rename the same ones, and core is the one place both may import from.
3
3
  // Runtime record ids: world save part version 2 numbered them `<kind>-<n>`, version 3 `<kind>#<n>` (an authored id may not contain `#`,
4
4
  // so the two can never collide; modules/content/ids.js).
@@ -1,6 +1,6 @@
1
1
  // Save format and per-part versions. A save is the envelope { format, savedAt, versions: { part: n }, parts: { part: data } }:
2
2
  // format is the version of the envelope itself (FORMAT); a save from a newer format is refused as a whole, one without format is format 1.
3
- // Each saves.register part carries its own version and migrate steps, so one module changing its format never touches the others; a part missing from versions is version 1.
3
+ // Each saves.define part carries its own version and migrate steps, so one module changing its format never touches the others; a part missing from versions is version 1.
4
4
  // Everything here runs before a load touches the game, and on a copy: a refused load leaves the game and the stored save as they were.
5
5
  import { codedError } from '../base/errorHints.js';
6
6
  import { fmt } from '../base/validate.js';
@@ -9,15 +9,17 @@ import { fmt } from '../base/validate.js';
9
9
  export const FORMAT = 1;
10
10
 
11
11
  const DEV = {
12
- badVersion: "saves.register('{k}'): version must be a whole number >= 1 (raise it by 1 whenever this part's saved data changes shape), got {v}",
13
- badMigrate: "saves.register('{k}'): migrate is { fromVersion: data => newData }, e.g. migrate: { 1: d => ({ ...d, gold: 0 }) }; key {m} is not a version below {v}",
12
+ badVersion: "saves.define('{k}'): version must be a whole number >= 1 (raise it by 1 whenever this part's saved data changes shape), got {v}",
13
+ badMigrate: "saves.define('{k}'): migrate is { fromVersion: data => newData }, e.g. migrate: { 1: d => ({ ...d, gold: 0 }) }; key {m} is not a version below {v}",
14
14
  tooNew: "[saves] not loaded: {list}. The save comes from a newer build of the game, which this build cannot read; nothing was changed and the save is kept. " +
15
15
  'To read it, run the newer build, or raise this part\'s version (with migrate steps) to match.',
16
16
  format: 'the save envelope is format {f}, this build reads up to format {max}',
17
17
  corrupt: "[saves] not loaded: slot '{slot}' is not a readable save ({why}). Nothing was changed and the stored save is kept as it was.",
18
- noStep: "save part '{k}' is version {from} but this build is version {to}, and migrate has no step {from}: add migrate: { {from}: data => newData } to saves.register('{k}')",
18
+ noStep: "save part '{k}' is version {from} but this build is version {to}, and migrate has no step {from}: add migrate: { {from}: data => newData } to saves.define('{k}')",
19
19
  };
20
20
 
21
+ // first: true loads before the rest (rank 0); a number ranks it (lower earlier: the level 0, the zones that need the level 1); no first = after them all
22
+ const firstRank = p => p.first === true ? 0 : Number.isFinite(p.first) ? p.first : Infinity;
21
23
  /**
22
24
  * Validate a part's version and migrate steps at register time (a typo shows up at once, not when an old save happens to be read).
23
25
  * @param {string} key
@@ -105,7 +107,7 @@ export function readSave(json, providers, slot) {
105
107
  if (!versions || typeof versions !== 'object' || Array.isArray(versions)) return { reason: 'corrupt', dev: fmt(DEV.corrupt, { slot, why: `versions ${JSON.stringify(versions)}` }) };
106
108
  const odd = Object.keys(versions).filter(k => !Number.isInteger(versions[k]) || versions[k] < 1);
107
109
  if (odd.length) return { reason: 'corrupt', dev: fmt(DEV.corrupt, { slot, why: `version of ${odd.map(k => `'${k}'`).join(', ')}` }) };
108
- const list = [...providers].filter(([k]) => Object.hasOwn(data.parts, k)).sort((a, b) => (b[1].first ? 1 : 0) - (a[1].first ? 1 : 0));
110
+ const list = [...providers].filter(([k]) => Object.hasOwn(data.parts, k)).sort((a, b) => { const x = firstRank(a[1]), y = firstRank(b[1]); return x < y ? -1 : x > y ? 1 : 0; }); // stable: equal ranks keep install order
109
111
  const newer = list.filter(([k, p]) => partVersion(versions, k) > p.version).map(([k, p]) => `part '${k}' is version ${versions[k]}, this build reads up to ${p.version}`);
110
112
  if (newer.length) return { reason: 'tooNew', dev: fmt(DEV.tooNew, { list: newer.join('; ') }) };
111
113
  // whole: the save as read, for migrate steps that need another part (upgradePart); kept on foreign so a part registered later (adoptPart) sees it too
@@ -20,13 +20,15 @@
20
20
  // A replacement that fails (a save part's load() threw: saveApply rolled the data back) keeps the old playthrough: tracked handles, function timers
21
21
  // and clocks stay as they were, background results still land, no 'session:start' or title follows, 'session:failed' { kind, slot? } fires instead (flow goes back to the state it left).
22
22
  // What session:end already ended stays ended (the music stopped, a running cutscene was skipped to its end).
23
- import { codedError } from '../base/errorHints.js';
24
- import { DEV as IS_DEV, fmt, warnOnce } from '../base/validate.js';
23
+ import { codedError, coded } from '../base/errorHints.js';
24
+ import { removeEach, reportError } from '../base/errors.js';
25
+ import { DEV as IS_DEV, fmt } from '../base/validate.js';
25
26
  import { applySave, partData } from './saveApply.js';
26
27
  import { readSave } from './saveVersions.js';
27
28
 
28
29
  const DEV = {
29
30
  early: 'engine.session.{fn}() was called before engine.start() finished: the new-game state is captured when loading completes. Call it from a button or after `await engine.start()`.',
31
+ missed: "a 'session:start' listener was added after engine.start() returned, but the playthrough had already started inside start() (?play, or newGame / load during start): it waits for the next new game and did not run for this one. Add it before `await engine.start()`, or read the state after start (engine.session.playing, engine.events.recent('session:start')).",
30
32
  badHandle: 'engine.session.track(handle): handle must have remove(), like the result of engine.events.on / onFixed / clock.after. Got {got}.'
31
33
  };
32
34
 
@@ -100,7 +102,7 @@ export class Session {
100
102
  delete base.parts[key]; delete base.versions[key];
101
103
  this._lateParts.add(key);
102
104
  // its save() cannot run yet, or has nothing to save (like collectParts): newGame leaves this part as it is. Data a save cannot hold is said now: it would refuse every save too
103
- try { const d = partData(key, p); if (d != null) { base.parts[key] = d; base.versions[key] = p.version; } } catch (err) { if (err?.code === 'save-part-threw') warnOnce(err.message); }
105
+ try { const d = partData(key, p); if (d != null) { base.parts[key] = d; base.versions[key] = p.version; } } catch (err) { if (err?.code === 'save-part-threw') reportError(this.engine, err, `new-game baseline of save part '${key}'`); }
104
106
  this._base = JSON.stringify(base);
105
107
  }
106
108
 
@@ -136,12 +138,13 @@ export class Session {
136
138
  /**
137
139
  * Start a new playthrough from the state the game had right after start(). Returns Promise<boolean> (false only if a save part failed to load: the
138
140
  * old playthrough then goes on, with its data, listeners and timers, and 'session:failed' fires instead of 'session:start').
141
+ * @param {{ turn?: object }} [o] turn: the running request's own (what a save part's load(), an afterLoad or a module's applyState was given): the call then runs inside that request instead of waiting behind it for itself, as level.load({ turn }) does
139
142
  * @returns {Promise<boolean>}
140
143
  * @example
141
144
  * // a "Restart" button in a game-over screen
142
145
  * restartBtn.onclick = () => engine.session.newGame();
143
146
  */
144
- newGame() { return this._turn('new', () => this._begin('newGame', () => this._applyBase(), { kind: 'new' })); }
147
+ newGame({ turn } = {}) { return this._turn('new', () => this._begin('newGame', () => this._applyBase(), { kind: 'new' }), turn); }
145
148
 
146
149
  /**
147
150
  * Continue from a save (or retry from a checkpoint) with nothing of the current playthrough left over: the new-game state with the save on top,
@@ -164,23 +167,25 @@ export class Session {
164
167
  /**
165
168
  * End the playthrough and show the title screen (the title part when the game turned it on; flow returns to its start state).
166
169
  * The state behind the title is the new-game state, so nothing from the old playthrough runs while the title is up.
170
+ * @param {{ turn?: object }} [o] turn: the running request's own (what a save part's load(), an afterLoad or a module's applyState was given): the call then runs inside that request instead of waiting behind it for itself, as level.load({ turn }) does
167
171
  * @returns {Promise<boolean>}
168
172
  * @example settingsBackToTitle.onclick = () => engine.session.quit();
169
173
  */
170
- quit() {
174
+ quit({ turn } = {}) {
171
175
  return this._turn('quit', async () => {
172
176
  const ok = await this._reset('quit', () => this._applyBase());
173
177
  if (ok) this._over = !this.engine.ui.open('title'); // ui.open answers false with no title part
174
178
  else this.engine.events.emit('session:failed', { kind: 'quit' }); // rolled back: the old playthrough goes on, so no title over it
175
179
  return ok;
176
- });
180
+ }, turn);
177
181
  }
178
182
 
179
183
  /**
180
184
  * @internal A session replacement takes its turn with every other one (stateReplace.js). The same request joins the last in line (a double-clicked
181
185
  * Restart); another one waits: joined, a load asked during ?play's new game answered true and never loaded.
186
+ * turn: the running request's own, when it asks (applyState): then it runs inside that request, as level.load({ turn }) does.
182
187
  */
183
- _turn(what, run) { return this.engine.saves._replace.run(what, run); }
188
+ _turn(what, run, turn) { return this.engine.saves._replace.run(what, run, { turn }); }
184
189
 
185
190
  /** @internal the new-game state as save data (_reset already refused a call before start() finished) */
186
191
  _baseData() { return JSON.parse(this._base); }
@@ -193,6 +198,9 @@ export class Session {
193
198
  const ok = await this._reset(fn, apply);
194
199
  if (ok) this._started();
195
200
  this.engine.events.emit(ok ? 'session:start' : 'session:failed', info);
201
+ // ?play starts the first run inside engine.start(), so a session:start listener attached after `await engine.start()` misses it silently; hint once.
202
+ // Mark only when fired during start(), and hint only once start() returned (phase 'running') with no tick yet; later listeners are waiting for the next run.
203
+ if (ok && this.engine.phase !== 'running') this.engine.events._firedNow('session:start', () => this.engine.phase === 'running', coded('session-start-missed', DEV.missed));
196
204
  return ok;
197
205
  }
198
206
 
@@ -218,7 +226,8 @@ export class Session {
218
226
  if (!ok) return false; // rolled back: the old playthrough's tracked handles and timers stay, so it goes on as it was (review 0.4 core B3)
219
227
  // shortcut: tracked handles stay registered while apply runs, so one may hear the load's own events (world:load); removing them first
220
228
  // would make a failed load unrecoverable. Upgrade if a game needs it: suspend tracked handles during apply instead
221
- for (const h of oldHandles) { h.remove(); this._tracked.delete(h); }
229
+ // one remove() that throws is reported and the switch goes on: stopping here would leave the new data in with no session id, timers or rebase (review l2 #11)
230
+ removeEach(e, oldHandles, 'remove() of a handle session.track held', h => this._tracked.delete(h));
222
231
  this.id++;
223
232
  e.time._restoreFn(this._timers, oldTimers); // event timers came back with the save; function timers are the boot-time ones, each with its original delay, and those apply set up
224
233
  e.commits.rebase(); // requests that outlived the load (a nextFixed, terrain colliders) were due on the old tick count, minutes away now that tick restarted
@@ -8,6 +8,9 @@
8
8
  // the caller's next lines) and a direct apply / load on those lines runs at once and takes over. The older job's hooks are then skipped:
9
9
  // they would rebuild for a state that is gone, and the newer job's hooks rebuild for the one that stayed. Not past something already in line:
10
10
  // apply(x); save('s'); apply(y) would store y.
11
+ // A late part's job (adoptPart) adds to the state, it replaces nothing, so paused it holds nobody back: a read (a save, a content commit) on those lines goes
12
+ // at once, and another late part takes over, its afterLoad round rebuilding for both. Held, use(content()); content.load(...) or a failed replaces putting
13
+ // its module back would leave the next line without its data until a microtask later; nothing it skips is half loaded (paused means every part is in).
11
14
  // - One marker. `replacing` is true from reading the save through its parts, afterLoad and any rollback; begin() / end() bracket that span
12
15
  // (saveApply.js). Ops read it (opsFail.js) instead of knowing freeze names, so a game's own freeze never looks like a load and a load never
13
16
  // looks like a menu. A session's turn is longer than the marker on purpose: session:end listeners (a skipped cutscene's last steps) and
@@ -51,6 +54,7 @@ export class StateReplace {
51
54
  /** True from reading a save until its load or rollback ended */ this.replacing = false;
52
55
  /** The freeze while the replacement waits on something */ this.freeze = null;
53
56
  /** How many stateTurns are open */ this.turns = 0;
57
+ /** Restore jobs (restoring) not ended yet: while any is, end() leaves the marker and the freeze on */ this.restores = 0;
54
58
  /** Which saved state the game holds: moves when a load starts changing parts, goes back when it fails. A level change does not move it, so what a level load's caller asked next survives (commits.epoch moves for both) */ this.generation = 0;
55
59
  }
56
60
 
@@ -58,15 +62,18 @@ export class StateReplace {
58
62
  * Run fn when its turn comes: at once when idle, else after the jobs before it. Returns what fn returned, as a Promise.
59
63
  * @param {string | null} key same key as the last job in line: join it instead of running again
60
64
  * @param {() => any} fn
61
- * @param {boolean} [behind] never take over a paused job: fn adds to the state that job leaves, it does not replace it (adoptPart)
65
+ * @param {{ behind?: boolean, whole?: boolean, turn?: object }} [o] behind: a late part (adoptPart), fn adds to the state the running job leaves: it takes over only a paused late part's job (_passable).
66
+ * whole: the job is one request from its first line to its last (a scene request, applyState), so it never pauses for a direct apply to take over.
67
+ * turn: the turn of the request asking. When it is the running one, fn is part of that request and runs now, inside it: in line it would wait for itself
62
68
  * @returns {Promise<any>}
63
69
  */
64
- run(key, fn, behind = false) {
70
+ run(key, fn, { behind = false, whole = false, turn } = {}) {
71
+ if (turn && this.job?.turn === turn) { try { return Promise.resolve(fn()); } catch (err) { return Promise.reject(err); } }
65
72
  const last = this.waiting.at(-1) ?? this.job;
66
73
  if (key && last?.key === key) return last.done;
67
- const job = { key, fn, done: null, settle: null, paused: false, turn: Object.freeze({}) };
74
+ const job = { key, fn, done: null, settle: null, paused: false, whole, behind, turn: Object.freeze({}) };
68
75
  job.done = new Promise(res => { job.settle = res; });
69
- if (this.job && (behind || !this.job.paused || this.waiting.length)) this._line(job); else this._start(job);
76
+ if (this.job && (behind && !this._passable() || !this.job.paused || this.waiting.length)) this._line(job); else this._start(job);
70
77
  return job.done;
71
78
  }
72
79
 
@@ -76,7 +83,7 @@ export class StateReplace {
76
83
  * @returns {Promise<any>}
77
84
  */
78
85
  read(fn) {
79
- if (!this.job) return fn();
86
+ if (!this.job || this._passable()) return fn();
80
87
  let give;
81
88
  const job = { key: null, fn: () => { try { give(fn()); } catch (err) { give(Promise.reject(err)); } }, done: new Promise(res => { give = res; }), settle() {}, paused: false }; // a throw reaches the one who asked, and the line goes on
82
89
  this._line(job);
@@ -88,10 +95,10 @@ export class StateReplace {
88
95
  * @param {Promise<any>} p
89
96
  */
90
97
  restoring(p) {
91
- const job = { key: null, fn: () => p, done: p, settle() {}, paused: false };
92
- this.begin(); this.hold();
93
- const over = () => this.endOf(job);
94
- p.then(over, over); // before _start's own: the job still holds the turn when the marker goes off
98
+ // the job ends itself once p settled and its turn came (_start's next). Asked while another job runs (an atomic op inside applyState), that job's own end()
99
+ // must not drop the marker, and nothing else would raise it again: restores keeps it on until this one ends
100
+ const job = { key: null, fn: () => p, done: p, settle() {}, paused: false, restoring: true };
101
+ this.restores++; this.begin(); this.hold();
95
102
  if (this.job) this.waiting.unshift(job); else this._start(job);
96
103
  }
97
104
 
@@ -113,18 +120,30 @@ export class StateReplace {
113
120
  _start(job) {
114
121
  this.job = job; this.moved = performance.now(); // measure: a sign of life for those in line
115
122
  const next = () => {
123
+ if (this.job !== job) return; // not its turn any more: taken over
124
+ if (job.restoring) { this.restores--; this.end(); } // the old state is whole again: gameplay and the line go on
125
+ // the notice is still this job's turn: a load asked in a state:replaced listener goes in line. Were the turn cleared first, that load would start at once and the
126
+ // job in line beside it right after (review l2 #1). Not paused either: a paused job would let it take over and skip the line
127
+ job.paused = false;
128
+ if (job.changed) this.engine.events.emit('state:replaced', { undone: job.changed === 'undone' });
116
129
  if (this.job !== job) return;
117
130
  this.job = null;
118
- if (job.changed) this.engine.events.emit('state:replaced', { undone: job.changed === 'undone' });
119
- const n = this.waiting.shift();
120
- if (n) this._start(n);
121
- }; // not its turn any more: taken over
131
+ this._next();
132
+ };
122
133
  let out;
123
134
  try { out = job.fn(); } catch (err) { out = Promise.reject(err); }
124
135
  if (typeof out?.then === 'function') out.then(next, next);
125
136
  else next();
126
137
  job.settle(out);
127
138
  }
139
+ /** A paused late part's job with nobody in line: what comes next does not wait for its afterLoad round (top of the file) */
140
+ _passable() { return !!this.job?.paused && this.job.behind && !this.waiting.length; }
141
+ /** The one place the next job starts: only when no job holds the turn, so a job ending inside another's notice cannot start a second one beside it */
142
+ _next() {
143
+ if (this.job) return;
144
+ const n = this.waiting.shift();
145
+ if (n) this._start(n);
146
+ }
128
147
 
129
148
  /** The state starts being replaced (the marker's span: top of the file) */
130
149
  begin() { this.replacing = true; }
@@ -134,7 +153,7 @@ export class StateReplace {
134
153
  * apply, and a job already holding the freeze is mid-load, so neither pauses. Returns the job, for resume */
135
154
  pause() {
136
155
  const job = this.job;
137
- if (!job.key && !this.freeze) { job.paused = true; this.replacing = false; }
156
+ if (!job.key && !job.whole && !this.freeze) { job.paused = true; this.replacing = false; }
138
157
  return job;
139
158
  }
140
159
  /** The wait ended: false when a newer job took over, else the marker is back on */
@@ -148,7 +167,7 @@ export class StateReplace {
148
167
  /** The replacement waits on something: stop fixed steps until end() */
149
168
  hold() { this.freeze ??= this.engine.freeze(FREEZE); }
150
169
  /** The load or its rollback ended */
151
- end() { this.replacing = false; this.freeze?.remove(); this.freeze = null; }
170
+ end() { if (this.restores) return; this.replacing = false; this.freeze?.remove(); this.freeze = null; }
152
171
  }
153
172
 
154
173
  /**