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
@@ -1,16 +1,16 @@
1
1
  // The history of engine.ops (split out of Ops.js): a ring of entries allocated once, so logging a run allocates nothing.
2
- // Entry: { seq, tick, phase, name, args, source, actor, ok, reason, depth, count }. Ops keeps the ring fields (_ring, _head, _len, _seq); these functions work on them.
2
+ // Entry: { seq, tick, phase, name, args, source, actor, ok, code, depth, count }. Ops keeps the ring fields (_ring, _head, _len, _seq); these functions work on them.
3
3
 
4
4
  /** A fresh ring of n empty entries @param {number} n */
5
- export const newRing = n => Array.from({ length: Math.max(1, n | 0) }, () => ({ seq: 0, tick: 0, phase: 'between', name: '', args: null, source: '', actor: '', ok: false, reason: null, depth: 0, count: 1 }));
5
+ export const newRing = n => Array.from({ length: Math.max(1, n | 0) }, () => ({ seq: 0, tick: 0, phase: 'between', name: '', args: null, source: '', actor: '', ok: false, code: null, depth: 0, count: 1 }));
6
6
 
7
- /** Write a history entry in place (no allocation); consecutive identical failures (same actor, op, reason) merge into one with count */
8
- export function logEntry(ops, name, args, ctx, ok, reason, depth) {
7
+ /** Write a history entry in place (no allocation); consecutive identical failures (same actor, op, code) merge into one with count */
8
+ export function logEntry(ops, name, args, ctx, ok, code, depth) {
9
9
  const n = ops._ring.length, last = ops._len ? ops._ring[(ops._head - 1 + n) % n] : null;
10
- if (!ok && last && !last.ok && last.name === name && last.reason === reason && last.actor === ctx.actor) { last.count++; return last; }
10
+ if (!ok && last && !last.ok && last.name === name && last.code === code && last.actor === ctx.actor) { last.count++; return last; }
11
11
  const h = ops._ring[ops._head];
12
12
  h.seq = ++ops._seq; h.tick = ctx.tick; h.phase = ops.engine._inFixed ? 'fixed' : 'between'; h.name = name; h.args = args;
13
- h.source = ctx.source; h.actor = ctx.actor; h.ok = ok; h.reason = reason; h.depth = depth; h.count = 1;
13
+ h.source = ctx.source; h.actor = ctx.actor; h.ok = ok; h.code = code; h.depth = depth; h.count = 1;
14
14
  ops._head = (ops._head + 1) % n;
15
15
  if (ops._len < n) ops._len++;
16
16
  return h;
package/core/opsRun.js ADDED
@@ -0,0 +1,77 @@
1
+ // ops.run itself (split out of Ops.js). Order: can -> log -> [snapshot if atomic] -> run -> commit (revision + 1, after hook) or fail (rollback if atomic).
2
+ // A run that returns or throws a structured failure { ok: false, code, facts?, nextActions? } counts as failed, like a can that said no (see opsFail.js).
3
+ import { DEV } from './validate.js';
4
+ import { devError, fmt, argRange } from './opsCheck.js';
5
+ import { reportError } from './errors.js';
6
+ import { failure, isRunFailure } from './opsFail.js';
7
+ import { snapshot, rollback, markRolledBack } from './opsAtomic.js';
8
+ import { withDefaults } from './params.js';
9
+
10
+ const MAX_DEPTH = 16;
11
+ export const RUN_STRINGS = {
12
+ canRun: "{name}'s can called ops.run('{inner}'). can is read-only; call other ops from run",
13
+ loop: 'ops call each other in a loop (deeper than ' + MAX_DEPTH + '): {chain}',
14
+ };
15
+
16
+ /** Undo an atomic run's writes; a failing rollback is reported, never thrown over the original failure */
17
+ function undoWrites(ops, e, snap, where, seq, depth) {
18
+ ops.revision++; // the revision only goes up: a rollback is a new state, never "the old number again"
19
+ markRolledBack(ops, seq, depth);
20
+ try { rollback(e, snap); } catch (err) { reportError(e, err, where + ' rollback'); }
21
+ }
22
+
23
+ /** @internal Called by Ops.run */
24
+ export function runOp(ops, name, args, opts) {
25
+ const e = ops.engine, d = ops._def(name);
26
+ if (!d) return ops._res(failure('unknownOp'));
27
+ args = withDefaults(d.defaults, args);
28
+ if (ops._inCan) throw devError(fmt(RUN_STRINGS.canRun, { name: ops._inCan, inner: name }));
29
+ if (ops._stack.length >= MAX_DEPTH) throw devError(fmt(RUN_STRINGS.loop, { chain: ops._stack.concat(name).join(' -> ') }));
30
+ if (ops._route) { const r = ops._route(d, args, opts); if (r) return r; } // net client: requests go to the host (also from inside a net: 'local' op)
31
+ const parent = ops._stack.length ? ops._last : null;
32
+ const ctx = ops._ctx(name, args, opts, parent);
33
+ const depth = ops._stack.length, ev = e.events, where = `ops.run('${name}')`;
34
+ if (e._freezers.has('error')) { ops._log(name, args, ctx, false, 'halted', depth); return ops._res(failure('halted')); }
35
+ if (DEV && args && typeof args === 'object') Object.freeze(args);
36
+ const failed = (f, h) => { // a failed run: log it, trace it with its code
37
+ if (h) { h.ok = false; h.code = f.code; } else ops._log(name, args, ctx, false, f.code, depth);
38
+ if (ev.traceSize > 0) ev.note('op:' + name, { code: f.code, obj: args?.id });
39
+ return ops._res(f);
40
+ };
41
+ if (!DEV) { const bad = argRange(d, args); if (bad) return failed(failure(bad), null); } // release: min / max / values still hold (dev throws earlier, in _ctx)
42
+ ops._stack.push(name);
43
+ const prevCtx = ops._last; ops._last = ctx;
44
+ const prevCause = ev._cur, atomic = d.atomic === true, mark = ops._txAfter.length; // events emitted by this op's run name it as their cause (Events.trace)
45
+ let h = null, seq = 0, snap = null;
46
+ if (atomic) ops._txDepth++;
47
+ try {
48
+ const res = ops._can(d, args, ctx);
49
+ if (res !== true) return failed(failure(res), null);
50
+ h = ops._log(name, args, ctx, true, null, depth); seq = h.seq; // logged before run so nested ops follow their parent in the history
51
+ if (ev.traceSize > 0) ev._cur = `op:${name}#${seq}`;
52
+ if (atomic) snap = snapshot(e);
53
+ let value;
54
+ try { value = d.run(e, args, ctx); } catch (err) { if (!isRunFailure(err)) throw err; value = err; }
55
+ if (isRunFailure(value)) {
56
+ if (snap) { undoWrites(ops, e, snap, where, seq, depth); ops._txAfter.length = mark; }
57
+ return failed(failure(value), h.seq === seq ? h : null);
58
+ }
59
+ ops.revision++;
60
+ if (d.after) {
61
+ const hook = () => { try { d.after(e, args, value, ctx); } catch (err) { reportError(e, err, where + ' after'); } };
62
+ if (ops._txDepth > 0) ops._txAfter.push(hook); else hook(); // in or inside an atomic run: queue, so hooks run in commit order (nested first) when the outermost one ends
63
+ }
64
+ return { ok: true, value, revision: ops.revision };
65
+ } catch (err) {
66
+ if (snap) { undoWrites(ops, e, snap, where, seq, depth); ops._txAfter.length = mark; }
67
+ if (err?.opsDevError) throw err;
68
+ if (h?.seq === seq) { h.ok = false; h.code = 'error'; } else ops._log(name, args, ctx, false, 'error', depth);
69
+ reportError(e, err, where);
70
+ if (e.error?.where === where && !e.error.ops) e.error.ops = ops.recent().slice(-5).map(r => `${r.name}${r.ok ? '' : ' x ' + r.code}`);
71
+ if (ev.traceSize > 0) ev.note('op:' + name, { code: 'error' });
72
+ return ops._res(failure('error'));
73
+ } finally {
74
+ ops._stack.pop(); ops._last = prevCtx; ev._cur = prevCause;
75
+ if (atomic && --ops._txDepth === 0) { const q = ops._txAfter.splice(0); for (const f of q) f(); } // outermost atomic op ended: its queued after hooks run now (empty after a rollback)
76
+ }
77
+ }
package/core/params.js ADDED
@@ -0,0 +1,132 @@
1
+ // Param schemas: one plain-object description per field, shared by op args (ops.define args) and module params (readParams).
2
+ // Why one shape for both: the same schema validates the call, fills its defaults and is what engine.catalog() shows, so code,
3
+ // catalog and the dev bridge cannot disagree about a field (no second copy in docs or TypeScript).
4
+ // short form: 'int' / 'int?' (type, ? = optional)
5
+ // full form: { type: 'int', default: 1, min: 1, max: 99, values: [...], desc: 'how many', optional: true } (default implies optional)
6
+ import { closest, fmt, DEV, warnOnce, unknownOptionText } from './validate.js';
7
+ import { codedError, coded } from './errorHints.js';
8
+
9
+ /** Types an op arg may use: plain data only. Two meanings of 'id' on purpose: as a module param it is any string; as an op arg it must also be a world record id (checked in dev by opsCheck) */
10
+ export const OP_TYPES = ['string', 'number', 'int', 'bool', 'position', 'id', 'any'];
11
+ export const TYPES = ['string', 'number', 'int', 'bool', 'position', 'id', 'any', 'object', 'array', 'function'];
12
+ const SPEC_KEYS = ['type', 'default', 'min', 'max', 'values', 'desc', 'optional'];
13
+ const isPos = v => Array.isArray(v) && (v.length === 2 || v.length === 3) && v.every(Number.isFinite);
14
+ /** type name -> value check (op args use the first seven: plain data only) */
15
+ export const CHECK = {
16
+ string: v => typeof v === 'string', number: v => Number.isFinite(v), int: v => Number.isInteger(v), bool: v => typeof v === 'boolean',
17
+ position: isPos, id: v => typeof v === 'string', any: () => true, object: v => !!v && typeof v === 'object' && !Array.isArray(v),
18
+ array: Array.isArray, function: v => typeof v === 'function',
19
+ };
20
+ const STRINGS = {
21
+ badType: "{where}: {key} has type '{type}'; use one of {list} (add ? for optional, e.g. 'int?', or { type: 'int', default: 1 })",
22
+ badSpec: '{where}: {key} has unknown schema field {field}{hint}; schema fields: ' + SPEC_KEYS.join(', '),
23
+ badDefault: '{where}: the default of {key} ({got}) does not fit its own schema: {why}',
24
+ wrong: '{where}: {key} {why}',
25
+ };
26
+
27
+ /** Parse one field spec ('int?' or { type, default, ... }) into { type, optional, default?, min?, max?, values?, desc? }; throws on a bad spec */
28
+ export function parseSpec(where, key, spec, err = codedError.bind(null, 'engine-misuse')) {
29
+ const s = typeof spec === 'string' ? { type: spec.replace(/\?$/, ''), optional: spec.endsWith('?') } : { ...spec };
30
+ if (typeof spec !== 'string') {
31
+ for (const f of Object.keys(s)) if (!SPEC_KEYS.includes(f)) {
32
+ const c = closest(f, SPEC_KEYS);
33
+ throw err(fmt(STRINGS.badSpec, { where, key, field: f, hint: c ? ` (did you mean ${c}?)` : '' }));
34
+ }
35
+ s.optional = !!s.optional || 'default' in s;
36
+ }
37
+ if (!TYPES.includes(s.type)) throw err(fmt(STRINGS.badType, { where, key, type: String(s.type ?? spec), list: TYPES.join(' ') }));
38
+ if ('default' in s) { const why = whyBad(s, s.default); if (why) throw err(fmt(STRINGS.badDefault, { where, key, got: JSON.stringify(s.default), why })); }
39
+ return s;
40
+ }
41
+
42
+ /** Parse a whole schema ({ key: spec }) -> { key: parsed } (null when there is none) */
43
+ export function parseSchema(where, schema, err) {
44
+ if (!schema) return null;
45
+ const out = {};
46
+ for (const key in schema) out[key] = parseSpec(where, key, schema[key], err);
47
+ return out;
48
+ }
49
+
50
+ /** Why v does not fit the parsed spec s (type, range, allowed values), or null when it does */
51
+ export function whyBad(s, v) {
52
+ if (!CHECK[s.type](v)) return `should be ${s.type === 'position' ? '[x, y, z]' : s.type}, got ${JSON.stringify(v) ?? typeof v}`;
53
+ if (s.min != null && v < s.min) return `must be >= ${s.min}, got ${v}`;
54
+ if (s.max != null && v > s.max) return `must be <= ${s.max}, got ${v}`;
55
+ if (s.values && !s.values.includes(v)) return `must be one of ${s.values.map(x => JSON.stringify(x)).join(', ')}, got ${JSON.stringify(v)}`;
56
+ return null;
57
+ }
58
+
59
+ /** { key: default } of the fields that declare one, or null when none do (so callers skip the copy) */
60
+ export function defaultsOf(shape) {
61
+ let out = null;
62
+ for (const key in shape || {}) if ('default' in shape[key]) (out ??= {})[key] = shape[key].default;
63
+ return out;
64
+ }
65
+
66
+ /** args with the missing fields filled from defaults (a new object; args itself may be frozen) */
67
+ export function withDefaults(defaults, args) {
68
+ if (!defaults) return args;
69
+ const out = { ...args };
70
+ for (const k in defaults) if (out[k] === undefined) out[k] = defaults[k];
71
+ return out;
72
+ }
73
+
74
+ /** Shape as plain data for engine.catalog() and the dev bridge: functions and undefined fields left out */
75
+ export function schemaInfo(shape) {
76
+ if (!shape) return null;
77
+ const out = {};
78
+ for (const key in shape) {
79
+ const s = shape[key], o = { type: s.type };
80
+ if (s.optional) o.optional = true;
81
+ for (const f of ['default', 'min', 'max', 'values', 'desc']) if (s[f] !== undefined && typeof s[f] !== 'function') o[f] = s[f];
82
+ out[key] = o;
83
+ }
84
+ return out;
85
+ }
86
+
87
+ /**
88
+ * Module options read through a params schema: unknown keys and wrong types throw (with the fix), defaults are filled in.
89
+ * Put the schema on the module definition too (`params`, `options`), so engine.catalog(name) shows every option, its default and the value in use.
90
+ * @param {string} where who reads them, for the error text (the module name)
91
+ * @param {Record<string, string | { type: string, default?: any, min?: number, max?: number, values?: any[], desc?: string, optional?: boolean }>} schema
92
+ * @param {object} [opts] what the game passed
93
+ * @returns {object} opts with defaults filled in
94
+ * @example
95
+ * const PARAMS = { radius: { type: 'number', default: 2, min: 0, desc: 'pickup reach in m' }, sound: 'string?' };
96
+ * export const magnet = (opts) => {
97
+ * const o = readParams('magnet', PARAMS, opts);
98
+ * return { name: 'magnet', params: PARAMS, options: o, install(e) { return { radius: o.radius }; } };
99
+ * };
100
+ */
101
+ export function readParams(where, schema, opts = {}) {
102
+ const shape = parseSchema(where, schema), err = msg => codedError('module-params', msg);
103
+ const out = withDefaults(defaultsOf(shape), opts ?? {}); // checked in every build: it runs once per factory call, and a wrong option is a bug anywhere
104
+ const keys = Object.keys(shape);
105
+ for (const key of Object.keys(out)) if (!shape[key]) {
106
+ const msg = unknownOptionText(where, key, keys); // one rule with checkOptions (validate.js)
107
+ if (DEV) throw err(msg); // an option typo: dev throws, a release build warns once and ignores it (decision 2026-11-01), so a shipped game never dies on a typo
108
+ warnOnce(coded('module-params', msg));
109
+ }
110
+ for (const key of keys) {
111
+ const v = out[key];
112
+ if (v === undefined) { if (!shape[key].optional) throw err(fmt(STRINGS.wrong, { where, key, why: 'is required' })); continue; }
113
+ const why = whyBad(shape[key], v);
114
+ if (why) throw err(fmt(STRINGS.wrong, { where, key, why }));
115
+ }
116
+ return out;
117
+ }
118
+
119
+ /**
120
+ * Schema for a module whose options are a key list (and maybe a defaults object): every key is `any` (nothing about the value is checked
121
+ * beyond the spelling of the key), and a key present in `defaults` shows that default in engine.catalog(). Why `any`: these modules' options
122
+ * accept several shapes (number | [x, z], preset name | object), and their own code already checks the values; the schema is for the key
123
+ * list, the catalog and R06. Pass `specs` ({ key: 'int?' | { type, ... } }) to give a key a real type; it wins over the generic one.
124
+ * @param {string[]} keys
125
+ * @param {Record<string, any>} [defaults] defaults shown in the catalog (not applied: the module's own code still does that)
126
+ * @param {Record<string, any>} [specs]
127
+ */
128
+ export function keysSchema(keys, defaults = {}, specs = {}) {
129
+ const out = {};
130
+ for (const k of keys) out[k] = specs[k] ?? (defaults[k] !== undefined ? { type: 'any', default: defaults[k] } : 'any?');
131
+ return out;
132
+ }
@@ -0,0 +1,22 @@
1
+ // The ONE list of names renamed in 0.2: plain data with no imports (errorHints.js re-exports it for the stubs; rule R39 reads it through 'threedog/error-hints').
2
+ /**
3
+ * The ONE list of names renamed in 0.2 (recipes/52-look.md "Renamed in 0.2"): key -> { old call, new call, find = a regex source that spots a
4
+ * use of the old name in source text }. The throwing stubs read `old` / `now` through renamed(key); rule R39 reads `find` to keep the old names out of the repo.
5
+ * `find: null` = no safe text pattern (the old name is a field name shared with unrelated objects).
6
+ * @type {Record<string, { old: string, now: string, find: string | null }>}
7
+ */
8
+ export const RENAMED = {
9
+ setExposure: { old: 'engine.setExposure(v)', now: 'engine.look.tone.set({ exposure: v })', find: '\\bsetExposure\\b' },
10
+ setToneMapping: { old: 'engine.setToneMapping(kind)', now: "engine.look.tone.set({ mapping: 'aces' })", find: '\\bsetToneMapping\\b' },
11
+ setEnvironment: { old: 'engine.sky.setEnvironment(o)', now: "engine.look.env.replace('sky') then engine.look.env.set({ intensity, rotation }); engine.look.env.replace(false) turns it off", find: '\\bsetEnvironment\\b' },
12
+ setShadow: { old: 'engine.sky.setShadow(o)', now: 'engine.look.shadow.set(o)', find: '\\bsetShadow\\b' },
13
+ weatherDefine: { old: 'engine.weather.define(field, spec)', now: 'engine.look.weather.replace({ [field]: spec })', find: '\\bweather\\??\\.define\\b' },
14
+ postAdd: { old: 'engine.post.add(effect)', now: 'engine.look.post.add(effect, { owner }) for one pass (returns { remove() }), patch(name, { glsl }) for a color effect, or replace([...effects]) for the whole chain', find: '(?<!look\\.)\\bpost\\??\\.add\\b' },
15
+ postEnable: { old: 'engine.post.enable(name, on)', now: "engine.look.post.set({ 'bloom.enabled': on }); MSAA: engine.post.setAntialias(on)", find: '\\bpost\\??\\.enable\\b' },
16
+ postHandle: { old: 'engine.post.get(name).set / .enable / .remove', now: "engine.look.post.set({ 'bloom.strength': 0.6 }); read with engine.post.get(name)", find: '\\bpost\\??\\.get\\([^)]*\\)\\??\\.(set|enable|remove)\\b' },
17
+ lookClouds: { old: 'engine.look.clouds', now: 'engine.look.cloudShadow', find: '\\blook\\.clouds\\b' },
18
+ cameraOverride: { old: 'engine.cameraOverride = {...}', now: "const cam = engine.takeCamera('owner', { focus }); cam.remove() releases it", find: '\\bcameraOverride\\s*=(?!=)' },
19
+ viewsPos: { old: "views.define(name, { pos })", now: 'views.define(name, { position: [x, y, z] })', find: null },
20
+ characterBody: { old: 'style.character.create / .model / .colors (a character body or tint from the style pack)', now: "character bodies are assets: createPlayer({ model: 'yourBody' }) (a generator from an asset pack via engine.assets.manifest(yourAssets)), any GLB asset name, or { rig } for a ready body; part colors are the style's material roles skin / cloth / trousers / hair, or { colors } per character", find: '\\bstyle\\.character\\??\\.(create|model|colors)\\b|\\bcharacter:\\s*\\{[^}]*\\b(create|colors):' },
21
+ reason: { old: 'result.reason (ops.run / can / undo failures), ops.recent() / catalog(op).last / net:result .reason', now: 'result.code (the same name in history, catalog and net:result)', find: null },
22
+ };
package/core/saveApply.js CHANGED
@@ -113,8 +113,8 @@ export function loadSlot(s, slot, base) {
113
113
  export async function afterLoad(e) {
114
114
  const hooks = [...e.modules.values()].filter(m => m.afterLoad);
115
115
  if (!hooks.length) return;
116
- e.freeze('load');
117
- try { await Promise.all(hooks.map(m => m.afterLoad(e))); } finally { e.unfreeze('load'); }
116
+ e.freeze('threedog:load'); // a namespaced owner: a game's own freeze('load') must not be released by (or release) the engine's
117
+ try { await Promise.all(hooks.map(m => m.afterLoad(e))); } finally { e.unfreeze('threedog:load'); }
118
118
  }
119
119
 
120
120
  /** Collect every part: { data, failed: [[key, error]] }. Parts of the loaded save that no module owns are carried along. */
@@ -2,32 +2,12 @@
2
2
  // tone mapping and exposure.
3
3
  // add registers each root in the thing registry (things.js) so engine.thing / hit.thing can say what it is and what a save keeps; engine.scene.add
4
4
  // stays the plain three.js way in, with no registration.
5
- import * as THREE from 'three';
6
5
  import { DEV } from './validate.js';
7
- import { codedError } from './errorHints.js';
6
+ import { codedError, renamed } from './errorHints.js';
8
7
  import { thing } from './thingOps.js';
9
- import { recordThing } from './Inspect.js';
8
+ import { TONE, exposureDriver } from './look/coreParts.js';
10
9
 
11
- /** style.toneMapping names -> three constants */
12
- export const TONE = { aces: THREE.ACESFilmicToneMapping, agx: THREE.AgXToneMapping, neutral: THREE.NeutralToneMapping, none: THREE.NoToneMapping };
13
-
14
- /**
15
- * Exposure over the day: [[time 0-1, exposure], ...] sorted by time, wrapping across midnight (after the last row it blends back to the first),
16
- * or (sky) => number. Returns the per-frame function, null for a plain number (set once)
17
- */
18
- function exposureDriver(v) {
19
- if (typeof v === 'number') return null;
20
- if (typeof v === 'function') return v;
21
- const ok = Array.isArray(v) && v.length > 0 && v.every((k, i) => Array.isArray(k) && typeof k[0] === 'number' && typeof k[1] === 'number' && k[0] >= 0 && k[0] <= 1 && (i === 0 || k[0] > v[i - 1][0]));
22
- if (!ok) throw new Error(`exposure must be a number, [[time 0-1, exposure], ...] sorted by time (e.g. [[0, 1.6], [0.5, 1], [0.8, 1.3]]) or (sky) => number; got ${JSON.stringify(v)}`);
23
- return sky => {
24
- const t = sky.timeOfDay, n = v.length;
25
- let i = -1; for (let k = 0; k < n; k++) if (v[k][0] <= t) i = k;
26
- const a = v[i < 0 ? n - 1 : i], b = v[(i + 1) % n]; // before the first row or after the last: the segment across midnight
27
- const span = (b[0] - a[0] + 1) % 1 || 1, f = ((t - a[0] + 1) % 1) / span;
28
- return a[1] + (b[1] - a[1]) * f;
29
- };
30
- }
10
+ export { TONE } from './look/coreParts.js'; // style.toneMapping names -> three constants (kept here for older imports)
31
11
 
32
12
  /** A short stack for "added at main.js:50" (dev): 4 frames are enough (this, add, its caller) and keep the cost low; it is formatted only when read */
33
13
  function captureStack() {
@@ -51,7 +31,7 @@ export const sceneMethods = {
51
31
  if (opts?.id != null && objs.length > 1) throw codedError('thing-id', `engine.add(a, b, …, { id: '${opts.id}' }): an id names one object; add the others in their own call`);
52
32
  const T = this._things, stack = DEV && !opts?.owner && T.wantStack() ? captureStack() : null;
53
33
  if (DEV && opts?.owner !== 'world') for (const o of objs) {
54
- const rid = this.world?.idOf(o);
34
+ const rid = this._things.idOf(o);
55
35
  if (rid) throw codedError('thing-owned', `engine.add(): this object is the model of world record '${rid}' (world builds, places and tears it down). Change the record instead: ops.run('thing.set', { id: '${rid}', position }) or world.set / world.move`);
56
36
  }
57
37
  this.scene.add(...objs);
@@ -67,7 +47,7 @@ export const sceneMethods = {
67
47
  * @param {string | import('three').Object3D} idOrObj
68
48
  * @returns {import('../types/core').Thing}
69
49
  */
70
- thing(idOrObj) { return thing(this, idOrObj, recordThing); },
50
+ thing(idOrObj) { return thing(this, idOrObj); },
71
51
  /** @internal Dev: a module found two systems managing one object; listed in describe().scene.conflicts and warned once (code thing-owned) */
72
52
  thingConflict(text) { this._things.conflict(text); },
73
53
  /** Detach from the parent only (no GPU release; use when you will add it back). Use remove for objects you are done with */
@@ -113,13 +93,8 @@ export const sceneMethods = {
113
93
  if (this.scene.fog) { this.scene.fog.far = d; this.scene.fog.near = d * 0.3; }
114
94
  this.camera.far = d + 150; this.camera.updateProjectionMatrix();
115
95
  },
116
- setToneMapping(kind) {
117
- if (!(kind in TONE)) throw new Error(`engine.setToneMapping('${kind}'): use ${Object.keys(TONE).map(k => `'${k}'`).join(' | ')}`);
118
- this.renderer.toneMapping = TONE[kind]; // three recompiles each material on its next draw (tone mapping is part of its program)
119
- },
120
- setExposure(v) {
121
- // keyframes / a function become exposureDriver, which a time-of-day module (sky) evaluates each frame; core knows no time of day
122
- this.exposureDriver = exposureDriver(v);
123
- if (typeof v === 'number') this.renderer.toneMappingExposure = v;
124
- }
96
+ /** Renamed in 0.2: throws and names the new call, engine.look.tone.set({ mapping }). @param {string} _kind @returns {never} */
97
+ setToneMapping(_kind) { return renamed('setToneMapping'); },
98
+ /** Renamed in 0.2: throws and names the new call, engine.look.tone.set({ exposure }). @param {any} _v @returns {never} */
99
+ setExposure(_v) { return renamed('setExposure'); }
125
100
  };
@@ -0,0 +1,73 @@
1
+ // Engine services: the objects every engine owns besides rendering (events, i18n, saves, input, audio, assets, clock, ops, jobs, streaming...).
2
+ // Split out of the Engine constructor so it stays readable; the order below matters (later services read earlier ones), do not reorder.
3
+ import { Events } from './Events.js';
4
+ import { I18n } from './I18n.js';
5
+ import { Saves } from './Saves.js';
6
+ import { Session } from './session.js';
7
+ import { Input } from './Input.js';
8
+ import { Audio } from './Audio.js';
9
+ import { Assets } from './Assets.js';
10
+ import { Clock } from './Clock.js';
11
+ import { Vars } from './Vars.js';
12
+ import { Budget } from './Budget.js';
13
+ import { Rays } from './Rays.js';
14
+ import { Random } from './Random.js';
15
+ import { UrlState } from './UrlState.js';
16
+ import { Jobs } from './Jobs.js';
17
+ import { Threads } from './Threads.js';
18
+ import { Commits } from './Commits.js';
19
+ import { Ops } from './Ops.js';
20
+ import { Views } from './Views.js';
21
+ import { Stream } from './Stream.js';
22
+ import { Batching } from './Batching.js';
23
+ import { claims } from './claims.js';
24
+ import { DebugOverrides } from './DebugOverrides.js';
25
+ import { describeApi } from './Describe.js';
26
+ import { reportListenerError } from './errors.js';
27
+ import { defineSkipOp } from './skip.js';
28
+ import { installThings } from './thingOps.js';
29
+
30
+ /**
31
+ * Create the engine services on `engine` (called once from the Engine constructor, after the renderer, scene and uniforms exist).
32
+ * @param engine the engine under construction
33
+ * @param o the createEngine options these services read, already defaulted by the constructor
34
+ */
35
+ export function createServices(engine, { canvas, validate, locale, strings, saveKey, joystick, bindings, padBindings, audio, decoders, budget, seed, headless, urlState, threads, batching }) {
36
+ engine.events = new Events({ check: import.meta.env?.DEV && validate !== false, // event-name spelling check runs in development only
37
+ onError: (name, err) => reportListenerError(engine, name, err), now: () => engine.tick }); // listener errors are handled by severity (errors.js)
38
+ engine.i18n = new I18n(engine, { locale, strings });
39
+ engine.saves = new Saves(engine, { prefix: saveKey + '-' });
40
+ engine.session = new Session(engine); // new game / continue / back to title from a clean slate (session.js)
41
+ engine.input = new Input(engine, canvas, { joystick, bindings, padBindings });
42
+ engine.events.on('ui:open', id => engine.openWindows.add(id));
43
+ engine.events.on('ui:close', id => engine.openWindows.delete(id));
44
+ engine.audio = new Audio(engine, audio);
45
+ engine.decoders = decoders;
46
+ engine.assets = new Assets(engine);
47
+ engine.clock = new Clock(engine); // game clock (game seconds, timers)
48
+ engine.vars = new Vars(engine); // story flags and counters
49
+ engine.budget = new Budget(engine); // performance budget (default off)
50
+ if (budget) engine.budget.enable(budget);
51
+ engine.rays = new Rays(engine); // ray registry: engine.raycast / pick
52
+ Object.assign(engine, describeApi(engine)); // describe / describeText / inspect / explain, see Describe.js
53
+ engine.random = new Random(seed ?? (headless ? 1 : Date.now())); // wall-clock: differs per run when no seed is given
54
+ engine.saves.register('random', { atomic: true, save: () => engine.random.toJSON(), load: d => engine.random.fromJSON(d) });
55
+ engine._urlState = new UrlState(engine, { fromUrl: urlState });
56
+ // who holds the engine still, one claims() each (claims.js: same owner rules for all, owners() in describe); pause / freeze / takeCamera in holds.js
57
+ const now = () => engine.elapsed ?? 0;
58
+ engine._freezers = claims({ what: 'engine.freeze', now }); // who froze gameplay
59
+ engine._pausers = claims({ what: 'engine.pause', now }); // who paused the loop; it resumes only when empty
60
+ engine._cameraClaims = claims({ what: 'engine.takeCamera', now }); // who holds the camera; the latest is in charge (cameraOverride)
61
+ engine.tick = 0; // fixed-step count (the gameplay timeline: commits, event history and input records use it; stops while frozen)
62
+ engine.commits = new Commits(engine); // background results that affect gameplay take effect on a fixed tick (see Commits.js)
63
+ engine.ops = new Ops(engine); // one entry point for actions (define / run / can / list / recent), see Ops.js
64
+ engine.views = new Views(engine); // named fixed camera views for repeatable screenshots (Views.js)
65
+ defineSkipOp(engine); // 'time.skip', behind engine.skip (skip.js)
66
+ installThings(engine); // engine.add registry, thing.set / remove, 'scene' save part
67
+ engine.debug = new DebugOverrides(engine); // diagnostic overrides and view modes, all core; the debug() panel module adds engine.debug.panel (DebugOverrides.js)
68
+ engine.jobs = new Jobs(engine); // frame-spread job scheduler
69
+ engine.threads = new Threads(threads); // worker pool (see Threads.js); workers start only when a lane is used
70
+ // spatial stream-in and the stream sources (where the world is loaded: stream, models, terrain, colliders read them)
71
+ engine.stream = new Stream(engine);
72
+ engine.batching = new Batching(engine, batching); // repeated static models drawn as InstancedMesh batches (Batching.js)
73
+ }
package/core/startup.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // A critical asset (manifest critical: true) that fails stops start() with the reason instead of starting a broken game.
4
4
 
5
5
  import { reportError } from './errors.js';
6
+ import { catalogSnap, catalogClaim } from './catalog.js';
6
7
  import { codedError } from './errorHints.js';
7
8
  import { touchStart } from './inputTouch.js';
8
9
  import { Loading, failureText } from './Loading.js';
@@ -47,7 +48,8 @@ export const startupMethods = {
47
48
  ls?.update({ progress: 0.1, text: this.t('common.preparing', { name: this.moduleName(m) }) });
48
49
  const t = performance.now(); // measure
49
50
  this._setModState(m, 'initializing'); // no hooks until init succeeded (modules.js)
50
- try { await m.init(this); L._done(task); this._setModState(m, 'running'); }
51
+ const snap = catalogSnap(this); // what init registers belongs to this module in engine.catalog()
52
+ try { await m.init(this); catalogClaim(this, m.name, snap); L._done(task); this._setModState(m, 'running'); }
51
53
  catch (e) {
52
54
  L._fail(task, e); this._setModState(m, 'failed');
53
55
  // a critical module stops start() with the reason (below); any other failure is reported by severity and start() goes on
@@ -1,6 +1,6 @@
1
- // A style built from parts: createEngine({ style: [lowpoly, { sky: mySky }, toonMaterials] }) merges the parts left to right into engine.style.
1
+ // A style built from parts: createEngine({ style: [basePack, { sky: mySky }, toonMaterials] }) merges the parts left to right into engine.style.
2
2
  // Why parts and not one object: a look is often borrowed piecemeal (one pack's materials, another's sky, the game's own UI colors), and a
3
- // spread `{ ...lowpoly, sky }` loses lowpoly's other sky fields; a deep merge keeps them. Rules (one place; recipes/09-style-pack.md "Composing"):
3
+ // spread `{ ...basePack, sky }` loses basePack's other sky fields; a deep merge keeps them. Rules (one place; recipes/09-style-pack.md "Composing"):
4
4
  // - parts merge left to right, later wins; nested arrays are flattened (a pack may itself be a list of parts); null / undefined / false parts are skipped
5
5
  // - plain objects ({ } literals) merge key by key, recursively: { sky: { sunSize: 600 } } changes only sunSize
6
6
  // - anything else replaces whole: arrays (sky.keyframes, post, terrain.steep), functions, numbers, strings, three.js objects and class instances
@@ -10,8 +10,8 @@
10
10
  // Zero cost when unused: a single object (not a list) is used as it is, engine.style === that object.
11
11
  // Looks only: a style never holds world state (water level, sea, terrain shape); checkStyleLooks throws in dev.
12
12
  import { DEV } from './validate.js';
13
+ import { isPlainObject as plain, getPath } from './util.js';
13
14
 
14
- const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v) && [Object.prototype, null].includes(Object.getPrototypeOf(v));
15
15
 
16
16
  // A post edit is a function carrying this mark: mergeInto calls it with the list built so far instead of replacing the list
17
17
  const EDIT = Symbol('threedog.postEdit');
@@ -20,7 +20,7 @@ const edit = fn => ({ post: Object.assign(fn, { [EDIT]: true }) });
20
20
  /**
21
21
  * A style part that adds post effects to the ones before it (a plain { post: [...] } would replace the whole list). An effect with the same name as
22
22
  * an earlier one replaces it in place; names are the effects' own ('bloom', 'ao', 'outline', or your own).
23
- * @example createEngine({ style: [lowpoly, postAdd(myGrain, bloom({ strength: 0.6 }))] }) // grain added, lowpoly's bloom swapped for yours
23
+ * @example createEngine({ style: [basePack, postAdd(myGrain, bloom({ strength: 0.6 }))] }) // grain added, the pack's bloom swapped for yours
24
24
  * @param {...import('../render/PostFX.js').PostEffect} effects
25
25
  * @returns {{ post: any }}
26
26
  */
@@ -34,7 +34,7 @@ export function postAdd(...effects) {
34
34
 
35
35
  /**
36
36
  * A style part that removes post effects by name from the ones before it.
37
- * @example createEngine({ style: [lowpoly, postRemove('ao', 'outline')] })
37
+ * @example createEngine({ style: [basePack, postRemove('ao', 'outline')] })
38
38
  * @param {...string} names
39
39
  * @returns {{ post: any }}
40
40
  */
@@ -83,7 +83,7 @@ const WORLD = [
83
83
  ];
84
84
  function checkStyleLooks(style) {
85
85
  for (const [path, isWorld, where] of WORLD) {
86
- const obj = path.split('.').reduce((o, k) => o?.[k], style);
86
+ const obj = getPath(style, path);
87
87
  if (!obj || typeof obj !== 'object') continue;
88
88
  for (const k of Object.keys(obj))
89
89
  if (isWorld(k)) throw new Error(`style.${path}.${k} is world state, not a look: swapping the style would change the map or the rules. Set it where the world is made: ${where}`);
@@ -91,6 +91,8 @@ function checkStyleLooks(style) {
91
91
  }
92
92
 
93
93
  // Dev warning when createEngine gets no style pack (shown once from Engine.js)
94
- export const NO_STYLE = 'createEngine(): no style pack given, so everything is a neutral gray placeholder: plain lights (one white hemisphere + one neutral '
95
- + 'directional light, no shadows, no tone mapping), gray background, ground, capsule characters and box props. This is not a look. '
96
- + "Pass one: import lowpoly from '@threedog/style-lowpoly'; createEngine({ canvas, style: lowpoly }) (or your own pack, recipes/09-style-pack.md)";
94
+ export const NO_STYLE = 'createEngine(): the style pack is missing or empty, so everything is a neutral gray placeholder: plain lights (one white hemisphere + one neutral '
95
+ + 'directional light, no shadows, no tone mapping), gray background, ground, capsule characters and box props. This is not a look and not an error. '
96
+ + 'Fill your own pack (style/index.js in a new game; recipes/09-style-pack.md, recipes/52-look.md) or pass a published one';
97
+ /** true when createEngine got no style, or only empty parts ({} / [{}, {}]): the game has no look yet */
98
+ export const styleIsEmpty = st => !st || (Array.isArray(st) ? st.every(styleIsEmpty) : typeof st === 'object' && Object.keys(st).every(k => k === 'name')); // a name alone (the new-game empty pack) is still empty
@@ -0,0 +1,68 @@
1
+ // engine.thing(id).explain(): everything known about one id in one plain object (JSON-able, same for the CLI `threedog thing <id>`, MCP and tests).
2
+ // Why one object: an AI asked "why is this crate here, blocking me, and how do I change it?" otherwise joins thing(), world.origin, material info, the
3
+ // template, collision settings and the op list by hand. Each part reads an existing source; nothing here is stored or changes any state.
4
+ import { materialInfo } from './MaterialInfo.js';
5
+
6
+ const MAT_MAX = 8;
7
+ const safe = f => { try { return f(); } catch { return null; } };
8
+
9
+ /** Unique materials under obj with role / name / where the spec came from */
10
+ function materialsOf(obj) {
11
+ const seen = new Set(), out = [];
12
+ obj?.traverse?.(o => {
13
+ for (const m of [o.material].flat()) {
14
+ if (!m || seen.has(m)) continue;
15
+ seen.add(m);
16
+ if (out.length < MAT_MAX) { const i = materialInfo(m, o); out.push({ role: i.role, name: m.name || null, from: i.from, keys: i.keys, type: i.type, color: i.color, mesh: o.name || null }); }
17
+ }
18
+ });
19
+ if (seen.size > MAT_MAX) out.push({ more: seen.size - MAT_MAX });
20
+ return out;
21
+ }
22
+
23
+ /** Ops whose definition says (targets) they are for this id, kind or template; thing.set / thing.remove target '*' */
24
+ function opsFor(e, t) {
25
+ const keys = new Set([t.id, t.kind, t.template].filter(Boolean));
26
+ return [...e.ops.defs.values()].filter(d => d.targets != null && [d.targets].flat().some(x => x === '*' || keys.has(x)))
27
+ .map(d => ({ op: d.name, desc: d.desc ?? null, args: d.args ?? null }));
28
+ }
29
+
30
+ /** What core knows about how the thing takes part in movement / picking: the size of its model. Template and record rules come from a module's explainer (below) */
31
+ function rulesOf(e, t, obj) {
32
+ const out = {};
33
+ if (obj) {
34
+ const T = e.THREE, size = new T.Box3().setFromObject(obj).getSize(new T.Vector3());
35
+ if (isFinite(size.y)) out.height = Math.round(size.y * 100) / 100;
36
+ }
37
+ return out;
38
+ }
39
+
40
+ /**
41
+ * @param {any} e @param {any} t the thing (engine.thing result) @internal
42
+ */
43
+ export function explainThing(e, t) {
44
+ const obj = t.object, T = e._things;
45
+ const over = e.debug.overridesOn(obj);
46
+ const state = obj ? { position: obj.position.toArray().map(v => Math.round(v * 100) / 100), visible: obj.visible, scale: obj.scale.toArray() } : {};
47
+ const saved = { tier: t.saved, keeps: t.keeps, loses: t.loses, ...(t.saved === 'code' && { overridden: T.over.has(t.id), removed: T.removed.has(t.id) }) };
48
+ const out = {
49
+ id: t.id, kind: t.kind, owner: t.owner,
50
+ definition: { at: t.definedAt ?? t.at ?? null, template: t.template ?? null, templateAt: t.templateAt ?? null, ...(t.level && { level: t.level, node: t.node }), ...(t.spawned && { spawned: t.spawned }) },
51
+ model: t.model ?? null,
52
+ materials: materialsOf(obj),
53
+ state,
54
+ rules: rulesOf(e, t, obj),
55
+ ops: opsFor(e, t),
56
+ saved,
57
+ change: {
58
+ runtime: `game state changes through ops: engine.ops.run('<op>', { id: '${t.id}' }); thing.set / thing.remove move, show or remove it (undoable)`,
59
+ permanent: t.edit ?? 'no source known: edit the code or content line that creates it, then reload',
60
+ diagnostic: `engine.debug.override(owner, '${t.id}', { visible, material: 'flat' | 'wire' }) changes the screen only (never saved); engine.debug.clear(owner) removes it`,
61
+ },
62
+ ...(over.length && { overrides: over, warning: 'diagnostic overrides are active on this thing: what is drawn is not its real state' }),
63
+ };
64
+ // Explain contributions (arch #6): a module that owns records or templates adds to the object with e._things.explainers.push((e, t, out) => { ... }),
65
+ // so core never reads their shapes. A throwing explainer is skipped: explain is a diagnostic and must not fail because of one part.
66
+ for (const f of T.explainers) safe(() => f(e, t, out));
67
+ return out;
68
+ }