threedog 0.1.0 → 0.2.1

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 (244) hide show
  1. package/README.md +4 -4
  2. package/core/Animator.js +1 -0
  3. package/core/Assets.js +28 -0
  4. package/core/DebugOverrides.js +143 -0
  5. package/core/Describe.js +14 -3
  6. package/core/Engine.js +44 -72
  7. package/core/Events.js +59 -1
  8. package/core/I18n.js +2 -2
  9. package/core/Inspect.js +12 -32
  10. package/core/InspectScene.js +7 -3
  11. package/core/MaterialInfo.js +32 -0
  12. package/core/Ops.js +43 -59
  13. package/core/Saves.js +5 -4
  14. package/core/UrlState.js +3 -2
  15. package/core/Vars.js +1 -0
  16. package/core/Views.js +49 -0
  17. package/core/actor.js +2 -2
  18. package/core/assetReport.js +83 -0
  19. package/core/catalog.js +169 -0
  20. package/core/checks.js +67 -0
  21. package/core/claims.js +51 -0
  22. package/core/debugView.js +76 -0
  23. package/core/describeRender.js +51 -0
  24. package/core/describeText.js +11 -4
  25. package/core/errorCodes.js +33 -0
  26. package/core/errorHints.js +6 -1
  27. package/core/grid.js +127 -0
  28. package/core/gridLoad.js +19 -0
  29. package/core/holds.js +106 -0
  30. package/core/lifecycle.js +1 -0
  31. package/core/lightWatch.js +23 -3
  32. package/core/look/coreParts.js +112 -0
  33. package/core/look/layers.js +136 -0
  34. package/core/look/part.js +173 -0
  35. package/core/look/report.js +79 -0
  36. package/core/look/write.js +86 -0
  37. package/core/loop.js +22 -16
  38. package/core/modules.js +19 -5
  39. package/core/opsAtomic.js +31 -0
  40. package/core/opsCheck.js +25 -14
  41. package/core/opsFail.js +20 -0
  42. package/core/opsHistory.js +6 -6
  43. package/core/opsRun.js +77 -0
  44. package/core/params.js +132 -0
  45. package/core/renamed.js +22 -0
  46. package/core/saveApply.js +2 -2
  47. package/core/sceneMethods.js +9 -34
  48. package/core/services.js +73 -0
  49. package/core/startup.js +3 -1
  50. package/core/styleParts.js +11 -9
  51. package/core/thingExplain.js +68 -0
  52. package/core/thingOps.js +35 -24
  53. package/core/things.js +15 -1
  54. package/core/util.js +11 -0
  55. package/core/validate.js +23 -7
  56. package/docs/AI.md +93 -114
  57. package/docs/API.md +8 -9
  58. package/docs/CODEMAP.md +67 -53
  59. package/docs/COMMANDS.md +21 -7
  60. package/docs/CONVENTIONS.md +22 -11
  61. package/docs/THREE.md +3 -3
  62. package/docs/api/assets.md +3 -0
  63. package/docs/api/characters.md +5 -2
  64. package/docs/api/collision.md +4 -0
  65. package/docs/api/content.md +1 -0
  66. package/docs/api/engine.md +23 -14
  67. package/docs/api/events.md +5 -1
  68. package/docs/api/post.md +5 -4
  69. package/docs/api/saves.md +2 -1
  70. package/docs/api/sky.md +3 -3
  71. package/docs/api/style.md +8 -8
  72. package/docs/api/tools.md +5 -2
  73. package/docs/api/vegetation.md +1 -0
  74. package/docs/api/weather.md +1 -1
  75. package/docs/recipes/01-new-game.md +41 -43
  76. package/docs/recipes/02-npc.md +38 -22
  77. package/docs/recipes/03-items-pickups.md +4 -4
  78. package/docs/recipes/04-quests.md +23 -23
  79. package/docs/recipes/05-props-bake.md +5 -5
  80. package/docs/recipes/06-clock-events.md +13 -0
  81. package/docs/recipes/07-flow-scenes-pause.md +6 -2
  82. package/docs/recipes/08-weather-sky.md +6 -6
  83. package/docs/recipes/09-style-pack.md +35 -100
  84. package/docs/recipes/12-navmesh.md +22 -0
  85. package/docs/recipes/13-animation.md +25 -6
  86. package/docs/recipes/14-custom-module.md +6 -7
  87. package/docs/recipes/15-perf.md +9 -1
  88. package/docs/recipes/16-dev-bridge.md +52 -18
  89. package/docs/recipes/18-world.md +5 -2
  90. package/docs/recipes/19-shooting-picking.md +9 -8
  91. package/docs/recipes/20-content-actions-save.md +10 -10
  92. package/docs/recipes/21-camera.md +51 -2
  93. package/docs/recipes/22-shop-gold.md +16 -16
  94. package/docs/recipes/23-ops.md +46 -10
  95. package/docs/recipes/27-net.md +3 -3
  96. package/docs/recipes/28-terrain.md +2 -2
  97. package/docs/recipes/29-grid.md +47 -27
  98. package/docs/recipes/34-environment-lighting.md +11 -10
  99. package/docs/recipes/35-style-from-reference.md +41 -46
  100. package/docs/recipes/36-sky-ground-plant-looks.md +22 -20
  101. package/docs/recipes/37-terrain-look-hooks.md +34 -13
  102. package/docs/recipes/38-environment-look-hooks.md +49 -42
  103. package/docs/recipes/40-scene.md +29 -0
  104. package/docs/recipes/41-thing-registry.md +29 -0
  105. package/docs/recipes/42-terrain-shape.md +1 -1
  106. package/docs/recipes/43-shader-patches-surface-looks.md +37 -20
  107. package/docs/recipes/44-water-weather-look-hooks.md +11 -9
  108. package/docs/recipes/45-cascaded-shadows.md +2 -2
  109. package/docs/recipes/46-blender-art-route.md +26 -4
  110. package/docs/recipes/47-island-snow-backdrop.md +4 -3
  111. package/docs/recipes/48-make-material.md +70 -0
  112. package/docs/recipes/49-game-module-contract.md +71 -0
  113. package/docs/recipes/50-own-renderer.md +12 -0
  114. package/docs/recipes/51-capability-catalog.md +63 -0
  115. package/docs/recipes/52-look.md +146 -0
  116. package/docs/recipes/53-ground-up-close.md +58 -0
  117. package/examples/action/GAMEMAP.md +7 -7
  118. package/examples/action/content/index.js +2 -1
  119. package/examples/action/content/views.js +6 -0
  120. package/examples/action/main.js +3 -2
  121. package/examples/sheepisland/GAMEMAP.md +3 -4
  122. package/examples/styletest/GAMEMAP.md +3 -3
  123. package/examples/styletest/content/npcs.js +1 -1
  124. package/examples/styletest/main.js +2 -2
  125. package/examples/styletest/panel.js +3 -3
  126. package/examples/world/GAMEMAP.md +3 -3
  127. package/examples/world/content/npcs.js +1 -1
  128. package/examples/world/main.js +1 -1
  129. package/index.d.ts +35 -2
  130. package/index.js +6 -3
  131. package/llms.txt +13 -7
  132. package/modules/ambience/Ambience.js +5 -2
  133. package/modules/camera/FirstPersonCamera.js +3 -5
  134. package/modules/camera/FixedCamera.js +19 -12
  135. package/modules/camera/FollowCamera.js +14 -8
  136. package/modules/camera/RtsCamera.js +3 -5
  137. package/modules/camera/common.js +40 -10
  138. package/modules/camera/index.js +1 -1
  139. package/modules/camera/projection.js +34 -0
  140. package/modules/characters/Character.js +45 -31
  141. package/modules/characters/assetModel.js +35 -7
  142. package/modules/characters/astar.js +14 -7
  143. package/modules/characters/index.js +6 -3
  144. package/modules/characters/movers/simple.js +6 -1
  145. package/modules/characters/npcSim.js +8 -2
  146. package/modules/characters/pathAsync.js +12 -6
  147. package/modules/characters/pathJob.js +2 -1
  148. package/modules/characters/proceduralRig.js +50 -11
  149. package/modules/characters/useModel.js +22 -0
  150. package/modules/characters/walkTo.js +58 -0
  151. package/modules/collision/Collision.js +102 -4
  152. package/modules/content/explain.js +13 -0
  153. package/modules/content/index.js +3 -1
  154. package/modules/content/loader.js +3 -0
  155. package/modules/content/rules.js +1 -0
  156. package/modules/debug/DebugPanel.js +11 -5
  157. package/modules/entities/Entities.js +6 -2
  158. package/modules/flow/index.js +5 -2
  159. package/modules/gameplay/Dialogue.js +5 -2
  160. package/modules/gameplay/Interactions.js +12 -2
  161. package/modules/gameplay/Inventory.js +21 -11
  162. package/modules/gameplay/Quests.js +13 -3
  163. package/modules/gameplay/pickups.js +6 -4
  164. package/modules/grid/Layer.js +1 -1
  165. package/modules/grid/index.js +1 -1
  166. package/modules/grid/tiles.js +9 -5
  167. package/modules/hlod/index.js +5 -2
  168. package/modules/hud/index.js +5 -2
  169. package/modules/level/index.js +5 -3
  170. package/modules/lights/index.js +5 -2
  171. package/modules/music/Music.js +6 -2
  172. package/modules/nav/index.js +5 -3
  173. package/modules/net/Client.js +4 -3
  174. package/modules/net/Host.js +2 -2
  175. package/modules/net/index.js +5 -3
  176. package/modules/particles/Particles.js +1 -1
  177. package/modules/photo/Photo.js +10 -7
  178. package/modules/rigid/RigidBodies.js +5 -2
  179. package/modules/settings/Settings.js +6 -3
  180. package/modules/settings/apply.js +2 -1
  181. package/modules/sky/Sky.js +21 -19
  182. package/modules/sky/cascades.js +6 -6
  183. package/modules/sky/domeLayers.js +1 -1
  184. package/modules/sky/environment.js +39 -13
  185. package/modules/sky/fog.js +9 -6
  186. package/modules/sky/frame.js +4 -3
  187. package/modules/sky/look.js +3 -2
  188. package/modules/sky/lookFog.js +80 -0
  189. package/modules/sky/lookShadow.js +50 -0
  190. package/modules/sky/lookSky.js +108 -0
  191. package/modules/sky/shader.js +2 -2
  192. package/modules/sky/shadow.js +4 -10
  193. package/modules/sky/skyModule.js +4 -3
  194. package/modules/terrain/ChunkManager.js +2 -33
  195. package/modules/terrain/chunkLevels.js +40 -0
  196. package/modules/terrain/index.js +10 -2
  197. package/modules/terrain/lookGround.js +61 -0
  198. package/modules/timeline/Timeline.js +7 -3
  199. package/modules/timeline/Tween.js +3 -7
  200. package/modules/timeline/shots.js +6 -4
  201. package/modules/triggers/index.js +9 -2
  202. package/modules/vegetation/Vegetation.js +17 -4
  203. package/modules/vegetation/index.js +7 -4
  204. package/modules/vegetation/lookWind.js +37 -0
  205. package/modules/vegetation/nearFade.js +39 -0
  206. package/modules/water/Water.js +19 -3
  207. package/modules/water/look.js +80 -0
  208. package/modules/weather/Weather.js +22 -31
  209. package/modules/weather/look.js +75 -0
  210. package/modules/weather/particles.js +1 -1
  211. package/modules/weather/strings.js +15 -0
  212. package/modules/world/explain.js +11 -0
  213. package/modules/world/index.js +11 -4
  214. package/modules/world/thingSource.js +44 -0
  215. package/package.json +2 -1
  216. package/render/PostFX.js +48 -51
  217. package/render/detail.js +39 -15
  218. package/render/effects.js +4 -2
  219. package/render/fuse.js +12 -0
  220. package/render/lights.js +4 -2
  221. package/render/lookSurface.js +161 -0
  222. package/render/materials.js +27 -10
  223. package/render/postLook.js +86 -0
  224. package/render/surface.js +3 -1
  225. package/types/core.d.ts +223 -29
  226. package/types/gameplay.d.ts +22 -6
  227. package/types/generated/core/DebugOverrides.d.ts +52 -0
  228. package/types/generated/core/Events.d.ts +43 -0
  229. package/types/generated/core/Ops.d.ts +62 -21
  230. package/types/generated/core/Saves.d.ts +1 -0
  231. package/types/generated/core/Views.d.ts +33 -0
  232. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  233. package/types/generated/modules/grid/Layer.d.ts +1 -0
  234. package/types/generated/modules/sky/Sky.d.ts +10 -17
  235. package/types/generated/modules/weather/Weather.d.ts +5 -15
  236. package/types/generated/render/PostFX.d.ts +20 -23
  237. package/types/generated/render/materials.d.ts +10 -0
  238. package/types/physics.d.ts +8 -0
  239. package/types/style.d.ts +35 -20
  240. package/types/world.d.ts +7 -1
  241. package/ui/Parts.js +6 -2
  242. package/ui/UI.js +1 -1
  243. package/ui/defaults.js +1 -1
  244. package/docs/api/debug.md +0 -10
