threedog 1.4.0 → 2.0.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 (117) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +13 -7
  3. package/bin/threedog.mjs +42 -0
  4. package/core/base/Events.js +7 -1
  5. package/core/base/errorCodes.js +1 -1
  6. package/core/base/events.generated.js +1 -0
  7. package/core/engine/Engine.js +2 -2
  8. package/core/engine/copies.js +1 -1
  9. package/core/engine/moduleTypes.js +1 -1
  10. package/core/engine/modules.js +19 -2
  11. package/core/engine/page.js +1 -0
  12. package/core/engine/services.js +2 -1
  13. package/core/engine/startup.js +4 -1
  14. package/core/inspect/InspectPerf.js +1 -1
  15. package/core/inspect/metadata.generated.js +33 -14
  16. package/core/ops/control.js +3 -3
  17. package/core/ops/holds.js +8 -3
  18. package/core/saves/saveApply.js +2 -2
  19. package/core/saves/session.js +20 -4
  20. package/core/scene/adaptive.js +2 -0
  21. package/core/scene/things.js +3 -2
  22. package/core/scene/tier.js +19 -2
  23. package/docs/AI.md +2 -2
  24. package/docs/CODEMAP.md +5 -5
  25. package/docs/COMMANDS.md +2 -2
  26. package/docs/CONVENTIONS.md +1 -0
  27. package/docs/THREE.md +1 -1
  28. package/docs/api/engine.md +5 -2
  29. package/docs/api/events.md +2 -1
  30. package/docs/api/particles.md +1 -1
  31. package/docs/api/pickups.md +1 -1
  32. package/docs/api/post.md +1 -1
  33. package/docs/api/rigid.md +1 -1
  34. package/docs/api/sky.md +1 -1
  35. package/docs/recipes/01-new-game.md +1 -1
  36. package/docs/recipes/03-items-pickups.md +1 -1
  37. package/docs/recipes/06-clock-events.md +3 -10
  38. package/docs/recipes/07-flow-scenes-pause.md +0 -1
  39. package/docs/recipes/10-blender-level.md +2 -2
  40. package/docs/recipes/{11-vehicles.md → 11-physics.md} +13 -5
  41. package/docs/recipes/12-navmesh.md +3 -3
  42. package/docs/recipes/14-custom-module.md +5 -4
  43. package/docs/recipes/20-content-actions-save.md +0 -1
  44. package/docs/recipes/21-camera.md +11 -1
  45. package/docs/recipes/27-net.md +1 -1
  46. package/docs/recipes/29-grid.md +1 -1
  47. package/docs/recipes/34-environment-lighting.md +5 -3
  48. package/docs/recipes/44-water-weather-hooks.md +1 -1
  49. package/docs/recipes/45-cascaded-shadows.md +6 -3
  50. package/docs/recipes/52-around-the-picture.md +6 -6
  51. package/docs/recipes/53-ground-up-close.md +2 -2
  52. package/docs/recipes/55-mods-time-wrap.md +3 -5
  53. package/docs/recipes/60-judge-the-picture.md +2 -2
  54. package/docs/recipes/62-picture-code.md +13 -17
  55. package/examples/action/GAMEMAP.md +4 -2
  56. package/examples/action/picture/lights.js +3 -2
  57. package/examples/perf-island/GAMEMAP.md +2 -1
  58. package/examples/perf-island/picture/lights.js +3 -2
  59. package/examples/styletest/GAMEMAP.md +2 -2
  60. package/examples/styletest/picture/env.js +1 -2
  61. package/examples/techniques/contact-shadows/README.md +1 -1
  62. package/examples/techniques/day-night-grade/picture/lights.js +3 -1
  63. package/examples/techniques/interior-light/picture/lights.js +4 -2
  64. package/examples/techniques/modular-building/picture/lights.js +3 -2
  65. package/examples/techniques/night-lights/picture/lights.js +3 -1
  66. package/examples/techniques/night-lights/picture/post.js +2 -2
  67. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -2
  68. package/examples/techniques/procedural-animation/picture/lights.js +3 -1
  69. package/examples/techniques/procedural-surface/picture/lights.js +3 -1
  70. package/examples/techniques/stylized-shading/picture/lights.js +3 -1
  71. package/examples/techniques/wet-road/picture/lights.js +3 -1
  72. package/examples/webgpu-tsl/GAMEMAP.md +4 -2
  73. package/examples/webgpu-tsl/picture/lights.js +3 -1
  74. package/examples/world/GAMEMAP.md +4 -3
  75. package/examples/world/picture/lights.js +3 -1
  76. package/examples/world/picture/post.js +2 -2
  77. package/llms.txt +33 -7
  78. package/modules/camera/common.js +22 -20
  79. package/modules/characters/Character.js +2 -2
  80. package/modules/characters/NPC.js +7 -8
  81. package/modules/characters/index.js +8 -8
  82. package/modules/characters/npcAvoid.js +2 -2
  83. package/modules/characters/player.js +10 -14
  84. package/modules/characters/playerStrings.js +1 -2
  85. package/modules/characters/seat.js +1 -1
  86. package/modules/content/index.js +2 -1
  87. package/modules/content/templates.js +3 -2
  88. package/modules/flow/index.js +5 -5
  89. package/modules/gameplay/Dialogue.js +1 -1
  90. package/modules/gameplay/Inventory.js +3 -3
  91. package/modules/gameplay/Quests.js +1 -0
  92. package/modules/gameplay/pickups.js +1 -1
  93. package/modules/gameplay/questLog.js +0 -1
  94. package/modules/grid/index.js +1 -1
  95. package/modules/hud/index.js +2 -2
  96. package/modules/level/index.js +1 -1
  97. package/modules/music/Music.js +1 -1
  98. package/modules/nav/index.js +1 -1
  99. package/modules/net/sync.js +1 -1
  100. package/modules/particles/Particles.js +13 -5
  101. package/modules/particles/effect.js +17 -3
  102. package/modules/rigid/RigidBodies.js +10 -9
  103. package/modules/rigid/sync.js +14 -0
  104. package/modules/sky/Sky.js +9 -4
  105. package/modules/sky/environment.js +4 -2
  106. package/modules/timeline/Timeline.js +1 -2
  107. package/modules/world/World.js +1 -0
  108. package/modules/world/index.js +1 -0
  109. package/modules/world/persist.js +1 -1
  110. package/package.json +6 -2
  111. package/render/PostFX.js +10 -5
  112. package/render/fx/postWebGPU.tsl.js +2 -1
  113. package/types/core.d.ts +14 -5
  114. package/types/gameplay.d.ts +1 -1
  115. package/types/generated/modules/sky/Sky.d.ts +4 -4
  116. package/types/generated/render/PostFX.d.ts +2 -2
  117. package/types/physics.d.ts +1 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,40 @@
