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,173 @@
1
+ // engine.look.<part>: set / patch / replace and the layers.
2
+ // Parts: tone, lights, cloudShadow (core), env (sky); fog / sky / water / post ... come from their modules.
3
+ // set(params, { owner }) change parameters (shallow merge into that owner's layer; null drops a key so the layer below shows again)
4
+ // patch(name, glsl, { owner }) swap one named GLSL hook the part registered (null gives the default back)
5
+ // replace(impl, { owner }) take the whole part over (null gives it back to the engine / style)
6
+ // Why one helper and not per-part code: layering, owner records, validation, catalog and describe were written differently in every module
7
+ // (sky.modify had owners, engine.look.tone.set had none, describeRender guessed the source by comparing against start values). A part author writes only
8
+ // apply / applyHook / applyReplace; everything a reader (describe, catalog, debug.override) needs comes from the same records.
9
+ // Layers per key, the upper one wins: engine default < style < game (each owner; the last one written wins) < debug (engine.debug.override).
10
+ // Hooks and the replace slot are keys too ('hook:<name>', '@replace'), so they get the same layering and records for free.
11
+ // A part author never touches `_` fields: write / ownerValue / extend / retract / has / resolved are the public author methods (review r2 #2).
12
+ import { closest } from '../validate.js';
13
+ import { codedError } from '../errorHints.js';
14
+ import { REPLACE, HOOK, addParams, topOf, allKeys, sourceOf, refresh, quietRefresh, commit, retractKeys, aliased } from './layers.js';
15
+ import { setOn, setStyle, writeLayer, dropLayer, takeVerb, example } from './write.js';
16
+
17
+ export { REPLACE };
18
+ export { disposeLooksOf } from './layers.js';
19
+ const SPEC_FIELDS = ['id', 'group', 'module', 'object', 'params', 'style', 'read', 'apply', 'applyAtStart', 'hooks', 'applyHook', 'noPatch',
20
+ 'replace', 'applyReplace', 'noReplace', 'docs', 'normalize', 'validate', 'verbs', 'appliesTo', 'extraSignatures'];
21
+ const SIG = { set: 'set(params, { owner })', patch: 'patch(name, glsl, { owner })', replace: 'replace(impl, { owner })' };
22
+
23
+ class LookPart {
24
+ /** @param {any} e @param {any} spec see defineLookPart */
25
+ constructor(e, spec) {
26
+ this._e = e; this._spec = spec; this._seq = 0;
27
+ this._params = {}; this._meta = {};
28
+ addParams(this, spec.params);
29
+ this._style = new Map();
30
+ this._owners = { game: new Map(), debug: new Map() }; // owner -> { values: Map, seq, at }
31
+ this._resolved = new Map();
32
+ this._driven = new Map(); // key -> who writes it every frame from the style (sky keyframes drive the sun)
33
+ }
34
+ /** Catalog / override id: 'look.<part>' */
35
+ get id() { return `look.${this._spec.id}`; }
36
+ /** The three.js object(s) behind this part (renderer, lights ...); changing them directly works but is tagged 'three' in describe().look */
37
+ get object() { return this._spec.object?.(); }
38
+ /** Each verb's call shape (spec.verbs overrides a default); the catalog lists it and verb errors quote it */
39
+ get signatures() {
40
+ const s = this._spec, out = { set: SIG.set };
41
+ if (s.hooks) out.patch = s.verbs?.patch?.signature ?? SIG.patch;
42
+ if (s.replace) out.replace = s.verbs?.replace?.signature ?? SIG.replace;
43
+ return Object.assign(out, s.extraSignatures); // a part's own verb (look.post.add), listed so the catalog shows it
44
+ }
45
+
46
+ /**
47
+ * Change parameters for one owner. Nested objects flatten to the part's dotted keys ({ sun: { intensity: 3 } } -> 'sun.intensity').
48
+ * @param {Record<string, any>} params null drops a key from this owner's layer
49
+ * @param {{ owner?: string }} [o]
50
+ * @returns {{ remove(): void }} removes this owner's whole layer on this part
51
+ */
52
+ set(params, { owner = 'game' } = {}) { return this._setOn('game', owner, params); }
53
+ /**
54
+ * Swap one named GLSL hook. Names and signatures: engine.catalog('look.<part>').hooks
55
+ * @param {string} name @param {any} glsl a GLSL string (or the part's hook spec); null gives the default back
56
+ * @param {{ owner?: string }} [o]
57
+ */
58
+ patch(name, glsl, o) {
59
+ const hooks = this._spec.hooks;
60
+ if (!hooks) throw codedError('look-verb', `${this.id}.patch(): this part has no GLSL hooks. ${this._spec.noPatch ?? `Change it with ${this.id}.set(${example(this)})`}`);
61
+ if (this._spec.verbs?.patch?.take) return this._take('patch', [...arguments]);
62
+ if (!(name in hooks) && !hooks['*']) { // hooks['*'] = any name the game picks (post: patch(name, fuse) makes an effect)
63
+ const c = closest(name, Object.keys(hooks)); throw codedError('look-verb', `${this.id}.patch('${name}'): unknown hook${c ? ` (did you mean '${c}'?)` : ''}; hooks: ${Object.keys(hooks).join(', ')}`);
64
+ }
65
+ return this.write(o?.owner ?? 'game', { [HOOK + name]: glsl });
66
+ }
67
+ /**
68
+ * Take the whole part over (what it accepts and what is lost: engine.catalog('look.<part>').replace); null gives it back
69
+ * @param {any} impl @param {{ owner?: string }} [o]
70
+ */
71
+ replace(impl, o) {
72
+ if (!this._spec.replace) throw codedError('look-verb', `${this.id}.replace(): this part cannot be swapped whole. ${this._spec.noReplace ?? `Change it with ${this.id}.set(${example(this)})`}`);
73
+ if (this._spec.verbs?.replace?.take) return this._take('replace', [...arguments]);
74
+ return this.write(o?.owner ?? 'game', { [REPLACE]: impl });
75
+ }
76
+ /** Remove every layer `owner` wrote on this part (game and debug); returns how many layers were removed (the same count shape as engine.debug.clear) */
77
+ clear(owner) { let n = 0; for (const l of ['game', 'debug']) if (this._drop(l, owner)) n++; return n; }
78
+ /** The value in effect for a key (after all layers) */
79
+ value(key) { return this._resolved.get(key); }
80
+ /** Only what the game or a debug override set for a key, else undefined (a driver writes its own value, then this one over it) */
81
+ top(key) { const t = topOf(this, key); return t ? t.value : undefined; }
82
+
83
+ /**
84
+ * Declare keys a style-driven system writes every frame (the sky drives sun and hemisphere from style.sky.keyframes). Those keys then read
85
+ * as by: 'style' in describe with the live value, and apply() gets undefined for them unless a game or debug layer set one (that system
86
+ * should write top(key) over its own value). drive(keys, null) hands them back to the layers.
87
+ * @param {string[]} keys @param {string | null} by the driver's name, e.g. 'sky' (a module name: disposing that module releases them)
88
+ */
89
+ drive(keys, by) {
90
+ for (const k of keys) by ? this._driven.set(k, by) : this._driven.delete(k);
91
+ this._refresh();
92
+ }
93
+ /** For a driver, after it wrote its keys this frame: re-apply the driven keys a game or debug layer set, so those layers win (cheap: a few keys) */
94
+ applyTop() {
95
+ let v = null, changed = null;
96
+ for (const k of this._driven.keys()) { const t = topOf(this, k); if (t) { (v ??= {})[k] = t.value; (changed ??= new Set()).add(k); } }
97
+ if (changed) this._spec.apply?.(v, changed);
98
+ }
99
+
100
+ // ---- for part authors (render/postLook.js, terrain, weather ...): public so no author reaches into `_` fields ------------------------------
101
+
102
+ /** Write raw keys (params, 'hook:<name>', '@replace', a part's own slot keys) for an owner on the game layer, no normalize; null drops a key */
103
+ write(owner, values, { layer = 'game' } = {}) { return this._write(layer, owner, values); }
104
+ /** What one owner holds for a key (undefined when it holds nothing): look.weather.replace adds to the object its owner put in the replace slot */
105
+ ownerValue(owner, key, { layer = 'game' } = {}) { return this._owners[layer].get(owner)?.values.get(key); }
106
+ /** Add declared keys to a started part (same spec fields as params; a known key is left alone). Values recompute without calling apply */
107
+ extend(params) { addParams(this, params, { skipKnown: true }); quietRefresh(this); }
108
+ /** Remove every key starting with prefix (e.g. 'bloom.'), with the values any layer holds for them */
109
+ retract(prefix) { retractKeys(this, prefix); }
110
+ /** Replace the style layer (post: a replaced effect chain brings its own defaults) */
111
+ restyle(values) { this._setStyle(values); }
112
+ /** Is key a declared param of this part */
113
+ has(key) { return key in this._params; }
114
+ /** [key, value] pairs in effect whose key starts with prefix ('hook:' lists the patches set) */
115
+ resolved(prefix = '') { return [...this._resolved].filter(([k]) => k.startsWith(prefix)); }
116
+ /** Unregister the part (its module is disposed, or its install failed): engine.look.<id> goes away and nothing drives its keys any more */
117
+ dispose() {
118
+ const look = this._e.look;
119
+ if (look?.[this._spec.id] === this) delete look[this._spec.id];
120
+ this._driven.clear(); this._started = false;
121
+ }
122
+
123
+ // ---- internal (layering: layers.js) ------------------------------------------------------------------------------------------------------
124
+
125
+ /** @internal set() and engine.debug.override share this (write.js: normalize, flatten, check, write) */
126
+ _setOn(layer, owner, params) { return setOn(this, layer, owner, params); }
127
+ /** @internal Replace the style layer (start, or a style swap); game and debug layers stay */
128
+ _setStyle(values) { setStyle(this, values); }
129
+ _write(layer, owner, values) { return writeLayer(this, layer, owner, values); }
130
+ _drop(layer, owner) { return dropLayer(this, layer, owner); }
131
+ /** @internal recompute (force: every key to apply again); _keys / _source: report.js */
132
+ _refresh(force = false) { refresh(this, force); }
133
+ _keys() { return allKeys(this); }
134
+ _source(key) { return sourceOf(this, key); }
135
+ /** @internal Resolved params as a plain object */
136
+ values() { const o = {}; for (const k in this._params) o[k] = this._resolved.get(k); return o; }
137
+ /** A verb with its own call shape (spec.verbs[verb].take) */
138
+ _take(verb, args) { return takeVerb(this, verb, args); }
139
+ }
140
+
141
+ /**
142
+ * Register a look part: engine.look.<id> gets set / patch / replace (the verbs the spec supports; the others throw and say which verb to use),
143
+ * engine.catalog('look.<id>') lists its params, hooks, replace contract and verb signatures, describe().look shows every key's value and who
144
+ * set it, and engine.debug.override(owner, 'look.<id>', values) writes its debug layer. Every param needs a default; a default that changes the
145
+ * picture needs why (what it is for) and off (how to turn it off), or neutral: true (checked by `npm run check`, rule R35).
146
+ * Its module's failed install drops it again (disposeLooksOf).
147
+ * @param {any} engine @param {{ id: string, group?: string, module?: string, object?: () => any, params?: Record<string, any>, style?: () => object,
148
+ * read?: () => object, apply?: (values: object, changed: Set<string>) => void, applyAtStart?: boolean,
149
+ * hooks?: Record<string, { signature?: string, scope?: string[], example?: string }>, applyHook?: (name: string, glsl: any) => void, noPatch?: string,
150
+ * replace?: { accepts: string, loses?: string[] }, applyReplace?: (impl: any) => void, noReplace?: string, docs?: string[],
151
+ * validate?: (key: string, value: any) => string | null | undefined,
152
+ * verbs?: Record<'patch' | 'replace', { signature: string, take: (bad: (msg: string) => never, ...args: any[]) => [Record<string, any>, string?] }>,
153
+ * appliesTo?: string }} spec validate: why a value is wrong (checked before anything is written); verbs: a verb with its own call shape
154
+ * (materials.replace(role, impl)); appliesTo: what a change reaches when not everything ('new materials')
155
+ * @returns {LookPart}
156
+ * @example
157
+ * defineLookPart(engine, { id: 'glow', group: 'screen', module: 'myGlow', object: () => glowPass,
158
+ * params: { strength: { type: 'number', default: 0, min: 0, neutral: true, desc: 'bloom strength' } },
159
+ * apply(v, changed) { glowPass.strength = v.strength; } });
160
+ * engine.look.glow.set({ strength: 0.6 }, { owner: 'night' });
161
+ */
162
+ export function defineLookPart(engine, spec) {
163
+ for (const k of Object.keys(spec ?? {})) if (!SPEC_FIELDS.includes(k)) { const c = closest(k, SPEC_FIELDS); throw codedError('look-param', `defineLookPart: unknown spec field ${k}${c ? ` (did you mean ${c}?)` : ''}; fields: ${SPEC_FIELDS.join(', ')}`); }
164
+ if (!/^[a-z][\w]*$/i.test(spec?.id ?? '')) throw codedError('look-param', `defineLookPart: id is the part name, e.g. 'fog' (engine.look.fog, catalog id 'look.fog'); got ${JSON.stringify(spec?.id)}`);
165
+ const look = aliased(engine.look ??= {});
166
+ if (look[spec.id] && look[spec.id]._spec.module !== spec.module) throw codedError('look-param', `defineLookPart('${spec.id}'): engine.look.${spec.id} is already registered (by ${look[spec.id]._spec.module ?? 'core'})`);
167
+ const part = new LookPart(engine, spec);
168
+ part._setStyle(spec.style?.());
169
+ part._started = true;
170
+ if (spec.applyAtStart !== false) part._refresh(true);
171
+ look[spec.id] = part;
172
+ return part;
173
+ }
@@ -0,0 +1,79 @@
1
+ // describe().look, catalog('look.*').
2
+ // Both read the same layer records (part.js), so "who set this"
3
+ // in describe and "what can I set" in the catalog cannot disagree. Values set straight on the three.js object (renderer.toneMappingExposure = 2)
4
+ // show up as by: 'three': the part's read() returns the live value and it no longer matches what the layers say.
5
+ import { schemaInfo } from '../params.js';
6
+ import { r1 } from '../math.js';
7
+
8
+ const shown = v => (typeof v === 'number' ? r1(v) : typeof v === 'function' ? '<function>' : Array.isArray(v) && v.length > 4 ? `<array of ${v.length}>` : v?.isObject3D || v?.isTexture || v?.isMaterial ? `<${v.type}>` : v);
9
+ /**
10
+ * Same value for the 'three' check: numbers within a small tolerance, arrays / Colors / vectors element by element. Why: the live read
11
+ * (a Color, a Vector2) is a different object from the layer value ([0.012, 0.006], '#fff'), and !== tagged it 'three' (review L5)
12
+ */
13
+ function same(a, b) {
14
+ if (a === b) return true;
15
+ if (typeof a === 'number' && typeof b === 'number') return Math.abs(a - b) <= 1e-6 * Math.max(1, Math.abs(a), Math.abs(b));
16
+ const arr = v => (Array.isArray(v) ? v : v?.isColor ? [v.r, v.g, v.b] : typeof v?.toArray === 'function' ? v.toArray() : null);
17
+ const x = arr(a), y = arr(b);
18
+ if (x && y) return x.length === y.length && x.every((v, i) => same(v, y[i]));
19
+ const c = a?.isColor ? a : b?.isColor ? b : null, other = c === a ? b : a;
20
+ if (c && (typeof other === 'number' || /^(#|rgb|hsl)/i.test(other ?? ''))) // 'horizon' and the like are not colors: three would warn return c.clone().set(other).equals(c);
21
+ return false;
22
+ }
23
+ /** by: 'game' | 'style' | 'engine' | '<layer>:<owner>' (layer game or debug, owner as given to set / debug.override), or 'three' */
24
+ const tag = (s) => (s.layer === 'game' && s.owner === 'game') || s.layer === 'style' || s.layer === 'engine' ? s.layer : `${s.layer}:${s.owner}`;
25
+
26
+ /** One part's keys: { key: { value, by, at?, under? } }; under lists the layers this value covers (top first) */
27
+ function partInfo(p) {
28
+ const live = p._spec.read?.() ?? {}, out = {};
29
+ for (const k of p._keys()) {
30
+ const s = p._source(k);
31
+ if (!s) continue;
32
+ const o = { value: shown(s.value), by: tag(s) };
33
+ if (s.driven) Object.assign(o, { value: shown(live[k]), driver: s.owner }); // written every frame from the style: the live value is the value
34
+ else if (k in live && live[k] !== undefined && !same(live[k], s.value)) Object.assign(o, { value: shown(live[k]), by: 'three', layers: tag(s) });
35
+ if (s.at) o.at = s.at;
36
+ if (s.under.length && s.layer !== 'engine') o.under = s.under.map(tag);
37
+ out[k] = o;
38
+ }
39
+ return out;
40
+ }
41
+
42
+ /** describe().look: { <part>: { key: { value, by } }, text } (undefined when no part is registered) @param {any} e */
43
+ export function describeLook(e) {
44
+ const parts = Object.values(e.look ?? {});
45
+ if (!parts.length) return undefined;
46
+ const out = {}, lines = [];
47
+ for (const p of parts) {
48
+ const info = out[p._spec.id] = partInfo(p);
49
+ lines.push(`${p._spec.id}${p._spec.appliesTo ? ` (applies to ${p._spec.appliesTo})` : ''}:${Object.entries(info).map(([k, v]) => `${k}=${typeof v.value === 'object' && v.value ? JSON.stringify(v.value) : v.value} (${v.by})`).join(' ')}`);
50
+ }
51
+ return { ...out, text: lines.join('\n') };
52
+ }
53
+
54
+ /** One part as catalog data: params (schema + why / off / cost + value in use and its source), hooks, replace contract, verbs */
55
+ function lookEntry(e, p) {
56
+ const s = p._spec, schema = schemaInfo(p._params), info = partInfo(p);
57
+ for (const k in schema) {
58
+ const m = p._meta[k];
59
+ for (const f of ['why', 'off', 'cost']) if (m[f] !== undefined) schema[k][f] = m[f];
60
+ if (m.neutral) schema[k].neutral = true;
61
+ if (info[k]) Object.assign(schema[k], { value: info[k].value, by: info[k].by });
62
+ }
63
+ return { id: p.id, kind: 'look', group: s.group ?? null, module: s.module ?? 'core', verbs: verbsOf(p), signatures: p.signatures, params: schema,
64
+ ...(s.appliesTo ? { appliesTo: s.appliesTo } : {}),
65
+ hooks: s.hooks ?? null, replace: s.replace ?? null, ...(s.docs ? { docs: s.docs } : {}), problems: [] };
66
+ }
67
+ const verbsOf = p => ['set', ...(p._spec.hooks ? ['patch'] : []), ...(p._spec.replace ? ['replace'] : [])];
68
+
69
+ /** Short list rows for engine.catalog() (same row shape as modules: ops / saves stay empty) @param {any} e */
70
+ export function lookSummaries(e) {
71
+ return Object.values(e.look ?? {}).map(p => ({ id: p.id, kind: 'look', group: p._spec.group ?? null, module: p._spec.module ?? 'core', verbs: verbsOf(p), ops: [], saves: [] }));
72
+ }
73
+
74
+ /** engine.catalog('look') -> every part expanded; 'look.<part>' -> that part; else null @param {any} e @param {string} id */
75
+ export function lookCatalog(e, id) {
76
+ if (id === 'look') return Object.values(e.look ?? {}).map(p => lookEntry(e, p));
77
+ const p = e.look?.[id.slice(5)];
78
+ return p ? lookEntry(e, p) : null;
79
+ }
@@ -0,0 +1,86 @@
1
+ // How a value gets into a LookPart: normalize, flatten, check, then write one owner's layer (part.js has the verbs a game and a part author call).
2
+ // Why a file of its own: this is the one path set(), engine.debug.override and a style swap share, and it is the part that grows with every new
3
+ // kind of check; the verbs in part.js stay short and the file-size cap holds. Functions take the part as `p`; LookPart methods delegate here.
4
+ import { closest, warnOnce } from '../validate.js';
5
+ import { whyBad } from '../params.js';
6
+ import { codedError, coded } from '../errorHints.js';
7
+ import { isPlainObject } from '../util.js';
8
+ import { REPLACE, HOOK, callerAt, commit } from './layers.js';
9
+
10
+ /** A sample call for error texts: { <first key>: <its default> } */
11
+ export function example(p) { const k = Object.keys(p._params)[0]; return k ? `{ ${k}: ${JSON.stringify(p._params[k].default)} }` : '{...}'; }
12
+
13
+ /** { sun: { intensity } } -> { 'sun.intensity' } for keys the part declares dotted */
14
+ export function flat(p, params) {
15
+ const out = {}, keys = Object.keys(p._params);
16
+ for (const [k, v] of Object.entries(params)) {
17
+ if (!(k in p._params) && isPlainObject(v) && keys.some(q => q.startsWith(k + '.'))) for (const [s, sv] of Object.entries(v)) out[`${k}.${s}`] = sv;
18
+ else out[k] = v;
19
+ }
20
+ return out;
21
+ }
22
+
23
+ /** Unknown keys and wrong values throw with the fix (same schema and wording as module params, params.js) */
24
+ export function check(p, values) {
25
+ const keys = Object.keys(p._params);
26
+ for (const [k, v] of Object.entries(values)) {
27
+ if (!(k in p._params)) { const c = closest(k, keys); throw codedError('look-param', `${p.id}.set(): unknown key ${k}${c ? ` (did you mean ${c}?)` : ''}; keys: ${keys.join(', ')}`); }
28
+ if (v === null) continue;
29
+ const why = whyBad(p._params[k], v) ?? p._meta[k].check?.(v);
30
+ if (why) throw codedError('look-param', `${p.id}.set(): ${k} ${why}`);
31
+ }
32
+ return values;
33
+ }
34
+
35
+ /** set() and engine.debug.override share this, so both normalize, flatten and check the same way (review M8) */
36
+ export function setOn(p, layer, owner, params) {
37
+ if (!isPlainObject(params)) throw codedError('look-param', `${p.id}.set(params): params is an object of keys to change, e.g. ${example(p)}; got ${JSON.stringify(params)}`);
38
+ const values = check(p, flat(p, p._spec.normalize?.(params) ?? params)); // normalize: a part's shorthand (post: { bloom: false })
39
+ const to = p._spec.appliesTo;
40
+ if (layer === 'debug' && to) warnOnce(coded('look-param', `${p.id}: a debug override changes only ${to}; what was made before keeps its look`));
41
+ return writeLayer(p, layer, owner, values);
42
+ }
43
+
44
+ /** Replace the style layer (start, or a style swap); game and debug layers stay */
45
+ export function setStyle(p, values) {
46
+ const given = Object.fromEntries(Object.entries(flat(p, values ?? {})).filter(([, v]) => v != null));
47
+ const params = Object.fromEntries(Object.entries(given).filter(([k]) => k !== REPLACE && !k.startsWith(HOOK))); // a style may also fill the replace slot / hooks
48
+ check(p, params); // a style pack value of the wrong type throws at start, with the key
49
+ const old = p._style;
50
+ p._style = new Map(Object.entries(given));
51
+ commit(p, () => { p._style = old; });
52
+ }
53
+
54
+ /** Where spec.validate's answer is quoted: the verb that carried the bad value, so the fix reads as a call */
55
+ const quoteVerb = (p, k) => k === REPLACE ? `${p.id}.replace(impl): impl` : k.startsWith(HOOK) ? `${p.id}.patch('${k.slice(HOOK.length)}', glsl):` : `${p.id}: ${k}`;
56
+
57
+ /** Write one owner's keys on the game or debug layer. All or nothing: if apply throws, the layer and the picture go back (review H1) */
58
+ export function writeLayer(p, layer, owner, values) {
59
+ if (!owner || typeof owner !== 'string') throw codedError('look-param', `${p.id}: owner is a non-empty string naming who changes it, e.g. { owner: 'cave' }`);
60
+ for (const [k, v] of Object.entries(values)) { // spec.validate stops a bad hook / replace value (or any key) before anything is written
61
+ const why = v === null ? null : p._spec.validate?.(k, v);
62
+ if (why) throw codedError(k === REPLACE || k.startsWith(HOOK) ? 'look-verb' : 'look-param', `${quoteVerb(p, k)} ${why}`);
63
+ }
64
+ const map = p._owners[layer], old = map.get(owner);
65
+ // `at` = the owner's first write: one stack capture per owner, not per set (#14)
66
+ const rec = { values: new Map(old?.values), seq: ++p._seq, at: old ? old.at : callerAt() };
67
+ for (const [k, v] of Object.entries(values)) v === null ? rec.values.delete(k) : rec.values.set(k, v);
68
+ map.delete(owner); if (rec.values.size) map.set(owner, rec);
69
+ commit(p, () => { map.delete(owner); if (old) map.set(owner, old); });
70
+ return { remove: () => dropLayer(p, layer, owner) };
71
+ }
72
+
73
+ export function dropLayer(p, layer, owner) {
74
+ const map = p._owners[layer], old = map.get(owner);
75
+ if (!old) return false;
76
+ map.delete(owner);
77
+ commit(p, () => map.set(owner, old));
78
+ return true;
79
+ }
80
+
81
+ /** A verb with its own call shape (spec.verbs[verb].take): take(bad, ...args) -> [values, owner]; bad(msg) throws quoting the signature */
82
+ export function takeVerb(p, verb, args) {
83
+ const sig = p.signatures[verb], bad = msg => { throw codedError('look-verb', `${p.id}.${verb}: ${msg}. Call it as ${p.id.slice(5)}.${sig}`); };
84
+ const [values, owner = 'game'] = p._spec.verbs[verb].take(bad, ...args);
85
+ return p.write(owner, values);
86
+ }
package/core/loop.js CHANGED
@@ -13,7 +13,7 @@
13
13
  // Determinism: in engine.step() and headless loading frames, jobs ignore the real-time budget and drain the queue (see Jobs.js),
14
14
  // and stream's synchronous builds are attached to the scene before step returns: same input and same seed (engine.random) give the same result.
15
15
  import { reportError } from './errors.js';
16
- import { DEV } from './validate.js';
16
+ import { DEV, warnOnce } from './validate.js';
17
17
  import { codedError } from './errorHints.js';
18
18
  import { watchLights } from './lightWatch.js';
19
19
 
@@ -94,20 +94,21 @@ export const loopMethods = {
94
94
  return r;
95
95
  },
96
96
 
97
- // ---------- pause and freeze (the other half of the loop: step() below is the deterministic way to advance) ----------
98
- /** Pause the real-time loop (the picture stops and the game stops advancing) */
99
- pause() { this.paused = true; return this; },
100
- /** Resume the real-time loop (in headless mode this starts live running) */
101
- resume() { if (!this.disposed) { this.paused = false; this._loop(); } return this; },
102
- // Gameplay freeze (menus, flow 'paused'): no fixed steps (movement, timers, game clock and engine.elapsed all stop) while frame hooks
103
- // and rendering go on, so the picture and UI stay alive.
104
- // Gameplay logic (quest checks, cutscene waits) belongs in fixed, or check engine.frozen first in frame (see the top of this file).
105
- // Unlike pause(), which stops rendering too and is for tests and step(). owner is the freezer's name; play resumes only when all
106
- // have unfrozen. step() obeys freezes as well.
107
- freeze(owner = 'game') { this._freezers.add(owner); return this; },
108
- unfreeze(owner = 'game') { this._freezers.delete(owner); return this; },
109
- /** True while someone has frozen gameplay */
110
- get frozen() { return this._freezers.size > 0; },
97
+ // ---------- nextFixed (pause / freeze / runState live in holds.js; step() below is the deterministic way to advance) ----------
98
+ /**
99
+ * Run fn at the start of the next fixed step (before that step's fixed hooks), from any callback (UI click, promise, worker result): gameplay state is safe to write there.
100
+ * Returns a Promise of fn's value (rejects if fn throws). Waits while frozen or loading. Built on engine.commits: applies in request order and survives save loads.
101
+ * @template T
102
+ * @param {() => T} fn
103
+ * @returns {Promise<T>}
104
+ * @example engine.nextFixed(() => engine.ops.run('door.open', { id: 'gate' }));
105
+ */
106
+ nextFixed(fn) {
107
+ return new Promise((resolve, reject) => {
108
+ const t = this.commits.request({ lag: 1, valid: () => true, fallback: () => undefined, apply: () => { try { resolve(fn()); } catch (err) { reject(err); } } });
109
+ t.resolve(undefined); // nothing to wait for: otherwise the fallback would count as late
110
+ });
111
+ },
111
112
 
112
113
  _loop() {
113
114
  if (this._looping) return;
@@ -191,7 +192,12 @@ export const loopMethods = {
191
192
  if (a.t < 1) return;
192
193
  const fps = a.n / a.t; a.t = 0; a.n = 0;
193
194
  const pr = this.renderer.getPixelRatio();
194
- if (fps < a.target - 5 && pr > a.min + 0.01) { this.setPixelRatio(Math.max(a.min, +(pr - 0.1).toFixed(2))); a.good = 0; a.cooldown = 5; }
195
+ if (fps < a.target - 5 && pr > a.min + 0.01) {
196
+ const to = Math.max(a.min, +(pr - 0.1).toFixed(2));
197
+ // never silent: the picture gets softer, and the game or an AI should know why (dev warning once; describe().render.scale keeps the facts)
198
+ if (!a.lowered) { a.lowered = true; a.from = pr; if (DEV) warnOnce(`render scale ${pr} -> ${to} because fps ${fps.toFixed(0)} is under ${a.target}; adaptive resolution lowers it down to ${a.min}. Turn off with createEngine({ adaptiveResolution: false }) or engine.adaptive.on = false; see describe().render.scale`); }
199
+ this.setPixelRatio(to); a.good = 0; a.cooldown = 5;
200
+ }
195
201
  else if (fps >= a.target + 3 && pr < a.max - 0.01 && a.cooldown <= 0) {
196
202
  if (++a.good >= 4) { this.setPixelRatio(Math.min(a.max, +(pr + 0.05).toFixed(2))); a.good = 0; }
197
203
  } else a.good = 0;
package/core/modules.js CHANGED
@@ -22,6 +22,9 @@
22
22
  import { requiresText, warnOnce, DEV, fmt } from './validate.js';
23
23
  import { codedError, coded } from './errorHints.js';
24
24
  import { reportError } from './errors.js';
25
+ import { catalog, catalogSnap, catalogClaim } from './catalog.js';
26
+ import { readParams } from './params.js';
27
+ import { disposeLooksOf } from './look/part.js';
25
28
 
26
29
  /** Stage -> sort position */
27
30
  const STAGES = { control: 100, world: 200, environment: 300, gameplay: 400, presentation: 450, late: 500, audio: 510 };
@@ -91,18 +94,20 @@ export const moduleMethods = {
91
94
  const plan = this._planUse(mods.flat()), done = [];
92
95
  try {
93
96
  for (const m of plan) {
94
- const had = Object.hasOwn(this, m.name), api = m.install?.(this) ?? m;
97
+ const had = Object.hasOwn(this, m.name), prev = this[m.name], snap = catalogSnap(this), api = m.install?.(this) ?? m;
98
+ catalogClaim(this, m.name, snap); // ops / save parts / describe names it registered show under it in engine.catalog()
95
99
  this.modules.set(m.name, m);
96
100
  if (m.name) this[m.name] = api;
97
- done.push({ m, had });
101
+ done.push({ m, had, prev });
98
102
  this._modState.set(m.name, m.init ? (this._started ? 'initializing' : 'registered') : 'running');
99
103
  }
100
104
  } catch (err) {
101
- for (const { m, had } of done.reverse()) { // undo in reverse install order, like dispose
105
+ for (const { m, had, prev } of done.reverse()) { // undo in reverse install order, like dispose
102
106
  this.modules.delete(m.name); this._modState.delete(m.name);
103
- if (had) this[m.name] = undefined; else delete this[m.name];
107
+ if (had) this[m.name] = prev; else delete this[m.name]; // put back what was there (an undefined slot stays undefined), never blank it
104
108
  try { m.dispose?.(this); } catch { /* the install error below is the one to report */ }
105
109
  }
110
+ for (const m of plan) disposeLooksOf(this, m.name); // look parts and driven keys of every module in the batch, the one that threw too (review M9)
106
111
  this._sortHooks();
107
112
  throw err;
108
113
  }
@@ -124,6 +129,7 @@ export const moduleMethods = {
124
129
  throw codedError('module-stage', fmt(STRINGS.stage, { name: m.name, stage: m.stage, list: Object.keys(STAGES).join(', ') }));
125
130
  for (const dep of m.requires || []) if (!names.has(dep))
126
131
  throw codedError('module-requires', requiresText(m.name, dep, [...names]) ?? fmt(STRINGS.needs, { name: m.name, dep }));
132
+ if (DEV && m.params && m.options) readParams(m.name, m.params, m.options); // a definition built by hand still gets its options checked
127
133
  if (m.name in this && this[m.name] !== undefined) throw codedError('module-name', fmt(STRINGS.clash, { name: m.name }));
128
134
  names.add(m.name); plan.push(m);
129
135
  }
@@ -135,8 +141,9 @@ export const moduleMethods = {
135
141
  _lateInit(m) {
136
142
  const L = this.loading, task = L._begin(m.name, 'module');
137
143
  task.phase('build');
144
+ const snap = catalogSnap(this);
138
145
  L._track(Promise.resolve().then(() => m.init(this)).then(
139
- () => { L._done(task); this._setModState(m, 'running'); },
146
+ () => { catalogClaim(this, m.name, snap); L._done(task); this._setModState(m, 'running'); },
140
147
  e => { L._fail(task, e); this._setModState(m, 'failed'); reportError(this, e, fmt(STRINGS.lateInit, { name: m.name }), { module: m }); }));
141
148
  },
142
149
  /** @internal move a module to a new state and refresh the hooks (initializing / failed modules run none) */
@@ -151,6 +158,13 @@ export const moduleMethods = {
151
158
  * @example engine.use(shop()); await engine.loading.settled(); engine.moduleStates.shop // 'running'
152
159
  */
153
160
  get moduleStates() { return Object.fromEntries(this._modState); },
161
+ /**
162
+ * What this game can do, read from the registrations (see core/catalog.js): no argument = short list, a module id or op name = that entry expanded.
163
+ * @param {string | { find?: string }} [id]
164
+ * @returns {any}
165
+ * @example engine.catalog(); engine.catalog('sky'); engine.catalog('shop.buy'); engine.catalog({ find: 'buy' })
166
+ */
167
+ catalog(id) { return catalog(this, id); },
154
168
  /** Is this module installed? */
155
169
  has(name) { return this.modules.has(name); },
156
170
  /** Run order of module hooks (module names, first to last), for debugging "who runs first". */
@@ -0,0 +1,31 @@
1
+ // Atomic ops (op definition atomic: true): world records, inventory / containers and vars written during run are kept or all undone.
2
+ // How: the save parts declared atomic are copied before run and loaded back (as an op write) if run fails or throws. Honest limits, also in recipe 23:
3
+ // - it costs one save of those parts per atomic run: fine for a shop / craft op, not for a per-frame op in a huge world;
4
+ // - events already emitted, and anything outside the atomic parts (sound, animation, DOM, other modules' saves), are NOT undone: put such side effects in the op's `after`;
5
+ // - ops called from an atomic run join it: their `after` hooks wait for the outermost commit.
6
+ // Which parts: the ones whose module declared saves.register(key, { atomic: true }) (core names no module; a game's own part can opt in the same way).
7
+ // Rollback does not run afterLoad hooks (no model rebuild): atomic state must be plain data a load restores by itself. Events the load would emit are muted
8
+ // (the run's own events already went out and cannot be recalled), and the trace gets one 'ops:rollback' note.
9
+
10
+ /** Copy the atomic parts that exist now: [[provider, plain copy]] @internal */
11
+ export function snapshot(e) {
12
+ const out = [];
13
+ for (const p of e.saves.providers.values()) if (p.atomic) out.push([p, JSON.parse(JSON.stringify(p.save() ?? null))]);
14
+ return out;
15
+ }
16
+
17
+ /** Put a snapshot back (guarded writes allowed, change events muted) @internal */
18
+ export function rollback(e, snap) {
19
+ const ev = e.events;
20
+ ev.muted = (ev.muted || 0) + 1;
21
+ try { e.ops.allow(() => { for (const [p, d] of snap) p.load(JSON.parse(JSON.stringify(d))); }); } finally { ev.muted--; }
22
+ if (ev.traceSize > 0) ev.note('ops:rollback', { data: { parts: snap.length } });
23
+ }
24
+
25
+ /** Mark the history entries a rolled-back run left behind (committed nested ops deeper than it) as failed with code 'rolledBack' @internal */
26
+ export function markRolledBack(ops, seq, depth) {
27
+ for (const h of ops._ring) if (h.seq > seq && h.depth > depth && h.ok) { h.ok = false; h.code = 'rolledBack'; }
28
+ }
29
+
30
+ /** Which state an op definition covers, for list / explain / the catalog: honest about what atomic means */
31
+ export const atomicNote = d => d.atomic ? 'atomic: the parts declared atomic (world, inventory, containers, vars, quests, grids, random, scene) roll back if run fails; events, sound and other state do not (use after)' : null;
package/core/opsCheck.js CHANGED
@@ -2,11 +2,11 @@
2
2
  // Each message says what is wrong and how to write it, because the reader is usually an AI that will fix the call from the text alone.
3
3
  import { closest, fmt } from './validate.js';
4
4
  import { codedError } from './errorHints.js';
5
+ import { parseSchema, whyBad, CHECK, OP_TYPES as TYPES } from './params.js'; // one type check for op args and module params
5
6
 
6
7
  export const SOURCES = ['player', 'game', 'bridge', 'test', 'replay', 'net'];
7
- const TYPES = ['string', 'number', 'int', 'bool', 'position', 'id', 'any'];
8
8
  const NAME = /^[a-z][a-zA-Z0-9]*(\.[a-z][a-zA-Z0-9]*)+$/;
9
- const DEF_KEYS = ['desc', 'args', 'can', 'run', 'offers', 'reasons', 'undo', 'net', 'owner'];
9
+ const DEF_KEYS = ['desc', 'args', 'can', 'run', 'offers', 'reasons', 'undo', 'net', 'owner', 'targets', 'atomic', 'after'];
10
10
  export { fmt };
11
11
  const STRINGS = {
12
12
  badName: "ops.define('{name}'): name an op noun.verb, e.g. 'shop.buy' (lowercase start, camelCase)",
@@ -14,12 +14,15 @@ const STRINGS = {
14
14
  badKey: "ops.define('{name}'): unknown field '{key}'{hint}. Fields: " + DEF_KEYS.join(', '),
15
15
  badType: "ops.define('{name}'): args.{key} has type '{type}'; use one of " + TYPES.join(' ') + " (add ? for optional, e.g. 'int?')",
16
16
  badNet: "ops.define('{name}'): net is 'peer' (remote players may request it) or 'local' (runs on each machine, e.g. UI settings); leave it out to let only the host run it",
17
+ badTargets: "ops.define('{name}'): targets is a thing id, kind or template name (or a list of them, or '*'), the things this op is meant for, e.g. targets: 'chest'",
17
18
  badOwner: "ops.define('{name}'): owner is a function of the args returning the world record id the actor must own, e.g. owner: a => a.id",
18
19
  notPlain: "ops.run('{name}'): argument {key} is {what}; pass plain data: {fix}",
19
20
  argsObj: "ops.run('{name}'): args must be a plain object like { item: 'bread' }, got {what}",
20
21
  missing: "ops.run('{name}') is missing {key} (args: {shape})",
21
22
  extra: "ops.run('{name}'): unknown argument {key}{hint} (args: {shape})",
22
23
  wrong: "ops.run('{name}'): {key} should be {type}, got {got} (args: {shape})",
24
+ badAtomic: "ops.define('{name}'): atomic is true/false and after is a function (e, args, value, ctx) for sound / animation; it runs only when the op committed",
25
+ range: "ops.run('{name}'): {key} {why} (args: {shape})",
23
26
  noRecord: "ops.run('{name}'): {key} '{id}' is not a world record id",
24
27
  };
25
28
  const what = v => typeof v === 'function' ? 'a function' : v?.isVector3 ? 'a Vector3' : v?.isObject3D ? 'a three.js object' : (v?.constructor?.name ? 'a ' + v.constructor.name : typeof v);
@@ -35,11 +38,6 @@ function notPlain(v, depth = 0) {
35
38
  for (const k in v) { const b = notPlain(v[k], depth + 1); if (b) return b; }
36
39
  return null;
37
40
  }
38
- const isPos = v => Array.isArray(v) && (v.length === 2 || v.length === 3) && v.every(Number.isFinite);
39
- const CHECK = {
40
- string: v => typeof v === 'string', number: v => Number.isFinite(v), int: v => Number.isInteger(v), bool: v => typeof v === 'boolean',
41
- position: isPos, id: v => typeof v === 'string', any: () => true,
42
- };
43
41
 
44
42
  /** Dev mistakes (wrong name, args, can result) are thrown straight to the caller, not treated as gameplay errors */
45
43
  export function devError(msg) { const err = codedError('op-misuse', msg); err.opsDevError = true; return err; }
@@ -54,14 +52,13 @@ export function checkDef(name, def) {
54
52
  throw devError(fmt(STRINGS.badKey, { name, key, hint: c ? ` (did you mean ${c}?)` : '' }));
55
53
  }
56
54
  if (def.net !== undefined && def.net !== 'peer' && def.net !== 'local') throw devError(fmt(STRINGS.badNet, { name }));
55
+ if (def.targets !== undefined && ![def.targets].flat().every(t => typeof t === 'string' && t)) throw devError(fmt(STRINGS.badTargets, { name }));
57
56
  if (def.owner !== undefined && typeof def.owner !== 'function') throw devError(fmt(STRINGS.badOwner, { name }));
57
+ if ((def.atomic !== undefined && typeof def.atomic !== 'boolean') || (def.after !== undefined && typeof def.after !== 'function')) throw devError(fmt(STRINGS.badAtomic, { name }));
58
58
  if (!def.args) return null;
59
- const shape = {};
60
- for (const key in def.args) {
61
- const t = String(def.args[key]), type = t.replace(/\?$/, '');
62
- if (!TYPES.includes(type)) throw devError(fmt(STRINGS.badType, { name, key, type: t }));
63
- shape[key] = { type, optional: t.endsWith('?') };
64
- }
59
+ // the same schema form as module params (params.js): 'int?' or { type, default, min, max, values, desc }
60
+ const shape = parseSchema(`ops.define('${name}') args`, def.args, devError);
61
+ for (const key in shape) if (!TYPES.includes(shape[key].type)) throw devError(fmt(STRINGS.badType, { name, key, type: shape[key].type }));
65
62
  return shape;
66
63
  }
67
64
 
@@ -81,6 +78,20 @@ export function checkArgs(e, d, args) {
81
78
  const s = d.shape[key], v = args[key];
82
79
  if (v === undefined) { if (!s.optional) throw devError(fmt(STRINGS.missing, { name, key, shape: shapeText })); continue; }
83
80
  if (!CHECK[s.type](v)) throw devError(fmt(STRINGS.wrong, { name, key, type: s.type === 'position' ? '[x, y, z]' : s.type, got: JSON.stringify(v), shape: shapeText }));
84
- if (s.type === 'id' && e.world && !e.world.get(v)) throw devError(fmt(STRINGS.noRecord, { name, key, id: v }));
81
+ const range = whyBad(s, v); // min / max / values of the full schema form
82
+ if (range) throw devError(fmt(STRINGS.range, { name, key, why: range, shape: shapeText }));
83
+ if (s.type === 'id' && e._things.sources.length && !e._things.source(v)) throw devError(fmt(STRINGS.noRecord, { name, key, id: v }));
84
+ }
85
+ }
86
+
87
+ /** Release builds: the range part of the schema (min / max / values) is still checked, because a bad number from a UI or a net peer must not reach run. Returns a failure spec or null */
88
+ export function argRange(d, args) {
89
+ if (!d.shape || !args) return null;
90
+ for (const key in d.shape) {
91
+ const s = d.shape[key], v = args[key];
92
+ if (v === undefined || !CHECK[s.type](v)) { if (v !== undefined) return { code: 'badArgs', facts: [{ id: d.name, field: key, actual: v, expected: s.type }] }; continue; }
93
+ const why = whyBad(s, v);
94
+ if (why) return { code: 'badArgs', facts: [{ id: d.name, field: key, actual: v, expected: why }] };
85
95
  }
96
+ return null;
86
97
  }
@@ -0,0 +1,20 @@
1
+ // Structured op failures. can may return a reason string (kept working) or { code, facts?, nextActions? }:
2
+ // can: () => cond ? true : { code: 'noMoney', facts: { need: 5, have: 2 }, nextActions: [{ op: 'job.work', args: {} }] }
3
+ // facts: an object ({ need: 5, have: 2 }) or a list [{ id, field, actual, expected? }] (which record / field was wrong, and what it should have been). nextActions are declared by the game here, never guessed by the engine.
4
+ // run may fail the same way: return or throw { ok: false, code, facts?, nextActions? } (the op then counts as failed; an atomic op is rolled back).
5
+ // Every failed result from run / can / undo is normalized to { ok: false, code, facts, nextActions }; `code` is the name to read. The old field `reason`
6
+ // is a hidden (non-enumerable) trap: reading it throws renamed-api and names result.code, in every build.
7
+ import { renamed } from './errorHints.js';
8
+ const NONE = Object.freeze([]), NO_FACTS = Object.freeze({});
9
+ const TRAP = { get() { return renamed('reason'); }, enumerable: false, configurable: true };
10
+
11
+ /** @param {string | { code: string, facts?: object, nextActions?: any[] }} r a code string or a structured failure @returns {{ ok: false, code: string, facts: object, nextActions: any[], reason?: never }} */
12
+ export function failure(r) {
13
+ const out = typeof r === 'string' ? { ok: false, code: r, facts: NO_FACTS, nextActions: NONE }
14
+ : { ok: false, code: r.code, facts: r.facts ?? NO_FACTS, nextActions: r.nextActions ?? NONE };
15
+ return Object.defineProperty(out, 'reason', TRAP);
16
+ }
17
+ /** True when can returned a usable structured failure */
18
+ export const isStructured = r => r !== null && typeof r === 'object' && typeof r.code === 'string' && r.code.length > 0;
19
+ /** True when run returned or threw a structured failure: { ok: false, code, ... } (plain values with a code field are not failures) */
20
+ export const isRunFailure = r => r !== null && typeof r === 'object' && r.ok === false && typeof r.code === 'string' && r.code.length > 0;