threedog 2.2.0 → 2.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 (197) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +4 -4
  3. package/core/assets/Animator.js +66 -12
  4. package/core/assets/ik.js +144 -18
  5. package/core/assets/maskLayer.js +377 -0
  6. package/core/assets/rootMotion.js +148 -0
  7. package/core/audio/Audio.js +100 -4
  8. package/core/base/errorCodes.js +6 -369
  9. package/core/base/errorCodesModules.js +378 -0
  10. package/core/engine/Engine.js +8 -5
  11. package/core/engine/Loading.js +8 -4
  12. package/core/engine/copies.js +1 -1
  13. package/core/engine/headlessLoad.js +15 -4
  14. package/core/engine/lifecycle.js +1 -0
  15. package/core/engine/loop.js +23 -3
  16. package/core/engine/moduleSlots.js +3 -7
  17. package/core/engine/modules.js +30 -58
  18. package/core/engine/startup.js +3 -3
  19. package/core/input/Input.js +7 -3
  20. package/core/input/inputContext.js +3 -2
  21. package/core/input/inputSeat.js +1 -1
  22. package/core/inspect/DebugOverrides.js +1 -1
  23. package/core/inspect/Describe.js +7 -2
  24. package/core/inspect/describeRender.js +4 -1
  25. package/core/inspect/describeText.js +2 -2
  26. package/core/inspect/metadata.generated.js +380 -74
  27. package/core/inspect/pictureMenu.js +2 -0
  28. package/core/inspect/pictureWriters.js +4 -3
  29. package/core/ops/Ops.js +9 -3
  30. package/core/ops/actor.js +10 -0
  31. package/core/ops/control.js +17 -6
  32. package/core/ops/holds.js +1 -1
  33. package/core/ops/opsAtomic.js +6 -1
  34. package/core/ops/opsGuard.js +2 -2
  35. package/core/ops/owned.js +37 -11
  36. package/core/ops/sharedPoint.js +5 -1
  37. package/core/ops/stacks.js +30 -7
  38. package/core/saves/Saves.js +0 -2
  39. package/core/saves/saveApply.js +7 -7
  40. package/core/saves/session.js +6 -3
  41. package/core/saves/stateReplace.js +71 -41
  42. package/core/scene/Rays.js +74 -26
  43. package/core/scene/canvasBox.js +9 -0
  44. package/core/scene/gameLights.js +19 -11
  45. package/core/scene/sceneDelta.js +8 -4
  46. package/core/scene/sceneMethods.js +2 -1
  47. package/core/stream/chunkStream.js +21 -0
  48. package/core/stream/dirtyWatch.js +37 -0
  49. package/core/time/skip.js +9 -6
  50. package/core/time/time.js +72 -18
  51. package/docs/AI.md +22 -21
  52. package/docs/API.md +5 -4
  53. package/docs/CODEMAP.md +16 -10
  54. package/docs/COMMANDS.md +5 -5
  55. package/docs/CONVENTIONS.md +9 -25
  56. package/docs/api/ambience.md +1 -0
  57. package/docs/api/assets.md +10 -3
  58. package/docs/api/audio.md +5 -3
  59. package/docs/api/decals.md +16 -0
  60. package/docs/api/engine.md +1 -0
  61. package/docs/api/tools.md +3 -1
  62. package/docs/api/water.md +3 -0
  63. package/docs/recipes/09-materials-lights-models.md +15 -1
  64. package/docs/recipes/13-animation.md +51 -10
  65. package/docs/recipes/16-dev-bridge.md +4 -4
  66. package/docs/recipes/31-audio.md +15 -9
  67. package/docs/recipes/34-environment-lighting.md +11 -1
  68. package/docs/recipes/44-water-weather-hooks.md +1 -0
  69. package/examples/action/.threedog/content-index.json +1 -0
  70. package/examples/perf-island/.threedog/content-index.json +1 -0
  71. package/examples/plain-picture/.threedog/content-index.json +1 -0
  72. package/examples/rc2d/.threedog/content-index.json +1 -0
  73. package/examples/styletest/.threedog/content-index.json +1 -0
  74. package/examples/techniques/outlines-and-rim/main.js +1 -1
  75. package/examples/techniques/procedural-surface/main.js +1 -1
  76. package/examples/techniques/stylized-shading/main.js +1 -1
  77. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  78. package/examples/world/.threedog/content-index.json +1 -0
  79. package/index.d.ts +6 -2
  80. package/index.js +3 -2
  81. package/llms.txt +11 -10
  82. package/modules/ambience/Ambience.js +97 -15
  83. package/modules/camera/common.js +18 -12
  84. package/modules/characters/Character.js +30 -3
  85. package/modules/characters/NPC.js +2 -5
  86. package/modules/characters/astar.js +45 -14
  87. package/modules/characters/movers/rapier.js +53 -41
  88. package/modules/characters/movers/simple.js +37 -24
  89. package/modules/characters/npcView.js +2 -2
  90. package/modules/characters/pathAsync.js +3 -3
  91. package/modules/collision/contract.js +2 -2
  92. package/modules/content/index.js +3 -0
  93. package/modules/content/models.js +11 -4
  94. package/modules/content/templates.js +11 -11
  95. package/modules/debug/DebugPanel.js +1 -0
  96. package/modules/decals/Decals.js +393 -0
  97. package/modules/decals/index.js +1 -0
  98. package/modules/gameplay/Container.js +2 -0
  99. package/modules/gameplay/Containers.js +17 -3
  100. package/modules/gameplay/Dialogue.js +1 -1
  101. package/modules/gameplay/Interactions.js +7 -6
  102. package/modules/gameplay/Inventory.js +5 -1
  103. package/modules/gameplay/Quests.js +4 -3
  104. package/modules/gameplay/inventoryOps.js +2 -2
  105. package/modules/gameplay/pickups.js +32 -12
  106. package/modules/gameplay/questSave.js +2 -2
  107. package/modules/grid/index.js +8 -2
  108. package/modules/hud/index.js +1 -1
  109. package/modules/level/heightfield.js +1 -0
  110. package/modules/level/index.js +3 -2
  111. package/modules/level/nodes.js +2 -1
  112. package/modules/lights/index.js +27 -4
  113. package/modules/lights/slots.js +33 -16
  114. package/modules/nav/contract.js +4 -4
  115. package/modules/nav/index.js +6 -2
  116. package/modules/net/Client.js +24 -11
  117. package/modules/net/Host.js +73 -20
  118. package/modules/net/index.js +33 -21
  119. package/modules/net/sync.js +38 -8
  120. package/modules/net/transports.js +7 -3
  121. package/modules/particles/Particles.js +11 -4
  122. package/modules/particles/contract.js +6 -6
  123. package/modules/particles/effect.js +0 -1
  124. package/modules/rigid/RigidBodies.js +69 -57
  125. package/modules/rigid/Vehicles.js +8 -7
  126. package/modules/rigid/ragdoll.js +4 -6
  127. package/modules/rigid/rapierCompat.js +90 -0
  128. package/modules/rigid/sync.js +2 -5
  129. package/modules/settings/Settings.js +10 -4
  130. package/modules/sky/Sky.js +10 -2
  131. package/modules/sky/environment.js +29 -13
  132. package/modules/sky/frame.js +2 -2
  133. package/modules/sky/shader.js +5 -2
  134. package/modules/sky/skyModule.js +2 -2
  135. package/modules/swarm/Swarm.js +3 -2
  136. package/modules/swarm/grid.js +12 -7
  137. package/modules/terrain/ChunkManager.js +16 -26
  138. package/modules/triggers/index.js +5 -6
  139. package/modules/vegetation/draw.js +62 -26
  140. package/modules/vegetation/groundChunks.js +8 -22
  141. package/modules/water/Water.js +152 -24
  142. package/modules/water/surface.js +43 -20
  143. package/modules/weather/weatherDraw.js +4 -1
  144. package/modules/world/World.js +21 -2
  145. package/modules/world/index.js +5 -0
  146. package/modules/world/persist.js +1 -0
  147. package/modules/world/records.js +3 -1
  148. package/modules/world/sim.js +3 -2
  149. package/modules/world/simFar.js +4 -2
  150. package/modules/world/state.js +7 -1
  151. package/package.json +2 -2
  152. package/presets.js +30 -0
  153. package/render/PostFX.js +24 -17
  154. package/render/backend.js +72 -31
  155. package/render/cascades.js +25 -14
  156. package/render/cascades.tsl.js +32 -21
  157. package/render/fogLook.js +2 -1
  158. package/render/fx/detail.tsl.js +3 -0
  159. package/render/fx/library.tsl.js +1 -1
  160. package/render/fx/particles.tsl.js +4 -18
  161. package/render/fx/pcss.tsl.js +2 -2
  162. package/render/fx/postWebGPU.tsl.js +47 -25
  163. package/render/fx/sky.tsl.js +6 -18
  164. package/render/fx/uniforms.tsl.js +16 -0
  165. package/render/fx/water.tsl.js +24 -5
  166. package/render/fxNumbers.js +2 -0
  167. package/render/impostor.tsl.js +10 -6
  168. package/render/lights.js +6 -6
  169. package/render/occlusion.js +17 -6
  170. package/render/patches.js +40 -28
  171. package/render/postWebGL.js +6 -4
  172. package/render/reflectionProbes.js +302 -0
  173. package/render/shaderErrors.js +18 -8
  174. package/render/shadowCache.tsl.js +10 -5
  175. package/render/shadows.js +70 -49
  176. package/render/threeCompat.js +166 -0
  177. package/types/core.d.ts +33 -3
  178. package/types/gameplay.d.ts +80 -0
  179. package/types/generated/core/audio/Audio.d.ts +18 -1
  180. package/types/generated/core/ops/Ops.d.ts +2 -1
  181. package/types/generated/core/ops/control.d.ts +7 -3
  182. package/types/generated/core/saves/session.d.ts +4 -1
  183. package/types/generated/modules/ambience/Ambience.d.ts +6 -0
  184. package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
  185. package/types/generated/modules/grid/index.d.ts +27 -3
  186. package/types/generated/modules/net/index.d.ts +8 -3
  187. package/types/generated/modules/sky/Sky.d.ts +1 -0
  188. package/types/generated/modules/water/Water.d.ts +15 -0
  189. package/types/generated/modules/world/index.d.ts +5 -0
  190. package/types/generated/render/patches.d.ts +5 -0
  191. package/types/physics.d.ts +66 -9
  192. package/types/tsl.d.ts +2 -0
  193. package/types/world.d.ts +2 -0
  194. package/ui/Parts.js +3 -2
  195. package/docs/MIGRATING-0.7.md +0 -39
  196. package/docs/MIGRATING-0.8.md +0 -171
  197. package/modules/rigid/refresh.js +0 -10
