threedog 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/core/Animator.js +1 -0
  2. package/core/Assets.js +16 -0
  3. package/core/DebugOverrides.js +143 -0
  4. package/core/Describe.js +14 -3
  5. package/core/Engine.js +32 -69
  6. package/core/Events.js +59 -1
  7. package/core/I18n.js +2 -2
  8. package/core/Inspect.js +12 -32
  9. package/core/InspectScene.js +7 -3
  10. package/core/MaterialInfo.js +32 -0
  11. package/core/Ops.js +43 -59
  12. package/core/Saves.js +5 -4
  13. package/core/UrlState.js +3 -2
  14. package/core/Vars.js +1 -0
  15. package/core/Views.js +49 -0
  16. package/core/actor.js +2 -2
  17. package/core/assetReport.js +83 -0
  18. package/core/catalog.js +169 -0
  19. package/core/checks.js +67 -0
  20. package/core/claims.js +51 -0
  21. package/core/debugView.js +76 -0
  22. package/core/describeRender.js +45 -0
  23. package/core/describeText.js +11 -4
  24. package/core/errorCodes.js +33 -0
  25. package/core/errorHints.js +6 -1
  26. package/core/holds.js +106 -0
  27. package/core/lifecycle.js +1 -0
  28. package/core/lightWatch.js +23 -3
  29. package/core/look/coreParts.js +112 -0
  30. package/core/look/layers.js +136 -0
  31. package/core/look/part.js +173 -0
  32. package/core/look/report.js +79 -0
  33. package/core/look/write.js +86 -0
  34. package/core/loop.js +15 -14
  35. package/core/modules.js +19 -5
  36. package/core/opsAtomic.js +31 -0
  37. package/core/opsCheck.js +25 -14
  38. package/core/opsFail.js +20 -0
  39. package/core/opsHistory.js +6 -6
  40. package/core/opsRun.js +77 -0
  41. package/core/params.js +132 -0
  42. package/core/renamed.js +21 -0
  43. package/core/saveApply.js +2 -2
  44. package/core/sceneMethods.js +9 -34
  45. package/core/services.js +73 -0
  46. package/core/startup.js +3 -1
  47. package/core/styleParts.js +2 -2
  48. package/core/thingExplain.js +68 -0
  49. package/core/thingOps.js +35 -24
  50. package/core/things.js +15 -1
  51. package/core/util.js +11 -0
  52. package/core/validate.js +23 -7
  53. package/docs/AI.md +83 -109
  54. package/docs/API.md +7 -8
  55. package/docs/CODEMAP.md +63 -51
  56. package/docs/COMMANDS.md +17 -5
  57. package/docs/CONVENTIONS.md +17 -6
  58. package/docs/THREE.md +3 -3
  59. package/docs/api/assets.md +2 -0
  60. package/docs/api/characters.md +2 -0
  61. package/docs/api/collision.md +4 -0
  62. package/docs/api/content.md +1 -0
  63. package/docs/api/engine.md +20 -11
  64. package/docs/api/events.md +5 -1
  65. package/docs/api/post.md +5 -4
  66. package/docs/api/saves.md +2 -1
  67. package/docs/api/sky.md +3 -3
  68. package/docs/api/style.md +3 -3
  69. package/docs/api/tools.md +2 -0
  70. package/docs/api/weather.md +1 -1
  71. package/docs/recipes/02-npc.md +16 -0
  72. package/docs/recipes/03-items-pickups.md +1 -1
  73. package/docs/recipes/06-clock-events.md +13 -0
  74. package/docs/recipes/07-flow-scenes-pause.md +4 -0
  75. package/docs/recipes/08-weather-sky.md +1 -1
  76. package/docs/recipes/09-style-pack.md +5 -5
  77. package/docs/recipes/12-navmesh.md +22 -0
  78. package/docs/recipes/13-animation.md +3 -0
  79. package/docs/recipes/15-perf.md +1 -1
  80. package/docs/recipes/16-dev-bridge.md +51 -17
  81. package/docs/recipes/21-camera.md +51 -2
  82. package/docs/recipes/23-ops.md +45 -9
  83. package/docs/recipes/27-net.md +1 -1
  84. package/docs/recipes/29-grid.md +1 -1
  85. package/docs/recipes/34-environment-lighting.md +9 -8
  86. package/docs/recipes/38-environment-look-hooks.md +8 -6
  87. package/docs/recipes/40-scene.md +29 -0
  88. package/docs/recipes/41-thing-registry.md +29 -0
  89. package/docs/recipes/43-shader-patches-surface-looks.md +2 -0
  90. package/docs/recipes/44-water-weather-look-hooks.md +6 -4
  91. package/docs/recipes/45-cascaded-shadows.md +1 -1
  92. package/docs/recipes/46-blender-art-route.md +22 -0
  93. package/docs/recipes/48-make-material.md +70 -0
  94. package/docs/recipes/49-game-module-contract.md +71 -0
  95. package/docs/recipes/50-own-renderer.md +12 -0
  96. package/docs/recipes/51-capability-catalog.md +63 -0
  97. package/docs/recipes/52-look.md +108 -0
  98. package/examples/action/GAMEMAP.md +5 -5
  99. package/examples/action/content/index.js +2 -1
  100. package/examples/action/content/views.js +6 -0
  101. package/examples/sheepisland/GAMEMAP.md +2 -3
  102. package/examples/styletest/GAMEMAP.md +3 -3
  103. package/examples/styletest/main.js +1 -1
  104. package/examples/styletest/panel.js +3 -3
  105. package/examples/world/GAMEMAP.md +3 -3
  106. package/index.d.ts +27 -0
  107. package/index.js +3 -1
  108. package/llms.txt +5 -0
  109. package/modules/ambience/Ambience.js +5 -2
  110. package/modules/camera/FirstPersonCamera.js +3 -5
  111. package/modules/camera/FixedCamera.js +19 -12
  112. package/modules/camera/FollowCamera.js +14 -8
  113. package/modules/camera/RtsCamera.js +3 -5
  114. package/modules/camera/common.js +40 -10
  115. package/modules/camera/index.js +1 -1
  116. package/modules/camera/projection.js +34 -0
  117. package/modules/characters/Character.js +29 -17
  118. package/modules/characters/astar.js +14 -7
  119. package/modules/characters/index.js +6 -3
  120. package/modules/characters/movers/simple.js +6 -1
  121. package/modules/characters/npcSim.js +8 -2
  122. package/modules/characters/pathAsync.js +12 -6
  123. package/modules/characters/pathJob.js +2 -1
  124. package/modules/characters/proceduralRig.js +5 -1
  125. package/modules/characters/useModel.js +22 -0
  126. package/modules/characters/walkTo.js +58 -0
  127. package/modules/collision/Collision.js +102 -4
  128. package/modules/content/explain.js +13 -0
  129. package/modules/content/index.js +2 -0
  130. package/modules/content/loader.js +3 -0
  131. package/modules/content/rules.js +1 -0
  132. package/modules/debug/DebugPanel.js +11 -5
  133. package/modules/entities/Entities.js +6 -2
  134. package/modules/flow/index.js +5 -2
  135. package/modules/gameplay/Dialogue.js +5 -2
  136. package/modules/gameplay/Interactions.js +12 -2
  137. package/modules/gameplay/Inventory.js +21 -11
  138. package/modules/gameplay/Quests.js +13 -3
  139. package/modules/gameplay/pickups.js +5 -3
  140. package/modules/grid/Layer.js +1 -1
  141. package/modules/grid/index.js +1 -1
  142. package/modules/grid/tiles.js +9 -5
  143. package/modules/hlod/index.js +5 -2
  144. package/modules/hud/index.js +5 -2
  145. package/modules/level/index.js +5 -3
  146. package/modules/lights/index.js +5 -2
  147. package/modules/music/Music.js +6 -2
  148. package/modules/nav/index.js +5 -3
  149. package/modules/net/Client.js +4 -3
  150. package/modules/net/Host.js +2 -2
  151. package/modules/net/index.js +5 -3
  152. package/modules/particles/Particles.js +1 -1
  153. package/modules/photo/Photo.js +10 -7
  154. package/modules/rigid/RigidBodies.js +5 -2
  155. package/modules/settings/Settings.js +6 -3
  156. package/modules/settings/apply.js +2 -1
  157. package/modules/sky/Sky.js +21 -19
  158. package/modules/sky/cascades.js +6 -6
  159. package/modules/sky/domeLayers.js +1 -1
  160. package/modules/sky/environment.js +39 -13
  161. package/modules/sky/fog.js +9 -6
  162. package/modules/sky/frame.js +4 -3
  163. package/modules/sky/look.js +3 -2
  164. package/modules/sky/lookFog.js +80 -0
  165. package/modules/sky/lookShadow.js +50 -0
  166. package/modules/sky/lookSky.js +108 -0
  167. package/modules/sky/shader.js +2 -2
  168. package/modules/sky/shadow.js +4 -10
  169. package/modules/sky/skyModule.js +4 -3
  170. package/modules/terrain/ChunkManager.js +2 -33
  171. package/modules/terrain/chunkLevels.js +40 -0
  172. package/modules/terrain/index.js +10 -2
  173. package/modules/terrain/lookGround.js +61 -0
  174. package/modules/timeline/Timeline.js +7 -3
  175. package/modules/timeline/Tween.js +3 -7
  176. package/modules/timeline/shots.js +6 -4
  177. package/modules/triggers/index.js +9 -2
  178. package/modules/vegetation/Vegetation.js +2 -1
  179. package/modules/vegetation/index.js +6 -3
  180. package/modules/vegetation/lookWind.js +37 -0
  181. package/modules/water/Water.js +19 -3
  182. package/modules/water/look.js +80 -0
  183. package/modules/weather/Weather.js +22 -31
  184. package/modules/weather/look.js +75 -0
  185. package/modules/weather/particles.js +1 -1
  186. package/modules/weather/strings.js +15 -0
  187. package/modules/world/explain.js +11 -0
  188. package/modules/world/index.js +11 -4
  189. package/modules/world/thingSource.js +44 -0
  190. package/package.json +1 -1
  191. package/render/PostFX.js +48 -51
  192. package/render/effects.js +4 -2
  193. package/render/fuse.js +12 -0
  194. package/render/lights.js +4 -2
  195. package/render/lookSurface.js +161 -0
  196. package/render/materials.js +27 -10
  197. package/render/postLook.js +86 -0
  198. package/render/surface.js +3 -1
  199. package/types/core.d.ts +216 -24
  200. package/types/gameplay.d.ts +10 -0
  201. package/types/generated/core/DebugOverrides.d.ts +52 -0
  202. package/types/generated/core/Events.d.ts +43 -0
  203. package/types/generated/core/Ops.d.ts +62 -21
  204. package/types/generated/core/Saves.d.ts +1 -0
  205. package/types/generated/core/Views.d.ts +33 -0
  206. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  207. package/types/generated/modules/grid/Layer.d.ts +1 -0
  208. package/types/generated/modules/sky/Sky.d.ts +10 -17
  209. package/types/generated/modules/weather/Weather.d.ts +5 -15
  210. package/types/generated/render/PostFX.d.ts +20 -23
  211. package/types/generated/render/materials.d.ts +10 -0
  212. package/types/physics.d.ts +8 -0
  213. package/types/style.d.ts +16 -6
  214. package/ui/Parts.js +6 -2
  215. package/ui/UI.js +1 -1
  216. package/ui/defaults.js +1 -1
  217. package/docs/api/debug.md +0 -10