2
2
 
3
3
  What changed in each version and how a game upgrades.
4
4
 
5
+ ## Unreleased
6
+
7
+ ## 2.0.0 (2026-11-16)
8
+
9
+ A major version: some games need a change to upgrade (below). 1.5.0 was prepared but never published; its changes are part of this release.
10
+
11
+ **Upgrading from 1.x**
12
+ - Install the packages together at 2.0: `npm install threedog@2 @threedog/tools@2` (and `@threedog/post-effects@2`, `@threedog/terrain-noise@2` if you use them). The `threedog` command now comes with `threedog`, not `@threedog/tools`.
13
+ - `characters()` requires `world()`: a game that installs it without `world()` or `openWorld()` adds it before: `engine.use(world(), collision(), characters())`.
14
+ - The newGame / load reset runs in one declared order (below): a game's own `world:load` listener now always runs after the player is placed back. A game that relied on running before it moves that code into a module's `worldLoad(e, info)` hook.
15
+ - A module of your own that listened to `session:end`, `world:load` or `session:start` to reset itself keeps working; to run in the declared order, use the definition hooks `sessionEnd`, `worldLoad`, `sessionStart` instead.
16
+ - Something your picture sizes from `engine.tier` when it is made (a shadow map size, a light count) follows a later change only if you listen to `tier:change` (recipe 62).
17
+ - New games start from a neutral daytime palette with the sky as the fill light; existing games are not touched.
18
+
19
+ - Changed: new games (`threedog init`, `new-game`) start from a neutral, temperate daytime palette instead of grey: sky keyframes, warm sun, muted ground, water and player colors, all in the game's `picture/palette.js`, and with a sky the sky itself is the fill light (`engine.sky.environment`). The generated `CLAUDE.md` and the palette say it is a placeholder to restyle.
20
+ - Added: `sky.keyframes()` with no argument returns a copy of the rows in use, so a picture that sets its own can give them back when it leaves. A call with rows works as before and now returns them; nothing to migrate.
21
+ - Added: the `tier:change` event ({ tier }), fired after engine.tier changes (a settings preset, game code writing it). Something sized from the tier when made (a shadow map, a light budget) had no public way to follow it, so the template, the examples and the recipes read it once and kept a low-tier start's sizes after the player picked high; they now size at creation and follow this event. Particles: an effect's default max (60 on low) now follows a tier change in place.
22
+ - Changed: the session reset (newGame / load) runs in one declared order: modules join through sessionEnd(e), worldLoad(e, info) and sessionStart(e, info) on their definition, run in engine.moduleOrder (stage, then before / after), and only then the session:end / world:load / session:start events fire. Before, the order was install order. A game's own world:load listener now always runs after the player is placed back (before, one registered at boot ran before it).
23
+ - Fixed: a module installed before the provider it requires (the order engine.use(x, { replaces }) leaves) now inits during start() and is awaited; before, start() resolved without waiting for it, and a critical one failing there did not block the start.
24
+ - Fixed: on a headless page (tests, shots) a halt taken and removed left the engine running in real time; removing the last halt now gives back the state from before it (an explicit resume still goes live).
25
+ - Fixed: after a WebGL context is restored, the GPU timer behind adaptive resolution starts over (it read the last time from before the loss, so the resolution could stay low).
26
+ - Tools: a missing Playwright browser is one line with the install command (shot, perf, the dev bridge); other launch failures name their cause. init warns when a kept index.html, vite config or dev script would keep the game from starting. A timed-out MCP check ends its whole process tree.
27
+
28
+ - Changed: `characters()` now requires `world()`, and `engine.use()` says so at install. Before, `world` was listed as optional and only `characters.addPlayer()` (or the first NPC) threw at runtime, although the player and every NPC are world records. The docs' module lists that left `world()` out (recipes 10, 11, 12, the pickups page) now include it, and a guard test checks every `engine.use` list in the docs, templates and examples against what each module requires.
29
+ - New (docs): screen shake without taking the camera, recipe 21 §6b: an offset added in `engine.onRender` and put back in `onRender(fn, { when: 'after' })`; the camera's takeover warning now names it, and a guard test holds the hook order it relies on.
30
+ - Fixed: solver settings a game writes on `engine.rigid.world.integrationParameters` (such as `numSolverIterations`, and `contact_natural_frequency`) are kept when newGame or a load rebuilds the physics world. Before, they fell back to Rapier's defaults.
31
+ - Docs: recipe 11 §3c says when bodies can be added, that `rigid.impulse` wakes a sleeping body (explosions), and that resting stacks overlap a little because of Rapier's soft contacts, not a smaller collider (more iterations do not change it).
32
+ - Renamed: `docs/recipes/11-vehicles.md` is now `docs/recipes/11-physics.md` (it covers all rigid bodies, joints and explosions, not only vehicles). No alias.
33
+ - Docs: CONVENTIONS "One task, which entry" has a hit-stop / bullet-time row (`engine.mod('time.world', ...)`, `for` in real seconds; `clock.rate` is the calendar).
34
+ - Changed: the `threedog` command now comes with the `threedog` package, and `@threedog/tools` has no bin of its own (one package may own a bin name). It runs the commands of `@threedog/tools`; with only the engine installed, `npx threedog init` used to fail with "could not determine executable to run", and now prints the line that installs `@threedog/tools`. Release both packages together: `@threedog/tools` needs an engine that carries the bin.
35
+ - Changed: the package README and `llms.txt` open with one start sequence (install, `npx threedog init`, `npx threedog play`); `llms.txt` copies it from the README so the two cannot drift. `@threedog/tools` is no longer described as optional.
36
+ - New: a new game's `CLAUDE.md` has a short "Before you call it done" checklist (compare `threedog shot` with the target style, recipes 60 and 62, `@threedog/post-effects`).
37
+ - Fixed: on WebGPU each `engine.sky.environment()` rebuild stalled the game (100 ms to seconds, once per interval while the sky moved): every material reading the environment built again for the new map. The rebuild now refills the same map; on WebGL it was already cheap. A moving day can light the scene with its own sky.
38
+
5
39
  ## 1.4.0 (2026-11-15)
6
40
 
