threedog 2.2.2 → 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 (194) hide show
  1. package/CHANGELOG.md +20 -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 +22 -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 +371 -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/gameLights.js +19 -11
  44. package/core/scene/sceneDelta.js +8 -4
  45. package/core/stream/chunkStream.js +21 -0
  46. package/core/stream/dirtyWatch.js +37 -0
  47. package/core/time/skip.js +9 -6
  48. package/core/time/time.js +72 -18
  49. package/docs/AI.md +22 -21
  50. package/docs/API.md +5 -4
  51. package/docs/CODEMAP.md +16 -10
  52. package/docs/COMMANDS.md +5 -5
  53. package/docs/CONVENTIONS.md +9 -25
  54. package/docs/api/ambience.md +1 -0
  55. package/docs/api/assets.md +10 -3
  56. package/docs/api/audio.md +5 -3
  57. package/docs/api/decals.md +16 -0
  58. package/docs/api/engine.md +1 -0
  59. package/docs/api/tools.md +3 -1
  60. package/docs/api/water.md +3 -0
  61. package/docs/recipes/09-materials-lights-models.md +15 -1
  62. package/docs/recipes/13-animation.md +51 -10
  63. package/docs/recipes/16-dev-bridge.md +1 -1
  64. package/docs/recipes/31-audio.md +15 -9
  65. package/docs/recipes/34-environment-lighting.md +11 -1
  66. package/docs/recipes/44-water-weather-hooks.md +1 -0
  67. package/examples/action/.threedog/content-index.json +1 -0
  68. package/examples/perf-island/.threedog/content-index.json +1 -0
  69. package/examples/plain-picture/.threedog/content-index.json +1 -0
  70. package/examples/rc2d/.threedog/content-index.json +1 -0
  71. package/examples/styletest/.threedog/content-index.json +1 -0
  72. package/examples/techniques/outlines-and-rim/main.js +1 -1
  73. package/examples/techniques/procedural-surface/main.js +1 -1
  74. package/examples/techniques/stylized-shading/main.js +1 -1
  75. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  76. package/examples/world/.threedog/content-index.json +1 -0
  77. package/index.d.ts +6 -2
  78. package/index.js +3 -2
  79. package/llms.txt +11 -10
  80. package/modules/ambience/Ambience.js +97 -15
  81. package/modules/camera/common.js +18 -12
  82. package/modules/characters/Character.js +30 -3
  83. package/modules/characters/NPC.js +2 -5
  84. package/modules/characters/astar.js +45 -14
  85. package/modules/characters/movers/rapier.js +53 -41
  86. package/modules/characters/movers/simple.js +37 -24
  87. package/modules/characters/npcView.js +2 -2
  88. package/modules/characters/pathAsync.js +3 -3
  89. package/modules/collision/contract.js +2 -2
  90. package/modules/content/index.js +3 -0
  91. package/modules/content/models.js +11 -4
  92. package/modules/content/templates.js +11 -11
  93. package/modules/debug/DebugPanel.js +1 -0
  94. package/modules/decals/Decals.js +393 -0
  95. package/modules/decals/index.js +1 -0
  96. package/modules/gameplay/Container.js +2 -0
  97. package/modules/gameplay/Containers.js +17 -3
  98. package/modules/gameplay/Dialogue.js +1 -1
  99. package/modules/gameplay/Interactions.js +7 -6
  100. package/modules/gameplay/Inventory.js +5 -1
  101. package/modules/gameplay/Quests.js +4 -3
  102. package/modules/gameplay/inventoryOps.js +2 -2
  103. package/modules/gameplay/pickups.js +32 -12
  104. package/modules/gameplay/questSave.js +2 -2
  105. package/modules/grid/index.js +8 -2
  106. package/modules/hud/index.js +1 -1
  107. package/modules/level/heightfield.js +1 -0
  108. package/modules/level/index.js +3 -2
  109. package/modules/level/nodes.js +2 -1
  110. package/modules/lights/index.js +27 -4
  111. package/modules/lights/slots.js +33 -16
  112. package/modules/nav/contract.js +4 -4
  113. package/modules/nav/index.js +6 -2
  114. package/modules/net/Client.js +24 -11
  115. package/modules/net/Host.js +73 -20
  116. package/modules/net/index.js +33 -21
  117. package/modules/net/sync.js +38 -8
  118. package/modules/net/transports.js +7 -3
  119. package/modules/particles/Particles.js +11 -4
  120. package/modules/particles/contract.js +6 -6
  121. package/modules/particles/effect.js +0 -1
  122. package/modules/rigid/RigidBodies.js +69 -57
  123. package/modules/rigid/Vehicles.js +8 -7
  124. package/modules/rigid/ragdoll.js +4 -6
  125. package/modules/rigid/rapierCompat.js +90 -0
  126. package/modules/rigid/sync.js +2 -5
  127. package/modules/settings/Settings.js +10 -4
  128. package/modules/sky/Sky.js +10 -2
  129. package/modules/sky/environment.js +29 -13
  130. package/modules/sky/frame.js +2 -2
  131. package/modules/sky/shader.js +5 -2
  132. package/modules/sky/skyModule.js +2 -2
  133. package/modules/swarm/Swarm.js +3 -2
  134. package/modules/swarm/grid.js +12 -7
  135. package/modules/terrain/ChunkManager.js +16 -26
  136. package/modules/triggers/index.js +5 -6
  137. package/modules/vegetation/draw.js +62 -26
  138. package/modules/vegetation/groundChunks.js +8 -22
  139. package/modules/water/Water.js +152 -24
  140. package/modules/water/surface.js +43 -20
  141. package/modules/weather/weatherDraw.js +4 -1
  142. package/modules/world/World.js +21 -2
  143. package/modules/world/index.js +5 -0
  144. package/modules/world/persist.js +1 -0
  145. package/modules/world/records.js +3 -1
  146. package/modules/world/sim.js +3 -2
  147. package/modules/world/simFar.js +4 -2
  148. package/modules/world/state.js +7 -1
  149. package/package.json +2 -2
  150. package/presets.js +30 -0
  151. package/render/PostFX.js +24 -17
  152. package/render/backend.js +72 -31
  153. package/render/cascades.js +25 -14
  154. package/render/cascades.tsl.js +32 -21
  155. package/render/fogLook.js +2 -1
  156. package/render/fx/library.tsl.js +1 -1
  157. package/render/fx/particles.tsl.js +4 -18
  158. package/render/fx/pcss.tsl.js +2 -2
  159. package/render/fx/postWebGPU.tsl.js +47 -25
  160. package/render/fx/sky.tsl.js +6 -18
  161. package/render/fx/uniforms.tsl.js +16 -0
  162. package/render/fx/water.tsl.js +24 -5
  163. package/render/fxNumbers.js +2 -0
  164. package/render/impostor.tsl.js +10 -6
  165. package/render/lights.js +6 -6
  166. package/render/occlusion.js +17 -6
  167. package/render/patches.js +40 -28
  168. package/render/postWebGL.js +6 -4
  169. package/render/reflectionProbes.js +302 -0
  170. package/render/shaderErrors.js +18 -8
  171. package/render/shadowCache.tsl.js +10 -5
  172. package/render/shadows.js +70 -49
  173. package/render/threeCompat.js +166 -0
  174. package/types/core.d.ts +33 -3
  175. package/types/gameplay.d.ts +80 -0
  176. package/types/generated/core/audio/Audio.d.ts +18 -1
  177. package/types/generated/core/ops/Ops.d.ts +2 -1
  178. package/types/generated/core/ops/control.d.ts +7 -3
  179. package/types/generated/core/saves/session.d.ts +4 -1
  180. package/types/generated/modules/ambience/Ambience.d.ts +6 -0
  181. package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
  182. package/types/generated/modules/grid/index.d.ts +27 -3
  183. package/types/generated/modules/net/index.d.ts +8 -3
  184. package/types/generated/modules/sky/Sky.d.ts +1 -0
  185. package/types/generated/modules/water/Water.d.ts +15 -0
  186. package/types/generated/modules/world/index.d.ts +5 -0
  187. package/types/generated/render/patches.d.ts +5 -0
  188. package/types/physics.d.ts +66 -9
  189. package/types/tsl.d.ts +2 -0
  190. package/types/world.d.ts +2 -0
  191. package/ui/Parts.js +3 -2
  192. package/docs/MIGRATING-0.7.md +0 -39
  193. package/docs/MIGRATING-0.8.md +0 -171
  194. package/modules/rigid/refresh.js +0 -10