@@ -23,11 +23,11 @@ engine.ops.define('shop.buy', {
23
23
  },
24
24
  offers: (e, ctx) => [{ shop: 'shop-bakery', item: 'bread' }], // optional: arg sets possible now (ops list / dev bridge `ops`)
25
25
  reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold' }, // optional developer notes
26
- // optional: undo(e, args, value, ctx) reverses a finished run; engine.ops.undo('shop.buy', args, r.value) calls it ({ ok: false, reason: 'noUndo' } without one)
26
+ // optional: undo(e, args, value, ctx) reverses a finished run; engine.ops.undo('shop.buy', args, r.value) calls it ({ ok: false, code: 'noUndo', facts: { op } } without one)
27
27
  });
28
28
 
29
29
  const r = engine.ops.run('shop.buy', { shop: 'shop-bakery', item: 'bread' });
30
- // r = { ok: true, value: 1 } or { ok: false, reason: 'noMoney' }
30
+ // r = { ok: true, value: 1 } or { ok: false, code: 'noMoney', facts, nextActions }
31
31
  const { ok } = engine.ops.can('shop.buy', { shop: 'shop-bakery', item: 'bread' }); // ask only: grey out a button
32
32
  ```
33
33
  Rules that keep ops replayable and network-ready:
@@ -37,7 +37,7 @@ Rules that keep ops replayable and network-ready:
37
37
  - **Args are plain data and self-contained**: no three.js objects (pass `[x, y, z]`), and anything not in world data (aim direction, a clicked build
38
38
  position) goes in the args. Pass a fresh object each call; in dev the args are frozen because the history keeps them.
39
39
  - **All "may I" checks live in `can`**, so `run` never stops halfway. A failure always has a reason (camelCase English). Show it to the player through
40
- i18n (`e.t('op.shop.buy.' + r.reason)`); the engine shows nothing itself.
40
+ i18n (`e.t('op.shop.buy.' + r.code)`); the engine shows nothing itself.
41
41
  - An op may call another op inside `run` (logged with `depth`); `can` must not call `run` or change state.
42
42
  - Name ops `noun.verb`. A dot means "asking to do"; events (`noun:action`) mean "already happened". `run` keeps emitting your domain events as before.
43
43
 
@@ -70,11 +70,11 @@ returns `'halted'`.
70
70
 
71
71
  ## 4. Read the log
72
72
  ```js
73
- engine.ops.recent('shop.buy'); // [{ seq, tick, phase, name, args, source, actor, ok, reason, depth, count }] old -> new
73
+ engine.ops.recent('shop.buy'); // [{ seq, tick, phase, name, args, source, actor, ok, code, depth, count }] old -> new
74
74
  engine.ops.list(); // defined ops [{ name, desc, args }]
75
- engine.ops.list({ available: true }); // each offer checked with can [{ name, args, ok, reason }]
75
+ engine.ops.list({ available: true }); // each offer checked with can [{ name, args, ok, code }]
76
76
  ```
77
- Consecutive identical failures (same actor, op and reason, e.g. `cooldown` while the trigger is held) merge into one entry with `count`.
77
+ Consecutive identical failures (same actor, op and code, e.g. `cooldown` while the trigger is held) merge into one entry with `count`.
78
78
  The ring keeps `engine.ops.historySize` entries (256). A save load writes a `(load)` entry: what follows happened in the loaded world.
79
79
  A thrown `run` freezes gameplay in dev / tests and `engine.error` names `ops.run('name')` plus the last 5 ops.
80
80
 
@@ -92,7 +92,7 @@ of each writing method, and wrap writes that are allowed anyway (loading your sa
92
92
  A test runs the op directly instead of walking, pressing keys and waiting for typing:
93
93
  ```js
94
94
  engine.ops.run('shop.buy', { shop: 'shop-bakery', item: 'bread', n: 2 }, { source: 'test' });
95
- // check engine.inventory.count('bread'), and engine.ops.recent('shop.buy').at(-1).reason on failure
95
+ // check engine.inventory.count('bread'), and engine.ops.recent('shop.buy').at(-1).code on failure
96
96
  ```
97
97
  Keep one `press` test per key to prove "key -> op" itself works (the history shows `interaction.use` after `press interact`).
98
98
 
@@ -112,7 +112,7 @@ Put `<workspace>/tests/scenarios/<name>.json` in the engine package or a game; `
112
112
  ```
113
113
  - `state` is `engine.applyState` params; `"pos": "@id"` stands 1 m beside a world record. The page is paused first, so game time moves only in `step`
114
114
  (seconds) and `press`.
115
- - `op` steps run with `source: 'test'` (`actor` optional); `expect` is `"ok"` (default) or the reason. A failure prints the `engine.explain` sentence.
115
+ - `op` steps run with `source: 'test'` (`actor` optional); `expect` is `"ok"` (default) or the failure code. A failure prints the `engine.explain` sentence.
116
116
  - `expect` maps `describe()` paths to values (`nearby[0].name` works; numbers within 0.01; `null` = absent). `snapshot` compares with
117
117
  `tests/snapshots/<name>.describe.json` (`only` / `ignore` / `tolerance`; write it with `threedog test <name> --update-snapshots`).
118
118
  - Before any step runs, every op name and step field is checked; a typo fails with "did you mean". The run stops at the first failed step.
@@ -120,7 +120,7 @@ Put `<workspace>/tests/scenarios/<name>.json` in the engine package or a game; `
120
120
 