@@ -1,40 +1,9 @@
1
- // Replacing the game state is one transaction, owned here. saves.apply, saves.load, session.newGame / load / quit all enter through run(), so:
2
- // - One at a time. A request made while another runs waits its turn, in order, and only then reads its save and takes its rollback point:
3
- // two overlapping loads left a mix of both saves (X from one, Y from the other), and the second one's rollback point was the first one's half.
4
- // A request with a key joins the last one in line when the key is the same (a double-clicked Restart). Nothing is refused for being busy.
5
- // - Idle means now. run() calls fn synchronously and a job that returns a plain value ends before run() returns. A save whose parts are all
6
- // synchronous is applied on the line after apply, and replays rely on apply, step, apply, step in one stretch of code. So when only its afterLoad
7
- // is left, which starts a microtask later, the job is paused: the marker is off (no click or net message can arrive before a microtask, only
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
- // 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
- // 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).
14
- // - One marker. `replacing` is true from reading the save through its parts, afterLoad and any rollback; begin() / end() bracket that span
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
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
17
- // session:start listeners still run ops, while the turn stays taken so the next replacement cannot cut in between.
18
- // - One read rule. saves.save asks through read(): a save collected while parts are half loaded would mix two states, so it waits for every replacement
19
- // already in line. It never takes over a paused job (that job's hooks must still run) and holds the turn only for the collect, not for the disk write.
20
- // - One freeze. hold() stops fixed steps while the replacement waits on something; it is the only freeze a load takes, and end() drops it.
21
- // - One identity, passed by hand. A part's load(data, turn) and a module's afterLoad(engine, turn) get the turn of their replacement, and level.load / content.load take it back as { turn }:
22
- // that call belongs to the replacement and goes at once, before or after any await. Nothing else can say so. A browser has no async context, so what runs after an await looks like a click;
23
- // a marker held across the await would let the click in as well. No turn, or one that ended, is an outside request and waits in line, however it was made. The cost is the one a caller
24
- // can forget: an awaited request without its turn waits for itself. Dev names it when something stalls in line (save-nested). The rule is the same before and after the first await, so
25
- // a load() does not start hanging on the day it gains an await.
26
- // Async rebuild work needs no other stamp: a part's load() and every afterLoad settle inside their turn (saveApply.js waits for all of them, even when one failed), and a late part
27
- // loads in a turn of its own, whole (adoptPart). What a module starts and does not return (a background job) is engine.commits' case: invalidate() drops it unless its valid() says otherwise.
28
- // - One word for a change that takes several steps. A door trip or a cutscene holds a stateTurn: between its first and last line the world is between two states no load could continue from, so
29
- // an autosave waits for it to end. Only the autosave: a save the game asks for itself picked its moment, and may be awaited inside that very trip. A replacement does not wait either, a new game
30
- // is how a cutscene ends. The owners call stateTurn; this file does not know who they are.
31
- // - A level change waits for a replacement already in line (whenTurnFree) and does not take the turn: two doors in a row still overtake each other, and a save made while a file downloads
32
- // stores the level that stands, whole. What a part's load() or afterLoad asks with its turn goes at once: it is inside the turn and cannot wait for itself.
33
- // - One word for "the state was replaced". A job that changed the state emits the internal state:replaced { undone } as it ends, last, whichever door it came through, so derived state listens to
34
- // that alone. undone: a failed load put the old state back. A job that refused before changing anything says nothing; a job taken over is announced by the one that took over.
35
- // - One way back. A failed pack that has to wait for its old level holds everything in line and gameplay until the old state is whole again (restoring): a save or a load in the gap would
36
- // read or write half of it. Nothing about the saved state changed, so no state:replaced.
37
- // A new replacement has no place inside a running one: it starts after, so a load() may ask for it and not await it (or ask from a save:loaded or session:start listener).
1
+ // State replacement transactions (saves.apply / load, session.newGame / load / quit, applyState):
2
+ // - Serialized queue: one replacement runs at a time in request order; same-key requests join the tail.
3
+ // - Synchronous fast path: idle sync jobs finish immediately; jobs paused only for afterLoad may be overtaken by a direct apply/load when nobody else is waiting (late adoptPart jobs are passable by reads and other late parts).
4
+ // - Lifecycle markers: `replacing` spans save reading through part loads, afterLoad, and rollback; `hold()` freezes fixed steps only while awaiting; `restoring` keeps the marker and freeze until rollback completes.
5
+ // - Turn identity: `load(data, ctx)` and `afterLoad(engine, ctx)` receive the job's frozen turn context. Registered helpers (`ctx.loadLevel`, `ctx.loadContent`, or `{ turn }` to `whenTurnFree`) run inside the active turn; new replacements (`loadSave`, `loadSession`, `newGame`, `quit`) inline only inside an outer whole container (e.g. UrlState) when no replacement is running, and otherwise queue after the current job.
6
+ // - Completion: jobs that changed state emit `state:replaced { undone }` at the end of their turn; `stateTurn()` pauses autosave across multi-step transitions.
38
7
  import { DEV, warnOnce } from '../base/validate.js';
