threedog 2.1.0 → 2.2.2

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 (77) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/core/assets/Animator.js +1 -1
  3. package/core/audio/Audio.js +55 -8
  4. package/core/audio/audioReverb.js +2 -2
  5. package/core/base/Random.js +1 -1
  6. package/core/base/errorCodes.js +1 -1
  7. package/core/engine/Loading.js +3 -1
  8. package/core/engine/copies.js +1 -1
  9. package/core/engine/loop.js +1 -0
  10. package/core/input/Input.js +3 -3
  11. package/core/inspect/InspectPerf.js +1 -1
  12. package/core/inspect/describeText.js +3 -2
  13. package/core/inspect/metadata.generated.js +76 -24
  14. package/core/ops/holds.js +1 -1
  15. package/core/ops/sharedPoint.js +6 -1
  16. package/core/saves/Saves.js +24 -12
  17. package/core/saves/saveVersions.js +15 -0
  18. package/core/scene/Rays.js +1 -1
  19. package/core/scene/Views.js +20 -1
  20. package/core/scene/canvasBox.js +9 -0
  21. package/core/scene/sceneMethods.js +2 -1
  22. package/core/threads/Jobs.js +1 -1
  23. package/docs/AI.md +2 -2
  24. package/docs/API.md +2 -2
  25. package/docs/COMMANDS.md +4 -3
  26. package/docs/api/audio.md +1 -0
  27. package/docs/api/music.md +2 -2
  28. package/docs/api/saves.md +2 -1
  29. package/docs/api/settings.md +0 -2
  30. package/docs/recipes/02-npc.md +1 -1
  31. package/docs/recipes/03-items-pickups.md +4 -5
  32. package/docs/recipes/06-clock-events.md +2 -6
  33. package/docs/recipes/07-flow-scenes-pause.md +1 -1
  34. package/docs/recipes/08-weather-sky.md +2 -4
  35. package/docs/recipes/09-materials-lights-models.md +2 -2
  36. package/docs/recipes/14-custom-module.md +4 -1
  37. package/docs/recipes/15-perf.md +9 -5
  38. package/docs/recipes/16-dev-bridge.md +46 -36
  39. package/docs/recipes/20-content-actions-save.md +1 -0
  40. package/docs/recipes/21-camera.md +3 -4
  41. package/docs/recipes/26-ui-parts.md +3 -2
  42. package/docs/recipes/31-audio.md +19 -3
  43. package/docs/recipes/44-water-weather-hooks.md +1 -1
  44. package/docs/recipes/52-around-the-picture.md +1 -1
  45. package/docs/recipes/55-mods-time-wrap.md +5 -1
  46. package/docs/recipes/56-webgpu-tsl.md +5 -7
  47. package/docs/recipes/58-input.md +4 -1
  48. package/docs/recipes/60-judge-the-picture.md +5 -5
  49. package/llms.txt +1 -1
  50. package/modules/camera/common.js +1 -1
  51. package/modules/collision/Collision.js +1 -1
  52. package/modules/debug/DebugPanel.js +1 -1
  53. package/modules/gameplay/Dialogue.js +1 -1
  54. package/modules/gameplay/Interactions.js +1 -1
  55. package/modules/gameplay/Inventory.js +1 -1
  56. package/modules/gameplay/Quests.js +1 -1
  57. package/modules/hud/parts.js +1 -1
  58. package/modules/music/Music.js +35 -3
  59. package/modules/particles/Particles.js +1 -1
  60. package/modules/rigid/RigidBodies.js +1 -1
  61. package/modules/settings/Settings.js +22 -16
  62. package/modules/settings/sections.js +1 -1
  63. package/modules/swarm/Swarm.js +1 -1
  64. package/modules/timeline/Timeline.js +1 -1
  65. package/modules/timeline/letterbox.js +1 -1
  66. package/package.json +1 -1
  67. package/render/PostFX.js +7 -1
  68. package/render/fx/detail.tsl.js +3 -0
  69. package/types/core.d.ts +2 -0
  70. package/types/gameplay.d.ts +6 -7
  71. package/types/generated/core/audio/Audio.d.ts +10 -0
  72. package/types/generated/core/saves/Saves.d.ts +6 -1
  73. package/types/generated/modules/music/Music.d.ts +4 -13
  74. package/ui/Focus.js +1 -1
  75. package/ui/Parts.js +19 -7
  76. package/ui/defaults.js +1 -1
  77. package/ui/theme.js +14 -8
@@ -19,7 +19,7 @@ import { DEV, warnOnce, fmt } from '../base/validate.js';
19
19
  import { readParams } from '../base/params.js';
20
20
  import { reportError } from '../base/errors.js';
21
21
  import { codedError, coded } from '../base/errorHints.js';
22
- import { checkPartVersion, readSave } from './saveVersions.js';
22
+ import { checkPartVersion, readSave, summarize } from './saveVersions.js';
23
23
  import { exportSaveFile, importSaveFile, importText, SAVE_STRINGS } from './saveFiles.js';
24
24
  import { applyAnnounced, loadSlot, adoptPart, collectParts, partData } from './saveApply.js';
25
25
  import { autosaveHook } from './session.js';
@@ -43,7 +43,7 @@ const DEV_STRINGS = {
43
43
  };
44
44
 
45
45
  /** What saves.define takes: without a working save and load the failure would wait for the player's first save or load */
46
- const PROVIDER = { save: 'function', load: 'function', first: 'any?', version: 'any?', migrate: 'any?', atomic: 'any?', notAtomic: 'string?', checkNewGame: 'any?' };
46
+ const PROVIDER = { save: 'function', load: 'function', first: 'any?', version: 'any?', migrate: 'any?', atomic: 'any?', notAtomic: 'string?', checkNewGame: 'any?', summary: 'bool?' };
47
47
 
48
48
  /** Save data as a save file would hold it: no reference into the part's live state stays behind */
49
49
  const copyData = d => JSON.parse(JSON.stringify(d));