121
121
  ## 8. Inspect and explain
122
122
  ```js
123
- engine.inspect(); // { actor: 'player', at, near: [...nearby], ops: [{ op, args, ok, reason?, why? }] }: what is around and possible now
123
+ engine.inspect(); // { actor: 'player', at, near: [...nearby], ops: [{ op, args, ok, code?, why? }] }: what is around and possible now
124
124
  engine.inspect('npc_3'); // the same as another actor; engine.inspect([x, z]) around a spot
125
125
  engine.explain({ op: 'shop.buy', args: { shop: 'bakery', item: 'bread' } }).text;
126
126
  // text: 'shop.buy {...} cannot run now: noMoney (Not enough gold)'; detail: 'last attempt at tick 812 (player, player): noMoney' (+ recent, events)
@@ -129,6 +129,10 @@ engine.explain({ quest: 'first-light' }).text; // 'quest ... waits on step 2/3
129
129
  Other keys come from modules: add `explain: { myKey(e, value, query) { return { ok, text }; } }` to the module definition. Dev bridge: `npx threedog
130
130
  inspect [id | x,z]`, `npx threedog explain op shop.buy shop=bakery item=bread`, `npx threedog explain quest first-light`.
131
131
 
132
+ Why did this event fire? In dev set `engine.events.traceSize = 200` (default 0 = off, no cost). Every emitted event then records its cause: `engine.events.trace('item:add').at(-1)`
133
+ is `{ id, tick, name, parent: 'op:shop.buy#12', chain: ['op:shop.buy#12'] }`; a parent is `ev:<id>` (a handler of that event emitted it) or `op:<name>#<seq>` (the
134
+ op's `run` emitted it, seq is the history seq); `chain` walks up to the root as far as the ring holds.
135
+
132
136
  ## 9. Randomness
133
137
  Gameplay randomness uses `engine.random` (`next / range / int / pick / chance`): it is saved with the game and `createEngine({ seed })` fixes it, so a
134
138
  scenario replays the same. `Math.random` breaks both.
@@ -137,3 +141,35 @@ scenario replays the same. `Math.random` breaks both.
137
141
  The engine repository's `Properties` specs (fast-check, a devDependency) runs random sequences of ops / saves / newGame inside the page in one `ev()` and checks the state rules (item totals kept, a refused op changes nothing, save then load is identical, newGame leaves nothing behind, a failed `engine.use` batch changes nothing).
138
142
  A failure prints the shrunk minimal sequence and the seed. Replay: `FC_SEED=<seed> npm test -- "Properties: random op"`; more cases: `FC_RUNS=300` (default 25). Without fast-check installed the specs skip and say why.
139
143
  To check a new rule, add a step kind to `stepArb` and a check in `pageRun`; turn every found sequence into a fixed regression spec.