7
41
  - New: `threedog hub`, a local web page that lists your threedog games and shows each game's screenshot wall. The points to shoot are in the game's own `shots.json` (each point takes the options of `threedog shot`: `view`, `cam`, `pos`, `at`, `play`, `time`, `weather`, `wait`, `size`, `page`). After a file of a game changes and 30 s pass with no further change, the hub shoots all its points again, one game at a time, and the page updates by itself; each point keeps its last 10 pictures, and a point that fails shows its reason. From the page you can create a game (the `threedog init` starts), add an existing game folder, open a game or its asset gallery, and re-shoot by hand. `threedog hub --shortcut` (or the page's button) puts a desktop icon that opens it (Windows). The server answers only on 127.0.0.1 and refuses requests from other web pages.
package/README.md CHANGED
@@ -2,21 +2,27 @@
2
2
 
3
3
  A web 3D game engine on three.js 0.187: **core** (rendering, main loop, input, audio, saving, UI) -> **modules** (terrain, sky and weather, physics, characters, dialogue, inventory, quests... installed on demand); all art is the game's own (`picture/` folder, `assets.js`).
4
4
 
5
- ## Install
6
- This README describes threedog 1.0 (older releases do not match it; from 0.x read `docs/MIGRATING-1.0.md`, from 0.8.0 `CHANGELOG.md`, from 0.7.0 first `docs/MIGRATING-0.8.md`). To work on the engine itself, clone the [repository](https://github.com/penstic123-code/Threedog.js-Game-Engine), run `npm install`, then `npm run new-game -- my-game`. A game in its own folder:
5
+ ## Start here
6
+ One way to start a game, in an empty folder (the same for a person and for an AI agent):
7
7
  ```sh
8
8
  npm install threedog@1 three@~0.187.0
9
- npm install @threedog/terrain-noise@1 # optional: the noise terrain generator terrainPreset() (without one the ground is flat)
10
- npm install -D vite @threedog/tools@1 # optional: the vite preset and the threedog command line
9
+ npm install -D @threedog/tools@1 # the threedog commands: init, shot, check, how, dev, play, test
10
+ npx playwright install chromium # once per machine: the headless browser behind shot, play and test
11
+ npx threedog init # writes the game (main.js, picture/, content/) and its CLAUDE.md; never overwrites a file
12
+ npm install
13
+ npx threedog play # runs the game and reports it (--stop ends it); npm run dev opens it for a person
11
14
  ```
12
- Then let it set up the folder: `npx threedog init` (flags: `--open-world` for generated ground, sky, follow camera and a player; the default is a blank scene with a camera and a gray starter picture in `picture/`) writes index.html, main.js, vite.config.js, content/, CLAUDE.md and `.mcp.json` (Claude Code then starts the threedog MCP server by itself), never overwriting a file you have. Finish with `npm install` (for what the new files need) and `npm run dev`.
15
+ Then read the new `CLAUDE.md`: it lists what the engine already has, the loop (`threedog play`, `threedog shot`, `threedog check`), the picture recipes (60 judge the picture, 62 picture code) and `@threedog/post-effects` (bloom, AO, color grading). `npx threedog how "<task words>"` finds everything else.
16
+
17
+ `init` flags: `--open-world` (generated ground, sky, follow camera and a player; it adds `@threedog/terrain-noise`), `--pixel`, `--scene-only`, `--webgl` (WebGL and GLSL instead of WebGPU and TSL). The default is a blank scene with a camera and a neutral, correctly lit starting picture in `picture/` (gray surfaces, white sun, soft shadows, AO, light bloom). It also writes `.mcp.json`, so Claude Code opened in the folder starts the threedog MCP server by itself.
18
+ `npx threedog` comes with this package and runs the commands of `@threedog/tools`; without that package installed it prints the line to install it. To work on the engine itself, clone the [repository](https://github.com/penstic123-code/Threedog.js-Game-Engine), run `npm install`, then `npm run new-game -- my-game`. This README describes threedog 1.x (from 0.x read `docs/MIGRATING-1.0.md`).
13
19
  `three` is a peer dependency: your game and the engine share one copy. Types for three come with the engine (`@types/three`, same version), so `// @ts-check` JS and TypeScript both see real three.js types.
14
20
 
15
- ## Minimal usage
21
+ ## The code, in short (the `--open-world` start)
16
22
  ```js
17
23
  import 'threedog/tsl'; // WebGPU with TSL, what a new game starts on; a game started with --webgl leaves this line out and the renderer option below
18
24
  import { createEngine, presets, openWorld } from 'threedog';
19
- import { terrainPreset } from '@threedog/terrain-noise'; // optional terrain generator (npm install @threedog/terrain-noise)
25
+ import { terrainPreset } from '@threedog/terrain-noise'; // the noise terrain generator (init --open-world adds it; without one the ground is flat)
20
26
 
21
27
  const engine = createEngine({ canvas: document.getElementById('view'), renderer: 'webgpu' }); // no picture code yet: gray placeholders
22
28
  engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset() }));
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ // The `threedog` command. Why it lives in the engine package and only forwards: `npx threedog init` names the package called threedog, so
3
+ // with the engine installed alone npx used to fail with "could not determine executable to run", and an AI concluded the package has no init.
4
+ // The commands themselves stay in @threedog/tools (dev-only weight: playwright, vite, typescript); this file runs them in the same process,
5
+ // or says the one line to install them. Only one package may own a bin name, so @threedog/tools has no bin of its own.
6
+ import { readFileSync, existsSync, realpathSync } from 'node:fs';
7
+ import { fileURLToPath, pathToFileURL } from 'node:url';
8
+ import { join, dirname } from 'node:path';
9
+
10
+ // The project's own install first (walking up from where the command runs): under pnpm's strict layout or Yarn PnP the engine's real folder
11
+ // cannot see @threedog/tools even when the project has it. Then the engine-relative lookup (a hoisted install, this repository's workspaces).
12
+ function findTools() {
13
+ for (let dir = process.cwd(); ; dir = dirname(dir)) {
14
+ const pkg = join(dir, 'node_modules', '@threedog', 'tools');
15
+ if (existsSync(join(pkg, 'package.json'))) return join(pkg, 'bin', 'threedog.mjs');
16
+ if (dirname(dir) === dir) break;
17
+ }
18
+ try { return join(dirname(fileURLToPath(import.meta.resolve('@threedog/tools/paths'))), 'bin', 'threedog.mjs'); } catch { return null; }
19
+ }
20
+
21
+ const found = findTools();
22
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
23
+ const install = `npm install -D @threedog/tools@${version.split('.')[0]}`;
24
+ if (!found) {
25
+ console.error(`✗ The threedog commands (init, shot, check, how, dev) come with @threedog/tools, which is not installed here. Run:
26
+ ${install}
27
+ npx threedog ${process.argv.slice(2).join(' ') || 'init'}`);
28
+ process.exit(1);
29
+ }
30
+ // A half-installed or broken copy: one repair line instead of a module-not-found stack
31
+ const broken = what => { console.error(`✗ @threedog/tools is installed but incomplete (${what}). Reinstall it: ${install}`); process.exit(1); };
32
+ if (!existsSync(found)) broken(`no ${found}`);
33
+ // The real path: through a link (workspaces, pnpm) Node's module-not-found message names real paths, so the check below compares like with like
34
+ const toolsBin = realpathSync(found);
35
+ // The tools entry runs when argv[1] is its own path (it is also imported by tests, where it must not run)
36
+ process.argv[1] = toolsBin;
37
+ try { await import(pathToFileURL(toolsBin).href); }
38
+ // Only a missing file OF the tools package counts as a broken install; any other error (a game's own missing import) stays as it is
39
+ catch (e) {
40
+ const norm = s => String(s).replaceAll('\\', '/').toLowerCase(), first = e?.message?.split('\n')[0] ?? '';
41
+ if (e?.code === 'ERR_MODULE_NOT_FOUND' && norm(first).includes(`module '${norm(dirname(dirname(toolsBin)))}/`)) broken(first); else throw e;
42
+ }
@@ -139,9 +139,15 @@ export class Events {
139
139
  const s = this.map.get(name); if (!s) { if (this.traceSize > 0) this._note(name); return; }
140
140
  const prev = this._cur;
141
141
  if (this.traceSize > 0) this._cur = `ev:${this._note(name)}`; // handlers run under this event: what they emit names it as parent
142
- try { for (const fn of [...s]) { if (!s.has(fn)) continue; /* removed by an earlier listener of this emit */ try { const r = fn(...args); if (this._scopes.length) syncOnly(r, `a listener of '${name}' inside a load`, true); } catch (err) { if (this._scopes.length) this._scopes.at(-1).push({ name, err }); else if (this.onError) this.onError(name, err); else console.error(`[event ${name}]`, err); } } }
142
+ try { for (const fn of [...s]) { if (!s.has(fn)) continue; /* removed by an earlier listener of this emit */ this._call(name, fn, args); } }
143
143
  finally { this._cur = prev; }
144
144
  }
145
+ /** @internal run one handler the way a listener runs: an error is collected by the load in progress (it fails it) or reported, never thrown to the caller.
146
+ * Shared with the session reset steps (engine._resetStep), so a module's reset hook fails or reports exactly as the listener it replaced did */
147
+ _call(name, fn, args) {
148
+ try { const r = fn(...args); if (this._scopes.length) syncOnly(r, `a listener of '${name}' inside a load`, true); }
149
+ catch (err) { if (this._scopes.length) this._scopes.at(-1).push({ name, err }); else if (this.onError) this.onError(name, err); else console.error(`[event ${name}]`, err); }
150
+ }
145
151
  /** @internal trace entries old -> new */
146
152
  _ordered() { const t = this._trace; return this._th ? t.slice(this._th).concat(t.slice(0, this._th)) : t; }
147
153
  /** @internal Record one trace entry, returns its id */
@@ -424,7 +424,7 @@ export const ERROR_CODES = {
424
424
  docs: ['recipes/27-net.md', 'api/net.md'],
425
425
  fix: 'net() needs role \'host\' or \'client\' and a transport; reconnect() is for clients only.' },
426
426
  'rigid-misuse': {
427
- docs: ['recipes/11-vehicles.md §3', 'api/rigid.md'],
427
+ docs: ['recipes/11-physics.md §3', 'api/rigid.md'],
428
428
  fix: "The message says which: an id already used by another body or vehicle (give each its own id); a mesh that another body or a character already owns (one object, one physics owner: remove the first, or give the second its own object); joints lost when newGame / a load rebuilt the physics world (re-create them in a rigid:rebuilt listener, recipe 11 section 3 \"Joints\"); rigid.ragdoll() got something it cannot drive (a skinned character out of its vehicle, with the bones named when they cannot be read); or a moving body left the terrain colliders and froze (raise rigid({ terrainRing }) if it must keep moving there, recipe 11 section 3)." },
429
429
  'settings-row': {
430
430
  docs: ['api/settings.md'],
@@ -13,6 +13,7 @@ export const ENGINE_EVENTS = [
13
13
  'ui:close',
14
14
  'settings:shadows',
15
15
  'settings:change',
16
+ 'tier:change',
16
17
  'post:add',
17
18
  'water:add',
18
19
  'water:remove',
@@ -130,8 +130,8 @@ export class Engine {
130
130
  const canvas = canvasIn ?? (gpuWanted ? undefined : rendererIn?.domElement);
131
131
  this.movement = createMovement(movement); // character radius / height / slope / step height: the single copy shared by collision, physics and nav
132
132
  if (opts.lights !== false) warnOnce(NO_PICTURE);
133
- // a game-supplied renderer keeps its settings: the engine configures pixel ratio, size, tone mapping and shadows only on a renderer it created itself.
134
- // One write on every renderer: info.autoReset = false below, because the frame stats count a whole frame, not each render call
133
+ // a game-supplied renderer keeps its settings: the engine configures pixel ratio, tone mapping and shadows only on a renderer it created itself.
134
+ // Written on every renderer: the drawing size follows the canvas box (core/scene/canvasBox.js; a frame of another size would stretch), and info.autoReset = false below, because the frame stats count a whole frame, not each render call
135
135
  const owned = !rendererIn || gpuWanted;
136
136
  this._ownsRenderer = owned; // dispose() releases the WebGL context only of a renderer the engine built
137
137
  if (owned) checkCanvasUsable(canvas);
@@ -6,7 +6,7 @@
6
6
  // A hot reload re-runs the same file (same path, a ?t= query): that is one copy, not two, so the path without the query decides.
7
7
  import { coded } from '../base/errorHints.js';
8
8
 
9
- export const VERSION = '1.2.0'; // kept equal to package.json by the "[guard] engine copies" spec
9
+ export const VERSION = '2.0.0'; // kept equal to package.json by the "[guard] engine copies" spec
10
10
 
11
11
  const KEY = Symbol.for('threedog.engine.copies');
12
12
 
@@ -27,7 +27,7 @@ export const MODULE_TYPES = {
27
27
  /** How engine.skip advances a module (the skipKind field): what each word means is on ModuleDefinition in types/core.d.ts */
28
28
  export const SKIP_KINDS = ['exact', 'approx', 'step', 'none'];
29
29
  /** The time hooks a module definition may carry (engine.catalog and the generated metadata list the ones a module has) */
30
- export const TIME_HOOKS = ['fixed', 'frame', 'afterRender', 'skip', 'afterLoad'];
30
+ export const TIME_HOOKS = ['fixed', 'frame', 'afterRender', 'skip', 'sessionEnd', 'worldLoad', 'afterLoad', 'sessionStart'];
31
31
 
32
32
  const STRINGS = {
33
33
  badSkip: "module {name} has skipKind '{kind}'. Fix: use one of {list}",
@@ -6,6 +6,8 @@
6
6
  // Stages (first to last): control timeline, camera -> ground terrain, level -> environment weather, sky, water
7
7
  // -> gameplay interactions, dialogue, trigger zones -> effects particles, settings, objective markers
8
8
  // -> late (the default) characters, physics, navigation... -> audio music
9
+ // The session reset steps (sessionEnd, worldLoad, afterLoad, sessionStart: the sequence is declared in core/saves/session.js) run in this same order, so an
10
+ // order between two modules' resets is declared like any other (stage, before / after), never left to install order or to when a listener was added.
9
11
  // before / after: lists of module or capability names (not-installed names are ignored; a capability means whichever module provides it now, so the order follows a replaces);
10
12
  // they order modules only inside one stage. One that contradicts the stage order (a 'control' module with after: ['sky']) makes use() throw naming both modules and stages;
11
13
  // a cycle makes use() throw on the spot, naming the modules on it. A contradiction reached through provides throws the same way: an order must not turn into a hint after a replaces.
@@ -28,7 +30,7 @@
28
30
  // ctx.mod(point, o) = ctx.track(engine.mod(point, { ...o, owner: ctx.name })): a module's changes to shared values go with it too.
29
31
  // ctx.rule(name, default, names?) = a replaceable rule on a plain shared point: .decide(id, facts) gives a built-in name, false for manual, or what the game's function answered.
30
32
  // ctx.input.define(name, { context }) / ctx.input.bind(name, keys): the module's input declarations and bindings, gone with it too.
31
- // ctx.ops.define, ctx.saves.define, ctx.ui.define, ctx.stream.addReadyCheck, ctx.budget.metric, ctx.things.addSource / explainWith, ctx.ground.provide / addColliders:
33
+ // ctx.ops.define, ctx.saves.define, ctx.ui.define, ctx.stream.addReadyCheck, ctx.budget.metric, ctx.things.addSource / explainWith / recordsLoaded, ctx.ground.provide / addColliders:
32
34
  // the same registrars, recorded in the one scope with kind, id, owner and instance (engine.catalog(name).resources reads it). Built-in modules register only through
33
35
  // these (tools/tests/module-boundaries). A save part leaving keeps its data as unattached data of the save (Saves.define), so a module unloaded for a while loses nothing.
34
36
  // Every install is its own instance (engine._modInst: name -> token): a ctx belongs to one install, not to a name. An async init that resumes after
@@ -289,6 +291,19 @@ export const moduleMethods = {
289
291
  },
290
292
  /** @internal the one gate for module hooks, the loop's and afterLoad (saveApply.js): registered (init not run yet), initializing, failed, disabled, blocked run none */
291
293
  _runsHooks(name) { return this._modState.get(name) === 'running' && !this._modBlocked.has(name); },
294
+ /**
295
+ * @internal One step of the session reset (session.js declares the sequence): every installed module's hook of that name, in moduleOrder, each run like
296
+ * an event listener (Events._call: inside a load an error fails the load, outside it is reported). The gate is the one the listeners these hooks
297
+ * replaced had: a module whose init failed lost its listeners (_dropTracked), so it gets no reset either; one still initializing gets it (it guards itself)
298
+ */
299
+ _resetStep(step, ...args) {
300
+ if (this.events.muted > 0) return; // an atomic op's rollback puts plain data back and announces nothing (opsAtomic.js): it is no reset either
301
+ for (const name of this.moduleOrder) {
302
+ const m = this.modules.get(name), st = this._modState.get(name);
303
+ if (typeof m?.[step] !== 'function' || st === 'failed' || st === 'disabled' || st === 'disposed') continue; // disabled: a picture / ui module switched off after a throw lost its listeners too (errors.js disableModule)
304
+ this.events._call(`${name}.${step}`, () => m[step](this, ...args), []);
305
+ }
306
+ },
292
307
  /**
293
308
  * @internal may this install (token from engine._modInst) still register? It is the one under its name and not closed. Closed = its signal aborted (_dropTracked:
294
309
  * unload, rollback, failed init), set before the cleanup runs, so a late callback and a remove() that calls ctx.track during that cleanup are both refused (design 6.1)
@@ -423,7 +438,9 @@ export const moduleMethods = {
423
438
  ui: { define: owned('ui', (n, factory, def) => this.ui.define(n, factory, def)) },
424
439
  stream: { addReadyCheck: owned('ready', (n, fn) => this.stream.addReadyCheck(n, fn)) },
425
440
  budget: { metric: owned('metric', (n, read, o) => this.budget.metric(n, read, o)) },
426
- things: { addSource: ifLive(src => own('source', name, this._things.addSource(src))), explainWith: ifLive(fn => own('explainer', name, this.explainWith(fn))) },
441
+ things: { addSource: ifLive(src => own('source', name, this._things.addSource(src))), explainWith: ifLive(fn => own('explainer', name, this.explainWith(fn))),
442
+ // the records source replaced its records wholesale (a load): core runs the worldLoad reset step, then tells the game (session.js step 2)
443
+ recordsLoaded: info => { this._resetStep('worldLoad', info); this.events.emit('world:load', info); } },
427
444
  ground: { provide: provideGround, addColliders: ifLive(fn => own('colliders', name, this.addGroundColliders(fn))) },
428
445
  };
429
446
  },
@@ -87,6 +87,7 @@ export class Page {
87
87
  toast(engine, engine.t('page.gpuBack'));
88
88
  // a restored context has empty shadow maps, and a map kept on purpose (autoUpdate off, a budget) would stay blank until the game next asked for it
89
89
  setShadowUpdate(engine.renderer, engine.scene, { now: true });
90
+ engine._gpu?.reset(); // its timer queries belonged to the lost context: adaptive resolution would keep reading the last time from before the loss
90
91
  engine.events.emit('page:contextrestored');
91
92
  }, { signal });
92
93
  // WebGPU fires no canvas event, three calls this hook. Its WebGL2 backend calls it too, but there the listeners above report the loss and its return
@@ -41,7 +41,7 @@ import { defineSkipOp } from '../time/skip.js';
41
41
  import { installThings } from '../scene/thingOps.js';
42
42
  import { Plugins } from './plugins.js';
43
43
  import { watchGameLights } from '../scene/gameLights.js';
44
- import { tierChanged } from '../scene/tier.js';
44
+ import { tierChanged, tierDefined } from '../scene/tier.js';
45
45
 
46
46
  /**
47
47
  * Create the engine services on `engine` (called once from the Engine constructor, after the renderer, scene and uniforms exist).
@@ -84,6 +84,7 @@ export function createServices(engine, { canvas, validate, locale, strings, save
84
84
  defineHoldStacks(engine);
85
85
  // the one quality value (engine.tier): the device gives the base, the player's preset sets over it. settingsSet: on this point the player's choice is a choice, not a restriction
86
86
  engine.stacks.define('tier', { kind: 'value', base: engine._deviceTier, save: false, settingsSet: true, onChange: () => tierChanged(engine) }); // the post chain and cascades follow it (core/scene/tier.js onTierChange)
87
+ tierDefined(engine);
87
88
  engine.commits = new Commits(engine); // background results that affect gameplay take effect on a fixed tick (see Commits.js)
88
89
  engine.ops = new Ops(engine); // one entry point for actions (define / run / can / list / recent), see Ops.js
89
90
  engine.views = new Views(engine); // named fixed camera views for repeatable screenshots (Views.js)
@@ -70,7 +70,10 @@ export const startupMethods = {
70
70
  const ls = this.ui.get('loading'), t0 = performance.now(), L = this.loading; // measure
71
71
  const ms = t => Math.round(performance.now() - t); // measure
72
72
  const timing = {}; // module name -> { init, ready } in ms (ready = time spent waiting for isReady)
73
- for (const m of this.modules.values()) if (m.init && !this._modBlocked.has(m.name)) { // a blocked one inits if its provider comes up (modules.js)
73
+ // In waves: a module that waited for its provider (one installed later, e.g. use(x, { replaces })) inits in the next wave, awaited like the rest,
74
+ // so start() resolves only after it and critical still blocks. It used to go to _initWaiting below, which does not wait
75
+ const due = () => [...this.modules.values()].filter(m => m.init && !this._modBlocked.has(m.name) && this._modState.get(m.name) === 'registered');
76
+ for (let wave = due(); wave.length; wave = due()) for (const m of wave) if (this.modules.get(m.name) === m && !this._modBlocked.has(m.name) && this._modState.get(m.name) === 'registered') { // m itself: one replaced meanwhile inits in the next wave
74
77
  const task = L._begin(m.name, 'module', { critical: !!m.critical });
75
78
  task.phase('build');
76
79
  ls?.update({ progress: 0.1, text: this.t('common.preparing', { name: this.moduleName(m) }) });
@@ -22,7 +22,7 @@ const NEXT = {
22
22
  lights: 'many lights: light pool, engine.use(lightPool({ point: 8 })) then engine.lightPool.add(torch, { intensity: 4, distance: 8 })',
23
23
  shadowLights: 'set castShadow = false on the lights that can go without; a point light draws six shadow maps',
24
24
  shadowMaps: 'set castShadow = false on the lights that can go without; a point light draws six shadow maps',
25
- shadowMapSize: 'pick light.shadow.mapSize from engine.tier in the picture code',
25
+ shadowMapSize: 'size it with engine.shadows.mapSize(light, n) from engine.tier in the picture code, again on tier:change',
26
26
  };
27
27
 
28
28
  // "first frame 1840 ms = script 210 + construct 40 + ..." (engine.startup.phases; startup.js); empty before the first frame
@@ -38,7 +38,7 @@ export const sectionHomes = {
38
38
  "grids": "grids() after world()",
39
39
  "items": "inventory()",
40
40
  "level": "level()",
41
- "npcs": "characters()",
41
+ "npcs": "characters() after world()",
42
42
  "pickups": "pickups() after world()",
43
43
  "places": "content()",
44
44
  "props": "content()",
@@ -273,7 +273,8 @@ export const metadata = {
273
273
  "time": {
274
274
  "kind": "none",
275
275
  "hooks": [
276
- "frame"
276
+ "frame",
277
+ "sessionStart"
277
278
  ]
278
279
  }
279
280
  },
@@ -286,7 +287,9 @@ export const metadata = {
286
287
  "provides": [
287
288
  "characters"
288
289
  ],
289
- "requires": [],
290
+ "requires": [
291
+ "world"
292
+ ],
290
293
  "handRolled": "none: walking code is game movement, and any code shape would match ordinary maths",
291
294
  "stage": "late",
292
295
  "before": [
@@ -300,8 +303,7 @@ export const metadata = {
300
303
  "dialogue",
301
304
  "nav",
302
305
  "collision",
303
- "rigid",
304
- "world"
306
+ "rigid"
305
307
  ],
306
308
  "params": {
307
309
  "npcs": {
@@ -353,7 +355,8 @@ export const metadata = {
353
355
  "kind": "none",
354
356
  "hooks": [
355
357
  "fixed",
356
- "frame"
358
+ "frame",
359
+ "worldLoad"
357
360
  ],
358
361
  "noSkip": "fixed steps paths, control holders and riders, none of which a time jump moves; schedules read the calendar clock"
359
362
  }
@@ -502,7 +505,9 @@ export const metadata = {
502
505
  ],
503
506
  "time": {
504
507
  "kind": "none",
505
- "hooks": []
508
+ "hooks": [
509
+ "worldLoad"
510
+ ]
506
511
  }
507
512
  },
508
513
  "debugPanel": {
@@ -608,6 +613,7 @@ export const metadata = {
608
613
  "kind": "none",
609
614
  "hooks": [
610
615
  "frame",
616
+ "sessionEnd",
611
617
  "afterLoad"
612
618
  ]
613
619
  }
@@ -650,7 +656,10 @@ export const metadata = {
650
656
  "saves": [],
651
657
  "time": {
652
658
  "kind": "none",
653
- "hooks": []
659
+ "hooks": [
660
+ "sessionEnd",
661
+ "sessionStart"
662
+ ]
654
663
  }
655
664
  },
656
665
  "grids": {
@@ -733,7 +742,8 @@ export const metadata = {
733
742
  "time": {
734
743
  "kind": "none",
735
744
  "hooks": [
736
- "frame"
745
+ "frame",
746
+ "worldLoad"
737
747
  ]
738
748
  }
739
749
  },
@@ -847,7 +857,8 @@ export const metadata = {
847
857
  "time": {
848
858
  "kind": "none",
849
859
  "hooks": [
850
- "frame"
860
+ "frame",
861
+ "sessionEnd"
851
862
  ]
852
863
  }
853
864
  },
@@ -1009,7 +1020,9 @@ export const metadata = {
1009
1020
  "time": {
1010
1021
  "kind": "none",
1011
1022
  "hooks": [
1012
- "frame"
1023
+ "frame",
1024
+ "sessionEnd",
1025
+ "sessionStart"
1013
1026
  ],
1014
1027
  "noSkip": "no timers or spatial state"
1015
1028
  }
@@ -1294,7 +1307,8 @@ export const metadata = {
1294
1307
  "time": {
1295
1308
  "kind": "none",
1296
1309
  "hooks": [
1297
- "frame"
1310
+ "frame",
1311
+ "sessionEnd"
1298
1312
  ]
1299
1313
  }
1300
1314
  },
@@ -1722,7 +1736,8 @@ export const metadata = {
1722
1736
  "time": {
1723
1737
  "kind": "exact",
1724
1738
  "hooks": [
1725
- "fixed"
1739
+ "fixed",
1740
+ "worldLoad"
1726
1741
  ],
1727
1742
  "noSkip": "auto pickups are spatial; respawn follows the game clock"
1728
1743
  }
@@ -1791,7 +1806,8 @@ export const metadata = {
1791
1806
  "hooks": [
1792
1807
  "fixed",
1793
1808
  "frame",
1794
- "skip"
1809
+ "skip",
1810
+ "sessionEnd"
1795
1811
  ]
1796
1812
  }
1797
1813
  },
@@ -1923,6 +1939,8 @@ export const metadata = {
1923
1939
  "kind": "none",
1924
1940
  "hooks": [
1925
1941
  "fixed",
1942
+ "sessionEnd",
1943
+ "worldLoad",
1926
1944
  "afterLoad"
1927
1945
  ],
1928
1946
  "noSkip": "bodies rest while time jumps (stepping seconds of physics would only scatter them)"
@@ -2541,6 +2559,7 @@ export const metadata = {
2541
2559
  "kind": "none",
2542
2560
  "hooks": [
2543
2561
  "frame",
2562
+ "sessionEnd",
2544
2563
  "afterLoad"
2545
2564
  ]
2546
2565
  }
@@ -50,9 +50,9 @@ export class Control {
50
50
  /** @internal the entry whose move is running now (handle.move / a behaviour run): the one caller character.move() lets through */ this._cur = null;
51
51
  /** @internal id -> Character; set by the characters module through resolveWith (core names no module) */ this.characterOf = () => null;
52
52
  engine.events.on('world:remove', ({ id }) => this.forget(id));
53
- // Two moments, and state:replaced is neither. session:end: the old playthrough stops, before anything is replaced, so no walk runs on into the swap. save:loaded: a save landed on a
54
- // running playthrough, the only word a direct apply gives. state:replaced comes last, after the save:loaded and session:start listeners that start the new state's walks: it would end them
55
- for (const n of ['save:loaded', 'session:end']) engine.events.on(n, () => this.endTasks(null, 'replaced'));
53
+ // Two moments, and state:replaced is neither. A playthrough ending: session.js calls endTasks first in its end step, before anything is replaced, so no walk runs on into the swap.
54
+ // save:loaded: a save landed on a running playthrough, the only word a direct apply gives. state:replaced comes last, after the save:loaded and session:start listeners that start the new state's walks: it would end them
55
+ engine.events.on('save:loaded', () => this.endTasks(null, 'replaced'));
56
56
  }
57
57
  /**
58
58
  * Take a character's control. step (optional): (dt, character) => ({ x, y?, z, run? }) | null | false, called each fixed step while this owner is in
package/core/ops/holds.js CHANGED
@@ -25,8 +25,11 @@ function handle(owner, remove) { return { owner, remove }; }
25
25
  export function defineHoldStacks(engine) {
26
26
  engine.stacks.define('freeze', { kind: 'any', save: false, onChange: () => engine.input?._kbSync?.() }); // who froze gameplay; a freeze gives the page's key lock back (inputKeyboard.js)
27
27
  engine.stacks.define('halt', { kind: 'any', save: false, onChange: () => { // who stopped the loop; it restarts only when empty
28
- if (engine.stacks.get('halt').size()) engine.halted = true;
29
- else if (!engine.disposed) { engine.halted = false; engine._loop(); }
28
+ // the last holder leaving gives back what was there before the first: a headless page (tests, shots) stays stepped by hand, and an engine not
29
+ // started yet gets no loop (start() begins it). Setting false and looping here made a halt taken and removed on such a page run in real time
30
+ const P = engine.stacks.get('halt');
31
+ if (P.size()) { if (!engine.halted) engine._haltBase = false; else engine._haltBase ??= true; engine.halted = true; }
32
+ else if (!engine.disposed) { engine.halted = engine._haltBase ?? false; engine._haltBase = null; if (!engine.halted && engine.phase !== 'constructed') engine._loop(); }
30
33
  engine.page._sync(); // a page hold is about the real-time loop: there is none while the loop is stopped (core/engine/page.js)
31
34
  } });
32
35
  // who holds the camera; the latest is in charge (cameraOverride). A claim that is in charge again after a newer one left gets its opts.onTop() called: it holds the camera
@@ -66,7 +69,9 @@ export const holdMethods = {
66
69
  const P = this.stacks.get('halt');
67
70
  if (P.size() && !P.has(o)) { warnOnce(coded('halt-owner', `ending the halt of '${o}': halted by ${P.names().map(n => `'${n}'`).join(', ')}, not by '${o}'. End a halt with the handle haltLoop() returned (h.remove()), or the loop stays stopped`)); return this; }
68
71
  // with holders the stack's onChange restarts the loop; with none (headless start) this call starts it
69
- if (!P.release(o) && !P.size() && !this.disposed) { this.halted = false; this._loop(); }
72
+ // an explicit resume (the bridge's threedog resume): live once no one holds a halt, also where releasing the last one gave back a headless page's stepped state
73
+ const had = P.release(o);
74
+ if (!P.size() && !this.disposed && (!had || this.halted)) { this.halted = false; this._loop(); }
70
75
  return this;
71
76
  },
72
77
  // Gameplay freeze (menus, flow 'paused'): no fixed steps (movement, timers, tick and every time view but ambient stop) while frame hooks
@@ -1,7 +1,7 @@
1
1
  // Applying a save (split out of Saves.js): every part is checked and migrated before anything changes (saveVersions.js), then loaded in order;
2
2
  // if anything in the load throws, every part reloads the state from just before the load (rollback), so a game is never left half-loaded.
3
3
  // "Anything" is the whole load, not only load() itself: a listener of an event a part emits while loading (world:load) and the modules' afterLoad
4
- // hooks count too. Reported on their own they let the load carry on: a hand-edited player position threw in a world:load listener and left the game
4
+ // hooks count too. Reported on their own they let the load carry on: a hand-edited player position threw in a worldLoad hook (then a world:load listener) and left the game
5
5
  // frozen half-loaded (durability audit 2026-11-02).
6
6
  // The capture lasts the whole load, past every await: an async part that emits after `await` (async load(d) { apply(d); await res(); emit(...) })
7
7
  // is part of the load as much as its first line. The browser has no async context to tell whose code emitted after an await, so each load
@@ -291,7 +291,7 @@ export function applyAnnounced(s, data, slot, done) {
291
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
292
292
  * freeze with them: the lines right after an unawaited apply can still step, run ops and apply again (stateReplace.js, pause). */
293
293
  function afterLoad(s, e, slot, scope) {
294
- const has = [...e.modules.values()].filter(m => m.afterLoad), q = s._replace;
294
+ const has = e.moduleOrder.map(n => e.modules.get(n)).filter(m => m?.afterLoad), q = s._replace; // in module order, like every reset step (session.js)
295
295
  if (!has.length) { takeListenerError(scope, 0); return true; }
296
296
  const job = q.pause();
297
297
  let hooks = [];
@@ -8,8 +8,18 @@
8
8
  //
9
9
  // What ending a playthrough clears: handles passed to track() and clock function timers added after start() (boot-time ones and a module's install-time ones, ctx.track, follow the module: they come back with their original delay while it stays; what a part's load() or an afterLoad sets up belongs to the new playthrough and stays),
10
10
  // a running engine.skip (cancelled), background results not yet applied (commits: worker / job results requested in the old playthrough never land), and every
11
- // save part (the state captured when start() finished is applied). Modules end their own part on 'session:end' (a cutscene is skipped, the music stops),
12
- // and the camera starts over on 'session:start' (the same rig object, as installed, keeping the view the load left on it). Listeners and hooks the game registered at boot stay: they belong to the game, not the playthrough.
11
+ // save part (the state captured when start() finished is applied). Modules end their own part in their sessionEnd hook (a cutscene is skipped, the music stops),
12
+ // and the camera starts over in its sessionStart hook (the same rig object, as installed, keeping the view the load left on it). Listeners and hooks the game registered at boot stay: they belong to the game, not the playthrough.
13
+ //
14
+ // The reset sequence, one declared order (a module joins with hooks on its definition, never with listeners whose order would be install order):
15
+ // 1. end core first (control ends the old walks), then every module's sessionEnd(e), then the 'session:end' event
16
+ // 2. apply the save parts load (saveApply.js); when the records part (world module) replaced its records it calls ctx.things.recordsLoaded, which runs
17
+ // every module's worldLoad(e, info), then emits 'world:load' (outside a session too: a quick load, a level load; an atomic op's muted rollback runs neither)
18
+ // 3. rebuild every module's afterLoad(e, turn) (saveApply.js; gameplay frozen until they settle)
19
+ // 4. start core first (what is added now is setup, things.js), then every module's sessionStart(e, info), then the 'session:start' event
20
+ // Within a step modules run in engine.moduleOrder (stage, then before / after, then install order: modules.js), so an order that matters is declared there.
21
+ // The events are notifications for the game, after the modules' step: no module relies on them for its reset. A quick load (saves.load / apply)
22
+ // runs steps 2 and 3 only.
13
23
  // engine.time.tick and every time view (core/time/time.js) start again from 0 or the save's value, and physics (rigid) rebuilds its world (velocities, sleep, solver caches), as on a fresh page.
14
24
  // Events: 'session:end' (before the reset; flow returns to its start state), 'session:start' { kind: 'new' | 'load', slot? } (after; flow goes to 'playing').
15
25
  // Around a state replacement, one list for every door (saves.apply, saves.load, session.newGame / load / quit):
@@ -196,7 +206,11 @@ export class Session {
196
206
  /** @internal end the playthrough, apply, then announce the new one */
197
207
  async _begin(fn, apply, info) {
198
208
  const ok = await this._reset(fn, apply);
199
- if (ok) this._started();
209
+ if (ok) {
210
+ this._started();
211
+ this.engine._things.setupTurn(); // step 4, core first: what the hooks and listeners below add is setup, rebuilt by code every playthrough
212
+ this.engine._resetStep('sessionStart', info);
213
+ }
200
214
  this.engine.events.emit(ok ? 'session:start' : 'session:failed', info);
201
215
  // ?play starts the first run inside engine.start(), so a session:start listener attached after `await engine.start()` misses it silently; hint once.
202
216
  // 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.
@@ -210,7 +224,9 @@ export class Session {
210
224
  if (!this._base) throw codedError('session-early', fmt(DEV.early, { fn }));
211
225
  this._busy = true;
212
226
  try {
213
- e.events.emit('session:end'); // modules end their part: a running engine.skip is cancelled, a cutscene skipped, the music stopped
227
+ e.events._call('session:end', () => e.control.endTasks(null, 'replaced'), []); // step 1, core first: no walk runs on into the swap (a throwing task callback is reported, as from the listener it was)
228
+ e._resetStep('sessionEnd'); // modules end their part: a cutscene skipped, the music stopped
229
+ e.events.emit('session:end'); // then the game hears it (a running engine.skip listens here and is cancelled)
214
230
  await new Promise(r => setTimeout(r, 0)); // main-loop: one macrotask, so what session:end listeners started (a skipped cutscene's last steps) settles first
215
231
  if (e.disposed) return false; // disposed in that macrotask: there is no state left to replace
216
232
  // background results die inside apply (saveApply), which gives them back when it fails, before its rollback: a second epoch held here made what the rollback asked for look old
@@ -222,5 +222,7 @@ export class GpuTimer {
222
222
  this.free.push(q);
223
223
  }
224
224
  }
225
+ /** A restored context: the queries were the lost one's (never answer, so timing stopped) and ms was measured under the pressure that lost it */
226
+ reset() { this.pending = []; this.free = []; this.active = null; this.ms = null; this.ext = this.gl?.getExtension?.('EXT_disjoint_timer_query_webgl2') ?? null; }
225
227
  dispose() { if (!this.ext || this.gl.isContextLost()) return; for (const q of [...this.pending, ...this.free]) this.gl.deleteQuery(q); this.pending = []; this.free = []; }
226
228
  }
@@ -86,15 +86,16 @@ export class Things {
86
86
  this.byId = new Map(); // id -> WeakRef(root)
87
87
  this.n = 0; // session ids obj#n
88
88
  this.stacks = 0;
89
- this.setup = false; // true inside session:start listeners: what they add is rebuilt by code every playthrough
89
+ this.setup = false; // true inside sessionStart hooks and session:start listeners: what they add is rebuilt by code every playthrough
90
90
  this.over = new Map(); // stable id -> { orig, cur }: thing.set overrides (orig = the code-built transform, for load / newGame / undo)
91
91
  this.removed = new Set(); // stable ids removed with thing.remove (saved)
92
92
  this.gone = new Map(); // id -> { obj, parent }: removed with thing.remove, detached and held so undo or a load can put it back
93
93
  this.pending = { set: {}, removed: new Set() }; // from a loaded save, objects not registered yet (orphans if they never come)
94
94
  this.unsaved = new Set(); // WeakRefs of session-tier objects someone expected to keep (save: true, or made inside an op)
95
95
  this.conflicts = []; // dev: "two systems manage one object" findings, newest last
96
- e.events.on('session:start', () => { this.setup = true; queueMicrotask(() => { this.setup = false; }); });
97
96
  }
97
+ /** @internal step 4 of the session reset (session.js), before the modules' sessionStart hooks and the 'session:start' listeners: what they add is setup */
98
+ setupTurn() { this.setup = true; queueMicrotask(() => { this.setup = false; }); }
98
99
  /**
99
100
  * A store of records that share the id space with engine.add objects (the world module registers itself at install). The shape core uses:
100
101
  * { has(id), get(id) -> { position, ... }, ids(), idOf(obj) -> id | null (model -> record), view(id) -> Object3D | null,