@@ -40,6 +40,8 @@ const THREE_ROWS = [
40
40
  limits: 'only what never moves; a moved mesh keeps its old light, a new light is not in it' },
41
41
  { id: 'light probes', on: (e, has) => !!e._probeSets?.size || has.probes, cost: 'low', how: 'await engine.bakeProbes({ bounds, spacing })', recipe: R34('Light probes (baked indirect light)'),
42
42
  limits: 'soft indirect light only, no reflections; light blends between probes, so thin walls leak' },
43
+ { id: 'reflection probes', on: e => !!e._reflectionProbes?.size, cost: 'low', how: 'engine.addReflectionProbe({ bounds })', recipe: R34('Reflection probes (local indoor reflections)'),
44
+ limits: 'static local capture until probe.bake() is called; parallax follows each zone capture origin' },
43
45
  { id: 'area lights', on: (e, has) => has.area, cost: 'medium', how: 'engine.scene.add(new THREE.RectAreaLight(color, intensity, w, h))', recipe: EXTRAS,
44
46
  limits: 'no shadows; lights MeshStandard / MeshPhysical only' },
45
47
  { id: 'translucency (SSS)', on: (e, has) => has.sss, webgpuOnly: true, cost: 'low', how: 'new THREE.MeshSSSNodeMaterial({ ... }) (three/webgpu)', recipe: EXTRAS,
@@ -201,6 +201,7 @@ class Writers {
201
201
  watchNamed(label, o, key) {
202
202
  const old = this.top.get(label);
203
203
  if (page.off || (old && !old.game)) return { watching: false, remove() {} };
204
+ if (old) { real(old).close = false; this.release(old); }
204
205
  const rec = this.named(label, NOT.none);
205
206
  rec.game = true;
206
207
  const watching = this.hook(rec, o, key);
@@ -219,7 +220,7 @@ class Writers {
219
220
 
220
221
  /** A fog assigned now: its values were set by whoever wrote scene.fog, so they start with that answer, not with "not tracked" */
221
222
  fog(f, slotRec) {
222
- for (const k of ['near', 'far', 'density', 'color']) this.top.delete('fog.' + k);
223
+ for (const k of ['near', 'far', 'density', 'color']) { const old = this.top.get('fog.' + k); if (old) { this.top.delete('fog.' + k); this.release(old); } }
223
224
  if (!f) return;
224
225
  const seed = r => { r.at = slotRec.at; r.why = slotRec.why; r.seen = slotRec.seen; return r; };
225
226
  for (const k of f.isFogExp2 ? ['density'] : ['near', 'far']) this.number(f, k, seed(this.named('fog.' + k, NOT.before)));
@@ -229,7 +230,7 @@ class Writers {
229
230
  light(l) {
230
231
  if (this.parts.has(l) || page.off) return;
231
232
  const at = this.e._things?.entryOf(l)?.[0]?.at, why = NOT.before + (at ? ` (added at ${at})` : '');
232
- const rec = k => newRec(why, () => `light:${l.name}.${k}`); // read at each write: a light can be named after it entered the scene
233
+ const rec = k => newRec(why, () => `light:${l.name || l.type}.${k}`); // read at each write: a light can be named after it entered the scene
233
234
  const p = { intensity: rec('intensity'), color: rec('color'), position: rec('position') };
234
235
  this.parts.set(l, p);
235
236
  this.number(l, 'intensity', p.intensity);
@@ -414,7 +415,7 @@ class Writers {
414
415
  if (k.startsWith('material:')) { if (!real(r).at) continue; if (++mats > MATERIALS_MAX) { more++; continue; } }
415
416
  values[k] = this.answer(r);
416
417
  }
417
- return { tracked: true, limit: LIMIT, frame: this.frame, stacks: this.stacks, values, conflicts: this.fights, held: this.held.map(({ key, ...h }) => h), leftovers: this.leftovers, ...(more ? { moreMaterials: more } : {}) };
418
+ return { tracked: true, limit: LIMIT, frame: this.frame, stacks: this.stacks, values, conflicts: this.fights, held: this.held.map(x => { const h = { ...x }; delete h.key; return h; }), leftovers: this.leftovers, ...(more ? { moreMaterials: more } : {}) };
418
419
  }
419
420
  /** One value by its describe name, a shared point's name or a name given to engine.debug.watch @param {string} label */
420
421
  why(label) {
package/core/ops/Ops.js CHANGED
@@ -136,7 +136,7 @@ export class Ops {
136
136
  * @param {object} args
137
137
  * @param {any} value
138
138
  * @param {{ actor?: string }} [opts]
139
- * @returns {{ ok: boolean, code?: string, facts?: object, nextActions?: { op: string, args?: object }[] }}
139
+ * @returns {{ ok: boolean, revision: number, code?: string, facts?: object, nextActions?: { op: string, args?: object }[] }}
140
140
  */
141
141
  undo(name, args, value, opts) {
142
142
  const d = this._def(name);
@@ -155,12 +155,13 @@ export class Ops {
155
155
  // the op's code is the defining module's, not the caller's (run)
156
156
  asModule(this.engine, null, () => this._as(name, ctx, () => d.undo(this.engine, args, value, ctx)));
157
157
  } catch (err) {
158
+ this.revision++; // the state may have changed (a half-done undo too): bump before stamping the failure result
158
159
  return broke(err);
159
160
  } finally {
160
161
  this._allowDepth--;
161
- this.revision++; // the state changed, a half-done undo too: "did anything change since I looked" must see it
162
162
  }
163
- return { ok: true };
163
+ this.revision++;
164
+ return { ok: true, revision: this.revision };
164
165
  }
165
166
  /** @internal Run fn as part of op `name` with its ctx, when the op is not on the stack (undo, an after hook held for the commit, a use after a walk): nested ops, ops.actor and content words read it */
166
167
  _as(name, ctx, fn) {
@@ -253,6 +254,11 @@ export class Ops {
253
254
  if (!DEV) return; // release builds do not check; games cannot read DEV, so the no-op lives here
254
255
  guardWrite(this, where);
255
256
  }
257
+ /** @internal Dev guard for writes permitted locally on a routed net client (e.g. local movement) @param {string} where */
258
+ guardClientAllowed(where) {
259
+ if (!DEV) return;
260
+ guardWrite(this, where, true);
261
+ }
256
262
  /**
257
263
  * Send every op to someone else instead of running it here (a multiplayer client: the host decides). fn(def, args, opts) returns the result to
258
264
  * hand back, or null to run the op locally after all. While routed, a write outside an op or allow() is reported even in fixed steps (only the
package/core/ops/actor.js CHANGED
@@ -15,6 +15,16 @@ export const actorMethods = {
15
15
  // without any player (builder, strategy view) the camera focus stands in for 'player'
16
16
  return this._actorObject(id)?.position ?? this._things.source(id)?.get(id).position ?? (id === 'player' ? this.focus : null);
17
17
  },
18
+ /** @internal Local actors controlled on this machine: engine.actor first, followed by unique seat actors @returns {string[]} */
19
+ localActors() {
20
+ const out = [this.actor];
21
+ for (const s of this.input?.seats ?? []) if (s.actor && !out.includes(s.actor)) out.push(s.actor);
22
+ return out;
23
+ },
24
+ /** @internal Live actor position without falling back to camera focus when 'player' has no character @param {string} [id] @returns {{ x: number, y: number, z: number } | null} */
25
+ liveActorPosition(id = this.actor) {
26
+ return id === 'player' && !this.player ? null : this.actorPosition(id);
27
+ },
18
28
  /** @internal The actor's three.js object right now (player root, or the world model when built); null when it has none */
19
29
  _actorObject(id = this.actor) {
20
30
  if (id === 'player' && this.player) return this.player.root;
@@ -55,11 +55,11 @@ export class Control {
55
55
  engine.events.on('save:loaded', () => this.endTasks(null, 'replaced'));
56
56
  }
57
57
  /**
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
59
- * charge (dt on the character's time channel): a direction moves it, null stands still (gravity and the idle pose go on), false skips the
58
+ * Take a character's control. step (optional): (dt, character) => ({ x, y?, z, run? } | { dx, dz, dy? }) | null | false, called each fixed step while this owner is in
59
+ * charge (dt on the character's time channel): a direction moves it, { dx, dz, dy? } steps an exact displacement (root motion, bypassing walk speed and auto-turn), null stands still (gravity and the idle pose go on), false skips the
60
60
  * move this step (you placed it yourself). Without step, move it with handle.move(x, z, run, dt), which does nothing while paused.
61
61
  * @param {any} who a Character, an NPC handle or a character id ('player', an NPC id)
62
- * @param {{ owner: string, layer?: 'base' | 'script' | 'cutscene' | 'physics' | 'net', step?: (dt: number, ch: any) => ({ x: number, y?: number, z: number, run?: boolean } | null | false | void) }} o
62
+ * @param {{ owner: string, layer?: 'base' | 'script' | 'cutscene' | 'physics' | 'net', step?: (dt: number, ch: any) => ({ x: number, y?: number, z: number, run?: boolean } | { dx: number, dz: number, dy?: number } | null | false | void) }} o
63
63
  * @returns {{ owner: string, layer: string, id: string, readonly active: boolean, move(x: number, z: number, run?: boolean, dt?: number): boolean, remove(): void }}
64
64
  * @example const h = engine.control.take(player, { owner: 'tutorial', layer: 'script', step: () => ({ x: 0, z: 1 }) }); ... h.remove();
65
65
  */
@@ -84,8 +84,9 @@ export class Control {
84
84
  }
85
85
  if (layer === 'physics') this.endTasks(id, 'physics');
86
86
  const old = m.get(owner);
87
+ if (old?.hold) this.engine.session._untrack(old.hold);
87
88
  m.delete(owner); // a new object: the old handle goes stale, so its remove() cannot end the new hold
88
- const ent = { id, owner, layer, step, task, at: old ? old.at : at, ch: typeof who === 'object' && who?.move ? who : null };
89
+ const ent = { id, owner, layer, step, task, at: old ? old.at : at, ch: typeof who === 'object' && who?.move ? who : null, hold: null };
89
90
  m.set(owner, ent);
90
91
  const self = this;
91
92
  const hold = {
@@ -104,6 +105,7 @@ export class Control {
104
105
  },
105
106
  remove() { self.engine.session._untrack(hold); const mm = self._by.get(id); if (mm?.get(owner) === ent) { mm.delete(owner); if (!mm.size) self._by.delete(id); ent.task?.('replaced'); } }, // a task's own ending removes its hold too and ignores this; here the playthrough ended the hold first
106
107
  };
108
+ ent.hold = hold;
107
109
  // a hold taken during play is not saved and what ends it (a timer, a callback) dies with the playthrough, so it ends there too. Base and net holds stand for a character's whole life, not a move in it
108
110
  if (this.engine.session.captured && layer !== 'base' && layer !== 'net') this.engine.session.track(hold);
109
111
  return hold;
@@ -130,7 +132,12 @@ export class Control {
130
132
  /** describe().control: every held character by id, as of() */
131
133
  describe() { const out = {}; for (const id of this._by.keys()) out[id] = this.of(id); return out; }
132
134
  /** Drop every hold on a character (its record left the world, or a record-less character was disposed) @param {string} id @experimental */
133
- forget(id) { this.endTasks(id, 'gone'); this._by.delete(id); }
135
+ forget(id) {
136
+ this.endTasks(id, 'gone');
137
+ const m = this._by.get(id);
138
+ if (m) for (const ent of m.values()) if (ent.hold) this.engine.session._untrack(ent.hold);
139
+ this._by.delete(id);
140
+ }
134
141
  /** @internal the entry in charge: highest layer, latest taker inside it (only one per layer in dev) */
135
142
  _top(id) {
136
143
  const m = this._by.get(id); if (!m) return null;
@@ -161,7 +168,11 @@ export class Control {
161
168
  let m;
162
169
  try { m = top.step(dt, ch); } catch (err) { reportError(this.engine, err, `control step of '${top.owner}' on character '${id}'`); continue; } // the next character's holder is not to blame
163
170
  if (m === false || this._top(id) !== top) continue; // placed by hand this step, or the step handed control on (ended itself, something took it)
164
- this._drive(top, () => ch.move(m?.x ?? 0, m?.z ?? 0, !!m?.run, dt, m?.y ?? 0));
171
+ if (m && typeof m.dx === 'number' && typeof m.dz === 'number') {
172
+ this._drive(top, () => { if (ch.moveDelta?.(m.dx, m.dz, dt, m.dy ?? 0) === undefined && dt > 0) ch.move(m.dx / dt, m.dz / dt, false, dt, m.dy ?? 0); });
173
+ } else {
174
+ this._drive(top, () => ch.move(m?.x ?? 0, m?.z ?? 0, !!m?.run, dt, m?.y ?? 0));
175
+ }
165
176
  }
166
177
  }
167
178
  /** @internal dev check from character.move(): a held character moves only through its holder (the header's bypass rule) */
package/core/ops/holds.js CHANGED
@@ -109,7 +109,7 @@ export const holdMethods = {
109
109
  get runState() {
110
110
  const F = this.stacks.get('freeze'), owners = [...this.stacks.get('halt').names(), ...F.names()];
111
111
  const lv = this.loading?.view();
112
- const state = !this.ready || !lv?.done ? 'loading' : F.entries().some(d => d.value.kind === 'title') ? 'title-frozen'
112
+ const state = !this.ready || !lv?.done ? 'loading' : F.entries().some(d => d.value?.kind === 'title') ? 'title-frozen'
113
113
  : this.halted ? 'halted' : F.size() ? 'frozen' : 'running';
114
114
  const blockedBy = this.input.blockedBy();
115
115
  if (F.has('error')) blockedBy.push('error');
@@ -49,4 +49,9 @@ export function markRolledBack(ops, seq, depth) {
49
49
  }
50
50
 
51
51
  /** Which state an op definition covers, for list / explain / the catalog: honest about what atomic means */
52
- export const atomicNote = d => d.atomic ? 'atomic: the parts declared atomic (world, inventory, containers, vars, quests, interactions, content, grids, random, scene) roll back if run fails; events, sound and other state do not (use after)' : null;
52
+ export const atomicNote = (d, e) => {
53
+ if (!d.atomic) return null;
54
+ const names = e ? [...e.saves.providers].filter(([, p]) => p.atomic).map(([k]) => k) : null;
55
+ const list = names?.length ? ` (${names.join(', ')})` : '';
56
+ return `atomic: save parts declared atomic${list} roll back if run fails; events, sound and other state do not (use after)`;
57
+ };
@@ -13,10 +13,10 @@ const STRINGS = {
13
13
  };
14
14
 
15
15
  /** Warn once per call site when `where` writes state outside the allowed places; throws when called from inside a can() */
16
- export function guardWrite(ops, where) {
16
+ export function guardWrite(ops, where, clientAllowed = false) {
17
17
  const e = ops.engine;
18
18
  if (ops._inCan) throw devError(fmt(STRINGS.canWrote, { name: ops._inCan, where }));
19
- if (ops._client ? !e.ready || ops._allowDepth > 0 || where === 'world.move' : !e.ready || e._inFixed || ops._stack.length || ops._allowDepth > 0) return;
19
+ if (ops._client ? !e.ready || ops._allowDepth > 0 || clientAllowed : !e.ready || e._inFixed || ops._stack.length || ops._allowDepth > 0) return;
20
20
  // first caller outside the engine: skip frames in engine folders, or in the bundle file this guard itself lives in
21
21
  const lines = (new Error().stack || '').split('\n'), file = l => l.match(/\(?([^()\s]+?):\d+:\d+\)?$/)?.[1], own = file(lines[1] || '');
22
22
  // 0 Error, 1 guardWrite, 2 Ops.guard, 3 the module method that called guard, then its callers
package/core/ops/owned.js CHANGED
@@ -33,7 +33,7 @@ export function allowOwned(owner, what) {
33
33
  if (what === false || what == null) {
34
34
  // the animation's last value is the game's choice, not an outside write: take it as the new reference
35
35
  const s = exempt.get(owner); exempt.delete(owner);
36
- if (s) for (const o of live) if (o._snap && covers(s, o)) o.mark();
36
+ if (s) for (const o of live) if (o._hasSnap && covers(s, o)) o.mark();
37
37
  return;
38
38
  }
39
39
  exempt.set(owner, new Set(what));
@@ -44,8 +44,7 @@ function isExempt(entry) {
44
44
  return false;
45
45
  }
46
46
 
47
- const flat = v => [].concat(v);
48
- const differs = (a, b) => a.length !== b.length || a.some((x, i) => x !== b[i]);
47
+ const sameVal = (a, b) => a === b || Object.is(a, b);
49
48
 
50
49
  class Owned {
51
50
  constructor(e, spec) {
@@ -58,19 +57,34 @@ class Owned {
58
57
  /** 'engine' | 'manual' | 'yielded' */ this.mode = 'engine';
59
58
  /** who took it: 'game' (manual()), or 'three' for a direct write */ this.by = 'engine';
60
59
  /** @type {string | null} the line that made the engine yield, when the dev server saw it */ this.writtenAt = null;
60
+ this._hasSnap = false;
61
+ this._isArr = false;
61
62
  this._snap = null;
63
+ this._snapArr = null;
64
+ this._cur = [];
62
65
  this._onChange = spec.onChange;
63
66
  // once: the engine never writes it, it only keeps the value read here (renderer.toneMapping). So a direct write is the documented way to change it (yielding warns
64
67
  // nothing), and handing it back writes that value again (spec.write)
65
- this._once = spec.once ? { value: this._read() } : null;
68
+ this._once = spec.once ? { value: this._read(this._cur) } : null;
66
69
  }
67
70
  /** Does the engine write this property now */
68
71
  get on() { return this.mode === 'engine'; }
69
72
  /** Before the engine writes: a value different from the last mark() was written by someone else, so yield to it (once per takeover) */
70
73
  check() {
71
- if (this.mode !== 'engine' || !this._snap) return;
72
- const v = flat(this._read());
73
- if (!differs(v, this._snap) || isExempt(this)) return;
74
+ if (this.mode !== 'engine' || !this._hasSnap) return;
75
+ const v = this._read(this._cur);
76
+ let diff;
77
+ if (this._isArr) {
78
+ const snap = this._snap;
79
+ if (!Array.isArray(v) || v.length !== snap.length) diff = true;
80
+ else {
81
+ diff = false;
82
+ for (let i = 0; i < v.length; i++) if (!sameVal(v[i], snap[i])) { diff = true; break; }
83
+ }
84
+ } else {
85
+ diff = Array.isArray(v) || !sameVal(v, this._snap);
86
+ }
87
+ if (!diff || isExempt(this)) return;
74
88
  this._set('yielded', 'three');
75
89
  if (DEV) this.writtenAt = this._e._picture?.outside(this.id) ?? null; // dev server only: who took it, as the writers tool saw it (core/inspect/pictureWriters.js)
76
90
  if (DEV && this._e.validate && !this._once) {
@@ -83,18 +97,30 @@ class Owned {
83
97
  * @param {any} [reference] what the engine left there, when that is not what is there now: a property registered after the game could already write it
84
98
  * (a sky installed once picture code ran), so the first check() still sees that write
85
99
  */
86
- mark(reference = this._read()) { this._snap = flat(reference); }
100
+ mark(reference = this._read(this._cur)) {
101
+ if (Array.isArray(reference)) {
102
+ this._isArr = true;
103
+ const dst = this._snapArr ?? (this._snapArr = new Array(reference.length));
104
+ dst.length = reference.length;
105
+ for (let i = 0; i < reference.length; i++) dst[i] = reference[i];
106
+ this._snap = dst;
107
+ } else {
108
+ this._isArr = false;
109
+ this._snap = reference;
110
+ }
111
+ this._hasSnap = true;
112
+ }
87
113
  /** check, write when the engine owns it, mark. Needs spec.write */
88
114
  drive(v) { this.check(); if (this.on) this._write(v); this.mark(); }
89
115
  /** Take over (on) or hand back (false). Hand-back forgets the snapshot so the engine's next write is not mistaken for an outside one */
90
116
  manual(on = true, by = 'game') {
91
117
  if (on) this._set('manual', by);
92
118
  else if (this._once) { this._write?.(this._once.value); this._set('engine', 'engine'); this.mark(); } // nothing writes it per frame: write it back now
93
- else { this._snap = null; this._set('engine', 'engine'); }
119
+ else { this._hasSnap = false; this._snap = null; this._set('engine', 'engine'); }
94
120
  }
95
121
  _set(mode, by) {
96
122
  const was = this.mode;
97
- this.mode = mode; this.by = by; this.at = this._e.time?.frame ?? null;
123
+ this.mode = mode; this.by = by; this.at = this._e.time?.tick ?? null;
98
124
  if (was !== mode) this._onChange?.(this);
99
125
  }
100
126
  /** describe().owned row: writer = who writes it now ('engine' | 'manual:<who>' | 'three (engine yielded)') */
@@ -142,7 +168,7 @@ export function movedOwned(engine, moved) {
142
168
  if (!o.objects.some(x => moved.has(x))) continue;
143
169
  o.objects = o.objects.map(x => moved.get(x) ?? x);
144
170
  engine._picture?.owned(o);
145
- if (o._snap) o.mark();
171
+ if (o._hasSnap) o.mark();
146
172
  }
147
173
  }
148
174
  /** Remove registrations (a module disposed) @param {any} engine @param {Iterable<{ id: string }>} list */
@@ -64,7 +64,11 @@ export function ownerArgs(a, b, fallback = 'game') {
64
64
  const label = (name, id) => (id == null ? name : `${name}[${id}]`);
65
65
 
66
66
  /** a value as describe / how-strings / the changed line print it (a rule's value may be a function; JSON.stringify(undefined) is undefined) */
67
- export const showValue = v => (typeof v === 'number' ? String(+v.toFixed(4)) : typeof v === 'function' ? 'function' : JSON.stringify(v) ?? String(v));
67
+ export const showValue = v => {
68
+ if (typeof v === 'number') return String(+v.toFixed(4));
69
+ if (typeof v === 'function') return 'function';
70
+ try { return JSON.stringify(v) ?? String(v); } catch { return String(v); }
71
+ };
68
72
 
69
73
  /** One shared point. Made by engine.stacks.define; games normally only call engine.mod(name, ...) and read value(). */
70
74
  export class Stack {
@@ -121,7 +121,11 @@ export class Stacks {
121
121
  * @example engine.stacks.changed() // [{ name: 'move.speed[player]', base: 6, now: 4.2, how: 'default 6 × haste 1.4 × mud 0.5' }]
122
122
  */
123
123
  changed(max = 5, snap = this._rows()) {
124
- const same = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);
124
+ const same = (a, b) => {
125
+ if (Object.is(a, b)) return true;
126
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;
127
+ try { return JSON.stringify(a) === JSON.stringify(b); } catch { return false; }
128
+ };
125
129
  const rows = [];
126
130
  for (const { label: name, s, row: r, has } of snap) {
127
131
  if (s.kind !== 'number' && s.kind !== 'value') continue;
@@ -132,7 +136,7 @@ export class Stacks {
132
136
  }
133
137
  // important points are picked first (they must not fall off the cap), then the list is ordered by distance from base
134
138
  const pick = rows.sort((a, b) => b.keep - a.keep || b.far - a.far).slice(0, max);
135
- return pick.sort((a, b) => b.far - a.far).map(({ far, keep, ...row }) => row);
139
+ return pick.sort((a, b) => b.far - a.far).map(r => ({ name: r.name, base: r.base, now: r.now, how: r.how, text: r.text }));
136
140
  }
137
141
  /**
138
142
  * Everything one owner changes now, grouped the other way round from describe().shared: "what did rainyNight change?"
@@ -160,10 +164,27 @@ export class Stacks {
160
164
  */
161
165
  _expire() {
162
166
  if (!this._timedDirty) return 0;
163
- const timed = this._timed();
164
- if (!timed.length) { this._timedDirty = false; return 0; } // nothing timed: later steps return at once until the next timed mod
165
- const due = timed.map(([s, e]) => ({ s, e, over: this._nowOf(e.clock) - e.until })).filter(d => d.over >= -1e-9);
166
- due.sort((a, b) => b.over - a.over); // the most overdue ended first in time
167
+ let hasTimed = false, hasDue = false;
168
+ for (const s of this._all.values()) {
169
+ for (const m of s._by.values()) {
170
+ for (const e of m.values()) {
171
+ if (e.until == null) continue;
172
+ hasTimed = true;
173
+ if (this._nowOf(e.clock) - e.until >= -1e-9) { hasDue = true; break; }
174
+ }
175
+ if (hasDue) break;
176
+ }
177
+ if (hasDue) break;
178
+ }
179
+ if (!hasTimed) { this._timedDirty = false; return 0; } // nothing timed: later steps return at once until the next timed mod
180
+ if (!hasDue) return 0;
181
+ const due = [];
182
+ for (const s of this._all.values()) for (const m of s._by.values()) for (const e of m.values()) {
183
+ if (e.until == null) continue;
184
+ const over = this._nowOf(e.clock) - e.until;
185
+ if (over >= -1e-9) due.push({ s, e, over });
186
+ }
187
+ if (due.length > 1) due.sort((a, b) => b.over - a.over); // the most overdue ended first in time
167
188
  for (const { s, e } of due) {
168
189
  if (!s._drop(e.owner, e.id, e)) continue;
169
190
  this.engine.events?.emit('mod:end', { target: s.name, owner: e.owner, id: e.id });
@@ -215,7 +236,9 @@ export class Stacks {
215
236
  const had = new Map();
216
237
  for (const m of [...s._by.values()]) for (const e of [...m.values()]) if (saved(e)) { had.set(`${e.id ?? ''}\0${e.owner}`, e); s._drop(e.owner, e.id, e); }
217
238
  for (const e of list) {
218
- const m = s._map(e.id, true), clock = e.clock, old = had.get(`${e.id ?? ''}\0${e.owner}`);
239
+ const m = s._map(e.id, true);
240
+ if (m.has(e.owner)) continue; // a non-saved layer (system / settings / debug) holds this owner: keep it instead of overwriting its handle
241
+ const clock = e.clock, old = had.get(`${e.id ?? ''}\0${e.owner}`);
219
242
  const fields = { since: this._at(), op: e.op, value: e.value, layer: e.layer, clock, until: e.left == null ? null : this._nowOf(clock) + e.left };
220
243
  m.set(e.owner, old ? Object.assign(old, fields) : { owner: e.owner, id: e.id ?? null, where: null, ...fields });
221
244
  this._timedDirty = true;
@@ -36,7 +36,6 @@ const DEV_STRINGS = {
36
36
  badFirst: "saves.define('{key}'): first must be true, false or a finite number (lower loads earlier, true counts as 0), got {got}",
37
37
  staleBlob: "[saves] attachment '{group}/{id}' was not changed: another tab or window of this game wrote it after this one last saw it. Read saves.attachments('{group}') first, or use another id",
38
38
  busy: 'saves.collect() was called during a load, so it would hold half of each state. Wait for the load, or use saves.save, which waits by itself',
39
- owner: "saves.define('{key}'): that key already has a part, and this one takes it over: the first owner's data is no longer saved. Remove the first part, or use another key",
40
39
  autosave: 'saves.autosave(minutes): minutes must be a positive number of minutes of play, got {got}',
41
40
  asyncAtomic: "saves.define('{key}'): an atomic part's load must be synchronous, but it is an async function. An atomic op's rollback puts the part back before the op returns; a load still running after its first await would write the old data over what the outer op committed, its events past the mute. Make load plain (do the async work before), or drop atomic: true",
42
41
  protoName: "saves.define('__proto__'): a save cannot hold a part with this name (assigning it swaps the parts object's prototype, and save text drops it on reading), so its data would be lost without a word. Pick another name",
@@ -121,7 +120,6 @@ export class Saves {
121
120
  checkPartVersion(key, version, migrate);
122
121
  const f = this._foreign, held = Object.hasOwn(f.parts, key) ? { data: copyData(f.parts[key]), version: f.versions[key] ?? 1 } : null;
123
122
  const part = { save, load, first, version, migrate, atomic: atomic === true, checkNewGame, summary: summary === true };
124
- if (DEV && this.providers.has(key)) warnOnce(fmt(DEV_STRINGS.owner, { key }), `save-owner-${key}`); // the newer owner takes it, as a replaced module does; the older one stops being saved
125
123
  this.providers.set(key, part); this._summaries.clear(); // which parts are summaries changed
126
124
  try { this.engine.session._late(key); } // a part registered after start() (a module installed later) joins the new-game state as it is now
127
125
  catch (err) { this.providers.delete(key); this.engine.session._lateParts.delete(key); throw err; } // define() hands back no handle on a throw, so the key must not stay taken
@@ -58,12 +58,12 @@ export function applySave(s, data, slot) {
58
58
 
59
59
  /** fn under the marker, from its first line until what it returned settled (top of stateReplace.js) */
60
60
  function marked(s, fn) {
61
- const q = s._replace, job = q.job;
61
+ const q = s._replace, job = q.job, nested = q.replacing;
62
62
  q.begin();
63
63
  let out;
64
- try { out = fn(); } catch (err) { q.end(); throw err; }
65
- if (typeof out !== 'boolean') return out.finally(() => q.endOf(job));
66
- q.end();
64
+ try { out = fn(); } catch (err) { if (!nested) q.end(); throw err; }
65
+ if (typeof out !== 'boolean') return out.finally(() => { if (!nested) q.endOf(job); });
66
+ if (!nested) q.end();
67
67
  return out;
68
68
  }
69
69
 
@@ -177,7 +177,7 @@ function runParts(s, list, slot, scope, onFail, turn, reached, sync = false) {
177
177
  if (s.providers.get(k) !== p) { failed(k, null, codedError('save-provider-changed', fmt(DEV_STRINGS.changed, { k, slot }))); continue; } // a rollback reports it and goes on; a load fails and rolls back
178
178
  let r;
179
179
  reached?.add(k); // a part that started loading may hold half of the new data; one never reached holds nothing of it
180
- try { r = callLoad(s, () => p.load(d, turn), scope); } catch (err) { failed(k, err); continue; }
180
+ try { r = callLoad(s, () => s._replace.withTurn(turn, () => p.load(d, turn)), scope); } catch (err) { failed(k, err); continue; }
181
181
  if (!isThenable(r)) continue;
182
182
  if (sync) { try { syncOnly(r, `save part '${k}' load() in ${slot}`, true); } catch (err) { failed(k, null, err); } continue; }
183
183
  return r.then(() => step(i + 1), err => { failed(k, err); return step(i + 1); });
@@ -234,7 +234,7 @@ export function adoptPart(s, key, part) {
234
234
  const done = ok => { part.adopting = false; if (!ok) back(); return ok; };
235
235
  let out;
236
236
  try { out = marked(s, () => applyRead(s, { list }, `(late part '${key}')`, true)); } catch (err) { done(false); throw err; }
237
- return typeof out === 'boolean' ? done(out) : out.then(done);
237
+ return typeof out === 'boolean' ? done(out) : out.then(done, err => { done(false); throw err; });
238
238
  }, { behind: true }), L._parts);
239
239
  }
240
240
 
@@ -302,7 +302,7 @@ function afterLoad(s, e, slot, scope) {
302
302
  // built (review l2 #10). Not waited for: an init that defines a save part (a late job holding the turn) and then awaits a load would wait for this very job.
303
303
  // Its init builds for the state that stands when it runs
304
304
  hooks = has.filter(m => e._runsHooks(m.name));
305
- return Promise.allSettled(hooks.map(m => Promise.resolve().then(() => m.afterLoad(e, job.turn))));
305
+ return Promise.allSettled(hooks.map(m => Promise.resolve().then(() => q.withTurn(job.turn, () => m.afterLoad(e, job.turn)))));
306
306
  };
307
307
  return Promise.resolve().then(run).then(res => {
308
308
  // taken over: the state is the newer load's, so nothing here may fail or roll back; what the scope caught is a listener error like any other
@@ -118,6 +118,7 @@ export class Session {
118
118
 
119
119
  /** @internal A module used after start() finished init: what its parts took from install was half built, and boot parts are captured after init too */
120
120
  _lateInit(keys) {
121
+ if (!this._base) return;
121
122
  for (const key of keys) if (this._lateParts.delete(key) && this.engine.saves.providers.has(key)) { const b = JSON.parse(this._base); delete b.parts[key]; delete b.versions[key]; this._base = JSON.stringify(b); this._late(key); this._lateParts.delete(key); }
122
123
  }
123
124
 
@@ -161,17 +162,18 @@ export class Session {
161
162
  * so a part the save does not have (a module added in a later version of the game) starts from its new-game state.
162
163
  * A save that cannot be read (missing, corrupt, from a newer build) is refused before anything changes: returns false, the current game and the save stay as they were.
163
164
  * @param {string} [slot]
165
+ * @param {{ turn?: object }} [o] turn: the running request's own (what a save part's load(), an afterLoad or a module's applyState was given): the call then runs inside that request instead of waiting behind it for itself, as level.load({ turn }) does
164
166
  * @returns {Promise<boolean>}
165
167
  * @example
166
168
  * engine.events.on('player:dead', () => engine.session.load('checkpoint')); // retry; the checkpoint was saved with engine.saves.save('checkpoint')
167
169
  */
168
- load(slot = 'auto') {
170
+ load(slot = 'auto', { turn } = {}) {
169
171
  const S = this.engine.saves;
170
172
  return this._turn(`load ${slot}`, () => {
171
173
  const bad = S.check(slot);
172
174
  if (bad) return bad === 'missing' ? false : S._load(slot); // load shows the message and changes nothing
173
175
  return this._begin('load', () => S._load(slot, this._baseData()), { kind: 'load', slot });
174
- });
176
+ }, turn);
175
177
  }
176
178
 
177
179
  /**
@@ -222,6 +224,7 @@ export class Session {
222
224
  async _reset(fn, apply) {
223
225
  const e = this.engine;
224
226
  if (!this._base) throw codedError('session-early', fmt(DEV.early, { fn }));
227
+ const prevBusy = this._busy;
225
228
  this._busy = true;
226
229
  try {
227
230
  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)
@@ -248,7 +251,7 @@ export class Session {
248
251
  e.time._restoreFn(this._timers, oldTimers); // event timers came back with the save; function timers are the boot-time ones, each with its original delay, and those apply set up
249
252
  e.commits.rebase(); // requests that outlived the load (a nextFixed, terrain colliders) were due on the old tick count, minutes away now that tick restarted
250
253
  return true;
251
- } finally { this._busy = false; }
254
+ } finally { this._busy = prevBusy; }
252
255
  }
253
256
 
254
257
  /** @internal for describe */