39
8
  import { coded, codedError } from '../base/errorHints.js';
40
9
 
@@ -44,6 +13,23 @@ const NESTED = "something has waited long behind a state replacement that has no
44
13
  const STALL_MS = 3000; // a dev hint only: a slow download behind a load is told too, and the words say "if"
45
14
  const FREEZE = 'threedog:state-replace'; // a namespaced owner: a game's own freeze('load') must not be released by (or release) the engine's
46
15
 
16
+ /**
17
+ * Bound replacement context passed as the 2nd argument to load(data, ctx) and afterLoad(e, ctx):
18
+ * remains a frozen identity token for legacy `{ turn }` callers while letting code call `ctx.loadSave(...)` or module-registered helpers (`ctx.loadLevel`, `ctx.loadContent`, ...) without hand-threading `{ turn }`.
19
+ */
20
+ function makeTurn(q, helpers) {
21
+ const e = q.engine;
22
+ const inline = () => (q.job?.turn === turn && q.job.whole && !q.replacing && !e.session._busy ? { turn } : undefined);
23
+ const turn = {
24
+ loadSave(slot) { return e.saves.load(slot, inline()); },
25
+ loadSession(slot) { return e.session.load(slot, inline()); },
26
+ newGame() { return e.session.newGame(inline()); },
27
+ quit() { return e.session.quit(inline()); },
28
+ };
29
+ for (const [name, fn] of helpers) turn[name] = (...args) => q._asHelper(() => fn(turn, ...args));
30
+ return Object.freeze(turn);
31
+ }
32
+
47
33
  /** @internal One state replacement at a time, and the marker that says one is under way (top of the file) */
48
34
  export class StateReplace {
49
35
  constructor(engine) {
@@ -56,6 +42,29 @@ export class StateReplace {
56
42
  /** How many stateTurns are open */ this.turns = 0;
57
43
  /** Restore jobs (restoring) not ended yet: while any is, end() leaves the marker and the freeze on */ this.restores = 0;
58
44
  /** 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;
45
+ /** @internal Turn currently running synchronously inside load() / afterLoad(): detects missing { turn } immediately in dev */ this._syncTurn = null;
46
+ /** @internal Depth of addTurnHelper invocations */ this._helperDepth = 0;
47
+ /** @internal Module-registered helpers exposed on each turn context (e.g. loadLevel, loadContent) */ this._helpers = new Map();
48
+ }
49
+
50
+ /** @internal Run a registered turn helper so helper-originated work is distinguished from a nested replacement */
51
+ _asHelper(fn) {
52
+ this._helperDepth++;
53
+ try { return fn(); } finally { this._helperDepth--; }
54
+ }
55
+
56
+ /** Current replacement phase: 'idle' | 'replacing' | 'paused' | 'restoring' */
57
+ get phase() {
58
+ if (this.restores > 0) return 'restoring';
59
+ if (!this.job) return 'idle';
60
+ return this.job.paused ? 'paused' : 'replacing';
61
+ }
62
+
63
+ /** @internal Run fn synchronously while recording its active turn (for instant dev diagnostics if a nested request forgets { turn }) */
64
+ withTurn(turn, fn) {
65
+ const prev = this._syncTurn;
66
+ this._syncTurn = turn;
67
+ try { return fn(); } finally { this._syncTurn = prev; }
59
68
  }
60
69
 
61
70
  /**
@@ -68,10 +77,12 @@ export class StateReplace {
68
77
  * @returns {Promise<any>}
69
78
  */
70
79
  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); } }