@@ -61,6 +61,7 @@ export class Saves {
61
61
  /** @internal */ this._auto = null;
62
62
  /** @internal Slot -> JSON text (all saves stay in memory: list / check / export are synchronous) */ this._json = new Map();
63
63
  /** @internal Slot -> savedAt */ this._meta = new Map();
64
+ /** @internal Slot -> list() summary parsed from that slot's text; dropped when the text or the set of parts changes */ this._summaries = new Map();
64
65
  /** @internal Disk-write queue: earlier saves are written first */ this._queue = Promise.resolve();
65
66
  /** @internal Slot -> rev of the copy in memory (a slot without a record is absent) */ this._rev = new Map();
66
67
  /** @internal Slot -> rev this tab may overwrite: the one it read at boot, last wrote or last loaded (absent = expects no record) */ this._mine = new Map();
@@ -114,20 +115,20 @@ export class Saves {
114
115
  readParams(`saves.define('${key}')`, PROVIDER, provider);
115
116
  if (provider.first !== undefined && typeof provider.first !== 'boolean' && !Number.isFinite(provider.first)) throw codedError('module-params', fmt(DEV_STRINGS.badFirst, { key, got: JSON.stringify(provider.first) }));
116
117
  if (key === '__proto__') throw codedError('module-params', DEV_STRINGS.protoName);
117
- const { save, load, first = false, version = 1, migrate = {}, atomic = false, checkNewGame = null } = provider;
118
+ const { save, load, first = false, version = 1, migrate = {}, atomic = false, checkNewGame = null, summary = false } = provider;
118
119
  // shortcut: only a load declared async is known here; a plain function that returns a Promise is refused when the rollback meets it (restoreParts, saveApply.js)
119
120
  if (atomic === true && load.constructor?.name === 'AsyncFunction') throw codedError('module-params', fmt(DEV_STRINGS.asyncAtomic, { key }));
120
121
  checkPartVersion(key, version, migrate);
121
122
  const f = this._foreign, held = Object.hasOwn(f.parts, key) ? { data: copyData(f.parts[key]), version: f.versions[key] ?? 1 } : null;
122
- const part = { save, load, first, version, migrate, atomic: atomic === true, checkNewGame };
123
+ const part = { save, load, first, version, migrate, atomic: atomic === true, checkNewGame, summary: summary === true };
123
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
124
- this.providers.set(key, part);
125
+ this.providers.set(key, part); this._summaries.clear(); // which parts are summaries changed
125
126
  try { this.engine.session._late(key); } // a part registered after start() (a module installed later) joins the new-game state as it is now
126
127
  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
127
128
  if (held) adoptPart(this, key, part);
128
129
  return { remove: ({ keep = true } = {}) => {
129
130
  if (this.providers.get(key) !== part) return; // a stale handle: the key belongs to someone newer
130
- this.providers.delete(key);
131
+ this.providers.delete(key); this._summaries.clear();
131
132
  let left = held; // removed while its late data loads (adoptPart): that data goes back unattached, not the half-loaded state
132
133
  if (keep && !part.adopting && !Object.hasOwn(this._foreign.parts, key)) try { const d = partData(key, part); left = d == null ? null : { data: copyData(d), version }; }
133
134
  catch (err) { reportError(this.engine, err, `save() of part '${key}' while it was removed`, { soft: true }); }
@@ -148,7 +149,7 @@ export class Saves {
148
149
  try {
149
150
  for (const r of await this.store.slots()) {
150
151
  this._rev.set(r.slot, r.rev ?? ''); this._mine.set(r.slot, r.rev ?? ''); // also for a save made before this ran: its write comes after and expects this record
151
- if (!this._json.has(r.slot)) { this._json.set(r.slot, r.json); this._meta.set(r.slot, r.savedAt); }
152
+ if (!this._json.has(r.slot)) { this._json.set(r.slot, r.json); this._meta.set(r.slot, r.savedAt); this._summaries.delete(r.slot); }
152
153
  }
153
154
  this._sawBlobs(await this.store.blobs());
154
155
  } catch (e) { this._fail(e); }
@@ -275,7 +276,7 @@ export class Saves {
275
276
  /** @internal Put a save in memory and queue the disk write; returns Promise<boolean> (write succeeded) */
276
277
  _put(slot, json, savedAt) {
277
278
  const rev = this._newRev();
278
- this._json.set(slot, json); this._meta.set(slot, savedAt);
279
+ this._json.set(slot, json); this._meta.set(slot, savedAt); this._summaries.delete(slot);
279
280
  // expect is read when the write runs, not now: an earlier queued save of this tab moves _mine first
280
281
  return this._enqueue(() => this.store.putSlot(slot, savedAt, json, rev, this._mine.get(slot) ?? null)).then(() => {
281
282
  this._rev.set(slot, rev); this._mine.set(slot, rev);
@@ -307,6 +308,7 @@ export class Saves {
307
308
  _newRev() { return `${this._tab}:${++this._n}`; }
308
309
  /** @internal Memory shows a stored record (null = none); a stored record leaves the rev this tab may overwrite as it was */
309
310
  _show(slot, r) {
311
+ this._summaries.delete(slot);
310
312
  if (!r) { this._json.delete(slot); this._meta.delete(slot); this._rev.delete(slot); this._mine.delete(slot); return; } // deleted: no newer progress to protect, so the next save may write
311
313
  this._json.set(slot, r.json); this._meta.set(slot, r.savedAt); this._rev.set(slot, r.rev ?? '');
312
314
  }
@@ -359,9 +361,19 @@ export class Saves {
359
361
  load(slot = 'auto', { turn } = {}) { return this._replace.run(null, () => this._load(slot), { turn }); }
360
362
  /** @internal Load a slot inside a turn already taken; with base (a collect() result) the save goes on top of it, so a part missing from the save gets base's state (session.load) */
361
363
  _load(slot, base) { return loadSlot(this, slot, base); }
362
- /** All slots, newest first (synchronous, reads the in-memory index) @returns {{ slot: string, savedAt: number }[]} */
364
+ /**
365
+ * All slots, newest first (synchronous). summary: the parts marked `summary: true` in saves.define, read from the stored save and migrated; {} if none.
366
+ * @returns {{ slot: string, savedAt: number, summary: Record<string, any> }[]}
367
+ * @example for (const { slot, summary } of engine.saves.list()) console.log(slot, summary.hero?.level);
368
+ */
363
369
  list() {
364
- return [...this._meta].map(([slot, savedAt]) => ({ slot, savedAt })).sort((a, b) => b.savedAt - a.savedAt);
370
+ return [...this._meta].map(([slot, savedAt]) => ({ slot, savedAt, summary: this._summary(slot) })).sort((a, b) => b.savedAt - a.savedAt);
371
+ }
372
+ /** @internal One slot's summary, parsed once per stored text: every place that changes the text (_init, _put, _show, remove) drops it. Cached results are copied so a caller's edit cannot change the next list() */
373
+ _summary(slot) {
374
+ let s = this._summaries.get(slot);
375
+ if (!s) this._summaries.set(slot, s = summarize(this._json.get(slot), this.providers));
376
+ return structuredClone(s);
365
377
  }
366
378
  /**
367
379
  * Delete a slot. Returns a Promise (disk write done); awaiting is optional. A newer save another tab wrote meanwhile is kept: the slot lists again, with a toast (save-stale).
@@ -369,7 +381,7 @@ export class Saves {
369
381
  * @param {string} slot @returns {Promise<void>}
370
382
  */
371
383
  remove(slot) {
372
- this._json.delete(slot); this._meta.delete(slot);
384
+ this._json.delete(slot); this._meta.delete(slot); this._summaries.delete(slot);
373
385
  // the revs are cleared when the delete runs, not now: a save queued before this remove sets _mine when its write lands,
374
386
  // and a _mine left over for a deleted record would refuse every later save of this slot as "another tab saved"
375
387
  // what it expects is what this tab lists (_rev): a save the note from another tab brought in is the player's to delete
@@ -433,4 +445,4 @@ export class Saves {
433
445
  dispose() { this._auto?.remove(); this._bc?.close(); this._bc = null; this._queue.then(() => this.whenReady).catch(() => {}).finally(() => this.store.close()); } // close the database only after queued writes finish and the open (which sets store.db later) is done
434
446
  }
435
447
 
436
- export const handRolled = [{ kind: 'save', seen: 'a save of its own in localStorage', use: "engine.saves: autosave(minutes), define('game', { version: 1, save, load }), and Continue on the start screen (recipe 63); versions, slots and a corrupt save are handled", quiet: /\bengine\.saves\b/, code: /\blocalStorage\.setItem\s*\(/, notRaw: /setItem\s*\(\s*(?![^,)]*(?:save|progress))[^,)]*(?:volume|mute|lang|locale|theme|music|sfx|quality|sensitiv|brightness|fullscreen|tutorial|dismiss|setting|pref|option|keybind)/i }];
448
+ export const handRolled = [{ kind: 'save', docRef: 'recipes/20-content-actions-save.md §4', seen: 'a save of its own in localStorage', use: "engine.saves: autosave(minutes), define('game', { version: 1, save, load }), and Continue on the start screen; versions, slots and a corrupt save are handled", quiet: /\bengine\.saves\b/, code: /\blocalStorage\.setItem\s*\(/, notRaw: /setItem\s*\(\s*(?![^,)]*(?:save|progress))[^,)]*(?:volume|mute|lang|locale|theme|music|sfx|quality|sensitiv|brightness|fullscreen|tutorial|dismiss|setting|pref|option|keybind)/i }];
@@ -115,3 +115,18 @@ export function readSave(json, providers, slot) {
115
115
  for (const k of Object.keys(data.parts)) if (!providers.has(k)) { foreign.parts[k] = data.parts[k]; foreign.versions[k] = partVersion(versions, k); }
116
116
  try { return { data, foreign, list: list.map(([k, p]) => [k, p, upgradePart(k, p, data.parts[k], partVersion(versions, k), whole)]) }; } catch (e) { return { reason: 'migrate', dev: e.message }; }
117
117
  }
118
+
119
+ /**
120
+ * The parts a game marked `summary: true`, from one stored save text, read and migrated by readSave (the same checks and steps a load runs), so an old
121
+ * save lists in the shape the game reads now. A save that load() would refuse (corrupt, too new, a missing step) lists with no summary; load() says why.
122
+ * @param {string} json
123
+ * @param {Map<string, any>} providers
124
+ * @returns {Record<string, any>}
125
+ * @internal
126
+ */
127
+ export function summarize(json, providers) {
128
+ const marked = new Map([...providers].filter(([, p]) => p.summary));
129
+ if (!marked.size) return {};
130
+ const r = readSave(json, marked, 'list()');
131
+ return r.reason ? {} : Object.fromEntries(r.list.map(([k, , data]) => [k, data]));
132
+ }
@@ -218,4 +218,4 @@ function toHit(h) {
218
218
  return { ...h, normal };
219
219
  }
220
220
 
221
- export const handRolled = [{ kind: 'picking', 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 (recipe 19)', quiet: /\b(engine|e|eng|ctx)\.(rays|raycast|pick)\b/, code: /\.setFromCamera\s*\(/ }];
221
+ 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*\(/ }];
@@ -8,6 +8,7 @@ import { warnMissing } from '../base/validate.js';
8
8
  import { readParams, keysSchema } from '../base/params.js';
9
9
  import { codedError } from '../base/errorHints.js';
10
10
  import { holdFov, baseFov } from './view.js';
11
+ import { defineOwned, dropOwned } from '../ops/owned.js';
11
12
 
12
13
  const vec3 = a => Array.isArray(a) && a.length === 3 && a.every(Number.isFinite);
13
14
 
@@ -60,11 +61,28 @@ export class Views {
60
61
  // focus: the world loads around what the view looks at, not around a player far away (the view was an empty sheet of ground without it)
61
62
  const focus = e.camera.position.clone().fromArray(v.target);
62
63
  // onTop: a newer claim (a timeline shot) that moved the camera has released, and this one is in charge again: the view is put back, not just the claim (stack hook in core/ops/holds.js)
64
+ // The pose is placed once and then held, so a game script that writes the camera every frame (and ignores engine.cameraOverride) undoes the view without a word:
65
+ // the shared "an outside write makes the engine yield, said once" check watches it each frame while this claim is the one in charge
66
+ this._watch(e);
63
67
  this._cam = e.takeCamera('views', { focus, onTop: () => this._put(name, v, focus) });
64
68
  this._put(name, v, focus);
65
69
  const cam = this._cam; // this showing, not the name: a handle kept from an earlier one must not end a later one
66
70
  return { remove: () => { if (this._cam === cam) this.release(); } };
67
71
  }
72
+ /** @internal Register the camera pose as owned for this showing and check it every frame while the views claim is in charge (a cutscene on top moves the camera on purpose) */
73
+ _watch(e) {
74
+ this._unwatch();
75
+ const c = e.camera;
76
+ this._owned = defineOwned(e, { id: 'views-camera', part: 'view', key: 'views-camera', objects: [c, c.position, c.quaternion],
77
+ read: () => { const { position: p, quaternion: q } = c; return [p.x, p.y, p.z, q.x, q.y, q.z, q.w]; },
78
+ levels: { manual: "engine.autoView.manual('views-camera'), or make your camera script step aside while engine.cameraOverride is set", back: "engine.autoView.manual('views-camera', false)" } });
79
+ this._tick = e.onFrame(() => { if (e.cameraOverride?.owner === 'views') this._owned.check(); this._owned.mark(); });
80
+ }
81
+ _unwatch() {
82
+ this._tick?.remove(); this._tick = null;
83
+ if (this._owned) dropOwned(this.engine, [this._owned]);
84
+ this._owned = null;
85
+ }
68
86
  /** The view's pose and lens, on show and again each time the claim comes back on top */
69
87
  _put(name, v, focus) {
70
88
  const e = this.engine, c = e.camera;
@@ -72,11 +90,12 @@ export class Views {
72
90
  c.position.fromArray(v.position); c.lookAt(...v.target);
73
91
  holdFov(e, v.fov ?? baseFov(e)); // a view without a fov shows the base lens: a shot that stood in front of it may have left its own
74
92
  c.updateMatrixWorld(true);
93
+ this._owned?.mark(); // what is on the camera now is the view, not an outside write
75
94
  this.current = name;
76
95
  e.events.emit('camera:shot', { name }); // a cut: what follows the camera (the light pool) settles at once instead of easing over
77
96
  }
78
97
  /** Give the camera back (to the previous holder, e.g. a running cutscene, or to the rig) */
79
98
  release() {
80
- this._cam?.remove(); this._cam = null; this.current = null;
99
+ this._cam?.remove(); this._cam = null; this.current = null; this._unwatch();
81
100
  }
82
101
  }
@@ -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
  };
@@ -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);
@@ -8,7 +8,7 @@
8
8
  // If the job is not done by the due tick, the remaining steps run to completion on the spot, so such a job must be a plain function or generator (it cannot return a Promise).
9
9
  // Those steps are capped by maxSteps too: a generator that never ends would hang the fixed step, so past the cap its promise rejects with jobs-endless and apply does not run.
10
10
  // With apply, the returned Promise resolves when the work finishes, which may be before apply runs (it waits for the fixed tick); put anything that needs "state already changed" inside apply, do not assume it after await.
11
- // A single step that is too slow (one next() over slowStepMs in the real-time loop) warns once in dev: add more yields to a loop to slice it, since the budget only limits how many steps run, it cannot split one step.
11
+ // Steps are packed by time, not by count: a frame runs as many next() calls as fit in budgetMs (3 ms), so one yield per unit of work is enough and there is no row count to guess. One step over slowStepMs (8 ms, real-time loop) is only a reminder: it warns once in dev, so add more yields to slice that step (the budget cannot split one step).
12
12
  // Two ways to advance:
13
13
  // Real-time loop: at most budgetMs per frame (loadingMs while the loading screen is up), always at least one step so a slow job cannot starve.
14
14
  // Deterministic (engine.step(), headless loading): ignores real time and drains the queue on each run (generators run to the end);
package/docs/AI.md CHANGED
@@ -28,7 +28,7 @@ A row or `threedog how` -> recipe -> `api/<module>.md`. Also: `CONVENTIONS.md`,
28
28
  | Player actions, UI buttons (can refuse) | `engine.ops.define` | 23-ops.md §1 |
29
29
  | A value several systems change; one-holder parts | `engine.mod`, `engine.stacks`, `provides`, `wrap` | 55-mods-time-wrap.md §"The rules in full" |
30
30
  | Content: items, NPCs, places, packs; change an entry for good | `engine.content`, `threedog content set` | 20-content-actions-save.md §1b |
31
- | Save game, load game, autosave, story flags, counters | `engine.saves.define`, `engine.vars` | 20-content-actions-save.md §4 |
31
+ | Save game, load game, autosave, story flags, counters | `engine.saves.define` (`summary: true`), `engine.vars` | 20-content-actions-save.md §4 |
32
32
  | Preferences outside the save; turn off my effect | `engine.settings` (`limits: 'post.x.enabled'`) | 26-ui-parts.md §6 |
33
33
  | Timers, skip time; game time: rules, AI | `engine.clock` (after, every), `engine.onFixed(dt)`, `engine.time.now(…)` | 06-clock-events.md §1 |
34
34
  | What shows: animation, camera, HUD (`engine.stepBlend`) | `engine.onFrame` | 06-clock-events.md §1 |
@@ -53,7 +53,7 @@ A row or `threedog how` -> recipe -> `api/<module>.md`. Also: `CONVENTIONS.md`,
53
53
  | Many lights (torches); windows, signs at night | `engine.lightPool`, `uNight` | 09-materials-lights-models.md §1b |
54
54
  | Picture from a reference; judge | `threedog picture palette`, `threedog examples list` | 35-picture-from-reference.md §"The loop", 60-judge-the-picture.md |
55
55
  | Reuse effects, models of old games | `threedog lib` | 05-props-bake.md |
56
- | Sound, music, ambience | `engine.audio`, `engine.music`, `engine.ambience` | 31-audio.md |
56
+ | Sound, music, ambience, bus nodes | `engine.audio`, `engine.music`, `engine.ambience` | 31-audio.md |
57
57
 
58
58
  ### Rules, state, time
59
59
  | To do | Use | Recipe |
package/docs/API.md CHANGED
@@ -37,7 +37,7 @@
37
37
  - [`engine.vars`](api/vars.md) story flags and counters (autosaved): flag setFlag counter bump
38
38
  - [`engine.saves`](api/saves.md) engine.saves handles saving: define putAttachment removeAttachment attachments storageKey flush collect check apply save load list remove export …
39
39
  - [`engine.assets`](api/assets.md) Assets: manifest builder paramsOf setParams preload font model lod modelNow onModel geometry gridFromImage texture useTexture …
40
- - [`engine.audio`](api/audio.md) buses: addBus setVolume reverb duck condition measure value matches volumeOf sfx noiseBurst tone load play
40
+ - [`engine.audio`](api/audio.md) buses: addBus addNode setVolume reverb duck condition measure value matches volumeOf sfx noiseBurst tone load …
41
41
  - [`engine.i18n`](api/i18n.md) string tables: add setLocale has
42
42
  - [`engine.rays`](api/rays.md) engine.rays is the ray registry…: addStatic addProvider
43
43
  - [`engine.jobs`](api/jobs.md) engine.jobs queues build work in a binary heap: add run
@@ -66,7 +66,7 @@
66
66
  - [`engine.triggers`](api/triggers.md) triggers() Trigger zones: list add clear byTag fromMarkers
67
67
  - [`engine.particles`](api/particles.md) particles() Particles: define has emit attach count clear
68
68
  - [`engine.swarm`](api/swarm.md) swarm
69
- - [`engine.settings`](api/settings.md) settings() Settings menu: get set preset define addSection open close toggle reset resetBindings rebind actionList …
69
+ - [`engine.settings`](api/settings.md) settings() Settings menu: get set preset define addSection reset resetBindings rebind actionList save
70
70
  - [`engine.music`](api/music.md) music() Background music: define play stop stinger rules override pick
71
71
  - [`engine.characters`](api/characters.md) characters() Characters: findSpawn addPlayer moveInput addVehicle support removePlayer findPath findPathAsync; Character, NPC; engine.npcs: list add remove behavior tiers get character avoid (behavior and avoid: see recipes/02-npc)
72
72
  - [`engine.interactions`](api/interactions.md) interactions() Interaction prompts: add get
package/docs/COMMANDS.md CHANGED
@@ -69,7 +69,7 @@ export const specs = [{
69
69
  | `threedog shot --view name [--compare before.png]` | A named camera view (`engine.views.define`) and a pixel diff against an earlier picture. `recipes/46-blender-art-route.md` |
70
70
  | Result of every bridge command | CLI text ends with one line on the game state and the way back (`Game loop halted, tick 180: threedog resume restores real-time running`; frozen by a menu says which). MCP adds `structuredContent` { ok, code, summary, runtime { ready, mode running|halted|frozen, tick, headless, blockedBy[] }, data } and an `outputSchema` on every tool. `code`: ok, blocked (ran, refused), not-ready, no-server / starting / busy / page-error / no-bridge (cannot reach the game), command-error. **Advance game time**: step, press, hold, skip, scenario, verify. **No game time**: op, state, eval, js, resume, reload. Everything else only observes. eval / js and describe with a path or --full / --all print no state line (parseable); runtime still has it. |
71
71
  | `npm run map` | Regenerate CODEMAP, API.md + api/, each game's GAMEMAP and the event-name list (generated from `EventMap` in core.d.ts; add a new event to EventMap first) after changing code, JSDoc or content (run it before `check`) |
72
- | `npm run shot -- / --time 18:30 --weather rain --pos x,z` (or `--at place`: in play at a named place) | Only when you need to see the picture: 1 image of 960x540 into the workspace's .threedog/shots/; **read the state as text first with `--describe-only`** (`--json` gives the whole state). `/<page>.html` switches the page, `-w game` the game, `--wait seconds` advances time, `--play` starts in play past the title screen. The shot waits for loading and for the game's own code after `await engine.start()`, and fails naming what is still pending. Other options (`--no-build`, `--load-timeout`, `--keep-cutscene`, `--tier`, `--out`): `threedog shot --help` |
72
+ | `npm run shot -- / --time 18:30 --weather rain --pos x,z` (or `--at place`: in play at a named place) | Only when you need to see the picture: 1 image of 960x540 into the workspace's .threedog/shots/; **read the state as text first with `--describe-only`** (`--json` gives the whole state). `/<page>.html` switches the page, `-w game` the game, `--wait seconds` advances time, `--play` starts in play past the title screen. The shot waits for loading and for the game's own code after `await engine.start()`, and fails naming what is still pending. `--point name`: a shots.json point; checks the game's expectations. Other options: `threedog shot --help` |
73
73
  | `npm run shot -- / [--ref image] [--no-picture] [--json]` · `shot http://localhost:5173/` · `shot --image file.png` | After every shot (and every `threedog snap`): picture numbers measured on the 3D canvas and at most four one-sentence hints (contradictions, facts, intent; recipes/35 "Picture check after every shot"). Nothing fails and nothing is changed; every value touched by its few extra renders is put back. `--json` gives every hint in full. A full URL opens an already running page without a build; `--image` reads a picture taken another way and gives the pixel part only. A screenshot of your own skips the check: take pictures with `shot` or `snap` |
74
74
  | `npm run shot -- styletest --view room --time dusk --weather rain` | The fixed style-judging scene (`examples/styletest`, page `/styletest.html`; a bare name is a page of the workspace). Views and the `--time` / `--weather` words: recipes/35. Same arguments every round, so only the style differs. `--panel` is not a shot option: open `/styletest.html?panel=1` in a browser for the workbench (recipes/35) |
75
75
  | `threedog capture [page] [--top N] [--no-spector] [--spector-url url] [--full] [--no-build]` | Find out what a frame draws: renders one steady frame headless and prints draw calls, shadow-map draws, render passes (post effects) and the largest draws with world record id, budget tag and material purpose. Also records the WebGL command stream of that frame with Spector.js (fetched on first use into `.threedog/cache/`, not a dependency) to `.threedog/captures/`; `--no-spector` skips it, `--spector-url` fetches it from another source. Works on the game's own renderer, WebGL or WebGPU, and prints which one it measured; Spector only runs on WebGL. A frame with no draws fails |
@@ -85,6 +85,7 @@ export const specs = [{
85
85
  | `threedog picture palette <image> [--n 8] [--average] [--region x,y,w,h] [--ignore-ui] [--crop out.png] [--json]` | Dominant colors of a reference picture and a one-line summary; `--region` measures one rectangle, `--ignore-ui` cuts a flat frame around the picture (a plain sky at the edge looks the same: check with `--crop out.png`, which saves the measured area). A measurement, not a design decision |
86
86
  | `threedog picture compare <reference> <screenshot> [--region x,y,w,h] [--ref-region ..] [--shot-region ..] [--json]` | Differences as numbers (brightness, saturation, contrast, fine detail, main color) plus one neutral sentence ("18% darker, 2.3x more broken up"); both pictures are scaled down to one size. Regions match by position, so cut the same content with `--ref-region` / `--shot-region`. **An aid to judging, not a replacement for looking; no number is a quality score and there is no "similarity %".** recipes/35 |
87
87
  | `?panel=1` with `import('@threedog/tools/panel').then(m => m.openPanel(engine))` | The dev panel in any game: live sliders straight on the three.js objects, "write back" for `threedog tune`. `recipes/35-picture-from-reference.md` |
88
+ | `threedog expect <value> --min\|--max\|--is v --why "…" [--point p]` · `threedog expect drop <value> [--point p]` · `threedog expect list [--json]` | Keep what must stay true in `expectations.jsonl` (one line per value and point; writing again changes it and prints the earlier reason). `shot.*` needs a `--point` from `shots.json`. `budget.*` is refused (limits stay in `engine.budget`) |
88
89
  | `threedog tune show [-w game]` · `threedog tune write [file] [--apply] [-w game]` | Values from `.threedog/tune.json` as one `// threedog:tune begin ... end` block of plain three.js writes (`engine.scene.fog.far = 90;`, `material.setValues` by name, UI CSS variables) in `file`. A later write merges into the block, so values the panel no longer holds stay; delete a line to drop it. Model generator params (the panel's models folder) become the `default` in that model's `params` schema where it is registered (no file needed for those). Without `--apply` it only prints the diff. `recipes/35-picture-from-reference.md` |
89
90
  | Tuning without a mouse | Try values with `threedog js` (`engine.scene.fog.far = 90`), look with `threedog snap`, then write the result into `.threedog/tune.json` as `{ "values": { "engine.scene.fog.far": 90, "engine.scene.background": "#336699" }, "css": { "accent": "#7fd3ff" }, "materials": { "rock": { "roughness": 0.8 } }, "models": { "tree": { "height": 4 } } }` and run `threedog tune write main.js --apply`, or write the value straight into the code |
90
91
  | `threedog gallery [-w game]` · `threedog gallery --shots [--mode …] [--light …] [--material name]` | Every registered model and texture on a turntable under three neutral light setups (tone mapping copied from the game), and the look-dev page (recipe 05 "Look-dev"). Without `--shots` it serves the game in dev and prints the `?gallery=1` URL; `--shots` writes `.threedog/gallery/` pictures, `index.html` and `index.json` headless, and `--mode` adds review pictures (silhouette, value, material channels) with measured facts and no thresholds. Options: `threedog gallery --help`. `recipes/05-props-bake.md` section 2c |
@@ -106,8 +107,8 @@ They drive the running game. Run them inside the game folder or with `-w game`;
106
107
  | `threedog skip` | jump the clock like sleeping: skip to=06:00 / skip seconds=600 (engine.skip: op time.skip, sky clock and time-keeping modules catch up; optional fade=0.6 save=auto). to works with calendar() alone; the sky only follows the clock when installed |
107
108
  | `threedog press` | press a key or action: press interact / press KeyE / press e (held 0.1 s, then renders 1/60 s; --for 0.02 shortens the hold) |
108
109
  | `threedog hold` | hold for N seconds: hold moveForward 1.5. moveForward walks along the camera's heading, so with a follow camera at its start angle it goes diagonally, not along an axis: place things by reading player after a short hold |
109
- | `threedog state` | change the scenario without a reload: state time=18:30 weather=rain pos=40,-20; view=name or view=x,y,z,tx,ty,tz[,fov] puts the camera on a declared view or a pose, for the next snap (pos=x,z has no height: the hero stands on the highest support over that spot, a ledge included; to stand under it, js "engine.player.placeAt([x, y, z])") |
110
- | `threedog js` | evaluate an expression in the page (engine is available, await works; one expression prints its value, several statements print what they return): js "engine.calendar.timeOfDay"; long scripts: js --file path. A script that calls assert(cond, msg) or expect(v).toBe/toEqual/toBeCloseTo/toBeGreaterThan(x, msg) (or expect(v, msg)) runs as checks in ONE call: failed checks are recorded and the script goes on, a throw stops it; output ✓ 7 checks passed, or the failures then ✗ 2 of 7 checks failed; exit 1 on failure; --verbose adds passes, log lines and the return value. A script without those calls is the plain form. Both modes get the globals engine, step(seconds), log(...), assert, expect. --wait <seconds>, default 120: how long a script may wait on a page that looks stopped (driven by manual step, nothing loading, no clock tick); the command then ends and says the script may be waiting on the game clock, and the script may still run in the page |
110
+ | `threedog state` | change the scenario without a reload: state time=18:30 weather=rain pos=40,-20 (key=value words, not --time; also wait=5 advances real seconds afterwards, cutscene=skip, save=slot loads a save without writing one, state=name applies an engine.defineState state); view=name or view=x,y,z,tx,ty,tz[,fov] puts the camera on a declared view or a pose, for the next snap (pos=x,z has no height: the hero stands on the highest support over that spot, a ledge included; to stand under it, js "engine.player.placeAt([x, y, z])") |
111
+ | `threedog js` | evaluate an expression in the page (engine is available, await works; one expression prints its value, several statements print what they return): js "engine.calendar.timeOfDay"; long scripts: js --file path. --max N caps the printed characters. A script that calls assert(cond, msg) or expect(v).toBe/toEqual/toBeCloseTo/toBeGreaterThan(x, msg) (or expect(v, msg)) runs as checks in ONE call: failed checks are recorded and the script goes on, a throw stops it; output ✓ 7 checks passed, or the failures then ✗ 2 of 7 checks failed; exit 1 on failure; --verbose adds passes, log lines and the return value. A script without those calls is the plain form. Both modes get the globals engine, step(seconds), log(...), assert, expect. --wait <seconds>, default 120: how long a script may wait on a page that looks stopped (driven by manual step, nothing loading, no clock tick); the command then ends and says the script may be waiting on the game clock, and the script may still run in the page |
111
112
  | `threedog snap-describe` | describe snapshot instead of a screenshot, a baseline of the gameplay part of describe(): snap-describe save\|diff name [--only a,b] [--ignore x.y] [--tolerance 0.5] (recipes/16-dev-bridge.md section 7); in tests one line expectDescribe({ check, ev }, name, { only, tolerance }) from @threedog/tools/describe-snapshot |
112
113
  | `threedog snap` | save a screenshot to .threedog/shots/name.png and run the picture check on the page, as threedog shot does (snap name, or snap path/to/file.png used as given; --play first leaves the title as shot --play; --width N scales the returned image down, the saved file stays full size; --no-picture skips the check) |
113
114
  | `threedog errors` | page errors with id (E1…), time, tick, source and count; the same error repeated is one line with its first and last id / time and ×N. errors = new since the last read; errors latest [N] = the last N (default 3), same answer every time; errors --since E5 = after id 5, never moves the read position. Every result prints a cursor (known classes come with the cause and the doc page) |
package/docs/api/audio.md CHANGED
@@ -1,6 +1,7 @@
1
1
  # engine.audio (Audio) — engine.audio: buses, sounds by name, ducking
2
2
 
3
3
  - `audio.addBus(name: string, opts?: { level?: number; owner?: string }) → { owner?: string; remove(): void }` — Add a bus of your own (routed to master). It gets a settings slider like the others (label key settings.vol.<name>) until the handle is removed (the one give-back form, like every other handle). A name that is already a bus throws: two owners of one bus could not both remove it. Example: `const voice = engine.audio.addBus('voice', { level: 1 }); engine.audio.sfx('line-01', { bus: 'voice' }); voice.remove();`
4
+ - `audio.addNode(bus: string, make: (ctx: AudioContext) => AudioNode) → { remove(): void }` — Your Web Audio node in a bus's path, after volume and duck, before master and reverb, in call order ('master': before the speakers). `make(ctx)` returns the node; it runs once audio is unlocked; taps you add to it stay
4
5
  - `audio.setVolume(bus: string, v: number)` — Set a bus volume 0-1 ('master' for the total). Example: `engine.audio.setVolume('music', 0.3);`
5
6
  - `audio.reverb(opts: { wet?, decay?, size?, sends?, fade? } | null)` — (experimental) The one reverb: a send/return any bus can feed (a cave, a hall, a bathroom). Off until called: nothing is built or heard before. Each call changes only the keys given (sends merge per bus; 0 stops one); null turns it off. The echo of a bus follows its slider and its ducks, and comes back through master. The impulse is generated (decaying noise, no file): changing size or decay rebuilds it, wet and sends only fade. Called before the first click it waits for audio to unlock. Places: an ambience rule { reverb: 0.6, when: { zone: 'cave' } } sets wet while it holds (recipes/31 §9). Example: `engine.audio.reverb({ sends: { sfx: 0.5, ambience: 0.8 }, decay: 3, size: 0.8, wet: 0.4 });`
6
7
  - `audio.duck(levels: Record<string, number>, opts?: { fade?: number }) → { remove(fade?: number): void }` — Lower buses until the handle is removed (dialogue, pause menu, a cutscene). Several ducks stack (their levels multiply). Example: `const d = engine.audio.duck({ music: 0.3, ambience: 0.5 }); engine.events.once('dialogue:end', () => d.remove());`
package/docs/api/music.md CHANGED
@@ -12,7 +12,7 @@ Background music (music() module)
12
12
  - `interval?: number` Rule check interval (seconds), default 1
13
13
 
14
14
  ## Methods and properties
15
- - `music.define(name: string, track: MusicTrack)` — Define a track: a url, or { url, volume, loop, stems }. The same name again replaces it. Example: `engine.music.define('town', '/music/town.ogg')`
15
+ - `music.define(name: string, track: MusicTrack)` — Define a track: a url, { url, volume, loop, stems }, or { generate } (your own Web Audio nodes). The same name again replaces it. Example: `engine.music.define('town', '/music/town.ogg')`
16
16
  - `music.play(name: string | null, opts?: { fade?: number; force?: boolean })` — Play a track (cross-fade over fade seconds). Does nothing if it is already playing; force replays it
17
17
  - `music.stop(opts?: { fade?: number })` — Fade out and stop (fade over fade seconds; default the music({ fade }) option). An options object like play's: stop(3) throws in dev
18
18
  - `music.stinger(name: string, opts?: { duck?: number; volume?: number })` — Layer a one-shot piece (victory, discovered place...); the background dips to `duck` while it plays
@@ -20,7 +20,7 @@ Background music (music() module)
20
20
  - `music.override(name: string | null, opts?: { fade?: number; force?: boolean })` — Pick a track by hand, pausing the rules; override(null) hands control back
21
21
  - `music.pick() → string | null | undefined` — Which track the current rules would pick (without switching)
22
22
  - Properties:
23
- - `tracks: Map<string, { url?: string; volume?: number; loop?: boolean…` Registered tracks
23
+ - `tracks: Map<string, Exclude<MusicTrack, string>>` Registered tracks
24
24
  - `current: string | null` Name of the track playing (or wanted)
25
25
  - `intensity: number` 0-1: how loud each stem of the playing track is (see the stems `at` range); fades in about half a second
26
26
  - `ready: boolean` Whether audio is usable
package/docs/api/saves.md CHANGED
@@ -11,7 +11,7 @@
11
11
  - `saves.apply(data: any, slot?: string) → Promise<boolean>` — Apply a save's data (an object from collect(), or save text) onto the running game. Resolves true when every part loaded. Refused before anything changes (false, toast) when the data is corrupt, from a newer build or cannot be migrated. After every part loaded it runs the modules' afterLoad hooks (gameplay frozen until they resolve), for saves.load, session.newGame / quit and direct calls alike. If a part's load throws, a listener of an event it emits while loading (world:load) throws, or a module's afterLoad throws, the game is rolled back to how it was before (every part reloads its pre-load state) and it resolves false; the error goes through the error tiers. "While loading" lasts until the result settles, past every await of an async load(); a listener that throws in that window for any reason fails this load.
12
12
  - `saves.save(slot?: string) → Promise<boolean>` — Save into a slot (default 'auto'). Returns Promise<boolean> (resolves after the write to IndexedDB: true on success, false with a toast and console error on failure). The in-memory save updates immediately, so a following load / list / export sees it at once; the 'save:written' event fires only after the write succeeds. Asked for while a load, newGame or quit is under way, it waits for that to end and saves the result: a save never holds half of each state. If any part's save() throws, or its data holds NaN or Infinity at any depth (the message names the part and the path), nothing is written and the slot keeps its previous save (false). A failed write keeps the previous save too. Show "saved" only after the result is true. Example: `if (await engine.saves.save('slot1')) toast(engine, 'Saved'); // on false the engine already showed why`
13
13
  - `saves.load(slot?: string, { turn }?: { turn?: object }) → Promise<boolean>` — Load a slot onto the running playthrough (a quick load: what the game added during play stays) and resolve true on success; the 'save:loaded' event fires on success. A missing slot resolves false; a corrupt / too new / unmigratable save resolves false with a toast and changes nothing; a part whose load throws rolls the game back. To continue or retry with nothing of the current playthrough left over, use engine.session.load(slot). Example: `if (!(await engine.saves.load('quick'))) toast(engine, 'No quick save');`
14
- - `saves.list() → { slot: string; savedAt: number }[]` — All slots, newest first (synchronous, reads the in-memory index)
14
+ - `saves.list() → { slot, savedAt, summary }[]` — All slots, newest first (synchronous). summary: the parts marked `summary: true` in saves.define, read from the stored save and migrated; {} if none. Example: `for (const { slot, summary } of engine.saves.list()) console.log(slot, summary.hero?.level);`
15
15
  - `saves.remove(slot: string) → Promise<void>` — Delete a slot. Returns a Promise (disk write done); awaiting is optional. A newer save another tab wrote meanwhile is kept: the slot lists again, with a toast (save-stale). A delete the store refused lists the slot again too, with a toast.
16
16
  - `saves.export(slot?: string) → string` — (experimental) Export as a piece of text (can be copied as a backup; synchronous, without binary attachments)
17
17
  - `saves.import(text: string, slot?: string) → Promise<boolean>` — Import text from export() into a slot (default 'imported'); checked like importFile and written before it resolves. Resolves true once stored (save:imported fires), false when the text is not a save or the write failed. It does not load the slot.
@@ -32,5 +32,6 @@
32
32
  - `atomic?: boolean` Join atomic ops: copied before an atomic op runs, put back if it fails (plain data; afterLoad does not run on rollback; load() must be synchronous: an async function is refused at define, a returned Promise at rollback as engine-misuse)
33
33
  - `notAtomic?: string` Why an atomic op leaves this part alone. Every engine part gives atomic: true or this (rule R67); a game's part may
34
34
  - `checkNewGame?: (data: any) => void` Dev only: called once start() finished with this part's data in the new-game state, to warn about what should not be there yet (world: records placed by code)
35
+ - `summary?: boolean` Show this part in saves.list() rows (`summary[key]`), read from the stored save and migrated: a title screen's level, gold or play time without loading the slot. Keep the part small
35
36
  - `version?: number` This part's format version, default 1: raise it by 1 when what save() returns changes shape. A save with a newer version is refused
36
37
  - `migrate?: Record<number, (data: any, save: { parts: Record<string, an…` Upgrade steps: old version -> data => data in the next version's shape, e.g. { 1: d => ({ ...d, beds: [] }) }. The second argument is the whole save as read ({ parts, versions }, read only), for a step that depends on another part
@@ -20,12 +20,10 @@ Settings menu (settings() module)
20
20
  - `settings.rebind(action: string, code: string)` — Change the first key of an action to code
21
21
  - `settings.actionList() → any[]` — (experimental) Key list (for the UI)
22
22
  - `settings.save()` — Save to the browser
23
- - Also: `settings.open()`, `settings.close()`, `settings.toggle(on?: boolean)`
24
23
  - Properties:
25
24
  - `values: Record<string, any>` All current setting values, read only (set() changes one). pixelRatio is the renderer's real ratio
26
25
  - `presets: Record<string, QualityPreset>` Graphics presets
27
26
  - `sections: Map<string, any>` (experimental) Tabs
28
- - `isOpen: boolean` Whether the menu is open
29
27
 
30
28
  ## Data structures
31
29
  - **SettingsSection** One settings tab
@@ -62,7 +62,7 @@ name string is rejected): `do: { op: ['delivery.done', { parcel: 'p1' }] }` (`23
62
62
  The items used (coin, pass) must be defined in `items.js`, otherwise validation fails. A `place` name comes from `content/places.js`, `content.load(data, { places })` or
63
63
  from a level marker (such as `npc_guard`). Add a new content file to `content/index.js`.
64
64
 
65
- ## 2. Add in code (temporary NPCs, dynamic schedules)
65
+ ## 2. Add in code: an NPC you talk to (a villager, `engine.dialogue`), temporary NPCs, dynamic schedules
66
66
  ```js
67
67
  engine.dialogue.define('passerby', { start: { text: 'Nice day.', speaker: 'Passerby' } });
68
68
  const npc = engine.npcs.add({ id: 'passerby', name: 'Passerby', position: [10, 0, 5], schedule: [{ at: '08:00', position: [20, 0, 5] }], interact: { op: 'npc.talk' } }); // at: 'HH:MM' or 0-1; without id the name is used
@@ -5,7 +5,7 @@
5
5
  > **Shortest:** `engine.interactions.add(mesh, { id, label })` on your own mesh, or items as data (§1).
6
6
  > **Sections:** Pick and count meshes · Items and pickups · 1 Write data recommended) · 2 In code dynamic · Single pieces durability, upgrade · Limits all optional, none · Using and dropping ops) · The inventory window UI · Chests / corpses / · 3 Verify
7
7
 
8
- ## Pick and count: meshes you built, no bag
8
+ ## Pick and count: take or mine a mesh you built when the player is near it (`interactions.add`), no bag
9
9
  Shells on a beach, four kinds of flowers, letters to collect: things the player takes and a number goes up. `interactions()`, `hud()` and a key (`createEngine({ bindings: presets.bindings.interact })`: E) are enough:
10
10
  ```js fragment
11
11
  engine.hud.addCounter('shells', { label: 'Shells', value: 0, max: 4 }); // at setup, not on session:start
@@ -71,7 +71,7 @@ The default reach is `pickups({ radius: 2 })`; each pickup can set its own `radi
71
71
  interact key, auto pickups, a net client's press (sent to the host, which puts the item into that peer's bag) and tests all run it as `ctx.actor`.
72
72
  A give function is not saved data: code that spawns one spawns it again on load (content and setup code do); a runtime drop gives an item id.
73
73
 
74
- ## Single pieces: durability, upgrade level, ammo in the magazine, freshness
74
+ ## Single pieces: unique items with their own data (`setData`): durability, upgrade level, affix rolls, ammo, freshness
75
75
  An item can carry its own data (a plain object). Pieces with different data never mix; stackable pieces with equal data share an entry; a `stack: 1`
76
76
  item with data is one entry per piece.
77
77
  Each entry has a **key**: the item id for plain items (`'arrow'`), `'<item>#<n>'` for pieces with data (`'sword#3'`). Every call that takes an item
@@ -91,8 +91,8 @@ I.setData(t.key, { quality: 1 }, 2); // only 2 of that stack change: they split
91
91
  ```
92
92
  Data and keys are saved with the container. Which piece a player means is chosen by key (a click on a row of `list()`), so ops take `item` as an id or a key.
93
93
 
94
- ## Limits (all optional, none by default)
95
- `inventory({ capacity, maxWeight })` for the player and `inventory.container(id, { capacity, maxWeight })` for others:
94
+ ## Limits: a backpack with a weight limit (all optional, none by default)
95
+ `inventory({ capacity, maxWeight })` for the player (`engine.inventory`) and `inventory.container(id, { capacity, maxWeight })` for others:
96
96
  `capacity` = slots (an entry uses `ceil(count / stack)`), `maxWeight` = sum of item `weight` × count.
97
97
 
98
98
  ## Using and dropping (ops)
@@ -173,7 +173,6 @@ chest.on('remove', ({ id, count, actor }) => console.log(actor, 'took', id, coun
173
173
  `engine.world.query({ kind: 'pickup' })`.
174
174
  - `describe()`: `inventory.items` (key -> count, or `{ count, data }` for pieces with data), `inventory.slots`; items still on the ground appear in
175
175
  `nearby` with `kind: 'pickup'` and `id`.
176
- Text version: `npm run shot -- / --pos x,z --describe-only` shows the pickup entries in "nearby" and an `inventory: {...}` line.
177
176
  - Simulate picking up (in tests): put the player next to the item with `engine.player.placeAt({ x, z })`, run `engine.ops.run('interaction.use')` (no
178
177
  id = the nearest interaction) after `engine.step(0.2)`, then check `engine.inventory.count(id)`. Auto pickups need only `engine.step(0.2)` with the
179
178
  player inside the radius.
@@ -5,7 +5,7 @@
5
5
  > **Shortest:** `engine.clock.after(seconds, fn)`.
6
6
  > **Sections:** Changing how fast time · The time table the · 1 Where to write · 1b Smooth movement between · 2 Skipping time sleep · 3 Verify
7
7
 
8
- ## Changing how fast time runs: `engine.mod`
8
+ ## Changing how fast time runs: `engine.mod`; does a timed modifier (`for: seconds`) keep running while frozen
9
9
  ```js
10
10
  engine.time.channel('enemies'); // once: a channel of your own (world and player are built in)
11
11
  const bt = engine.mod('time.enemies', { owner: 'bullet-time', mul: 0.35, for: 2 }); // bullet time: enemies at 35% for 2 real seconds
@@ -24,7 +24,7 @@ Details, only when you need them:
24
24
  `world.remove(id)` drops that record's entries.
25
25
  - Reading: `engine.time.scale(ch, id?)`, `engine.time.now(ch)`; `describe().time.channels` lists speeds and holders. Saved: entries below `'system'`; `system` / `debug` ones (menus, debug panel) are screen state and are taken again after a load.
26
26
 
27
- ## The time table (the single source; other docs link here)
27
+ ## The time table: read the current game time (`engine.time.now`; the single source, other docs link here)
28
28
  **One time source.** `engine.time` counts one thing, `engine.time.tick` (fixed steps run). Every other time is a
29
29
  read-only view of it, moved only by the engine, and always together: a fixed step, `engine.skip` and a new playthrough move or reset all of them.
30
30
  Read any view with `engine.time.now(name)`: `'real'`, `'ambient'`, `'calendar'` or a channel (`'world'`, `'player'`, your own).
@@ -156,10 +156,6 @@ When a game has several systems, a default that keeps this order in one place: o
156
156
  returns the describe).
157
157
  Time-window switch: after `await engine.applyState({ time: '17:50' })` read the state immediately (between has already aligned), then
158
158
  `engine.step(...)` across the boundary.
159
- The length of a day is `describe().time.dayLength` (calendar seconds); with `clock.rate` 1, `step(1 clock minute)` = `step(dayLength / 1440)` (24-hour day); if the rate
160
- is not 1, divide by `engine.clock.speed` as well.
161
- - Reproduce a scenario: `npm run shot -- / --time 17:58 --wait 10 --describe-only`, then look at the time (18:0x) and your effect (lamps, NPCs, items).
162
- - After `npm run map`, the "timed events" section of GAMEMAP.md lists every `calendar.at/between/daily/onSeason` and `clock.after/every`.
163
159
  - Is skip the same as living through it? `const r = await engine.checkSkip(600)` skips 600 calendar seconds, rewinds, steps the same span and compares the saved state: `{ ok, diffs: [{ path, a, b }] }`
164
160
  (a = skip, b = step; `{ ignore: ['parts.world', 'parts.rigid', 'parts.random'] }` drops paths; it refuses while frozen or with the clock stopped). Skip runs no near simulation, so a moving player/NPC
165
161
  or a settling physics body always differs: ignore those parts and read the rest. It leaves the world at the stepped state, so run it on a scratch playthrough or in a test. A diff usually means a
@@ -10,7 +10,7 @@ Needs the module `flow()` (not in openWorld; add it yourself: `engine.use(openWo
10
10
  - **Scene transition** `transition(fn)`: lock input -> fade to black -> fade music out -> (with `{ autosave: 'auto' }` save slot 'auto'; off by If the world does not settle within `engine.loading.timeoutMs`, it rejects with `module-not-ready` and gives the screen and input back. Autosave waits for the end of a transition.
11
11
  default) -> run fn -> wait until every module is ready -> fade in -> unlock. Repeated calls queue up automatically.
12
12
 
13
- ## 1. Pause / title / ending (in main.js)
13
+ ## 1. Pause, title, game over screen (when a lamp, timer or health runs out), win screen / ending (`flow`, in main.js)
14
14
  ```js
15
15
  import { flow, toast } from 'threedog';
16
16
  const titleEl = document.getElementById('title'), startBtn = document.getElementById('start'); // elements you wrote in the page html
@@ -92,12 +92,12 @@ Fields: `cloud` cloud cover 0-1, `sun` sunlight multiplier, `fog` fog distance m
92
92
  0-1, `grey` how gray the sky turns, `lightning` lightning (a type above 0.5 strikes). A table where nothing rains or snows builds no particles.
93
93
  With openWorld the weather module is already installed; pass its options through the preset: `openWorld({ camera: 'follow', weather: { types, autoPool } })`.
94
94
 
95
- ## 3. Changing sky colors, sun, stars: the day and night sky
95
+ ## 3. Change the sky colors, sun glow (`uSunGlow`), stars and the horizon fog band: the day and night sky
96
96
  `sky({ keyframes })`:
97
97
  `[time 0-1, zenith color, horizon color, sun color, ambient intensity]`, interpolated by time; the rows are sorted and
98
98
  run from time 0 to time 1, else the sky throws (both ends are midnight: give the last row the first row's values, or the colors jump there). What each column drives
99
99
  is on `keyframes` in `SkyPictureOptions`, `types/world.d.ts`;
100
- also `sunSize sunGlow starDensity clouds` (defaults and ranges there too; `hoursPerDay` is timing, so it is a
100
+ also `sunSize sunGlow` (the glow round the sun disk; 0 = none, or paint your own with `engine.sky.layer`; the fog band at the horizon is recipe 34) `starDensity clouds` (defaults and ranges there too; `hoursPerDay` is timing, so it is a
101
101
  `calendar()` option, not a sky key). All of these are `sky({ ... })` start values; at run time use the entries at the top of this page.
102
102
  **Day and night brightness** is your `picture/` code: the sky lights nothing. Read `uDaylight` and write your own lights (recipe 62), and check with `shot --time 12:00` and
103
103
  `--time 22:00`. The keyframes only color the dome; the ambient column also dims a skybox and the weather's sky tint. `engine.sky.environment({ into: engine.scene })` builds an environment map
@@ -141,8 +141,6 @@ cave.remove(); // leave the cave
141
141
 
142
142
  ## 5. Verify
143
143
  - Text: `npm run shot -- / --time 19:30 --weather dust --wait 2 --describe-only`, then look for "Time: 19:30..." and "Weather: dust (rain 0, snow 0, fog 0.35)".
144
- `describe().weather` has `name progress rain snow fog wind cloud`; `describe().time` has `clock day season isDay dayLength rate`.
145
- - Take a screenshot only after the picture changed: `npm run shot -- / --time 19:30 --weather dust`.
146
144
 
147
145
  ## 6. Day and night in game logic
148
146
  Gameplay reads `engine.calendar.isDay` and fades with `engine.calendar.daylight` (0-1), with or without a sky, never the clock text; things that follow the hour use `engine.calendar.between(...)` (`api/calendar.md`).
@@ -67,7 +67,7 @@ Terrain, water, plants, rain and snow, pickups and grid layers keep their engine
67
67
 
68
68
  Each piece's own recipe has its details: water and weather 44, terrain 28, plants 36, pickups 03, grids 29.
69
69
 
70
- ## 1b. Lights and stalls
70
+ ## 1b. Lights and stalls, street lamps (`lightPool`)
71
71
  The placeholder lights and your own: recipe 34. This section is what a changing light setup costs.
72
72
 
73
73
  three.js builds one shader program per material for each light setup. `engine.start()` compiles everything visible behind the
@@ -95,7 +95,7 @@ source's `glow` stand-in keeps the far room reading as lit); give the few lights
95
95
  enough that the light dies before the next room. Plain three.js lights of your own with a shadow map work beside the pool.
96
96
 
97
97
  `describe().lightPool` lists which source each real light holds; `focus` measures from the player instead of the
98
- camera. Options and handle: `../api/lightPool.md`. Windows and signs that light up at night need no real light each: see below.
98
+ camera. Options and handle: `../api/lightPool.md`. Lit windows and signs need no real light: see below.
99
99
 
100
100
  ### Night glow: emissive that follows daylight
101
101
  Lit windows, neon signs, lamp bulbs, glowing mushrooms, screens. `engine.uniforms.uNight` is 0 by day and 1 at night, on the curve `dusk` lamps fade on
@@ -51,6 +51,9 @@ export function stamina(opts = {}) {
51
51
  ```
52
52
  Install it: `engine.use(openWorld({ camera: 'follow', ...}), stamina({ max: 80 }))` (dependencies must be installed first). Or put the file in `plugins/` with `export default stamina({ max: 80 })`: plugged with `engine.use` at start, switched off by `plugins.json` `off` (THREE.md, plugins folder).
53
53
 
54
+ ## A typed place for the module's handle on `engine` (`declare module`)
55
+ What `install` returns is `engine.<name>`; type it with `declare module 'threedog' { interface Engine { stamina: { value: number } } }` in a `.d.ts` so `check` knows the property.
56
+
54
57
  ## Type: what the module may own
55
58
  `type` is not when it runs (that is `stage`); it says what the module may own. It is optional: a module without one is `'rules'`, game logic. An unknown name throws with the list. Pick by what it changes:
56
59
 
@@ -71,7 +74,7 @@ A module that does two kinds of thing is two definitions returned together (`wea
71
74
  ## 2. Hooks and order cheat sheet; who frees materials and textures when a module goes
72
75
  - `install(e, ctx)` returns the public object; `init(e, ctx)` (may be async) prepares at start; `ctx.track(handle)` ties a listener or timer to
73
76
  the module (next bullet but four); while `isReady(e)` returns false the loading screen waits for it
74
- (the hook is called isReady; `ready` is always a boolean property in the engine); `afterLoad(e, turn)` (may be async; recipe 20 says what `turn` is for) runs after a save loaded, to rebuild
77
+ ; `afterLoad(e, turn)` (may be async; recipe 20 says what `turn` is for) runs after a save loaded, to rebuild
75
78
  what the loaded state needs nearby, with gameplay frozen and ops refused (`'loading'`) until it resolves. It rebuilds by writing state directly, inside
76
79
  `e.ops.allow(...)` when the write is guarded, not through `e.ops.run`.
77
80
  - `fixed(dt, e)` movement, timing, gameplay keys (`input.pressed` read in fixed is this step's snapshot, independent of frame rate); `frame(dt, e)`