@@ -0,0 +1,169 @@
1
+ // engine.catalog(): what this game can do, read from the registrations that already exist (module definitions, ops.define,
2
+ // saves.register, describe.add, module hooks, params schemas). Why a reader and not a registry: a second list would drift from the code;
3
+ // this file runs no gameplay and stores only who registered what (so an op or save part can be traced back to its module).
4
+ // engine.catalog() -> short list, one line of data per module (+ 'core' and 'game' for what no module registered)
5
+ // engine.catalog('shop') -> one module expanded: dependencies, ops with args / defaults / failure codes, saved parts, time model
6
+ // engine.catalog('shop.buy') -> one op expanded (args schema, reasons, its last attempt)
7
+ // engine.catalog({ find: 'buy' }) -> the short list filtered by id, label, op or save name
8
+ // Ownership: engine.use / module init take a snapshot of the op, save and describe names before and after (catalogSnap / catalogClaim);
9
+ // what existed before the first engine.use is 'core', what appeared outside any module is 'game'. An op named '<module>.verb' or a save
10
+ // part keyed by the module name belongs to that module even when registered later (from game code calling into the module).
11
+ import { parseSchema, schemaInfo } from './params.js';
12
+ import { lookCatalog, lookSummaries } from './look/report.js';
13
+
14
+ const TIME_HOOKS = ['fixed', 'frame', 'afterRender', 'skip', 'afterLoad'];
15
+ const MAX_API = 200; // the dev bridge narrows this to what the api page lists (tools/threedog/catalog.mjs)
16
+
17
+ const keysOf = e => [
18
+ ...[...e.ops.defs.keys()].map(k => 'op:' + k),
19
+ ...[...e.saves.providers.keys()].map(k => 'save:' + k),
20
+ ...[...(e.describe?._extras?.keys() ?? [])].map(k => 'describe:' + k),
21
+ ];
22
+ const track = e => e._catalog ??= { core: null, owner: new Map() };
23
+
24
+ /** @internal before a module's install / init: names registered so far (the first call also fixes what counts as core) */
25
+ export function catalogSnap(e) {
26
+ const c = track(e), now = new Set(keysOf(e));
27
+ c.core ??= now;
28
+ return now;
29
+ }
30
+ /** @internal after it: the names that appeared since snap belong to that module */
31
+ export function catalogClaim(e, name, snap) {
32
+ const c = track(e);
33
+ for (const k of keysOf(e)) if (!snap.has(k) && !c.owner.has(k)) c.owner.set(k, name);
34
+ }
35
+
36
+ /** Who registered this 'op:x' / 'save:x' / 'describe:x' name: a module name, 'core' or 'game' */
37
+ function ownerOf(e, key) {
38
+ const c = track(e), claimed = c.owner.get(key);
39
+ if (claimed && e.modules.has(claimed)) return claimed;
40
+ const [type, name] = [key.slice(0, key.indexOf(':')), key.slice(key.indexOf(':') + 1)];
41
+ const guess = type === 'op' ? name.split('.')[0] : name;
42
+ if (e.modules.has(guess)) return guess;
43
+ return c.core?.has(key) ? 'core' : 'game';
44
+ }
45
+ function owned(e, id) {
46
+ const out = { op: [], save: [], describe: [] };
47
+ for (const k of keysOf(e)) if (ownerOf(e, k) === id) { const i = k.indexOf(':'); out[k.slice(0, i)].push(k.slice(i + 1)); }
48
+ return out;
49
+ }
50
+
51
+ /** A value shown in the catalog: plain data as is, anything else only by kind (functions, three.js objects are not JSON) */
52
+ function toData(v) {
53
+ if (v == null || ['string', 'number', 'boolean'].includes(typeof v)) return v;
54
+ if (typeof v === 'function') return '<function>';
55
+ if (Array.isArray(v)) return v.length <= 8 && v.every(x => x == null || typeof x !== 'object') ? v : `<array of ${v.length}>`;
56
+ return Object.getPrototypeOf(v) === Object.prototype && Object.keys(v).length <= 8 ? v : '<object>';
57
+ }
58
+
59
+ function opInfo(e, name, full) {
60
+ const d = e.ops.defs.get(name), args = schemaInfo(d.shape);
61
+ const o = { name, desc: d.desc, args, failures: Object.keys(d.reasons || {}) };
62
+ if (!full) return o;
63
+ const last = e.ops.recent(name).at(-1);
64
+ return { id: name, kind: 'op', owner: ownerOf(e, 'op:' + name), ...o, reasons: d.reasons || {}, can: !!d.can, offers: !!d.offers,
65
+ undo: !!d.undo, net: d.net ?? 'host', last: last ? { tick: last.tick, ok: last.ok, code: last.code, args: last.args, source: last.source } : null };
66
+ }
67
+ function saveInfo(e, key) {
68
+ const p = e.saves.providers.get(key);
69
+ return { key, version: p.version, ...(p.first ? { first: true } : {}), ...(Object.keys(p.migrate || {}).length ? { migrates: Object.keys(p.migrate).map(Number) } : {}) };
70
+ }
71
+
72
+ /** Public methods and properties of a module's api object (own and inherited, no _private ones) */
73
+ function apiNames(api) {
74
+ if (!api || typeof api !== 'object') return [];
75
+ const out = new Set();
76
+ for (let o = api; o && o !== Object.prototype; o = Object.getPrototypeOf(o))
77
+ for (const k of Object.getOwnPropertyNames(o)) if (k !== 'constructor' && !k.startsWith('_') && out.size < MAX_API) out.add(k);
78
+ return [...out];
79
+ }
80
+
81
+ /** Time model: which loop hooks it has, and the gap that breaks engine.skip (accumulates in fixed, no skip hook) */
82
+ function timeOf(m) {
83
+ const hooks = TIME_HOOKS.filter(h => typeof m[h] === 'function');
84
+ return { hooks, step: m.fixed ? 'fixed' : m.frame ? 'frame' : 'none', skip: !!m.skip, ...(m.noSkip ? { noSkip: m.noSkip } : {}) };
85
+ }
86
+
87
+ function optionalOf(e, m) {
88
+ const opt = m.optional;
89
+ if (!opt) return [];
90
+ const list = Array.isArray(opt) ? opt.map(n => [n, null]) : Object.entries(opt);
91
+ return list.map(([name, lost]) => ({ name, installed: e.modules.has(name), ...(lost ? { lost } : {}) }));
92
+ }
93
+
94
+ function paramsOf(m) {
95
+ if (!m.params) return null;
96
+ const info = schemaInfo(parseSchema(`module ${m.name} params`, m.params));
97
+ if (m.options) for (const k in info) if (m.options[k] !== undefined) info[k].value = toData(m.options[k]);
98
+ return info;
99
+ }
100
+
101
+ function problemsOf(e, m, entry) {
102
+ const out = [];
103
+ if (entry.state === 'failed') out.push('init failed (engine.errors has the reason); no hooks run');
104
+ if (m.fixed && !m.skip && !m.noSkip) out.push('fixed hook but no skip hook: engine.skip does not advance it (fine when its state derives from clock.now; or declare noSkip: "why nothing needs to catch up" on the module)');
105
+ for (const o of entry.optional) if (!o.installed && o.lost) out.push(`optional ${o.name} missing: ${o.lost}`);
106
+ return out;
107
+ }
108
+
109
+ function moduleEntry(e, m) {
110
+ const id = m.name, own = owned(e, id);
111
+ const entry = {
112
+ id, kind: 'module', ...(m.label ? { label: m.label } : {}), state: e.moduleStates[id], stage: m.stage ?? 'late', runIndex: e.moduleOrder.indexOf(id),
113
+ critical: !!m.critical, requires: m.requires ?? [], optional: optionalOf(e, m), time: timeOf(m), params: paramsOf(m),
114
+ ops: own.op.map(n => opInfo(e, n, false)), saves: own.save.map(k => saveInfo(e, k)),
115
+ queries: { describe: m.describe ? `describe().${id}` : null, extra: own.describe.map(n => `describe().${n}`), api: apiNames(e[id]) },
116
+ ...(m.docs ? { docs: m.docs } : {}),
117
+ };
118
+ entry.problems = problemsOf(e, m, entry);
119
+ return entry;
120
+ }
121
+ function looseEntry(e, id) {
122
+ const own = owned(e, id);
123
+ return { id, kind: id, ops: own.op.map(n => opInfo(e, n, false)), saves: own.save.map(k => saveInfo(e, k)),
124
+ queries: { describe: null, extra: own.describe.map(n => `describe().${n}`), api: [] }, problems: [] };
125
+ }
126
+
127
+ function summary(x) {
128
+ const s = { id: x.id, kind: x.kind };
129
+ if (x.label) s.label = x.label;
130
+ if (x.state) s.state = x.state;
131
+ if (x.stage) s.stage = x.stage;
132
+ s.ops = x.ops.map(o => o.name);
133
+ s.saves = x.saves.map(p => p.key);
134
+ if (x.time) s.time = [x.time.step, x.time.skip ? 'skip' : null].filter(Boolean).join('+');
135
+ if (x.problems.length) s.problems = x.problems.length;
136
+ return s;
137
+ }
138
+
139
+ function entries(e) {
140
+ const out = [...e.modules.values()].map(m => moduleEntry(e, m));
141
+ for (const id of ['core', 'game']) { const x = looseEntry(e, id); if (x.ops.length || x.saves.length || x.queries.extra.length) out.push(x); }
142
+ return out;
143
+ }
144
+
145
+ /**
146
+ * What this game can do, from the registrations that already exist (modules, ops, save parts, describe, params schemas); no second list to keep in sync.
147
+ * No argument: a short list (id, state, stage, op and save names, time model, problem count). A module id: that module expanded
148
+ * (requires / optional, params with defaults and the values in use, ops with args schema and failure codes, saved parts and versions,
149
+ * time hooks, describe fields and api names, problems such as "fixed hook but no skip hook"). An op name: that op expanded, with its last attempt.
150
+ * The dev bridge `threedog catalog [id]` prints the same data and adds the doc, recipe and source files.
151
+ * @param {string | { find?: string }} [id]
152
+ * @returns {any}
153
+ * @example engine.catalog(); // [{ id: 'sky', kind: 'module', state: 'running', stage: 'environment', ops: [], saves: ['sky'], time: 'fixed+skip' }, ...]
154
+ * engine.catalog('shop').ops[0]; // { name: 'shop.buy', args: { n: { type: 'int', optional: true, default: 1 } }, failures: ['soldOut', 'noMoney'] }
155
+ * engine.catalog('shop.buy').last; // { tick: 812, ok: false, code: 'noMoney', ... }
156
+ * engine.catalog({ find: 'throw' }); // only entries whose id, label, op or save mentions "throw"
157
+ */
158
+ export function catalog(e, id) {
159
+ if (typeof id === 'string') {
160
+ if (e.modules.has(id)) return moduleEntry(e, e.modules.get(id));
161
+ if (e.ops.defs.has(id)) return opInfo(e, id, true);
162
+ if (id === 'core' || id === 'game') return looseEntry(e, id);
163
+ if (id === 'look' || id.startsWith('look.')) return lookCatalog(e, id); // look parts (look/part.js): params with why / off, hooks, replace contract
164
+ return null;
165
+ }
166
+ const list = [...entries(e).map(summary), ...lookSummaries(e)];
167
+ const q = id?.find?.toLowerCase();
168
+ return q ? list.filter(s => [s.id, s.label, ...s.ops, ...s.saves].some(x => x?.toLowerCase().includes(q))) : list;
169
+ }
package/core/checks.js ADDED
@@ -0,0 +1,67 @@
1
+ // Consistency checks a game (or an AI) can call in dev and tests, mixed into Engine.prototype. They never throw on a mismatch: they return { ok, diffs }, so a test
2
+ // or the dev bridge prints the first differing paths instead of a bare "false".
3
+ // await engine.checkSkip(600) // engine.skip(600 game seconds) vs stepping the same time in fixed steps: same saved state?
4
+ // await engine.checkSave() // save -> load: same saved state?
5
+ // "State" is what engine.saves.collect() returns (every save part), so a module that keeps state outside its save part is invisible here: that is the point
6
+ // of the check, a skip or a load that loses it shows up as a diff of the part's data.
7
+
8
+ const MAX_DIFFS = 20;
9
+
10
+ /** Flatten two JSON values into the paths where they differ: [{ path, a, b }] (at most MAX_DIFFS; numbers within 1e-6 are equal) */
11
+ export function diffState(a, b, ignore = []) {
12
+ const out = [];
13
+ const walk = (x, y, path) => {
14
+ if (out.length >= MAX_DIFFS || ignore.some(p => path === p || path.startsWith(p + '.'))) return;
15
+ if (typeof x === 'number' && typeof y === 'number') { if (Math.abs(x - y) > 1e-6 && !(Number.isNaN(x) && Number.isNaN(y))) out.push({ path, a: x, b: y }); return; }
16
+ if (x && y && typeof x === 'object' && typeof y === 'object' && Array.isArray(x) === Array.isArray(y)) {
17
+ for (const k of new Set([...Object.keys(x), ...Object.keys(y)])) walk(x[k], y[k], path ? path + '.' + k : k);
18
+ return;
19
+ }
20
+ if (x !== y) out.push({ path, a: x, b: y });
21
+ };
22
+ walk(a, b, '');
23
+ return out;
24
+ }
25
+
26
+ /** The comparable state: a JSON copy of collect() without the timestamp */
27
+ function snapshot(e) { const d = JSON.parse(JSON.stringify(e.saves.collect())); delete d.savedAt; return d; }
28
+
29
+ export const checkMethods = {
30
+ /**
31
+ * Is skipping time the same as living through it? Saves the state, runs engine.skip({ seconds }), saves it again, rewinds to the first state, steps the same
32
+ * span in fixed steps (engine.step, no rendering) and compares the two end states. The world is left at the stepped state, so call it on a scratch playthrough
33
+ * or a test, not in the middle of a real one. A diff usually means a module that keeps its own time lacks (or has a wrong) skip hook.
34
+ * @param {number} seconds game seconds, > 0
35
+ * @param {{ ignore?: string[] }} [opts] ignore: state paths (or their prefix, e.g. 'random') not to compare
36
+ * Refuses ({ ok: false, reason: 'frozen' | 'timeScale0' }) while gameplay is frozen or paused, or the clock is stopped.
37
+ * @returns {Promise<{ ok: boolean, reason?: string, diffs: { path: string, a: any, b: any }[] }>} a = after skip, b = after stepping
38
+ * @example const r = await engine.checkSkip(600); if (!r.ok) console.log(r.diffs);
39
+ */
40
+ async checkSkip(seconds, { ignore = [] } = {}) {
41
+ // Refuse where the two paths cannot be the same thing: frozen gameplay does not step, and a stopped clock (timeScale 0) makes "seconds" mean nothing
42
+ const refuse = (why, b) => ({ ok: false, reason: why, diffs: [{ path: '(precondition)', a: why, b }] });
43
+ if (this.frozen) return refuse('frozen', 'unfreeze first (stepping obeys freezes): ' + [...this._freezers.keys()].join(', '));
44
+ if (!(this.clock.timeScale > 0)) return refuse('timeScale0', 'set clock.timeScale > 0');
45
+ this.commits.tick(Infinity); // pending background results land first, so they cannot sit in one path's state and not the other's
46
+ const before = JSON.parse(JSON.stringify(this.saves.collect()));
47
+ await this.skip({ seconds });
48
+ const skipped = snapshot(this);
49
+ if (!(await this.saves.apply(before, 'checkSkip'))) return { ok: false, diffs: [{ path: '(rewind)', a: 'applied', b: 'refused' }] };
50
+ this.step(seconds / this.clock.timeScale, { render: false });
51
+ const diffs = diffState(skipped, snapshot(this), ignore);
52
+ return { ok: diffs.length === 0, diffs };
53
+ },
54
+ /**
55
+ * Does save -> load give the same state back? Collects the state, applies it as a load and compares with a second collect (nothing is written to the browser).
56
+ * A diff names a save part whose load() does not restore what its save() wrote.
57
+ * @param {{ ignore?: string[] }} [opts] ignore: state paths (or their prefix) not to compare
58
+ * @returns {Promise<{ ok: boolean, diffs: { path: string, a: any, b: any }[] }>} a = before the load, b = after
59
+ * @example const r = await engine.checkSave(); if (!r.ok) console.log(r.diffs);
60
+ */
61
+ async checkSave({ ignore = [] } = {}) {
62
+ const before = snapshot(this);
63
+ if (!(await this.saves.apply(JSON.parse(JSON.stringify(this.saves.collect())), 'checkSave'))) return { ok: false, diffs: [{ path: '(load)', a: 'applied', b: 'refused' }] };
64
+ const diffs = diffState(before, snapshot(this), ignore);
65
+ return { ok: diffs.length === 0, diffs };
66
+ },
67
+ };
package/core/claims.js ADDED
@@ -0,0 +1,51 @@
1
+ // claims(): one small "who holds this" primitive shared by pause, freeze, the camera takeover and debug views.
2
+ // Why one primitive: those four each grew their own owner rules (pause warned, freeze was silent, the camera had no owner at all, a debug view checked
3
+ // its owner only on 'off'), so a tool could not predict what release by a non-owner does. Here the rules are the same everywhere:
4
+ // - take(owner, data) -> { owner, remove() }: the same owner taking again updates its data, keeps its place and time (one claim per owner)
5
+ // - only the owner releases: release(owner) / handle.remove() drop that owner's claim and nothing else; a stale handle (the owner released and took
6
+ // again since) removes nothing, so an old handle cannot cancel a newer claim
7
+ // - owners() -> [{ owner, at }] is what describe shows, the same shape for every user
8
+ // Look layers, the input stack and sky.modify keep their own owner models on purpose (layered values, a stack, blended layers): different semantics.
9
+ import { codedError } from './errorHints.js';
10
+
11
+ /**
12
+ * @param {{ what: string, now?: () => number, onChange?: () => void }} o what names the user in error messages; now gives `at`; onChange runs after any take / release
13
+ */
14
+ export function claims({ what, now = () => 0, onChange = () => {} }) {
15
+ /** @type {Map<string, { owner: string, at: number, data: any }>} */
16
+ const held = new Map();
17
+ const drop = (owner, c) => { if (c && held.get(owner) !== c) return false; if (!held.delete(owner)) return false; onChange(); return true; };
18
+ return {
19
+ /** @param {string} owner @param {any} [data] */
20
+ take(owner, data) {
21
+ if (!owner || typeof owner !== 'string') throw codedError('claim-owner', `${what}: owner is a non-empty string naming who holds it, e.g. 'my-menu', got ${JSON.stringify(owner)}`);
22
+ let c = held.get(owner);
23
+ if (c) c.data = data; else held.set(owner, c = { owner, at: now(), data });
24
+ onChange();
25
+ return { owner, remove: () => { drop(owner, c); } };
26
+ },
27
+ /** Drop owner's claim; false when it held none @param {string} owner */
28
+ release(owner) { return drop(owner); },
29
+ /** @param {string} owner */
30
+ has(owner) { return held.has(owner); },
31
+ get size() { return held.size; },
32
+ /** Owner names in take order */
33
+ names() { return [...held.keys()]; },
34
+ /** @returns {{ owner: string, at: number }[]} */
35
+ owners() { return [...held.values()].map(({ owner, at }) => ({ owner, at })); },
36
+ /** The claim taken last (the one in charge where only one can act: the camera), or null */
37
+ top() { let t = null; for (const c of held.values()) t = c; return t; },
38
+ /** Claims whose data matches pred (pause kinds) @param {(data: any) => boolean} pred */
39
+ some(pred) { for (const c of held.values()) if (pred(c.data)) return true; return false; },
40
+ clear() { if (!held.size) return; held.clear(); onChange(); },
41
+ };
42
+ }
43
+
44
+ /**
45
+ * pause('x') and pause({ owner: 'x' }) both work: look parts pass { owner }, the loop kept a positional owner; both spellings are accepted everywhere
46
+ * @param {string | { owner?: string } | undefined} a @param {any} [b] @returns {{ owner: string, opts: any }}
47
+ */
48
+ export function ownerArgs(a, b, fallback = 'game') {
49
+ if (a && typeof a === 'object') return { owner: a.owner ?? fallback, opts: a };
50
+ return { owner: a ?? fallback, opts: b ?? {} };
51
+ }
@@ -0,0 +1,76 @@
1
+ // Diagnostic view modes behind engine.debug.view('albedo' | 'lighting' | 'shadow' | 'normals' | 'off') (DebugOverrides.js).
2
+ // Temporary and owner-scoped: it changes how the scene is drawn (material swap / scene.overrideMaterial / lights hidden) and puts everything back on 'off'
3
+ // or when its owner clears (engine.debug.clear(owner)). Never saved, never part of the game's state; describe().render says so while one is active,
4
+ // so an AI reading a screenshot does not take "all white clay" for the real look.
5
+ // Why a view is an entry of the debug override chain and not its own material swap: two independent swaps on one mesh restored each other's stale
6
+ // material and disposed the real one (review H3). In the chain, the albedo view is a { material: 'flat' } entry on the scene and the other modes an apply()
7
+ // entry whose undo only puts back what it changed, and only disposes the override material it created.
8
+ // One view at a time, held as a claim (core/claims.js): only its owner (or force) switches it or turns it off.
9
+ import * as THREE from 'three';
10
+ import { warnMissing } from './validate.js';
11
+ import { claims } from './claims.js';
12
+
13
+ const VIEW_MODES = ['albedo', 'lighting', 'shadow', 'normals', 'off'];
14
+ const EXPLAIN = {
15
+ albedo: 'unlit base color and texture only (no lights, no shadows)',
16
+ lighting: 'every surface plain white matte: shows only what the lights do (no textures)',
17
+ shadow: 'plain white matte lit by direct lights only (ambient and hemisphere lights hidden): shadows read as black',
18
+ normals: 'surface normals as color (x/y/z -> r/g/b); a normal map shows here, flat shading looks faceted',
19
+ };
20
+
21
+ /** apply() for the scene-wide modes: returns an undo that restores only what this call changed */
22
+ function sceneMode(mode) {
23
+ return scene => {
24
+ // plain three materials on purpose: a diagnostic must not depend on the style pack it diagnoses
25
+ const mat = mode === 'normals' ? new THREE.MeshNormalMaterial() : new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 1, metalness: 0 }); // debug view only
26
+ const was = scene.overrideMaterial, hidden = [];
27
+ scene.overrideMaterial = mat;
28
+ if (mode === 'shadow') scene.traverse(o => { if ((o.isAmbientLight || o.isHemisphereLight || o.isLightProbe) && o.visible) { o.visible = false; hidden.push(o); } });
29
+ return () => {
30
+ if (scene.overrideMaterial === mat) scene.overrideMaterial = was;
31
+ mat.dispose(); // ours: created above
32
+ for (const l of hidden) if (!l.visible) l.visible = true;
33
+ };
34
+ };
35
+ }
36
+
37
+ export class DebugView {
38
+ /** @param {any} engine @param {any} debug the engine.debug override chain it lives in */
39
+ constructor(engine, debug) {
40
+ this.engine = engine; this.debug = debug;
41
+ /** @type {{ mode: string, owner: string } | null} the active view (null = the real look) */
42
+ this.active = null;
43
+ this._holder = claims({ what: 'engine.debug.view', now: () => engine.elapsed ?? 0 });
44
+ this._entry = null;
45
+ }
46
+ /**
47
+ * Show a diagnostic view; 'off' restores the real look. Temporary: never saved, and a game that reads it must not branch on it.
48
+ * owner names who asked ('debug' by default): while one owner's view is on, another owner can neither switch it nor turn it off unless it passes force.
49
+ * @param {'albedo' | 'lighting' | 'shadow' | 'normals' | 'off'} mode
50
+ * @param {{ owner?: string, force?: boolean }} [opts]
51
+ * @returns {{ mode: string, owner: string | null, what?: string, note?: string }}
52
+ */
53
+ set(mode, { owner = 'debug', force = false } = {}) {
54
+ if (!VIEW_MODES.includes(mode)) { warnMissing('debug view', String(mode), VIEW_MODES); return this.state(); }
55
+ const a = this.active;
56
+ if (a && a.owner !== owner && !force) return { ...this.state(), note: `view "${a.mode}" belongs to "${a.owner}"; pass { owner: '${a.owner}' } or force: true to ${mode === 'off' ? 'clear' : 'switch'} it` };
57
+ this._off();
58
+ if (mode === 'off') return this.state();
59
+ const e = this.engine, scene = e.scene;
60
+ const patch = mode === 'albedo' ? { material: 'flat' } : { apply: sceneMode(mode) };
61
+ this._entry = this.debug._add({ owner, id: 'view:' + mode, byId: false, obj: scene, patch, undo: null, view: true });
62
+ this._holder.take(owner, { mode });
63
+ this.active = { mode, owner };
64
+ return this.state();
65
+ }
66
+ /** Turn off the view if owner holds it (engine.debug.clear(owner)); true when it did */
67
+ releaseOwner(owner) { if (this.active?.owner !== owner) return false; this._off(); return true; }
68
+ /** @returns {{ mode: string, owner: string | null, what?: string }} the active view, or { mode: 'off' } */
69
+ state() { return this.active ? { ...this.active, what: EXPLAIN[this.active.mode] } : { mode: 'off', owner: null }; }
70
+ /** Who holds the view, the same shape as every other claim: [{ owner, at }] */
71
+ owners() { return this._holder.owners(); }
72
+ _off() {
73
+ this._entry?.remove(); this._entry = null;
74
+ this._holder.clear(); this.active = null;
75
+ }
76
+ }
@@ -0,0 +1,51 @@
1
+ // describe().render: what the renderer, lights and post effects are set to now (facts read from three.js and the post chain).
2
+ // Who set a value lives in one place, describe().look: each `by` here is the path of that record ('look.tone.exposure'), not a second
3
+ // answer worked out again (review r2 #11); 'engine' when no look part covers it. The text line shows the look record's tag for reading.
4
+ // This is information only: the engine never warns when a game changes the renderer or lights.
5
+ import { SHADOW_TYPES } from './shadowTypes.js';
6
+ import { describeLook } from './look/report.js';
7
+ import { r1 } from './math.js';
8
+
9
+ const shadowName = v => Object.keys(SHADOW_TYPES).find(k => SHADOW_TYPES[k].three === v) ?? String(v);
10
+
11
+ /**
12
+ * Record how the renderer was made.
13
+ * @param {any} e
14
+ * @param {{ owned: boolean }} o owned: false when the game passed its own renderer (then the style's tone mapping / exposure were not applied by the engine)
15
+ */
16
+ export function recordRender(e, { owned }) {
17
+ e._renderBase = { owned };
18
+ }
19
+
20
+ /** The render section: structured data plus one compact text block (`text`) @param {any} e */
21
+ export function describeRender(e) {
22
+ const r = e.renderer, b = e._renderBase;
23
+ if (!b) return undefined;
24
+ const look = describeLook(e) ?? {};
25
+ const who = (part, key) => (look[part]?.[key] ? `look.${part}.${key}` : 'engine'); // the record to read in describe().look
26
+ const tag = path => { const [, part, ...k] = path.split('.'); return look[part]?.[k.join('.')]?.by ?? 'engine'; }; // for the text line only
27
+ const tone = { value: look.tone?.mapping?.value, by: who('tone', 'mapping') };
28
+ const exposure = { value: r1(r.toneMappingExposure), by: who('tone', 'exposure') }; // keyframes / a function: the value used this frame
29
+ const shadows = { enabled: r.shadowMap.enabled, type: shadowName(r.shadowMap.type), by: who('shadow', 'type') };
30
+ const post = (e.post?._list || []).map(h => ({ name: h.name, on: h.enabled, params: { ...h.params }, by: who('post', `${h.name}.enabled`),
31
+ ...(e.post._offWhy?.[h.name] && !h.enabled ? { why: e.post._offWhy[h.name] } : {}) }));
32
+ const lights = Object.entries(e.lights || {}).filter(([, l]) => l.parent)
33
+ .map(([name, l]) => ({ name, type: l.type, intensity: r1(l.intensity), source: 'engine-default', by: who('lights', `${name}.intensity`) }));
34
+ const kv = x => Object.entries(x).map(([k, v]) => `${k}=${typeof v === 'number' ? r1(v) : v}`).join(' ');
35
+ const srgb = r.outputColorSpace === 'srgb' ? '' : ' (WRONG: colors are encoded for srgb; color textures must be srgb, data maps linear, see assets.report)';
36
+ let text = [
37
+ `renderer: ${tone.value} (${tag(tone.by)}) exposure ${exposure.value} (${tag(exposure.by)}) shadows ${shadows.enabled ? shadows.type : 'off'} (${tag(shadows.by)})${b.owned ? '' : ' [game-supplied renderer]'} output ${r.outputColorSpace}${srgb}`,
38
+ `post: ${post.map(x => `${x.name}${x.on ? '' : x.why ? ' off (low-tier default)' : ' off'}${Object.keys(x.params).length ? `{${kv(x.params)}}` : ''} (${tag(x.by)})`).join(', ') || 'none'}${e.post?.antialias ? ' + MSAA' : ''}`,
39
+ `lights (engine-added defaults; extra scene lights are not listed): ${lights.map(l => `${l.name} ${l.type} ${l.intensity} (${tag(l.by)})`).join(', ')}`,
40
+ ].join('\n');
41
+ const dv0 = e.debug?.viewState?.(), dv = dv0 && dv0.mode !== 'off' ? dv0 : null;
42
+ if (dv) text = `DEBUG VIEW "${dv.mode}" (by ${dv.owner}) is ON: ${dv.what}. This is NOT the real look; the debug view 'off' restores it.
43
+ ` + text;
44
+ // render scale: the canvas resolution against the display. auto: the adaptive resolution lowered it at some point (it raises it back when frames are fast)
45
+ const dpr = (typeof devicePixelRatio === 'number' && devicePixelRatio) || 1, cur = r.getPixelRatio(), ad = e.adaptive;
46
+ const scale = { current: Math.round(cur * 100) / 100, devicePixelRatio: dpr, upscaled: cur < dpr - 0.01, autoLowered: !!ad?.lowered && cur < (ad.max ?? cur) - 0.01,
47
+ adaptive: !!ad?.on, floor: ad?.min ?? null, max: ad?.max ?? null };
48
+ text += `
49
+ render scale: ${scale.current} of device pixel ratio ${dpr}${scale.upscaled ? ' (picture is upscaled, softer than the screen)' : ''}${scale.autoLowered ? ` (auto-lowered by adaptive resolution, floor ${scale.floor}; adaptiveResolution: false turns it off)` : ''}`;
50
+ return { debugView: dv, scale, toneMapping: tone, exposure, shadows, post, lights, text };
51
+ }
@@ -20,9 +20,11 @@ const STRINGS = {
20
20
  changing: ', transitioning ({pct}%)',
21
21
  player: 'Player: ({x}, {y}, {z}), ground {ground}, {water}, state {state}',
22
22
  inWater: 'in water', dry: 'not in water', noPlayer: 'Player: none',
23
+ pointerLock: 'Pointer lock: {state}',
23
24
  camera: 'Camera: {type}, position ({x}, {y}, {z}), focus ({fx}, {fz}){over}',
24
25
  override: ', taken over by "{owner}"',
25
26
  cutscene: 'Cutscene: {n} playing{skip}',
27
+ overrides: 'Diagnostic overrides active (the screen is not the real state): {list}',
26
28
  skippable: ' (skippable)',
27
29
  dialogue: 'Dialogue: {speaker}: "{text}"{choices}',
28
30
  choices: ' Choices: {list}',
@@ -50,13 +52,14 @@ const STRINGS = {
50
52
  };
51
53
  import { fmt } from './validate.js';
52
54
  import { r1 } from './math.js';
55
+ import { getPath } from './util.js';
53
56
 
54
57
  const NEAR_SUMMARY = 5, LINE = 110;
55
58
  const tr = (table, k) => (k != null && STRINGS[table][k]) || (k ?? STRINGS.none);
56
59
  const n1 = v => (typeof v === 'number' ? r1(v) : v);
57
60
  // Standard fields get sentences above; data from other modules is squeezed into one JSON line
58
61
  const SHOWN = new Set(['nearbyRadius', 'ready', 'error', 'disabledModules', 'loading', 'time', 'player', 'camera', 'nearby', 'actions', 'ui', 'cutscene',
59
- 'modules', 'perf', 'weather']);
62
+ 'modules', 'perf', 'weather', 'render']);
60
63
  const argText = a => Object.entries(a || {}).map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(',') : v}`).join(' ');
61
64
 
62
65
  /** One module's data in a line: scalars as k=v, arrays as k[n], objects as k{n keys} (nested data is one describeText({ path }) away) */
@@ -72,8 +75,7 @@ function summary(v) {
72
75
 
73
76
  /** describe() at a dotted path as JSON text, or why there is nothing there */
74
77
  function atPath(d, path) {
75
- let v = d;
76
- for (const k of path.split('.')) v = v?.[k];
78
+ const v = getPath(d, path);
77
79
  return v === undefined ? fmt(STRINGS.noPath, { path, keys: Object.keys(d).join(', ') }) : `${path}: ${JSON.stringify(v, null, 1)}`;
78
80
  }
79
81
 
@@ -109,6 +111,10 @@ export function describeText(d, { full = false, path, maxLines = 30 } = {}) {
109
111
  const c = d.camera;
110
112
  L.push(fmt(STRINGS.camera, { type: tr('camType', c.type), x: c.x, y: c.y, z: c.z, fx: c.focus.x, fz: c.focus.z, over: c.override
111
113
  ? fmt(STRINGS.override, { owner: c.override }) : '' }));
114
+ const pl = c.pointerLock; // state machine from lockView (camera/common.js); only cameras with click-to-lock report a line
115
+ if (pl?.configured) L.push(fmt(STRINGS.pointerLock, { state: pl.state + (pl.lastFailure ? ` (${pl.lastFailure.reason}, ${pl.lastFailure.agoSec} s ago)` : '')
116
+ + (pl.covered ? `; canvas centre covered by ${pl.covered}` : '') + (pl.cameraOverride ? `; cameraOverride ${pl.cameraOverride} blocks locking` : '') }));
117
+ if (d.scene?.overrides) L.push(fmt(STRINGS.overrides, { list: d.scene.overrides.map(o => `${o.owner}:${o.target}`).join(', ') }));
112
118
  if (d.cutscene) L.push(fmt(STRINGS.cutscene, { n: d.cutscene.count, skip: d.cutscene.skippable ? STRINGS.skippable : '' }));
113
119
  const dl = d.ui.dialogue;
114
120
  if (dl) L.push(fmt(STRINGS.dialogue, { speaker: dl.speaker, text: dl.text, choices: dl.choices.length
@@ -123,10 +129,11 @@ export function describeText(d, { full = false, path, maxLines = 30 } = {}) {
123
129
  : '' }));
124
130
  if (near.length < d.nearby.length) L.push(fmt(STRINGS.nearMore, { n: d.nearby.length - near.length }));
125
131
  if (d.actions) L.push(fmt(STRINGS.actions,
126
- { list: d.actions.map(a => `${a.ok ? '✓' : '✗'} ${a.op}${a.args && Object.keys(a.args).length ? ' ' + argText(a.args) : ''}${a.ok ? '' : ` (${a.reason})`}`).join(' · ') }));
132
+ { list: d.actions.map(a => `${a.ok ? '✓' : '✗'} ${a.op}${a.args && Object.keys(a.args).length ? ' ' + argText(a.args) : ''}${a.ok ? '' : ` (${a.code})`}`).join(' · ') }));
127
133
  const pf = d.perf;
128
134
  L.push(fmt(STRINGS.perf, { fps: pf.fps ?? '-', cpu: pf.cpuMs ?? '-', calls: pf.drawCalls, tris: pf.triangles, chunks: pf.chunks
129
135
  ? fmt(STRINGS.chunks, pf.chunks) : '' }));
136
+ if (full && d.render?.text) L.push(d.render.text); // render block only in the full text; the summary stays short (describe render shows it)
130
137
  L.push(fmt(STRINGS.modules, { list: d.modules.join(', ') }));
131
138
  for (const k in d) if (!SHOWN.has(k)) L.push(fmt(STRINGS.extra, { name: k, json: full ? JSON.stringify(d[k]) : summary(d[k]) }));
132
139
  if (full) return L.join('\n');
@@ -1,6 +1,9 @@
1
1
  // Stable error codes: errors the engine raises by name end their message with "[code]" and carry err.code / err.fix / err.docs (codedError in errorHints.js).
2
2
  // Plain data with no imports (node tools load it through threedog/error-hints). A code never changes meaning once shipped: tools and tests match on it.
3
3
 
4
+ // Naming rule for a NEW code: `<area>-<problem>` in lowercase with hyphens (save-version, look-verb, unknown-name): the area first so the codes sort
5
+ // and grep by subsystem. Codes already published keep their names even where they do not follow it (renaming would break the tools and tests that match them).
6
+
4
7
  /**
5
8
  * Errors the engine raises by name (the message ends with "[code]"): code -> { fix, docs }. Codes are stable: tools and tests may match on them.
6
9
  * @type {Record<string, { fix: string, docs: string[] }>}
@@ -79,6 +82,18 @@ export const ERROR_CODES = {
79
82
  docs: ['recipes/23-ops.md', 'api/engine.md'],
80
83
  fix: 'Ops are defined with ops.define(name, { can, run }) and run with ops.run(name, args); args are plain data and can() only ' +
81
84
  'reads. The message says which rule was broken.' },
85
+ 'pause-owner': {
86
+ docs: ['recipes/23-ops.md', 'api/engine.md'],
87
+ fix: 'engine.pause(owner) and engine.resume(owner) must use the same owner name; the loop resumes only when every owner has resumed.' },
88
+ 'claim-owner': {
89
+ docs: ['api/engine.md'],
90
+ fix: 'pause / freeze / takeCamera / debug.view name who holds them with a non-empty owner string; only that owner releases it (resume, unfreeze, handle.remove()).' },
91
+ 'views-define': {
92
+ docs: ['recipes/46-blender-art-route.md', 'api/engine.md'],
93
+ fix: "engine.views.define(name, { position: [x, y, z], target?: [x, y, z], fov? }): position and target are 3-number arrays." },
94
+ 'renamed-api': {
95
+ docs: ['recipes/52-look.md'],
96
+ fix: 'The call was renamed in 0.2 and the old name now throws; the message names the new call. The table is in recipes/52-look.md "Renamed in 0.2".' },
82
97
  'ops-guard': {
83
98
  docs: ['recipes/23-ops.md'],
84
99
  fix: 'Gameplay state (world, containers, vars, quests) was changed outside a fixed step and outside an op. Do it inside ' +
@@ -115,6 +130,10 @@ export const ERROR_CODES = {
115
130
  docs: ['api/engine.md'],
116
131
  fix: 'The browser dropped the WebGL context (GPU reset, too many tabs); gameplay waits until it is restored. Nothing to fix ' +
117
132
  'unless it repeats: then lower quality or texture sizes.' },
133
+ 'module-params': {
134
+ docs: ['recipes/51-capability-catalog.md'],
135
+ fix: 'A module option does not fit the module params schema (unknown key, wrong type, out of range or not one of the allowed values). ' +
136
+ 'The message names the option and what it should be; engine.catalog(name).params lists every option with its default.' },
118
137
  'module-dispose': {
119
138
  docs: ['recipes/14-custom-module.md'],
120
139
  fix: 'A module\'s dispose(e) threw; the other modules and core were still cleaned up. Fix that module\'s dispose.' },
@@ -144,6 +163,16 @@ export const ERROR_CODES = {
144
163
  'open-world-camera': {
145
164
  docs: ['recipes/21-camera.md', 'api/openWorld.md'],
146
165
  fix: "openWorld() installs no camera on its own: pass camera: 'follow' | 'firstPerson' | 'rts' | 'fixed' | a camera module | false." },
166
+ 'look-param': {
167
+ docs: ['recipes/52-look.md'],
168
+ fix: 'A look part was given a key it does not have, a value of the wrong type, or a spec without a default. engine.catalog("look.<part>").params lists every key, its default, why and how to turn it off.' },
169
+ 'look-verb': {
170
+ docs: ['recipes/52-look.md'],
171
+ fix: 'This look part does not support that verb (set / patch / replace), or the hook name is unknown. engine.catalog("look.<part>").verbs lists what it supports; the message names the verb to use instead.' },
172
+ 'debug-override': {
173
+ docs: ['recipes/41-thing-registry.md'],
174
+ fix: "engine.debug.override(owner, target, patch): owner names who sets it (engine.debug.clear(owner) removes all of them), target is a thing id or Object3D, " +
175
+ "patch is { visible?, material?: 'flat' | 'wire', apply? }. Overrides change only what the screen shows and are never saved." },
147
176
  'thing-id': {
148
177
  docs: ['recipes/41-thing-registry.md'],
149
178
  fix: "Ids given to engine.add(obj, { id }) are non-empty strings without '#', unique across engine.add objects and world records. " +
@@ -163,6 +192,10 @@ export const ERROR_CODES = {
163
192
  'engine-misuse': {
164
193
  docs: ['api/engine.md'],
165
194
  fix: 'An engine call got an argument it cannot use; the message names the call and the accepted forms.' },
195
+ 'many-lights': {
196
+ docs: ['recipes/09-style-pack.md', 'api/lightPool.md'],
197
+ fix: 'More than 8 real-time lights are in the scene. Use engine.use(lightPool({ point: 8 })) and register torches / lamps with ' +
198
+ 'engine.lightPool.add(...) so a fixed small set of real lights follows the nearest sources.' },
166
199
  'light-recompile': {
167
200
  docs: ['recipes/09-style-pack.md', 'api/lightPool.md'],
168
201
  fix: 'The number of lights changed during play, so three.js compiled new shader programs (a long frame). Keep the light ' +
@@ -12,6 +12,8 @@
12
12
  // Doc paths are relative to the package docs (recipes/..., api/..., CONVENTIONS.md), same as the shipped docs.
13
13
  // Plain data (it imports only errorCodes.js, also plain data), so node tools can load it too. To add a class: append an entry (first match wins, so put specific ones first).
14
14
  import { ERROR_CODES } from './errorCodes.js';
15
+ import { RENAMED } from './renamed.js';
16
+ export { RENAMED };
15
17
 
16
18
 
17
19
  /** @typedef {{ id: string, match: RegExp, cause: string, docs: string[] }} ErrorHint */
@@ -106,7 +108,7 @@ export const ERROR_HINTS = [
106
108
  cause: 'A module rewrites this property every frame, so a direct assignment is lost. Use the module API named in the message (e.g. sky.modify).',
107
109
  docs: ['recipes/08-weather-sky.md', 'api/sky.md'] },
108
110
  { id: 'camera-kind', match: /has no camera kind/,
109
- cause: 'setCamera() got an unknown camera kind. Use one of the listed kinds; for a camera of your own, set engine.cameraOverride = { owner } and place engine.camera yourself (recipes/21-camera.md).',
111
+ cause: 'setCamera() got an unknown camera kind. Use one of the listed kinds; for a camera of your own, take it with engine.takeCamera(owner) and place engine.camera yourself (recipes/21-camera.md).',
110
112
  docs: ['recipes/21-camera.md', 'api/cameraRig.md'] },
111
113
  { id: 'movement', match: /movement\.\w+ must be a positive number/,
112
114
  cause: 'A movement parameter was zero, negative or not a number (a typo in a name gives undefined).',
@@ -187,6 +189,9 @@ export function codedError(code, message, Type = Error) {
187
189
  return Object.assign(err, errorInfo({ code }));
188
190
  }
189
191
 
192
+ /** The stub every removed old name becomes: throws `<old> was renamed: <new call>` [renamed-api]. @param {keyof RENAMED} key @param {string} [oldOverride] @returns {never} */
193
+ export function renamed(key, oldOverride) { throw codedError('renamed-api', `${oldOverride ?? RENAMED[key].old} was renamed: ${RENAMED[key].now}`); }
194
+
190
195
  /** A message tagged with its code, for warnings: warnOnce(coded('save-refused', text)). @param {string} code @param {string} message */
191
196
  export function coded(code, message) { return `${message} [${code}]`; }
192
197