80
+ if (turn && this.job?.turn === turn && ((!this.replacing && !this.engine.session._busy) || this._helperDepth > 0)) {
81
+ try { return Promise.resolve(fn()); } catch (err) { return Promise.reject(err); }
82
+ }
72
83
  const last = this.waiting.at(-1) ?? this.job;
73
84
  if (key && last?.key === key) return last.done;
74
- const job = { key, fn, done: null, settle: null, paused: false, whole, behind, turn: Object.freeze({}) };
85
+ const job = { key, fn, done: null, settle: null, paused: false, whole, behind, turn: makeTurn(this, this._helpers) };
75
86
  job.done = new Promise(res => { job.settle = res; });
76
87
  if (this.job && (behind && !this._passable() || !this.job.paused || this.waiting.length)) this._line(job); else this._start(job);
77
88
  return job.done;
@@ -109,11 +120,19 @@ export class StateReplace {
109
120
  _line(job) {
110
121
  const L = this.engine.loading, since = performance.now(); // measure: the limit is a wall clock, a stepped or frozen engine runs no frames
111
122
  this.waiting.push(job);
112
- if (DEV) setTimeout(() => { if (this.waiting.includes(job)) warnOnce(coded('save-nested', NESTED), 'save-nested'); }, STALL_MS); // debug: a dev hint on real time, gameplay never reads it
123
+ if (DEV && this._syncTurn && this.job?.turn === this._syncTurn) warnOnce(coded('save-nested', NESTED), 'save-nested');
113
124
  job.done = L._limit(job.done, () => this.waiting.includes(job) ? Math.max(since, this.moved, ...[...L.tasks.values()].map(t => t.at)) : null, () => {
114
- this.waiting.splice(this.waiting.indexOf(job), 1);
125
+ const i = this.waiting.indexOf(job); if (i >= 0) this.waiting.splice(i, 1);
115
126
  return codedError('save-nested', NESTED);
116
127
  });
128
+ if (DEV && !this.engine.signal?.aborted) {
129
+ const sig = this.engine.signal;
130
+ let timer;
131
+ const stop = () => { clearTimeout(timer); sig?.removeEventListener('abort', stop); };
132
+ timer = setTimeout(() => { stop(); if (this.waiting.includes(job)) warnOnce(coded('save-nested', NESTED), 'save-nested'); }, STALL_MS); // debug: a dev hint on real time, gameplay never reads it
133
+ sig?.addEventListener('abort', stop, { once: true });
134
+ job.done.then(stop, stop);
135
+ }
117
136
  }
118
137
 
119
138
  /** Start a job; its turn ends when fn's result settled, whichever way (a failed job must not block the next) */
@@ -201,3 +220,14 @@ export function whenTurnFree(e, fn, turn) { return liveTurn(e, turn) ? fn() : e.
201
220
 
202
221
  /** @internal Is this the turn of the replacement running now? A turn kept after its load ended is an outside request, like no turn at all @param {any} e @param {object} [turn] */
203
222
  export const liveTurn = (e, turn) => !!turn && e.saves._replace.job?.turn === turn;
223
+
224
+ /**
225
+ * @internal Register a bound helper method on each replacement turn context (e.g. `ctx.loadLevel` / `ctx.loadContent`).
226
+ * Tracked by modules via `ctx.track(...)` so core never imports or names concrete modules.
227
+ * @param {any} e @param {string} name @param {(turn: object, ...args: any[]) => any} fn @returns {{ remove(): void }}
228
+ */
229
+ export function addTurnHelper(e, name, fn) {
230
+ const m = e.saves._replace._helpers;
231
+ m.set(name, fn);
232
+ return { remove() { if (m.get(name) === fn) m.delete(name); } };
233
+ }
@@ -81,6 +81,10 @@ export class Rays {
81
81
  this.ray = new THREE.Raycaster();
82
82
  this.ray.firstHitOnly = true; // only the nearest hit per mesh (faster with a BVH)
83
83
  this.ray.layers.enable(RESERVED_LAYERS.batched); // originals drawn through engine.batching sit here and must still be hit
84
+ /** @internal reusable scratch array for m.raycast */ this._hits = [];
85
+ /** @internal re-entrancy guard for _hits */ this._hitsBusy = false;
86
+ /** @internal reusable provider origin/dir vectors (keeps _v / _d and multi-provider calls isolated without per-cast clone) */
87
+ this._po = new THREE.Vector3(); this._pd = new THREE.Vector3(); this._so = new THREE.Vector3(); this._sd = new THREE.Vector3();
84
88
  }
85
89
  /**
86
90
  * Register a static object and every mesh under it (an array also works; meshes over 256 triangles get a BVH); occluder: true also blocks the camera. Returns a handle { remove() }. Matrices are read once per tick and frame: a registered mesh moved between two rays of one step needs updateMatrixWorld() first.
@@ -164,41 +168,82 @@ export class Rays {
164
168
  const { far = Infinity, targets = 'static', filter = null, occluders = false } = opts;
165
169
  this.engine.camera.updateWorldMatrix(true, false); // moved in this step: the matrix is only refreshed by the render
166
170
  this.ray.setFromCamera(_ndc.set(ndcX, ndcY), this.engine.camera);
167
- this.ray.far = far;
171
+ this.ray.near = 0; this.ray.far = far;
168
172
  return this._cast(this.ray.ray.origin, this.ray.ray.direction, far, targets, filter, occluders);
169
173
  }
170
174
 
171
175
  /** @internal */
172
176
  _cast(o, d, far, targets, filter, occluders) {
173
- const scene = this.engine.scene, hits = [];
174
- let best = null;
175
- const take = h => { if (h && h.distance <= far && (!best || h.distance < best.distance) && (!filter || filter(h))) best = h; };
176
- if (Array.isArray(targets)) {
177
- for (const t of targets) t.updateWorldMatrix(true, true);
178
- this.ray.firstHitOnly = false;
179
- for (const h of this.ray.intersectObjects(targets, true)) { if (shown(h.object)) { take(toHit(h)); if (best) break; } }
180
- this.ray.firstHitOnly = true;
181
- } else {
182
- const ray = this.ray.ray, tick = this.engine.time.tick;
183
- // matrices are refreshed by the render, and a fixed step runs before it: what moved or was added since would answer from where it was.
184
- // Once per tick and per frame, not per ray (5000 statics x 4 rays a frame measured 12 ms against 3-5 ms): a static moved between two rays of one step needs updateMatrixWorld() on it first (docs/api/rays.md)
185
- if (this.fresh !== tick) { this.fresh = tick; for (const m of this.statics.keys()) m.updateWorldMatrix(true, false); }
186
- this.ray.firstHitOnly = !filter; // BVH keeps one hit per mesh: a filter running after that would lose the hit it accepts behind the one it refuses
187
- for (const [m, s] of this.statics) {
188
- if (occluders && !s.occ) continue; // first: a camera ray then pays one flag check for every mesh that is no blocker
189
- if (!mayHit(ray, m, far)) continue; // most statics are nowhere near the ray: skip them before walking parents
190
- if (occluders ? !isUnder(m, scene) : !shown(m, scene)) continue;
191
- hits.length = 0; m.raycast(this.ray, hits);
192
- for (const h of hits) take(toHit(h));
177
+ const scene = this.engine.scene;
178
+ const hits = this._hitsBusy ? [] : this._hits;
179
+ if (hits === this._hits) this._hitsBusy = true;
180
+ let best = null, bestRaw = null, hasBest = false, limit = far;
181
+ const takeHit = h => {
182
+ if (!h || h.distance > far || (hasBest && h.distance >= limit)) return false;
183
+ if (filter && !filter(h)) return false;
184
+ best = h; bestRaw = null; hasBest = true; limit = h.distance; this.ray.far = limit;
185
+ return true;
186
+ };
187
+ try {
188
+ if (Array.isArray(targets)) {
189
+ for (const t of targets) t.updateWorldMatrix(true, true);
190
+ this.ray.firstHitOnly = false;
191
+ try {
192
+ for (const h of this.ray.intersectObjects(targets, true)) {
193
+ if (!shown(h.object)) continue;
194
+ if (h.distance > far || (hasBest && h.distance >= limit)) break;
195
+ if (!filter) { bestRaw = h; hasBest = true; limit = h.distance; break; }
196
+ if (takeHit(toHit(h, this.engine))) break;
197
+ }
198
+ } finally { this.ray.firstHitOnly = true; }
199
+ } else {
200
+ const ray = this.ray.ray, tick = this.engine.time.tick;
201
+ // matrices are refreshed by the render, and a fixed step runs before it: what moved or was added since would answer from where it was.
202
+ // Once per tick and per frame, not per ray (5000 statics x 4 rays a frame measured 12 ms against 3-5 ms): a static moved between two rays of one step needs updateMatrixWorld() on it first (docs/api/rays.md)
203
+ if (this.fresh !== tick) { this.fresh = tick; for (const m of this.statics.keys()) m.updateWorldMatrix(true, false); }
204
+ this.ray.firstHitOnly = !filter; // BVH keeps one hit per mesh: a filter running after that would lose the hit it accepts behind the one it refuses
205
+ try {
206
+ for (const [m, s] of this.statics) {
207
+ if (occluders && !s.occ) continue; // first: a camera ray then pays one flag check for every mesh that is no blocker
208
+ if (!mayHit(ray, m, limit)) continue; // most statics are nowhere near the ray: skip them before walking parents
209
+ if (occluders ? !isUnder(m, scene) : !shown(m, scene)) continue;
210
+ hits.length = 0; m.raycast(this.ray, hits);
211
+ for (let i = 0; i < hits.length; i++) {
212
+ const h = hits[i];
213
+ if (h.distance > far || (hasBest && h.distance >= limit)) continue;
214
+ if (!filter) { bestRaw = h; best = null; hasBest = true; limit = h.distance; this.ray.far = limit; }
215
+ else takeHit(toHit(h, this.engine));
216
+ }
217
+ }
218
+ } finally { this.ray.firstHitOnly = true; }
219
+ if (targets === 'all' && this.providers.length) {
220
+ this._so.copy(o); this._sd.copy(d);
221
+ for (let i = 0; i < this.providers.length; i++) {
222
+ this._po.copy(this._so); this._pd.copy(this._sd);
223
+ takeHit(this.providers[i](this._po, this._pd, limit));
224
+ }
225
+ }
193
226
  }
194
- this.ray.firstHitOnly = true;
195
- if (targets === 'all') for (const p of this.providers) take(p(o.clone(), d.clone(), far));
227
+ } finally {
228
+ hits.length = 0;
229
+ if (hits === this._hits) this._hitsBusy = false;
230
+ }
231
+ if (bestRaw) return toHit(bestRaw, this.engine);
232
+ if (best && !(best instanceof HitResult)) {
233
+ const wrapped = Object.assign(new HitResult(), best);
234
+ wrapped[_hitEngine] = this.engine;
235
+ return wrapped;
196
236
  }
197
- if (best) { const e = this.engine, h = best; Object.defineProperty(h, 'thing', { get: () => thingOf(e, h.object, h), configurable: true }); } // computed only when read
198
237
  return best;
199
238
  }
200
239
  }
201
240
 
241
+ const _hitEngine = Symbol('hitEngine');
242
+ /** Raycast hit wrapper: fixed prototype getter for lazy hit.thing avoids per-hit Object.defineProperty */
243
+ class HitResult {
244
+ get thing() { return thingOf(this[_hitEngine], this.object, this); }
245
+ }
246
+
202
247
  // Shown: itself and all parents visible; with a scene given it must also be in that scene
203
248
  function shown(o, scene) {
204
249
  if (o.userData.lodLevel) return false; // a low level of a THREE.LOD (assetLod.js) stands in on screen only: the full model answers for it
@@ -206,7 +251,7 @@ function shown(o, scene) {
206
251
  return !scene;
207
252
  }
208
253
  /** three's hit as it came (instanceId, batchId, uv stay on it), with the normal in the world: an instance has a matrix of its own, and an uneven scale needs the normal matrix */
209
- function toHit(h) {
254
+ function toHit(h, engine) {
210
255
  const o = h.object;
211
256
  let normal = null;
212
257
  if (h.face) {
@@ -215,7 +260,10 @@ function toHit(h) {
215
260
  if (id !== undefined) { o.getMatrixAt(id, _i); _m.multiply(_i); }
216
261
  normal = h.face.normal.clone().applyNormalMatrix(_n.getNormalMatrix(_m));
217
262
  }
218
- return { ...h, normal };
263
+ const hit = Object.assign(new HitResult(), h);
264
+ hit.normal = normal;
265
+ hit[_hitEngine] = engine;
266
+ return hit;
219
267
  }
220
268
 
221
269
  export const handRolled = [{ kind: 'picking', docRef: 'recipes/19-shooting-picking.md', seen: 'a pointer-to-object raycast of its own', use: 'engine.pick(x, y), or engine.raycast / engine.rays: colliders and moving things are in the same query', quiet: /\b(engine|e|eng|ctx)\.(rays|raycast|pick)\b/, code: /\.setFromCamera\s*\(/ }];
@@ -53,6 +53,7 @@ export function placeUI(e) {
53
53
  export const resizeMethods = {
54
54
  _resize() {
55
55
  const { w, h } = canvasBox(this);
56
+ this._followed = { w, h }; // the box this resize answered: step() compares with it (_followBox)
56
57
  placeUI(this);
57
58
  if (fitPixelSize(this, w, h)) return;
58
59
  const now = this.renderer.getSize(_size);
@@ -60,4 +61,12 @@ export const resizeMethods = {
60
61
  this.renderer.setSize(w, h, !!this._autoSize); // the post chain follows the renderer on its next draw (postWebGL.js follow)
61
62
  this._oAspect.drive(w / h);
62
63
  },
64
+ /** step() calls this first: a frozen or stepped page has no rAF frame or ResizeObserver callback to follow a viewport change, so the box is compared here (the same path as the events).
65
+ * Compared with the box the last resize answered, not the renderer size: with pixelSize the renderer is smaller than the box by design, and a
66
+ * renderer the game or a test sized itself (renderer.setSize) must not be put back to the box while nothing on the page changed */
67
+ _followBox() {
68
+ const { w, h } = canvasBox(this), last = this._followed;
69
+ if (last && last.w === w && last.h === h) return;
70
+ this._resize();
71
+ },
63
72
  };
@@ -21,6 +21,7 @@ import { sceneVisitor } from './sceneDelta.js';
21
21
  import { moduleOwnerOf } from './things.js';
22
22
  import { notePatch, patchOn } from './threePatches.js';
23
23
  import { shadowMaps, webgpuPartOrNull } from '../../render/backend.js';
24
+ import { setLightShadowAutoUpdate } from '../../render/threeCompat.js';
24
25
  import { warnOnce, fmt } from '../base/validate.js';
25
26
  import { MANY } from '../inspect/lightWatch.js';
26
27
  import { isShown } from '../base/util.js';
@@ -36,11 +37,14 @@ const placeholderOn = e => ['sun', 'hemi'].some(k => { const l = e.lights?.[k];
36
37
  /** The engine module that owns o (it or an ancestor carries engineOwned), else null */
37
38
  function engineOwner(o) { for (let p = o; p; p = p.parent) { const m = moduleOwnerOf(p); if (m) return m; } return null; }
38
39
 
39
- let areaTables = false; // page-wide, as three's own tables are (R29 ALLOW)
40
+ const areaTables = { webgl: false, webgpu: false }; // page-wide, as three's own tables are; tracked per backend so WebGL loading before threedog/tsl still populates WebGPU later
40
41
  function loadAreaTables() {
41
- if (areaTables) return;
42
- areaTables = true;
43
- const node = webgpuPartOrNull('classes')?.RectAreaLightNode, size = 64 * 64 * 4;
42
+ const node = webgpuPartOrNull('classes')?.RectAreaLightNode;
43
+ const needWebGL = !areaTables.webgl, needWebGPU = !!node && !areaTables.webgpu;
44
+ if (!needWebGL && !needWebGPU) return;
45
+ if (needWebGL) areaTables.webgl = true;
46
+ if (needWebGPU) areaTables.webgpu = true;
47
+ const size = 64 * 64 * 4;
44
48
  const standIn = (half, matrix) => {
45
49
  const data = half ? new Uint16Array(size) : new Float32Array(size);
46
50
  if (matrix) for (let i = 0; i < size; i += 4) data[i] = data[i + 3] = half ? 0x3c00 : 1; // 0x3c00 is 1 as a half float
@@ -49,13 +53,17 @@ function loadAreaTables() {
49
53
  return t;
50
54
  };
51
55
  /** @type {Record<string, any> | null} */
52
- const stand = node ? { LTC_FLOAT_1: standIn(false, true), LTC_FLOAT_2: standIn(false, false), LTC_HALF_1: standIn(true, true), LTC_HALF_2: standIn(true, false) } : null;
56
+ const stand = needWebGPU ? { LTC_FLOAT_1: standIn(false, true), LTC_FLOAT_2: standIn(false, false), LTC_HALF_1: standIn(true, true), LTC_HALF_2: standIn(true, false) } : null;
53
57
  if (stand) node.setLTC(stand);
54
- Promise.all([import('three/addons/lights/RectAreaLightUniformsLib.js'), import('three/addons/lights/RectAreaLightTexturesLib.js')]).then(([{ RectAreaLightUniformsLib }, { RectAreaLightTexturesLib: lib }]) => {
55
- RectAreaLightUniformsLib.init(); // WebGLRenderer reads them from UniformsLib, the WebGPU node from the stand-ins
56
- for (const k in stand) { stand[k].image.data.set(lib[k].image.data); stand[k].needsUpdate = true; }
58
+ Promise.all([
59
+ needWebGL ? import('three/addons/lights/RectAreaLightUniformsLib.js') : null,
60
+ needWebGPU ? import('three/addons/lights/RectAreaLightTexturesLib.js') : null,
61
+ ]).then(([u, t]) => {
62
+ if (u) u.RectAreaLightUniformsLib.init(); // WebGLRenderer reads them from UniformsLib, the WebGPU node from the stand-ins
63
+ if (t && stand) for (const k in stand) { stand[k].image.data.set(t.RectAreaLightTexturesLib[k].image.data); stand[k].needsUpdate = true; }
57
64
  }, err => {
58
- areaTables = false;
65
+ if (needWebGL) areaTables.webgl = false;
66
+ if (needWebGPU) areaTables.webgpu = false;
59
67
  for (const k in stand) stand[k].dispose();
60
68
  warnOnce(`RectAreaLight: three's LTC tables did not load (${err?.message ?? err}): on WebGPU the light gives diffuse light only, no shine; on WebGL none. Loading is tried again when a RectAreaLight next enters the scene`);
61
69
  });
@@ -65,7 +73,7 @@ function loadAreaTables() {
65
73
  export function watchGameLights(e) {
66
74
  const all = new Set(), game = new Set(), idled = new WeakSet(), handed = new WeakSet();
67
75
  // The one place autoUpdate goes back to the game: only a light the engine idled, and only if the game has not written the value since (then it is the game's)
68
- const giveBack = l => { if (!idled.delete(l)) return; if (!l.shadow.autoUpdate) { l.shadow.autoUpdate = true; l.shadow.needsUpdate = true; } };
76
+ const giveBack = l => { if (!idled.delete(l)) return; if (!l.shadow.autoUpdate) setLightShadowAutoUpdate(l, true); };
69
77
  const view = sceneVisitor(e.scene, {
70
78
  enter(o) {
71
79
  if (o.isLight && !o.isLightProbe && !o.isLightProbeGrid && o !== e.lights?.sun && o !== e.lights?.hemi && !o.userData.fixedCount && !engineOwner(o) && placeholderOn(e))
@@ -105,7 +113,7 @@ export function watchGameLights(e) {
105
113
  if (idled.has(l)) {
106
114
  if (s.autoUpdate) { idled.delete(l); handed.add(l); } // the game turned redraws on itself while idled: its light from now on
107
115
  else if (l.intensity > 0 || !l.castShadow || opted) giveBack(l); // put back what was taken
108
- } else if (l.castShadow && l.intensity <= 0 && s.autoUpdate && !opted && !handed.has(l)) { s.autoUpdate = false; idled.add(l); }
116
+ } else if (l.castShadow && l.intensity <= 0 && s.autoUpdate && !opted && !handed.has(l)) { setLightShadowAutoUpdate(l, false); idled.add(l); }
109
117
  }
110
118
  },
111
119
  /** Engine dispose: stop watching the scene and hand every idled light back (a light may outlive the engine in another scene) */
@@ -35,7 +35,8 @@ if (!P[KEY]) {
35
35
  Object.defineProperty(P, KEY, { value: true, configurable: true });
36
36
  Object.defineProperty(P, ORIG, { value: { add, remove }, configurable: true });
37
37
  P.add = function (...a) {
38
- if (!patchOn('scene-add-hook')) return add.apply(this, a); // switched off while another library's wrapper sits on top of ours: pass through
38
+ // switched off, or multi-arg: three's add loops and calls single-arg this.add(arg) for each child, which runs this hook once per child
39
+ if (!patchOn('scene-add-hook') || a.length > 1) return add.apply(this, a);
39
40
  const out = add.apply(this, a); // three detaches each child from its old parent first (through remove below), then attaches
40
41
  const t = trackerOf(this);
41
42
  if (t) for (const c of a) if (c?.parent === this) t.pending.add(c);
@@ -45,7 +46,9 @@ if (!P[KEY]) {
45
46
  return out;
46
47
  };
47
48
  P.remove = function (...a) {
48
- const t = patchOn('scene-add-hook') ? trackerOf(this) : null;
49
+ // switched off, or multi-arg: three's remove loops and calls single-arg this.remove(arg) for each child, which runs this hook once per child
50
+ if (!patchOn('scene-add-hook') || a.length > 1) return remove.apply(this, a);
51
+ const t = trackerOf(this);
49
52
  if (!t) return remove.apply(this, a);
50
53
  let gone = null, roots = null;
51
54
  for (const c of a) if (c?.parent === this) (gone ??= []).push(c); // not only seen ones: a material swap unmarks the root, its children stay counted (left checks each)
@@ -150,12 +153,13 @@ class Tracker {
150
153
  /** Show the visitors what entered since the last flush (the first visitor to sync in a frame pays for all) */
151
154
  flush() {
152
155
  if (!this.pending.size) return;
153
- for (const r of this.pending) {
156
+ const batch = [...this.pending];
157
+ this.pending.clear();
158
+ for (const r of batch) {
154
159
  let top = r;
155
160
  while (top.parent) top = top.parent;
156
161
  if (top === this.scene) this._walk(r, null); // left again before the frame, or attached to an off-scene group: nothing to show
157
162
  }
158
- this.pending.clear();
159
163
  }
160
164
  }
161
165
 
@@ -6,7 +6,7 @@ import { askRatio, askPixelSize } from './pixelRatio.js';
6
6
  import { codedError } from '../base/errorHints.js';
7
7
  import { thing } from './thingOps.js';
8
8
  import { isUnder } from '../base/util.js';
9
- import { freshFrame, renderOnce as drawOnce } from '../../render/backend.js';
9
+ import { freshFrame, resetStats, renderOnce as drawOnce } from '../../render/backend.js';
10
10
  import { freeParts, partsOf as parts, copyOwns, kept } from '../base/freeParts.js';
11
11
  /**
12
12
  * How many objects in the scene use each geometry and material. Why remove asks: disposing a kit that other streamed blocks still draw makes the renderer
@@ -106,6 +106,7 @@ export const sceneMethods = {
106
106
  const own = this._ownFrame; // an engine draw, not the game taking the canvas over (render/ownFrame.js)
107
107
  this._gameLights?.sync(); // the light watch catches up first: a RectAreaLight added since the last frame gets its tables before this draw (gameLights.js)
108
108
  if (own) own.inside++;
109
+ resetStats(this.renderer); // autoReset is off: without this the counts of every renderOnce add up (same reset as _render)
109
110
  try {
110
111
  if (camera === this.camera) { freshFrame(this.renderer); this.post.render(0, target); return; }
111
112
  drawOnce(this.renderer, this.scene, camera, target);
@@ -53,6 +53,27 @@ export function ringsReady(chunks, size, position, rings, ok) {
53
53
  return true;
54
54
  }
55
55
 
56
+ /** @internal Shared viewChunks / density accessor definitions for chunk tables (terrain & ground vegetation) */
57
+ export function defineChunkSettings(proto, { onViewChunks, onDensity }) {
58
+ Object.defineProperties(proto, {
59
+ viewChunks: { get() { return this._viewChunks; }, set(n) { this._viewChunks = n; onViewChunks.call(this, n); }, configurable: true },
60
+ density: { get() { return this._density; }, set(d) { this._density = d; onDensity.call(this, d); }, configurable: true },
61
+ });
62
+ }
63
+
64
+ /** @internal Sync near-only species visibility on one chunk when its LOD ring changes */
65
+ export function syncChunkLevel(c, ring, list, onEnter, onLeave, onRing) {
66
+ if (c.level === ring) return;
67
+ c.level = ring;
68
+ for (const sp of list) {
69
+ if (!sp.nearOnly) continue;
70
+ const has = !!c.plants[sp.name];
71
+ if (ring <= sp.maxRing && !has) onEnter(sp);
72
+ else if (ring > sp.maxRing + 1 && has) onLeave(sp);
73
+ }
74
+ onRing?.(c, ring);
75
+ }
76
+
56
77
  export class ChunkStream {
57
78
  /** @param {any} table @param {{ show: Function, level: Function, count: Function, inArea?: Function }} hooks */
58
79
  constructor(table, hooks) {
@@ -0,0 +1,37 @@
1
+ // Zero-overhead dirty-set watcher helpers shared by World and Containers for O(dirty) incremental state sync.
2
+
3
+ /**
4
+ * Subscribe a watcher onto `host._watchers` (allocated lazily on first subscriber; reset to null when empty).
5
+ * @internal
6
+ * @param {any} host
7
+ * @param {Record<string, any>} [extra]
8
+ */
9
+ export function addDirtyWatcher(host, extra) {
10
+ const w = {
11
+ dirty: new Set(),
12
+ all: true,
13
+ ...extra,
14
+ remove() {
15
+ const ws = host._watchers;
16
+ if (!ws) return;
17
+ ws.delete(w);
18
+ if (ws.size === 0) host._watchers = null;
19
+ },
20
+ };
21
+ (host._watchers ??= new Set()).add(w);
22
+ return w;
23
+ }
24
+
25
+ /** Mark one key as dirty across active watchers on `host` (zero cost when unwatched). @internal */
26
+ export function touchDirty(host, id) {
27
+ const ws = host._watchers;
28
+ if (!ws) return;
29
+ for (const w of ws) if (!w.all) w.dirty.add(id);
30
+ }
31
+
32
+ /** Mark all keys for full reconciliation across active watchers on `host`. @internal */
33
+ export function touchDirtyAll(host) {
34
+ const ws = host._watchers;
35
+ if (!ws) return;
36
+ for (const w of ws) { w.all = true; w.dirty.clear(); }
37
+ }
package/core/time/skip.js CHANGED
@@ -32,7 +32,7 @@ function amount(e, o) {
32
32
  if (o.seconds != null) { if (!(o.seconds > 0) || !Number.isFinite(o.seconds)) throw bad(); return o.seconds; }
33
33
  if (o.to == null) throw bad();
34
34
  // engine.calendar is whatever module meets modules/calendar/contract.js (timeOfDay, dayLength, hoursPerDay, untilMark): core reads only those
35
- const cal = e.calendar; if (!cal) throw codedError('skip-amount', STRINGS.noCalendar);
35
+ const cal = e.usable('calendar') ? e.calendar : null; if (!cal) throw codedError('skip-amount', STRINGS.noCalendar);
36
36
  if (!Number.isFinite(cal.dayLength)) throw codedError('skip-amount', STRINGS.fixedDay); // the clock never reaches that time: an endless skip otherwise
37
37
  const f = parseClock(o.to, cal.hoursPerDay) % 1;
38
38
  if (!Number.isFinite(f)) throw bad();
@@ -43,25 +43,28 @@ function amount(e, o) {
43
43
 
44
44
  /** Advance calendar seconds in segments (see the top of the file). Called by the op 'time.skip' */
45
45
  function jump(e, seconds) {
46
- const clock = e.clock, cal = e.calendar, time = e.time; // clock: the calendar view of time (its timers are in time's one queue)
46
+ const clock = e.clock, cal = e.usable('calendar') ? e.calendar : null, time = e.time; // clock: the calendar view of time (its timers are in time's one queue)
47
47
  let left = seconds, ended = false;
48
48
  for (const h of e._hooks.fixed) if (!h.mod.skip && !h.mod.skipKind && !h.mod.noSkip) warnOnce(fmt(STRINGS.noSkip, { name: h.name })); // said at skip time, once per module: a skip that silently leaves a module behind
49
49
  const off = e.events.on('session:end', () => { ended = true; }); // a timer callback ended the playthrough mid-skip: the new one must not be skipped
50
50
  try {
51
- while (left > 0 && !ended) {
51
+ while (left > 0 && !ended && !e.disposed) {
52
52
  // calendar seconds per fixed second, read per segment (an ended mod changes it); a stopped calendar (0) would need infinite fixed seconds: skip as if at 1x
53
53
  const r = clock.speed, ts = r > 0 ? r : 1;
54
54
  let seg = Math.min(left, cal ? cal.untilMark() + NUDGE : Infinity, time._untilNext(ts) + NUDGE);
55
55
  left -= seg;
56
56
  if (left < NUDGE) { seg += left; left = 0; } // no sliver segment at the end
57
57
  const dt = seg / ts, done = left === 0;
58
- for (const h of e._hooks.skip) {
58
+ for (const h of [...e._hooks.skip]) {
59
+ if (e.disposed) break;
60
+ if (!e._hooks.skip.includes(h)) continue;
59
61
  try { asModule(e, h.mod, () => h.fn(dt, e, done)); } catch (err) { reportError(e, err, fmt(STRINGS.hook, { name: h.name }), { module: h.mod }); }
60
62
  }
63
+ if (e.disposed) break;
61
64
  time._skip(dt, seg);
62
65
  }
63
66
  } finally { off.remove(); }
64
- if (ended) return null;
67
+ if (ended || e.disposed) return null;
65
68
  e.events.emit('time:skip', { seconds });
66
69
  return { seconds, clock: cal?.clock ?? null, day: cal?.day ?? null };
67
70
  }
@@ -114,7 +117,7 @@ export const skipMethods = {
114
117
  const off = this.events.on('session:end', () => { ended = true; }); // newGame / load / quit cancel the skip cleanly (it resolves null)
115
118
  const end = () => { this._skipping = false; ctx.remove(); fz.remove(); off.remove(); };
116
119
  if (!(fade > 0)) { try { go(); } finally { end(); } return Promise.resolve(out); }
117
- const run = this.flow ? this.flow.transition(go, { fade, autosave: false, music: false })
120
+ const run = this.usable('flow') ? this.flow.transition(go, { fade, autosave: false, music: false })
118
121
  : (async () => { try { await fadeScreen(this, 1, { seconds: fade, owner: 'skip' }); go(); } finally { await fadeScreen(this, 0, { seconds: fade, owner: 'skip' }); } })();
119
122
  return run.finally(end).then(() => out);
120
123
  },