144
+
145
+ ## 11. Structured failures, nextFixed, and who paused
146
+ `can` may return a reason string (`'noMoney'`) or a structured failure. Every failed result from `run` / `can` / `undo` has `{ ok: false, code, facts, nextActions }`; a string failure becomes `code = that string`, `facts = {}`, `nextActions = []`, so read `.code` without checking the shape. `engine.inspect()`, `ops.list({ available: true })`, `engine.describe()` actions and `engine.explain({ op })` carry `facts` / `nextActions` too.
147
+ ```js
148
+ engine.ops.define('shop.buy', {
149
+ can: (e, a, ctx) => gold(ctx) >= 5 || { code: 'noMoney', facts: { need: 5, have: gold(ctx) }, nextActions: [{ op: 'job.work', args: {} }] },
150
+ run: (e, a, ctx) => { /* ... */ },
151
+ });
152
+ const r = engine.ops.run('shop.buy', {}); // r.ok === false, r.code === 'noMoney', r.facts.need === 5, r.nextActions[0].op === 'job.work'
153
+ ```
154
+ `engine.nextFixed(fn)` runs `fn` at the start of the next fixed step and returns a Promise of its value, so a UI click or a promise callback can safely write gameplay state: `await engine.nextFixed(() => engine.ops.run('door.open', { id: 'gate' }))`. It is built on `engine.commits` and waits while frozen or loading.
155
+
156
+ Tests that call `engine.pause(owner)` / `engine.resume(owner)` name themselves (default `'game'`). The loop stays paused until every owner has resumed; `resume('b')` while only `'a'` paused is ignored with a dev warning (`pause-owner`), so one helper cannot unpause another's pause.
157
+
158
+ ## 12. Failing in run, atomic ops, revision
159
+ `run` can fail like `can`: return or throw `{ ok: false, code, facts, nextActions }` (a value that merely has a `code` field is not a failure; `ok: false` is required). `facts` is an object (`{ need: 5 }`) or a list of `{ id, field, actual, expected? }` naming the record and field that were wrong. The engine never invents `nextActions`; only the op definition declares them. Every result carries `revision` (`engine.ops.revision`), a counter bumped once per committed op: "did anything change since I looked" is one compare.
160
+ ```js
161
+ engine.ops.define('craft.bread', {
162
+ atomic: true, // every part declared atomic (world, inventory, containers, vars, quests, grids, random, scene) is undone if run fails or throws
163
+ run(e, { oven }, ctx) {
164
+ e.inventory.container(ctx.actor).remove('flour', 2);
165
+ if (e.world.get(oven).heat < 3) return { ok: false, code: 'ovenCold', facts: [{ id: oven, field: 'heat', actual: e.world.get(oven).heat, expected: 3 }], nextActions: [{ op: 'oven.light', args: { oven } }] };
166
+ e.inventory.add('bread');
167
+ },
168
+ after: (e) => e.audio.sfx('ding'), // sound / animation: runs only after the op committed
169
+ });
170
+ ```
171
+ What atomic covers, honestly: it copies the save parts that declared `saves.register(key, { atomic: true })` (the built-ins above; a game's own part can opt in) before `run` and loads them back on failure, so it costs one save of those per run (fine for a craft op, wrong for a per-frame op in a huge world). Events already emitted, sound, animation and any other module's state are not undone; keep such effects in `after`. Ops called from an atomic run join it (their `after` hooks wait for the outermost commit, and a rolled-back outer also takes back their revision). `ops.list()` and `engine.explain({ op })` report `atomic`.
172
+
173
+ Causal trace (`events.traceSize > 0`, recipe 06): failed ops are noted as `op:<name>` with their `code`; `collision.lineClear(a, b, { who })` as `sight` (blocked lines always, clear ones for the focused object only); NPC state changes as `npc:state`. A game's behavior notes its own mode switch with `engine.events.note('npc:mode', { obj: rec.id, data: { from: 'patrol', to: 'investigate' } })`; `events.traceFocus('guard-1')` makes one object verbose.
174
+
175
+ Atomic details: a rolled-back run still bumps `ops.revision` (it only goes up, never back to an old number) and its committed nested ops show in `ops.recent()` as `ok: false` with code `rolledBack`. `after` hooks run in commit order (nested first, then the outer op) once the outermost atomic op ends. The rollback does not run `afterLoad` and mutes the events its loads would emit, so atomic state must be plain data. `reason` is a deprecated alias of `code` on failed results, kept until 1.0.
@@ -77,7 +77,7 @@ On a client `engine.ops.run` returns `{ ok: true, pending: true, seq }` after th
77
77
  real result comes later:
78
78
  ```js
79
79
  engine.events.on('net:sync', () => redrawBag()); // state changed (snapshot or diff)
80
- engine.events.on('net:result', r => { if (!r.ok) hint(engine.t('op.' + r.name + '.' + r.reason)); }); // after the state it caused
80
+ engine.events.on('net:result', r => { if (!r.ok) hint(engine.t('op.' + r.name + '.' + r.code)); }); // after the state it caused
81
81
  ```
82
82
  Single-player gets the same events from your own domain events, so writing "react to state" now means nothing changes when net() is added. Other
83
83
  events: `net:join` / `net:leave` (host), `net:open` / `net:close` (client). `engine.net.reconnect(webSocket(url, { key }))` reconnects with the same
@@ -64,7 +64,7 @@ Cells that exist from the start go in content: `content/grids.js` <!-- r18-ignor
64
64
  **Tiles.** The game gives a layer its colors: `farm.layer('soil', { tiles: { look: d => d.watered ? 0x5b3d2a : d.tilled ? 0x8a6243 : null } })`
65
65
  (what the data means is gameplay, so no style pack ships these). A layer with tiles shows crisp per-cell quads just above the ground, following its
66
66
  height (slopes, ramps, level meshes).
67
- `farm.layer('soil', { tiles: false })` turns them off; `{ tiles: true }` draws every non-empty cell gray; `lift` raises them; `{ tiles:
67
+ `tiles: { colors: { watered: 0x5b3d2a, tilled: 0x8a6243 } }` is the same as `look` from a table (first truthy field wins) and wins over a style pack's `style.grid.tiles`; `farm.layer('soil', { tiles: false })` turns them off; `{ tiles: true }` draws every non-empty cell gray; `lift` raises them; `{ tiles:
68
68
  (engine, layer) => ({ update(cells), dispose() }) }` is your own view. Options are read when the layer is first created.
69
69
 
70
70
  ## 4. Preview
@@ -4,21 +4,22 @@ The engine gives the mechanism and sets nothing: `scene.environment` is `null` u
4
4
  Lambert look is unchanged. The background (the sky dome or `sky.skybox`) and the environment lighting are two separate fields.
5
5
 
6
6
  ```js
7
- engine.sky.setEnvironment({ source: 'sky', intensity: 0.8 }); // lit by the procedural sky; follows the time of day
8
- engine.sky.setEnvironment({ source: 'hdr/studio.hdr', intensity: 1, rotation: Math.PI / 2 }); // an HDR / panorama asset (equirectangular)
9
- engine.sky.setEnvironment({ intensity: 0.5 }); // fields given change, the rest stay
10
- engine.sky.setEnvironment(null); // off, GPU memory released
7
+ engine.look.env.replace('sky'); // lit by the procedural sky; follows the time of day
8
+ engine.look.env.set({ intensity: 0.8 });
9
+ engine.look.env.replace('hdr/studio.hdr'); engine.look.env.set({ intensity: 1, rotation: Math.PI / 2 }); // an HDR / panorama asset (equirectangular)
10
+ engine.look.env.set({ intensity: 0.5 }); // fields given change, the rest stay
11
+ engine.look.env.replace(false); // off, GPU memory released
11
12
  engine.sky.environment; // { source, intensity, rotation, interval, builds } or null
12
13
  ```
13
- A pack gives defaults in `sky.environment` (same fields, plus `low`), the game overrides with `sky({ environment: {...} })` or by calling
14
- `setEnvironment`. `low: false` turns it off on low-tier devices; any other `low` object replaces fields there.
14
+ A pack gives defaults in `sky.environment` (same fields, plus `low`), the game overrides with `sky({ environment: {...} })` or at run time with
15
+ `look.env.replace(...)` / `look.env.set(...)`. `low: false` turns it off on low-tier devices; any other `low` object replaces fields there.
15
16
 
16
17
  ## Sources
17
18
  - `'sky'`: the dome is rendered into a cube and prefiltered with `PMREMGenerator`. It is rebuilt only when the sky colors, sun direction or cloud
18
19
  cover actually changed AND at least `interval` seconds (default 1, low tier 4x) passed since the last check, never every frame. A fixed time of
19
20
  day builds once. The first build waits for the first frame so it uses real colors. With `sky.skybox` use the skybox asset name as `source`.
20
21
  - an asset name or path: `.hdr` loads through three's `HDRLoader` (float, linear), `.jpg` / `.png` / `.ktx2` as ordinary textures. The asset system
21
- owns the texture; the engine owns only the prefiltered copy and disposes it on `setEnvironment(null)`, on a new source and on `engine.dispose()`.
22
+ owns the texture; the engine owns only the prefiltered copy and disposes it on `look.env.replace(false)`, on a new source and on `engine.dispose()`.
22
23
  - The cube is at least 256 px per face (PMREMGenerator's floor in 0.187), so a low tier saves time by rebuilding less often or by turning it off, not
23
24
  by a smaller cube.
24
25
 
@@ -30,6 +31,6 @@ A pack gives defaults in `sky.environment` (same fields, plus `low`), the game o
30
31
  reflections from the scene environment (use a Standard / Physical material for that).
31
32
  - Intensity is `scene.environmentIntensity`, direction offset is `scene.environmentRotation` (Y only here).
32
33
  - The hemisphere light stays and adds on top. When you turn the environment on, lower the ambient column of `sky.keyframes` (or
33
- `sky.modify('env', { ambient: 0.5 })`) so shadows do not wash out.
34
+ `sky.modify('env', { ambient: 0.5 })`, [recipe 52](52-look.md#skymodify-vs-looklights)) so shadows do not wash out.
34
35
  - The first frame with an environment recompiles every Lambert program once (the program key gains the env map); do it at start-up, not mid-game.
35
36
  - Toon, Basic and ShaderMaterial surfaces ignore it.
@@ -8,7 +8,7 @@ engine's part off and bringing your own three.js objects.
8
8
  ## Lights: let the sky drive them, drive them yourself, or switch them off
9
9
  The engine has one directional light (`engine.lights.sun`, also `engine.sky.sun`; moonlight at night, the shadows live on it) and one hemisphere
10
10
  ambient (`engine.lights.hemi` = `engine.sky.hemi`). The sky module rewrites their color and intensity every frame from `style.sky.keyframes`,
11
- so editing them directly is overwritten (a dev warning says so). Choose per light:
11
+ so editing them directly is overwritten (a dev warning says so). **Without the sky module** both lights still exist as a bright placeholder (hemi 1.2, white sun 2 at (40, 80, 30), no shadows): for a night scene set them yourself (`engine.lights.sun.color/intensity`, `engine.lights.hemi.intensity`) or install `sky`. Choose per light:
12
12
 
13
13
  ```js
14
14
  engine.use(sky({ sun: 'manual' })); // the sky still aims the sun along the time of day and moves the shadow box
@@ -18,12 +18,14 @@ engine.use(sky({ sun: false, hemisphere: false })); // a dungeon: both hidde
18
18
  const torch = new THREE.PointLight(0xffa040, 6, 12); engine.add(torch); // add your own lights before engine.start()
19
19
  ```
20
20
 
21
+ - `createEngine({ lights: false })` goes one step further: the default sun and hemisphere are never put in the scene (no placeholder light even before a sky is installed), `engine.lights.sun` / `hemi` stay as detached objects so nothing reads `undefined`. Use it for a scene lit entirely by your own lights.
22
+ - Many lights indoors (lamps, torches in every room): do not add a `PointLight` per lamp; `lightPool({ point: 6 })` keeps a fixed number of real lights and moves them to the nearest sources, so the light count (and shader recompiles) stays constant.
21
23
  - Default `true`: the sky drives everything (as before). `'manual'`: color and intensity are the game's; the sun keeps its direction and shadow box.
22
24
  `false`: `visible = false`, no shadows, never touched (lightning no longer flashes the ambient either).
23
- - Shadows: only the engine sun's shadow is managed (size, bias, snapping via `engine.sky.setShadow`). Your own `castShadow` lights work as in
25
+ - Shadows: only the engine sun's shadow is managed (size, bias, snapping via `engine.look.shadow.set`). Your own `castShadow` lights work as in
24
26
  three.js, each costing its own shadow pass; `engine.setShadows(false)` turns theirs off too and restores them after.
25
27
  - Add or remove lights before `engine.start()`: a light count that changes mid-play recompiles every material (one long frame). Many torches:
26
- `lightPool()`. Brightness tweaks without giving up the keyframes: `engine.sky.modify('cave', { sun: 0.3, ambient: 0.4 })`.
28
+ `lightPool()`. Brightness tweaks without giving up the keyframes: a multiplier layer, see [recipe 52](52-look.md#skymodify-vs-looklights).
27
29
 
28
30
  ## Fog: kind, color, density, or your own math
29
31
  `style.sky.fog` (a look; `sky({ fog })` overrides it):
@@ -57,8 +59,8 @@ fog: { kind: 'exp', glsl: `vec4 threedogFog(vec3 c, float depth, vec3 p){
57
59
  ```js
58
60
  exposure: [[0, 1.6], [0.3, 1], [0.75, 1.1]] // style: per time of day (0-1), wraps across midnight
59
61
  exposure: sky => sky.isDay ? 1 : 1.5 // or a function, evaluated by the sky module every frame
60
- engine.setExposure(1.3); // at run time: number, keyframes or function (replaces the style's)
61
- engine.setToneMapping('agx'); // 'aces' | 'agx' | 'neutral' | 'none'; materials recompile on their next draw
62
+ engine.look.tone.set({ exposure: 1.3 }); // at run time: number, keyframes or function (replaces the style's);
63
+ engine.look.tone.set({ mapping: 'agx' }); // 'aces' | 'agx' | 'neutral' | 'none'; materials recompile on their next draw
62
64
  ```
63
65
  A plain number behaves as before (set once, no per-frame work). Keyframes and functions need the sky module (it knows the time of day).
64
66
 
@@ -78,4 +80,4 @@ hide `engine.sky.dome` and add your own background.
78
80
 
79
81
  ## Water and weather particles
80
82
  Water depth color, crest foam, wave / surface GLSL, reflections; rain and snow shape, size, density and shaders, the lightning look, and
81
- particles for the game's own weather (`engine.weather.define`): `44-water-weather-look-hooks.md`.
83
+ particles for the game's own weather (`engine.look.weather.replace`): `44-water-weather-look-hooks.md`.
@@ -77,3 +77,32 @@ write a template, add a placement with an id. Delete the `engine.add` line. Noth
77
77
  ## 6. Verify
78
78
  `threedog check` flags the startup calls above; `engine.world.origin(id)` and `engine.pick(x, y).thing` say where a record came from (`30-templates.md`
79
79
  §5); `engine.world.query({ kind: 'windmill' })` lists the records a save would hold.
80
+
81
+ ## 7. Why is this mesh this colour? (material provenance)
82
+
83
+ `engine.inspect.scene()` / `npx threedog scene` list, for each mesh, one `material:` line and the renderer line (tone mapping, exposure; the same text as `describe().render`). Diagnostics only: nothing about the look changes.
84
+
85
+ ```
86
+ renderer: ACES (style) exposure 1.1 (style) shadows soft (engine)
87
+ ✓ roof [Mesh] (4, 3, 0) r=2 · MeshLambertMaterial/roof
88
+ material: roof from pack-spec [color] · MeshLambertMaterial #3b5168 · map x color #3b5168 (vertexColors off) · map (base colour)
89
+ note: map already carries colour and color #3b5168 is not white: the result is map x color (fine when it is a tint)
90
+ ```
91
+
92
+ - `from` is `pack-spec | pack-instance | pack-function | call-params | default`, `keys` the params the call passed; both come from `userData.materialSource`, which `makeMaterial` records (a material made by hand shows `unknown`).
93
+ - `--json` carries `material.info[]` per mesh: role, from, keys, type, color, maps (base colour vs detail), vertexColors, side, transparent, opacity, colorPath, notes.
94
+ - The tint note is not an error: a map times a non-white colour is how tinting works.
95
+
96
+ ## 8. When to write plain three.js directly, and which integrations you lose
97
+
98
+ Plain three.js is always allowed (`engine.scene`, `engine.renderer`, `engine.camera` are the real objects; `engine.add(obj, { id })` keeps it saveable). Write it directly for a one-off effect, a special mesh, a shader nothing else shares. What you give up depends on how the material or pass was made:
99
+
100
+ | You wrote | Not applied to it |
101
+ |---|---|
102
+ | `new THREE.MeshStandardMaterial(...)` (not `makeMaterial` / a look material) | wind sway, snow and season cover, cloud shadows, the engine fog hook, cascaded shadows, `look.surface` lighting and detail, `look.materials` roles, `debug.view` modes |
103
+ | your own `EffectComposer` / render call | `engine.post` effects, `look.post`, adaptive resolution, photo mode, `describe().render.post` |
104
+ | `renderer.toneMappingExposure = x`, `scene.fog = ...` | the owner record and the debug layer (`describe().look` tags it `three`); the sky keeps writing fog unless `look.fog.replace('manual')` |
105
+
106
+ Keep the integrations by going through the engine: `engine.makeMaterial('role', {...})` for the material, `look.materials.patch(name, { glsl }, { roles })` to add GLSL to a role, `look.post.patch(name, { glsl, slot })` or `look.post.replace([...])` for a screen effect.
107
+
108
+ `patch` vs `replace`: `patch(hook, glsl)` swaps one registered hook (`threedogWind`, `threedogFog`, `threedogLighting`, the water `wave`) and the rest of the engine's shader stays, so the integrations above still work. `replace(impl)` hands over the whole part (the ground material, the water surface, the whole post chain): everything that part did is now yours, including the fog, shadow and season hooks inside it. Prefer `patch`; use `replace` when the hook is too small. `engine.catalog('look.<part>')` lists the hooks and what each `replace` loses.
@@ -62,3 +62,32 @@ the override applies the moment `engine.add(obj, { id })` runs. One that never c
62
62
  - Rule R33 (`npm run check`) flags the static half: startup calls that create things saved whole, and code writing `world.view()` models.
63
63
  - Cost: a release build pays two table writes per `engine.add` (about 2 µs per add in `tests/specs/things.mjs`); dev builds also take a short stack
64
64
  for `at`, at most 2000 per session (`describe().scene.atCapped` after that).
65
+
66
+ ## 6. One id, everything: explain() and the three kinds of change
67
+ ```js
68
+ engine.thing('chest-home').explain(); // CLI: npx threedog thing chest-home (MCP: thing); the same JSON
69
+ // { id, kind, owner, definition: { at: 'content/props.js:14', template, templateAt, level?, node?, spawned? }, model, materials: [{ role, name, from, keys }],
70
+ // state, rules: { blocksMovement, pickable, interact, height }, ops: [{ op, desc, args }], saved: { tier, keeps, loses }, change: {…}, overrides? }
71
+ ```
72
+ `ops` lists the ops whose definition names this id, kind or template in the optional `targets` field (`engine.ops.define('chest.toggle', { targets: 'chest', … })`;
73
+ `'*'` = any thing, which `thing.set` / `thing.remove` use). `definition.at` is null in release builds and for code run without a file (page `eval`).
74
+ `thing.explain()` (type `ThingExplanation`) is not `engine.explain({ op | quest | … })`: that one takes a question and answers `{ ok, text }` about why an op or quest cannot run now (recipe 23); this one takes no question and returns the facts about one id. `rules.blocksMovement` is the template's / prop's `collide` shape; the engine does not model blocking sight. Pick the kind of change first:
75
+
76
+ | Kind | How | Lasts |
77
+ |---|---|---|
78
+ | Game state (a chest opens, a door moves) | an op: `ops.run('chest.toggle', { id })`, `thing.set`, `thing.remove` (section 3) | by the thing's save tier |
79
+ | Permanent edit (another model, place, material role) | content entry: `npx threedog content set <id> <field> <json>` (below); template or `engine.add` line: edit the file:line `explain().change.permanent` prints; then reload | forever |
80
+ | Diagnostic override ("show me without it") | `engine.debug.override(owner, id, { visible: false, material: 'flat' \| 'wire', apply })` | until `handle.remove()` / `engine.debug.clear(owner)`; never saved |
81
+
82
+ ```js
83
+ const h = engine.debug.override('ai-session', 'windmill', { material: 'flat' }); // unlit base colour: is the colour wrong, or the light?
84
+ engine.debug.override('ai-session', 'fence', { visible: false });
85
+ engine.describe().scene.overrides; // [{ owner, target, material: 'flat' }, …]: the screen differs from the real state while this is non-empty
86
+ h.remove(); engine.debug.clear('ai-session'); // clear removes every override of that owner (and its debug.view) and nothing else
87
+ ```
88
+ `apply(obj)` may return its undo function: any other look (a view mode) uses the same owner mechanism. Overrides do not touch game state, ops or saves.
89
+
90
+ `npx threedog content set cabin x=12 z=3 place=home --in props` sets several fields in one call (one write, one check, all or nothing; a bare word is a string). `npx threedog content set cabin x 12 --in props` writes a permanent change into the content entry (`-w game` or `--dir folder` picks the game; `--dry` only shows it). It edits just that
91
+ value in place (comments and spacing stay), adds the field when missing, runs the content check (reverting if it fails) and tells you to reload. Fields are the content file's names
92
+ (`x`, `z`, `y`, `rot`, `scale`, `template`, `place`, `model`), not the record's `position`; the value is JSON (`'"home"'` for a string). It refuses, and says why, for an entry built
93
+ by code (loop, spread, computed value) or an id matching several entries (`--in props`). A placed entry wins over a template or npc of the same name.
@@ -116,3 +116,5 @@ const looks = {
116
116
  };
117
117
  ```
118
118
  Fetch them with `engine.makeMaterial('wool')`. Check a pack with `threedog style check`; the pixel and program-count guarantees are in `tests/specs/surface.mjs`.
119
+
120
+ To change these from code at run time (`materials`, `surface`, `ground`, `wind` look parts), see recipe 52.
@@ -118,16 +118,18 @@ engine.events.on('weather:lightning', () => spawnBolt()); // when it st
118
118
  ```
119
119
 
120
120
  ## Particles of the game's own weather
121
- A field of the game's own weather table (`ash`, `petals`, `sparks`) gets particles with `engine.weather.define(field, spec)`; the amount is
121
+ A field of the game's own weather table (`ash`, `petals`, `sparks`) gets particles with `engine.look.weather.replace({ [field]: spec })`; the amount is
122
122
  `engine.weather.current[field]`, so they fade in and out with the weather. The spec takes the rain / snow keys above (default: drifting
123
123
  round sprites), or `create` for a system of your own:
124
124
 
125
125
  ```js
126
126
  engine.use(sky(), weather({ types: { clear: {}, ashfall: { ash: 1, grey: 0.5, sun: 0.6 } } }));
127
- engine.weather.define('ash', { shape: 'soft', color: 0x555555, size: 14, speed: 0.8, sway: 3 });
128
- engine.weather.define('rain', { create: (engine, { area, count }) => { // the same call replaces rain or snow
127
+ engine.look.weather.replace({ ash: { shape: 'soft', color: 0x555555, size: 14, speed: 0.8, sway: 3 } });
128
+ engine.look.weather.replace({ rain: { create: (engine, { area, count }) => { // the same call replaces rain or snow
129
129
  const drops = new THREE.InstancedMesh(new THREE.SphereGeometry(0.03), new THREE.MeshBasicMaterial({ color: 0x99bbff }), count);
130
130
  return { object: drops, update(amount, { camera, time, wind }) { /* move the instances; shown while amount > 0.02 */ } };
131
- } });
131
+ } } });
132
132
  ```
133
133
  A field no type has throws with the table's fields. Rain and snow are built only when a type rains or snows, so a desert pays nothing.
134
+
135
+ > Water and weather are also look parts (`engine.look.water`, `engine.look.weather`): recipes/52-look.md, "Water, weather, post".
@@ -6,7 +6,7 @@ world is bigger than one map covers well.
6
6
 
7
7
  ```js
8
8
  engine.use(sky({ shadow: { cascades: 3 } })); // or the style pack: style.sky.shadow.cascades
9
- engine.sky.setShadow({ cascades: 3, maxFar: 150 }); // at run time; { cascades: 1 } switches back
9
+ engine.look.shadow.set({ cascades: 3, maxFar: 150 }); // at run time; { cascades: 1 } switches back
10
10
  ```
11
11
 
12
12
  | field | default | meaning |
@@ -32,6 +32,13 @@ Do not join meshes or decimate a level: node names are its interface.
32
32
  threedog assets check art/models/town.glb # inspect only: spawns, col_ colliders, trigger_ zones, template / id nodes, material suspicions
33
33
  threedog assets # compress art/models/*.glb into public/models/ (add -w my-game for a game)
34
34
  ```
35
+ `assets check` also lists materials, textures with the color space three gives them (by slot), normal maps, clips, `col_` colliders and template / id nodes.
36
+ After loading, `engine.assets.report('hero')` (or `.reportText`; pass a copy from `model()` to check what the game shows) lists the same from the scene and
37
+ flags what the file has but the scene lost: `normal-map-lost`, `material-replaced` (a style role took over), `clip-lost`, `clip-unmapped` (an animation
38
+ state names a clip the file lacks), `node-lost`, and wrong color spaces. The engine never recomputes normals or drops a normal map on a GLB; only code
39
+ that swaps materials as in section 5 does.
40
+ Swapping an export for a new one: `threedog assets check new.glb --against old.glb` lists what the old file had and the new one lacks (errors: `col_`
41
+ colliders, template / id nodes, spawn / trigger_ / npc_ / marker_ points; warnings: clips, materials, points moved over 0.5 m, a bounding box that changed over 15%).
35
42
  `assets check` exits 1 on errors (`--strict`: on warnings too; `--json` for tools). It changes no file.
36
43
  `assets` keeps names, hierarchy and materials and only compresses:
37
44
  | Step | What it does | When it matters |
@@ -42,6 +49,21 @@ threedog assets # compress art/models/*.glb into pub
42
49
 
43
50
  It needs `@gltf-transform/cli` (`npm i -D @gltf-transform/cli`). Unchanged files are skipped; `--force` redoes everything.
44
51
 
52
+ ### The same shot again, before and after
53
+ Declare fixed views once: `engine.views.define('gate', { position: [10, 4, 12], target: [0, 1, 0], fov: 50 })` (`views.show(name)` also works in code). Then
54
+ `npm run shot -- -w my-game --view gate --keep` takes the picture from there in any game (the page's own `?view=` still wins where a page handles it, as
55
+ in the style test). After a change, `npm run shot -- -w my-game --view gate --compare .threedog/shots/<before>.png` prints both file names, one pixel-diff
56
+ number (0 = identical) and the brightness / saturation / contrast / detail differences. A view holds the camera (`engine.takeCamera`) until `views.release()` or the handle `show()` returns is removed; a cutscene that held it before gets it back.
57
+ Views can also be content: `content/views.js` = `{ gate: { position: [10, 4, 12], target: [0, 1, 0], fov: 50 } }` is defined by `engine.content.load` (checked by `npm run check`; example: `examples/action/content/views.js`, `npm run shot -- action --view corner`).
58
+ `describe render` also shows the renderer output color space and warns when it is not srgb; `assets.report` flags color maps that are not srgb and data maps that are.
59
+
60
+ ### Looking at one part of the render
61
+ `engine.debug.view('albedo')` shows only the base color and texture (unlit), `'lighting'` plain white clay under the scene lights, `'shadow'` the same with
62
+ ambient and hemisphere light hidden so shadows read black, `'normals'` the normals as color (a normal map shows here); `'off'` restores everything.
63
+ A view is temporary and owner-scoped (`{ owner }`; another owner needs `force: true` to clear it), never saved, and `describe().render` / `describe render`
64
+ start with a DEBUG VIEW line while one is on, so a screenshot of clay is not taken for the real look. Meshes added after the call are not covered: call it again.
65
+ It needs the debug module (`engine.use(debug())`).
66
+
45
67
  ## 4. Use it
46
68
  Register the compressed file in the asset pack and refer to it by name everywhere else:
47
69
  ```js
@@ -0,0 +1,70 @@
1
+ # 48. `engine.makeMaterial(role, spec)`: which keys work, who wins
2
+
3
+ `engine.makeMaterial('furniture', { color: 0x8a5a36 })` returns a normal three.js material. The **role** picks the look from the style pack
4
+ (`style.materials[role]`, unlisted roles use `materials.default`); the **spec** is this call's own settings.
5
+
6
+ ## Which spec keys are accepted
7
+
8
+ - **Any real property of the material**: `color`, `emissive`, `emissiveIntensity`, `roughness`, `metalness` (standard/physical only), `shininess` (phong),
9
+ `transparent`, `opacity`, `side` (`THREE.DoubleSide`), `vertexColors`, `flatShading`, `wireframe`, `alphaTest`, `depthWrite`, `fog`... Colors take
10
+ a hex, a CSS string or a `THREE.Color`; a Vector2 prop takes `[x, y]`.
11
+ - `type`: `'lambert' | 'phong' | 'standard' | 'physical' | 'toon' | 'basic'` (default `lambert`, or whatever the pack says).
12
+ - Texture slots by asset name (or a `THREE.Texture`): `map`, `emissiveMap` (sRGB), `normalMap`, `roughnessMap`, `metalnessMap`, `aoMap`, `bumpMap`,
13
+ `alphaMap`... The slot must exist on the type (`roughnessMap` needs `standard`). Plus `repeat` (number or `[x, y]`) and `wrap` (`repeat | clamp | mirror`).
14
+ - `detail`: grain / paper / strokes / a texture laid over the surface in world space (no UVs).
15
+ - `lighting`: extra light shaping (shadow tint, rim, wrap, own GLSL), merged over `style.lighting`; `false` opts out.
16
+ - toon only: `steps` (number of bands), or `ramp` (+ `soften`). `ramp` on a non-toon type throws.
17
+ - A key the chosen material does not have (`roughness` on lambert) is skipped on purpose, so one spec works for any type.
18
+ A key that looks like a typo of a real one (`roughnes`) warns once in dev with `did you mean 'roughness'?`. Nothing is ever blocked.
19
+
20
+ ## Who wins: pack or call
21
+
22
+ The pack entry is the default, the call wins. For a pack **spec** the two are merged (`default` spec, then the role's spec, then your call);
23
+ the same key in the call overrides the pack's:
24
+
25
+ ```js
26
+ // pack: materials: { building: { type: 'standard', roughness: 0.8 } }
27
+ engine.makeMaterial('building', { roughness: 0.2 }); // roughness 0.2, still standard
28
+ engine.makeMaterial('building', { type: 'toon', steps: 4 }); // your type wins too
29
+ ```
30
+
31
+ A pack entry that is a **Material instance** is cloned, then your keys are set on the clone (keys it lacks are skipped).
32
+ A pack **function** `(params, role, engine) => Material` receives your spec first and decides itself; keys it did not use are set afterwards.
33
+ The pack's `style.lighting` is added unless your spec says `lighting: false`.
34
+
35
+ ## Tweak the returned material directly
36
+
37
+ The result is an ordinary `THREE.Material`; edit it freely. The engine does not wrap or track it, so this is not "bypassing" anything:
38
+
39
+ ```js
40
+ const glass = engine.makeMaterial('window', { color: 0x9fd4ff, transparent: true, opacity: 0.35, side: THREE.DoubleSide });
41
+ glass.depthWrite = false; // plain property edit, fine
42
+ glass.onBeforeCompile = ...; // allowed, but it replaces the engine's shader patches (wind, clouds, detail, lighting) on this material
43
+ ```
44
+
45
+ Keep `makeMaterial` as the way to *create* materials (a style swap then restyles the game, `npm run check` flags a bare `new THREE.Mesh*Material`);
46
+ afterwards use three.js normally. Changing `needsUpdate`-type settings (`vertexColors`, `flatShading`, `transparent`) after first render needs `mat.needsUpdate = true`.
47
+
48
+ ## Copyable examples
49
+
50
+ ```js
51
+ // Solid prop with vertex colors (merged model)
52
+ engine.makeMaterial('prop', { vertexColors: true });
53
+
54
+ // Textured PBR stone
55
+ engine.makeMaterial('rock', { type: 'standard', map: 'rock.png', normalMap: 'rock_n.png', roughness: 0.9, repeat: 4 });
56
+
57
+ // See-through, double-sided
58
+ engine.makeMaterial('banner', { color: 0xd04a3a, transparent: true, opacity: 0.8, side: THREE.DoubleSide });
59
+
60
+ // Glowing lamp
61
+ engine.makeMaterial('lamp', { color: 0x6b5a40, emissive: 0xffc070, emissiveIntensity: 1.2 });
62
+
63
+ // Grain over the surface, no extra shading
64
+ engine.makeMaterial('wall', { color: 0xc9b99a, detail: { noise: 'paper' }, lighting: false });
65
+
66
+ // Toon with an explicit light ramp
67
+ engine.makeMaterial('character', { type: 'toon', color: 0xe8a0a0, ramp: [0.25, 0.6, 1] });
68
+ ```
69
+
70
+ See also: `09-style-pack.md` (writing the pack side), `43-shader-patches-surface-looks.md` (detail / lighting / patches).
@@ -0,0 +1,71 @@
1
+ # Writing a game system module (crops, burning, a production machine) that plugs into the engine's contracts
2
+
3
+ A game system is a module (`{ name, install, ... }`) given to `engine.use(...)`. If it follows the five contracts below it saves, loads, skips time,
4
+ shows in `describe()` and the dev bridge, and can be driven by ops, without special cases. Read recipe 06 (clock, skip), 18 (world records), 23 (ops).
5
+
6
+ ## The five contracts
7
+ 1. **State.** Prefer world records (`engine.world.add({ kind, ... })`, recipe 18): saved, streamed and far-simulated for you. State that is not a
8
+ record (a counter, a machine's queue) goes in `engine.saves.register(key, { save, load, version?, migrate? })`. Raise `version` by 1 whenever the
9
+ saved shape changes and add `migrate: { oldVersion: d => newData }`. Never keep game state only in a closure or module variable.
10
+ 2. **Time, normal play.** Store *when* something happened in game seconds (`engine.clock.now`), and derive the state from `now - startedAt`. Never use
11
+ `Date.now`, `performance.now` or `setTimeout` for game time: they ignore pause, `timeScale`, `step` and saves. If you must accumulate, do it in
12
+ the module `fixed(dt, e)` hook (dt is fixed seconds; game seconds = dt x `clock.timeScale`).
13
+ 3. **Time, skipped** (`engine.skip`, the op `time.skip`, recipe 06 section 2). `fixed` hooks, physics and near simulation do **not** run during a skip.
14
+ A state derived from `clock.now` is exact for free. A module that accumulates in `fixed` must also implement `skip(dt, e, done)` (called once per
15
+ segment, `done` on the last; do heavy work once when `done`), or put the logic in a world record `far(rec, dt)`, which gets one catch-up call.
16
+ 4. **Observable.** Module hook `describe(e, ctx)` puts its return value in `describe().<module name>` (plain JSON; the bridge `describe <name>` and
17
+ `describeText()` show it). A game without a module uses `engine.describe.add(name, fn)`. The name must be new (it throws on a clash).
18
+ 5. **Actions are ops.** `engine.ops.define('noun.verb', { args, can, run, offers, reasons, desc })`. `can` is read-only and returns `true` or a reason
19
+ string (a key of `reasons`); `run` changes state; `offers(e, ctx)` lists the arg sets possible right now (shown by the bridge `ops` command and
20
+ `describe`). Call with `engine.ops.run(name, args)` -> `{ ok, value }` or `{ ok: false, reason }`. Never mutate state from UI code directly.
21
+
22
+ ## Declaring stage and dependencies
23
+ `stage` picks where the hooks run (first to last): `control, world, environment, gameplay, presentation, late (default), audio`; `before / after`
24
+ (module names) only order modules inside one stage; a contradiction with the stage order throws. `requires: ['world']` must already be installed (throws
25
+ otherwise: put those `engine.use` calls first). `optional: { sky: 'what is lost without it' }` is a soft dependency (use `engine.sky?.`). Core never imports
26
+ modules. The module `name` must not clash with an existing engine property.
27
+
28
+ ## One copyable module: a crop
29
+ ```js
30
+ export const crops = () => {
31
+ const plots = new Map(); // id -> plantedAt (game seconds)
32
+ return {
33
+ name: 'crops', stage: 'gameplay', requires: [],
34
+ install(e) {
35
+ e.saves.register('crops', { version: 1, // contract 1: saved and restored
36
+ save: () => [...plots],
37
+ load: d => { plots.clear(); for (const [id, t] of d) plots.set(id, t); } });
38
+ const grown = id => Math.min(1, (e.clock.now - plots.get(id)) / 120); // contracts 2+3: derived from clock.now, so normal == skipped
39
+ e.ops.define('crop.plant', { args: { id: 'string' }, desc: 'Plant a crop plot', // contract 5
40
+ can: (_, { id }) => (plots.has(id) ? 'taken' : true),
41
+ run: (_, { id }) => { plots.set(id, e.clock.now); return id; }, reasons: { taken: 'Plot already planted' } });
42
+ e.ops.define('crop.harvest', { args: { id: 'string' }, desc: 'Harvest a ripe crop',
43
+ can: (_, { id }) => (!plots.has(id) ? 'empty' : grown(id) < 1 ? 'notRipe' : true),
44
+ offers: () => [...plots.keys()].filter(id => grown(id) >= 1).map(id => ({ id })),
45
+ run: (_, { id }) => { plots.delete(id); e.inventory.add('carrot', 2); return id; },
46
+ reasons: { empty: 'Nothing planted', notRipe: 'Not ripe yet' } });
47
+ return { grown }; // becomes engine.crops
48
+ },
49
+ describe: e => ({ plots: plots.size, ripe: [...plots.keys()].filter(id => e.crops.grown(id) >= 1) }), // contract 4
50
+ };
51
+ };
52
+ ```
53
+ Needs the `inventory`
54
+ module (add `requires: ['inventory']`, or drop the `inventory.add` line).
55
+
56
+ ## Check "advance 10h normally == skip 10h" (bridge, no new tools)
57
+ ```
58
+ npx threedog op crop.plant id=a ; npx threedog step 36000 ; npx threedog describe crops # A: normal play
59
+ npx threedog reload ; npx threedog op crop.plant id=a ; npx threedog op time.skip seconds=36000 ; npx threedog describe crops # B: skipped
60
+ npx threedog js "JSON.stringify(engine.crops.grown('a'))" # same number both times; compare whole state with: threedog snap-describe save|diff
61
+ ```
62
+ Both runs must give equal `describe crops` (and `describe time`); if B differs, the module accumulates in `fixed` and needs a `skip` hook or `far`.
63
+
64
+ ## What the engine does NOT check for you
65
+ - That `save` really includes **all** your state, or that `load` is the inverse of `save` (an unsaved field silently resets on load).
66
+ - That your state is equal after skip versus step: it only skips the hooks it knows about. A `setTimeout`, a closure counter or a `fixed` accumulator
67
+ is silently *not* advanced during a skip.
68
+ - That `can` is side-effect free and that `run` does not need `can` to have passed; `offers` is not checked against `can`.
69
+ - That `describe` returns everything that matters (a field left out is invisible to the AI and to snapshot diffs).
70
+ - That the stage/`before`/`after` you chose is the right one for your logic (only contradictions throw).
71
+ - Raising `version` and writing `migrate` when the saved shape changes (the engine only reports a missing step when an old save is loaded).
@@ -0,0 +1,12 @@
1
+ # Bring your own renderer: `createEngine({ renderer })`
2
+
3
+ Pass a ready three.js renderer when the game must own it (shared canvas, an editor, a custom context):
4
+
5
+ ```js
6
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
7
+ const engine = createEngine({ renderer, style }); // canvas defaults to renderer.domElement
8
+ ```
9
+
10
+ - The engine configures only a renderer it created itself. With yours it sets nothing: pixel ratio (unless `pixelRatio` is given), size, tone mapping, exposure and shadow map stay as you left them, so `style.toneMapping` / `style.exposure` do not apply. Set them yourself on the renderer.
11
+ - **WebGL is the fully supported path.** Shader patches (recipe 43) and post effects (the `EffectComposer` chain) are written for `WebGLRenderer`; a WebGPU-style renderer may not run them. Everything else (scene, modules, input, saves, ops) does not depend on the renderer.
12
+ - Changing the renderer, lights or post effects is yours to do at any time; the engine never warns. `engine.describe().render` (CLI: `describe render`) lists the current values and tags each `engine` / `style` / `game`, so an AI can see who set a look.
@@ -0,0 +1,63 @@
1
+ # Capability catalog: ask what the game can do before reading docs
2
+
3
+ `engine.catalog()` answers "which modules are here, what can they do, what do they save, how do they keep time" from the registrations
4
+ that already exist: module definitions (`requires`, `optional`, `stage`, hooks), `engine.ops.define`, `engine.saves.register`,
5
+ `engine.describe.add` and params schemas. There is no second list to keep in sync: a removed op is gone from the catalog at once.
6
+
7
+ ## 1. Ask
8
+ ```js
9
+ engine.catalog(); // short list: [{ id: 'sky', kind: 'module', state: 'running', stage: 'environment', ops: [], saves: ['sky'], time: 'fixed+skip' }, ...]
10
+ engine.catalog('shop'); // one module expanded (below)
11
+ engine.catalog('shop.buy'); // one op: args schema, reasons, can / offers / undo / net, its last attempt
12
+ engine.catalog({ find: 'throw' }); // the short list filtered by id, label, op or save name
13
+ engine.catalog('core'); // what the engine registered itself (time.skip, clock, random...); 'game': what game code registered outside modules
14
+ ```
15
+ From the dev bridge: `npx threedog catalog`, `npx threedog catalog shop`, `npx threedog catalog --find buy` (`--json` for the data). The bridge prints the
16
+ same data and adds the files: `source` (where `name: 'shop'` or `define('shop.buy'` is written), `api` (the generated api page), `recipes` and
17
+ `examples` that use `engine.shop`. The MCP server has one `catalog` tool with the same arguments.
18
+
19
+ A module entry has: `state`, `stage`, `runIndex` (place in `engine.moduleOrder`), `critical`, `requires`, `optional` (`{ name, installed, lost }`),
20
+ `params` (schema, default and the value in use), `ops` (`{ name, desc, args, failures }`), `saves` (`{ key, version, migrates }`),
21
+ `time` (`hooks`, `step: 'fixed' | 'frame' | 'none'`, `skip`), `queries` (`describe().<id>`, names added with `describe.add`, the api's public names) and
22
+ `problems`, such as "fixed hook but no skip hook" or an `optional` module that is missing.
23
+
24
+ `threedog catalog <id>` lists each param as `key:type=default — sentence`: the type (for `any` params) and sentence are read from the module's api page (its options typedef JSDoc), so the schema keeps only names, defaults and checks; a param with no sentence shows `(no doc)` and counts as a problem (rule R38 lists the modules).
25
+
26
+ Who owns what: an op, save part or describe name registered while a module's `install()` or `init()` runs belongs to that module; so does an op named
27
+ `<module>.verb` or a save part keyed by the module name. Everything registered before the first `engine.use` is `core`; the rest is `game`.
28
+
29
+ ## 2. Declare args once (ops)
30
+ An op arg is `'int?'` or the full schema `{ type, default, min, max, values, desc, optional }`. The same object validates the call in dev, fills the
31
+ default before `can` and `run`, and is what the catalog and `threedog catalog` show, so the code never needs `n = 1` in two places.
32
+ ```js
33
+ engine.ops.define('shop.buy', {
34
+ args: { item: 'string', n: { type: 'int', default: 1, min: 1, max: 99, desc: 'how many' } },
35
+ can: (e, { item, n }) => e.inventory.count('gold') >= n * PRICE[item] ? true : 'noMoney',
36
+ run: (e, { item, n }) => e.inventory.add(item, n),
37
+ reasons: { noMoney: 'Not enough gold' }, // the failure codes the catalog lists
38
+ });
39
+ engine.ops.run('shop.buy', { item: 'bread', n: 0 }); // dev: throws "n must be >= 1"; release: returns { ok: false, code: 'badArgs' } (run never starts)
40
+ ```
41
+
42
+ ## 3. Declare module options once (`readParams`)
43
+ ```js
44
+ import { readParams } from 'threedog';
45
+ const PARAMS = { radius: { type: 'number', default: 2, min: 0, desc: 'pickup reach in m' }, sound: 'string?' };
46
+ export const magnet = (opts) => {
47
+ const o = readParams('magnet', PARAMS, opts); // wrong type / out of range throws [module-params] with the fix; an unknown key throws in dev and warns once in a release build
48
+ return { name: 'magnet', params: PARAMS, options: o, stage: 'gameplay', install(e) { return { radius: o.radius }; } };
49
+ };
50
+ ```
51
+ `params` and `options` on the definition are what `engine.catalog('magnet').params` reads; `engine.use` re-checks them in dev for a definition built by hand.
52
+ The schema types are those of op args plus `object`, `array` and `function` (options may hold callbacks; op args may not).
53
+
54
+ ## 4. Debugging with it
55
+ "Why does the throw fail": `threedog catalog combat.throw` shows its args, the failure codes it can return and its last attempt with the reason;
56
+ `threedog explain op combat.throw ...` (recipe 23) then says why for given args. "Does sleeping advance my crops": `threedog catalog crops` shows the
57
+ time hooks; a `fixed` hook without `skip` is listed under problems (recipe 49).
58
+
59
+ ## 5. "How do I get this effect": `threedog how`
60
+ `npx threedog how "rain"` (also `how 下雨`) scores the words of the task against the AI.md task rows and the recipe headings with their first sentence, and prints the
61
+ top five: the API in the row, the recipe path with section (`recipes/08-weather-sky.md §1`) and a one-line snippet. It reads the docs only, so it works with no page
62
+ and prints the same list every run. When a dev page runs it adds up to three live catalog modules whose name matches the first English word. Words match at a word
63
+ start (`rain` does not hit `terrain`); a few Chinese task words are mapped to the English words the docs use. No hit means rephrase, or read AI.md.