threedog 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/README.md +4 -4
  2. package/core/Animator.js +1 -0
  3. package/core/Assets.js +28 -0
  4. package/core/DebugOverrides.js +143 -0
  5. package/core/Describe.js +14 -3
  6. package/core/Engine.js +44 -72
  7. package/core/Events.js +59 -1
  8. package/core/I18n.js +2 -2
  9. package/core/Inspect.js +12 -32
  10. package/core/InspectScene.js +7 -3
  11. package/core/MaterialInfo.js +32 -0
  12. package/core/Ops.js +43 -59
  13. package/core/Saves.js +5 -4
  14. package/core/UrlState.js +3 -2
  15. package/core/Vars.js +1 -0
  16. package/core/Views.js +49 -0
  17. package/core/actor.js +2 -2
  18. package/core/assetReport.js +83 -0
  19. package/core/catalog.js +169 -0
  20. package/core/checks.js +67 -0
  21. package/core/claims.js +51 -0
  22. package/core/debugView.js +76 -0
  23. package/core/describeRender.js +51 -0
  24. package/core/describeText.js +11 -4
  25. package/core/errorCodes.js +33 -0
  26. package/core/errorHints.js +6 -1
  27. package/core/grid.js +127 -0
  28. package/core/gridLoad.js +19 -0
  29. package/core/holds.js +106 -0
  30. package/core/lifecycle.js +1 -0
  31. package/core/lightWatch.js +23 -3
  32. package/core/look/coreParts.js +112 -0
  33. package/core/look/layers.js +136 -0
  34. package/core/look/part.js +173 -0
  35. package/core/look/report.js +79 -0
  36. package/core/look/write.js +86 -0
  37. package/core/loop.js +22 -16
  38. package/core/modules.js +19 -5
  39. package/core/opsAtomic.js +31 -0
  40. package/core/opsCheck.js +25 -14
  41. package/core/opsFail.js +20 -0
  42. package/core/opsHistory.js +6 -6
  43. package/core/opsRun.js +77 -0
  44. package/core/params.js +132 -0
  45. package/core/renamed.js +22 -0
  46. package/core/saveApply.js +2 -2
  47. package/core/sceneMethods.js +9 -34
  48. package/core/services.js +73 -0
  49. package/core/startup.js +3 -1
  50. package/core/styleParts.js +11 -9
  51. package/core/thingExplain.js +68 -0
  52. package/core/thingOps.js +35 -24
  53. package/core/things.js +15 -1
  54. package/core/util.js +11 -0
  55. package/core/validate.js +23 -7
  56. package/docs/AI.md +93 -114
  57. package/docs/API.md +8 -9
  58. package/docs/CODEMAP.md +67 -53
  59. package/docs/COMMANDS.md +21 -7
  60. package/docs/CONVENTIONS.md +22 -11
  61. package/docs/THREE.md +3 -3
  62. package/docs/api/assets.md +3 -0
  63. package/docs/api/characters.md +5 -2
  64. package/docs/api/collision.md +4 -0
  65. package/docs/api/content.md +1 -0
  66. package/docs/api/engine.md +23 -14
  67. package/docs/api/events.md +5 -1
  68. package/docs/api/post.md +5 -4
  69. package/docs/api/saves.md +2 -1
  70. package/docs/api/sky.md +3 -3
  71. package/docs/api/style.md +8 -8
  72. package/docs/api/tools.md +5 -2
  73. package/docs/api/vegetation.md +1 -0
  74. package/docs/api/weather.md +1 -1
  75. package/docs/recipes/01-new-game.md +41 -43
  76. package/docs/recipes/02-npc.md +38 -22
  77. package/docs/recipes/03-items-pickups.md +4 -4
  78. package/docs/recipes/04-quests.md +23 -23
  79. package/docs/recipes/05-props-bake.md +5 -5
  80. package/docs/recipes/06-clock-events.md +13 -0
  81. package/docs/recipes/07-flow-scenes-pause.md +6 -2
  82. package/docs/recipes/08-weather-sky.md +6 -6
  83. package/docs/recipes/09-style-pack.md +35 -100
  84. package/docs/recipes/12-navmesh.md +22 -0
  85. package/docs/recipes/13-animation.md +25 -6
  86. package/docs/recipes/14-custom-module.md +6 -7
  87. package/docs/recipes/15-perf.md +9 -1
  88. package/docs/recipes/16-dev-bridge.md +52 -18
  89. package/docs/recipes/18-world.md +5 -2
  90. package/docs/recipes/19-shooting-picking.md +9 -8
  91. package/docs/recipes/20-content-actions-save.md +10 -10
  92. package/docs/recipes/21-camera.md +51 -2
  93. package/docs/recipes/22-shop-gold.md +16 -16
  94. package/docs/recipes/23-ops.md +46 -10
  95. package/docs/recipes/27-net.md +3 -3
  96. package/docs/recipes/28-terrain.md +2 -2
  97. package/docs/recipes/29-grid.md +47 -27
  98. package/docs/recipes/34-environment-lighting.md +11 -10
  99. package/docs/recipes/35-style-from-reference.md +41 -46
  100. package/docs/recipes/36-sky-ground-plant-looks.md +22 -20
  101. package/docs/recipes/37-terrain-look-hooks.md +34 -13
  102. package/docs/recipes/38-environment-look-hooks.md +49 -42
  103. package/docs/recipes/40-scene.md +29 -0
  104. package/docs/recipes/41-thing-registry.md +29 -0
  105. package/docs/recipes/42-terrain-shape.md +1 -1
  106. package/docs/recipes/43-shader-patches-surface-looks.md +37 -20
  107. package/docs/recipes/44-water-weather-look-hooks.md +11 -9
  108. package/docs/recipes/45-cascaded-shadows.md +2 -2
  109. package/docs/recipes/46-blender-art-route.md +26 -4
  110. package/docs/recipes/47-island-snow-backdrop.md +4 -3
  111. package/docs/recipes/48-make-material.md +70 -0
  112. package/docs/recipes/49-game-module-contract.md +71 -0
  113. package/docs/recipes/50-own-renderer.md +12 -0
  114. package/docs/recipes/51-capability-catalog.md +63 -0
  115. package/docs/recipes/52-look.md +146 -0
  116. package/docs/recipes/53-ground-up-close.md +58 -0
  117. package/examples/action/GAMEMAP.md +7 -7
  118. package/examples/action/content/index.js +2 -1
  119. package/examples/action/content/views.js +6 -0
  120. package/examples/action/main.js +3 -2
  121. package/examples/sheepisland/GAMEMAP.md +3 -4
  122. package/examples/styletest/GAMEMAP.md +3 -3
  123. package/examples/styletest/content/npcs.js +1 -1
  124. package/examples/styletest/main.js +2 -2
  125. package/examples/styletest/panel.js +3 -3
  126. package/examples/world/GAMEMAP.md +3 -3
  127. package/examples/world/content/npcs.js +1 -1
  128. package/examples/world/main.js +1 -1
  129. package/index.d.ts +35 -2
  130. package/index.js +6 -3
  131. package/llms.txt +13 -7
  132. package/modules/ambience/Ambience.js +5 -2
  133. package/modules/camera/FirstPersonCamera.js +3 -5
  134. package/modules/camera/FixedCamera.js +19 -12
  135. package/modules/camera/FollowCamera.js +14 -8
  136. package/modules/camera/RtsCamera.js +3 -5
  137. package/modules/camera/common.js +40 -10
  138. package/modules/camera/index.js +1 -1
  139. package/modules/camera/projection.js +34 -0
  140. package/modules/characters/Character.js +45 -31
  141. package/modules/characters/assetModel.js +35 -7
  142. package/modules/characters/astar.js +14 -7
  143. package/modules/characters/index.js +6 -3
  144. package/modules/characters/movers/simple.js +6 -1
  145. package/modules/characters/npcSim.js +8 -2
  146. package/modules/characters/pathAsync.js +12 -6
  147. package/modules/characters/pathJob.js +2 -1
  148. package/modules/characters/proceduralRig.js +50 -11
  149. package/modules/characters/useModel.js +22 -0
  150. package/modules/characters/walkTo.js +58 -0
  151. package/modules/collision/Collision.js +102 -4
  152. package/modules/content/explain.js +13 -0
  153. package/modules/content/index.js +3 -1
  154. package/modules/content/loader.js +3 -0
  155. package/modules/content/rules.js +1 -0
  156. package/modules/debug/DebugPanel.js +11 -5
  157. package/modules/entities/Entities.js +6 -2
  158. package/modules/flow/index.js +5 -2
  159. package/modules/gameplay/Dialogue.js +5 -2
  160. package/modules/gameplay/Interactions.js +12 -2
  161. package/modules/gameplay/Inventory.js +21 -11
  162. package/modules/gameplay/Quests.js +13 -3
  163. package/modules/gameplay/pickups.js +6 -4
  164. package/modules/grid/Layer.js +1 -1
  165. package/modules/grid/index.js +1 -1
  166. package/modules/grid/tiles.js +9 -5
  167. package/modules/hlod/index.js +5 -2
  168. package/modules/hud/index.js +5 -2
  169. package/modules/level/index.js +5 -3
  170. package/modules/lights/index.js +5 -2
  171. package/modules/music/Music.js +6 -2
  172. package/modules/nav/index.js +5 -3
  173. package/modules/net/Client.js +4 -3
  174. package/modules/net/Host.js +2 -2
  175. package/modules/net/index.js +5 -3
  176. package/modules/particles/Particles.js +1 -1
  177. package/modules/photo/Photo.js +10 -7
  178. package/modules/rigid/RigidBodies.js +5 -2
  179. package/modules/settings/Settings.js +6 -3
  180. package/modules/settings/apply.js +2 -1
  181. package/modules/sky/Sky.js +21 -19
  182. package/modules/sky/cascades.js +6 -6
  183. package/modules/sky/domeLayers.js +1 -1
  184. package/modules/sky/environment.js +39 -13
  185. package/modules/sky/fog.js +9 -6
  186. package/modules/sky/frame.js +4 -3
  187. package/modules/sky/look.js +3 -2
  188. package/modules/sky/lookFog.js +80 -0
  189. package/modules/sky/lookShadow.js +50 -0
  190. package/modules/sky/lookSky.js +108 -0
  191. package/modules/sky/shader.js +2 -2
  192. package/modules/sky/shadow.js +4 -10
  193. package/modules/sky/skyModule.js +4 -3
  194. package/modules/terrain/ChunkManager.js +2 -33
  195. package/modules/terrain/chunkLevels.js +40 -0
  196. package/modules/terrain/index.js +10 -2
  197. package/modules/terrain/lookGround.js +61 -0
  198. package/modules/timeline/Timeline.js +7 -3
  199. package/modules/timeline/Tween.js +3 -7
  200. package/modules/timeline/shots.js +6 -4
  201. package/modules/triggers/index.js +9 -2
  202. package/modules/vegetation/Vegetation.js +17 -4
  203. package/modules/vegetation/index.js +7 -4
  204. package/modules/vegetation/lookWind.js +37 -0
  205. package/modules/vegetation/nearFade.js +39 -0
  206. package/modules/water/Water.js +19 -3
  207. package/modules/water/look.js +80 -0
  208. package/modules/weather/Weather.js +22 -31
  209. package/modules/weather/look.js +75 -0
  210. package/modules/weather/particles.js +1 -1
  211. package/modules/weather/strings.js +15 -0
  212. package/modules/world/explain.js +11 -0
  213. package/modules/world/index.js +11 -4
  214. package/modules/world/thingSource.js +44 -0
  215. package/package.json +2 -1
  216. package/render/PostFX.js +48 -51
  217. package/render/detail.js +39 -15
  218. package/render/effects.js +4 -2
  219. package/render/fuse.js +12 -0
  220. package/render/lights.js +4 -2
  221. package/render/lookSurface.js +161 -0
  222. package/render/materials.js +27 -10
  223. package/render/postLook.js +86 -0
  224. package/render/surface.js +3 -1
  225. package/types/core.d.ts +223 -29
  226. package/types/gameplay.d.ts +22 -6
  227. package/types/generated/core/DebugOverrides.d.ts +52 -0
  228. package/types/generated/core/Events.d.ts +43 -0
  229. package/types/generated/core/Ops.d.ts +62 -21
  230. package/types/generated/core/Saves.d.ts +1 -0
  231. package/types/generated/core/Views.d.ts +33 -0
  232. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  233. package/types/generated/modules/grid/Layer.d.ts +1 -0
  234. package/types/generated/modules/sky/Sky.d.ts +10 -17
  235. package/types/generated/modules/weather/Weather.d.ts +5 -15
  236. package/types/generated/render/PostFX.d.ts +20 -23
  237. package/types/generated/render/materials.d.ts +10 -0
  238. package/types/physics.d.ts +8 -0
  239. package/types/style.d.ts +35 -20
  240. package/types/world.d.ts +7 -1
  241. package/ui/Parts.js +6 -2
  242. package/ui/UI.js +1 -1
  243. package/ui/defaults.js +1 -1
  244. package/docs/api/debug.md +0 -10
@@ -0,0 +1,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`: a noise (`grain`, `paper`, `stroke`, `dabs`), a texture or your own GLSL laid over the surface in world space (no UVs); its keys: recipe 43.
15
+ - `lighting`: extra light shaping (shadow tint, rim, wrap, own GLSL), merged over `style.lighting`; `false` opts out (recipe 43).
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 (a smelter, a recharging turret, growing crops) 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 14 (template, hook cheat sheet), 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, code, facts, nextActions }` (read `r.code`). 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: something that finishes after a delay (a smelter, a turret recharge, a crop)
29
+ ```js
30
+ export const jobs = () => {
31
+ const started = new Map(); // id -> startedAt (game seconds)
32
+ return {
33
+ name: 'jobs', stage: 'gameplay', requires: [],
34
+ install(e) {
35
+ e.saves.register('jobs', { version: 1, // contract 1: saved and restored
36
+ save: () => [...started],
37
+ load: d => { started.clear(); for (const [id, t] of d) started.set(id, t); } });
38
+ const progress = id => Math.min(1, (e.clock.now - started.get(id)) / 120); // contracts 2+3: derived from clock.now, so normal == skipped
39
+ e.ops.define('job.start', { args: { id: 'string' }, desc: 'Start a job on a machine', // contract 5
40
+ can: (_, { id }) => (started.has(id) ? 'busy' : true),
41
+ run: (_, { id }) => { started.set(id, e.clock.now); return id; }, reasons: { busy: 'Already running' } });
42
+ e.ops.define('job.collect', { args: { id: 'string' }, desc: 'Collect a finished job',
43
+ can: (_, { id }) => (!started.has(id) ? 'idle' : progress(id) < 1 ? 'notDone' : true),
44
+ offers: () => [...started.keys()].filter(id => progress(id) >= 1).map(id => ({ id })),
45
+ run: (_, { id }) => { started.delete(id); e.inventory.add('item', 2); return id; },
46
+ reasons: { idle: 'Nothing running', notDone: 'Not done yet' } });
47
+ return { progress }; // becomes engine.jobs
48
+ },
49
+ describe: e => ({ running: started.size, done: [...started.keys()].filter(id => e.jobs.progress(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 job.start id=a ; npx threedog step 36000 ; npx threedog describe jobs # A: normal play
59
+ npx threedog reload ; npx threedog op job.start id=a ; npx threedog op time.skip seconds=36000 ; npx threedog describe jobs # B: skipped
60
+ npx threedog js "JSON.stringify(engine.jobs.progress('a'))" # same number both times; compare whole state with: threedog snap-describe save|diff
61
+ ```
62
+ Both runs must give equal `describe jobs` (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"` 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`). No hit means rephrase, or read AI.md.
@@ -0,0 +1,146 @@
1
+ # 52 Change any look: `engine.look`
2
+
3
+ Every look part lives at `engine.look.<part>` and is changed with the same verbs. The style pack gives the starting values; the game changes them on top.
4
+
5
+ Exits, in order: `set` params → `patch` (your own GLSL at a named hook) → textures in the material spec (`map`, `normalMap`) → `replace` (your own material or object) → plain three.js (recipe 40 §8). When two rounds of tuning params do not reach the reference, take the next exit instead of tuning on.
6
+
7
+ ```js
8
+ const cave = engine.look.tone.set({ exposure: 0.6 }, { owner: 'cave' }); // only the keys you give; null drops a key
9
+ engine.look.lights.set({ sun: { intensity: 0.5 } }, { owner: 'cave' });
10
+ cave.remove(); // or engine.look.tone.clear('cave'): the style value shows again
11
+ engine.look.env.replace('sky'); // take a part over whole; replace(null) gives it back
12
+ engine.describe().look.tone.exposure; // { value: 0.6, by: 'game:cave', at: 'main.js:12', under: ['style'] }
13
+ engine.catalog('look.tone'); // params with default, why, off; hooks; what replace accepts and loses
14
+ ```
15
+
16
+ - Layers, upper wins: engine default < style < game (each owner; the last one written wins) < `engine.debug.override(owner, 'look.<part>', values)`.
17
+ - `set` / `patch(name, glsl)` / `replace(impl)`: a part offers only the verbs that make sense for it; the others throw with the verb to use. A part whose verb takes other arguments (`materials.replace(role, impl)`) lists the call shape in `engine.catalog('look.<part>').signatures`, and a wrong call quotes it.
18
+ - `by` in describe is `'engine'`, `'style'`, `'game'` (owner `'game'`), `'<layer>:<owner>'` (for example game:cave or debug:probe: the layer, then the owner you passed) or `'three'`. `describe().render` keeps only renderer facts; its `by` is the path of the record to read here (`'look.tone.exposure'`).
19
+ - Look changes are not saved: after a load, set them again from your own state.
20
+ - Changing the three.js object directly (`engine.renderer.toneMappingExposure = 2`) still works; describe tags it `three` and you lose the owner and the debug layer.
21
+ - Old calls and names throw `renamed-api` and name the new call: see [Renamed in 0.2](#renamed-in-02).
22
+ - Your own module's part: `defineLookPart(engine, { id, params, style, apply })`. Every param declares `default`; a default that changes the picture declares `why` and `off`, or `neutral: true` (checked by `npm run check`; R36 checks that the part's `Look<Part>` type lists the same keys). A part author changes records only through the part's methods `write`, `ownerValue`, `extend`, `retract`, `has`, `resolved`, `restyle` (rule R25 flags `part._...`); `validate(key, value)` in the spec rejects a value before anything is written, and an `apply` that throws leaves no layer behind.
23
+
24
+ ## Atmosphere parts (sky module): fog, sky, shadow
25
+
26
+ ```js
27
+ engine.look.fog.set({ far: 220, color: '#9bb' }, { owner: 'cave' }); // kind, color, density, near, far, height, falloff, enabled
28
+ engine.look.fog.replace('manual'); // or a THREE.Fog: the sky stops writing scene.fog; replace(null) gives it back
29
+ engine.look.sky.set({ clouds: { coverage: 0.7, speed: [0.01, 0] }, backdrop: 0x335577 });
30
+ engine.look.sky.patch('layer:aurora', { glsl: '...threedogSkyLayer...', blend: 'add' }); // a named dome layer; patch('layer:aurora', null) removes it
31
+ engine.look.sky.patch('clouds', glsl); // the cloud function; replace(skyboxName | Texture | Object3D) swaps the dome
32
+ engine.look.shadow.set({ type: 'vsm', radius: 3, cascades: 3, maxFar: 150 }); // set only
33
+ ```
34
+
35
+ - `fog` shows `enabled` and `far` (fog reaches full strength at `engine.fogFar`, starting at 0.3 x that) as the visible defaults; turn off with `set({ enabled: false })`. Color, density, near, far, enabled and linear <-> exp2 are live. Kind `'exp'` / `'height'`, `height`, `falloff` and the `'fog'` hook replace three's shared fog shader chunks, so they only work before the first frame (style, `sky({ fog })`, or right after `createEngine`); later they throw and say so.
36
+ - `sky`: `clouds.*` are live uniforms of the dome (they only draw when `clouds.coverage` > 0). A hook change recompiles the dome material once. Style `layers` arrays are named by their `name` key, else `layer0`, `layer1`.
37
+ - `shadow`: no `patch` (the cascade patch is internal) and no `replace` (to own the shadows, light with your own lights: `sky({ sun: false })`).
38
+ - Fog kinds and the fog hook in detail, and taking lights or fog away from the sky entirely (`sky({ sun: 'manual' | false })`, `look.fog.replace('manual')`): [recipe 38](38-environment-look-hooks.md).
39
+
40
+ ## Surface parts: `materials`, `surface`, `ground`, `wind`
41
+
42
+ A change to these parts reaches the materials made **after** it, with one exception: `look.materials.set` of the plain properties `color`, `emissive`, `emissiveIntensity`, `roughness`, `metalness`, `opacity`, `envMapIntensity`, `shininess` and `specular` also changes the materials already made for that role (no recompile; clearing the layer goes back to the style's value). Shader-changing keys (`type`, `steps`, `ramp`, `soften`, `repeat`, `wrap`, `detail`, `lighting`, `patch`, `replace`) and all of `look.surface` are for new materials only (a Material already handed out, or cloned by your game, is not touched; catalog and describe say so as `appliesTo`, and a debug override warns). `engine.look.<part>.object` is the three.js object behind a part; for `materials` it is a function: `engine.look.materials.object('cloth')` is the last Material made for that role, `object()` all of them.
43
+
44
+ ```js
45
+ const L = engine.look;
46
+ L.materials.set({ cloth: { roughness: 0.4, color: 0xf2ece0 } }, { owner: 'shop' }); // merged into style.materials.cloth; any role name
47
+ L.materials.patch('dim', { glsl: { fragment: { color_fragment: 'diffuseColor.rgb *= 0.8;' } } }, { roles: ['metal'] }); // a ShaderPatch on those roles
48
+ L.materials.replace('glass', new THREE.MeshPhysicalMaterial({ transmission: 1 })); // the role is this Material (or (params, purpose, engine) => Material)
49
+ L.surface.set({ lighting: { wrap: 0.3, shadowTint: { color: '#4a5a9a', strength: 0.5 } }, detail: { noise: 'grain', strength: 0.15 } });
50
+ L.surface.set({ ramp: [0.35, 0.7, 1], soften: 0.2 }); // every toon material's ramp
51
+ L.surface.patch('lighting', glsl); // your threedogLighting(...), see recipe 43
52
+ L.ground.set({ shading: 'flat', colors: { grass: '#7cc06b' } }); // colors / biomeColors / steep / variation / shading rebuild the chunks
53
+ L.ground.set({ detail: { noise: 'paper', scale: 0.4, strength: 0.25 } }); // detail layer on the ground (style.terrain.detail)
54
+ L.ground.replace((e) => myGroundMaterial(e)); // Material or (engine) => Material; replace(null) gives it back
55
+ L.wind.set({ frequency: 1.5, amplitude: 0.5 }); // live on every plant, planted ones too
56
+ L.wind.patch('sway', glsl); // threedogWind(...); read when vegetation.add runs, so patch first
57
+ ```
58
+
59
+ - `materials`: `set` / `patch` / `replace` all name a role. `set` merges into spec entries; a role whose style entry is a Material or a function is changed with `replace`. Role names are free: invent new ones (`makeMaterial('lantern-glass')`); the engine only warns on a likely typo of a known role.
60
+ - `surface`: `set` / `patch('lighting' | 'detail', glsl)`; no `replace` (swap a whole material with `materials.replace`). `style.lighting` is the style layer.
61
+ - `ground` (terrain module): `set` / `patch('detail', glsl)` / `replace`. What `terrain({ colors, shading, material })` was given shows as owner `terrain()`.
62
+ - `wind` (vegetation module): `set` / `patch('sway', glsl)`; no `replace`. `style.wind` is the style layer.
63
+ - `set({ role: { key } })` accepts a key `makeMaterial` reads (type, steps, ramp, soften, repeat, wrap, detail, lighting, or a three.js material property); a typo throws.
64
+ - `look.cloudShadow` (cloud shadows, core) stays its own part: its `shadow` is read by every material and by the weather, not only by surfaces.
65
+
66
+ ## Water, weather, post
67
+
68
+ ```js
69
+ engine.look.water.set({ opacity: 0.5, waveHeight: 2 }, { owner: 'storm' }); // live, no recompile
70
+ engine.look.water.set({ foam: { color: 0xffffff }, depthColor: { shallow: 0x88ccdd, deep: 0x003355 } }); // rebuilds the water material once
71
+ engine.look.water.patch('wave', 'float threedogWaterWave(vec3 p, float t) { return sin(p.x + t) * 0.2; }'); // hooks: wave, surface
72
+ engine.look.water.replace((engine, { uniforms, waves, surface }) => myMaterial); // the whole surface (style.water.material)
73
+
74
+ engine.look.weather.set({ 'rain.speed': 10, 'snow.size': 8, 'lightning.brightness': 0.5, overcastColor: '#667' }); // rebuilds that field's particles once
75
+ engine.look.weather.patch('rain.fragment', wholeFragmentShaderText); // rain|snow . vertex|fragment: the WHOLE shader text, not a function
76
+ engine.look.weather.replace({ ash: { shape: 'soft', color: 0x555555 }, rain: { create } }); // null gives the fields back
77
+
78
+ engine.look.post.set({ bloom: { strength: 0.6 }, vignette: false }); // keys: '<effect>.<param>', '<effect>.enabled'
79
+ engine.look.post.patch('tint', { glsl: 'color.rgb *= vec3(1.0, 0.9, 0.8);', slot: 'ldr', order: 5 }); // generates a fuse effect named 'tint'; patch('tint', null) removes it
80
+ engine.look.post.add({ name: 'scan', slot: 'hdr', order: 5, create: (ctx) => myPass }, { owner: 'cave' }); // ONE custom pass; returns { remove() }. Same errors as the chain (duplicate name, second 'scene' pass, depth order) and nothing is added. Tune it with set({ 'scan.<param>': v })
81
+ engine.look.post.replace([bloom(), grain()]); // swaps the whole chain; replace(null) gives the style chain back
82
+ ```
83
+
84
+ - Water: structural keys (`depthColor`, `foam`, the hooks, `replace`) rebuild the shared material once and hand it to every water mesh; the live keys only write a uniform. `water({ opacity: 0.5 })` options are the game layer.
85
+ - Weather: a field the weather table lacks (`snow` in a desert) has no particles; setting it warns once. `replace({ [field]: spec })` holds one object per owner, so list every field you replace in each call; while a field is replaced, `set` on it is ignored.
86
+ - Post: `look.post.set` writes the `game` layer (keys `<effect>.<param>` and `<effect>.enabled`); style effects (bloom, ao ...) are the style layer; `engine.post.get(name)` only reads an effect. MSAA is `engine.post.setAntialias(on)`. Costly effects start off on low-tier devices: `look.post` lists `<effect>.enabled` with `why` and `off`. `postAdd` / `postRemove` stay style-pack parts (they edit the list before the engine exists).
87
+ - `describe().render.post` reads the same records (`by`: style, game, debug).
88
+
89
+ ## Post effect chain
90
+
91
+ Post-processing is an ordered list of named effects (`style.post`, then `look.post`). Each runs in a slot, then by `order` (low first):
92
+ `scene` (replaces the scene render, one at a time, e.g. pixelation) -> `hdr` (linear color: outline, AO, bloom) -> tone mapping -> `ldr` (sRGB: LUT,
93
+ palette, grain, vignette) -> `final` (FXAA / SMAA). An effect is `{ name, slot, order, params, create(ctx) => pass, update?(pass, params) }`; under
94
+ WebGL the pass is any three.js postprocessing Pass, built the first time it is on.
95
+ ```js
96
+ import { bloom, outline, vignette, lut } from '@threedog/post-effects'; // never from another style pack: packs do not depend on each other
97
+ import { LUTPass } from 'three/addons/postprocessing/LUTPass.js';
98
+ const myStyle = { post: [outline({ enabled: true, thickness: 1.5 }), bloom({ strength: 0.2 }), vignette(), lut({ saturation: 1.1 }),
99
+ { name: 'myLut', slot: 'ldr', params: { lut: myLut }, create: ({ params }) => new LUTPass({ lut: params.lut }) }] };
100
+ ```
101
+ - The engine ships no effects. `@threedog/post-effects` (import only what you use) has `bloom`, `ao`, `outline`, `dof` (all `hdr`; outline and dof
102
+ read depth) and `lut` (contrast / saturation / warm-cool / optional 3D LUT), `grain`, `vignette`, `chromatic` (`ldr`). `lut`, `grain`, `vignette`,
103
+ `chromatic`, `dof`, `ao` and `outline` are off until `enabled: true`. To add to or trim a pack's list without replacing it: `postAdd(...effects)` /
104
+ `postRemove(...names)` ([recipe 09](09-style-pack.md), 0b).
105
+ - Depth: an effect that reads scene depth (`needsDepth: true`, e.g. `outline`) must run before any pass that swaps buffers (a `ShaderPass`, a
106
+ scene-slot pixelation pass, the tone-mapping output). A chain that breaks this throws when the effect is added or enabled, naming both effects;
107
+ give the depth reader a lower `order`. `dof` keeps the scene depth (`pass.keepsDepth = true`), so `dof` and `outline` can both be on while `dof`
108
+ has the lower `order` (default: dof 5, outline 10). `threedog style check` reports the other order as an error.
109
+ - `createEngine({ post: { bloom: false } })` overrides an effect's startup on/off; `costly: true` effects start off on low-tier devices. MSAA
110
+ (`antialias`) works with every effect on. The settings menu shows `bloom` / `ao` toggles only when the style registers effects with those names.
111
+ - `fuse`: a light color effect can skip its own fullscreen pass by carrying a GLSL snippet instead of `create()`:
112
+ `fuse: { uniforms: { uMyAmount: 'float' }, values: p => ({ uMyAmount: p.amount }), glsl: 'color.rgb *= 1.0 - uMyAmount * length(vUv - 0.5);' }`.
113
+ Fused effects that are on and next to each other in one slot (never `scene`) compile into one shader and draw in one pass, in `order`. The
114
+ snippet edits `vec4 color` and may use `vUv`, `tDiffuse`, `uTime`, `uResolution`, `fxHash(vec2)`; uniform names are shared by the group, so prefix
115
+ them with the effect name. A snippet that samples `tDiffuse` elsewhere (blur, color fringe) sets `reads: true` and starts a new group.
116
+ `look.post.patch(name, { glsl })` builds such an effect for you.
117
+ - Outline: `outline({ mode: 'depth' | 'normal' | 'both' })`: `depth` (default, silhouettes), `normal` (creases; draws the scene once more with
118
+ normals, so it is `costly`), `both`. `fadeWithDistance: false` keeps lines at any distance; `wobble: 1.5` jitters lines by up to 1.5 px at 8 steps a
119
+ second. To exempt objects: `outline({ offLayer: OUTLINE_OFF_LAYER })` and `mesh.layers.enable(OUTLINE_OFF_LAYER)` (one extra render of just
120
+ those objects; nothing when `offLayer` is `null`).
121
+
122
+ ## sky.modify vs look.lights
123
+
124
+ Two ways to make the light darker or brighter; pick by what you want to keep.
125
+ - `engine.sky.modify('cave', { sun: 0.3, ambient: 0.4, fog: 0.5, tint, tintAmount })` is a **multiplier layer** on what the sky produces each frame (keyframes, weather, season). The time of day keeps moving underneath, layers from different owners multiply, `modify('cave', null)` removes yours, and `sky.modifiers` shows the combined result (read-only). Use it for "darker in the cave" or "ash over the ground" (`groundCover`, `coverAmount`).
126
+ - `engine.look.lights.set({ sun: { intensity: 0.5 } }, { owner: 'cave' })` is an **override layer** on the part's own values: the key you give replaces what the style or the keyframes said, whatever the hour. Use it for "the sun is exactly this".
127
+
128
+ ## Renamed in 0.2 (old call → new call)
129
+
130
+ The old calls below now throw `renamed-api` and the message names the new call (the list is `RENAMED` in `core/renamed.js`; rule R39 keeps the old names out of the repo).
131
+
132
+ | Old call | New call |
133
+ |---|---|
134
+ | `engine.setExposure(v)`, `engine.setToneMapping(m)` | `engine.look.tone.set({ exposure: v })`, `engine.look.tone.set({ mapping: m })` |
135
+ | `engine.sky.setShadow(o)` | `engine.look.shadow.set(o)` |
136
+ | `engine.sky.setEnvironment(o)` | `engine.look.env.replace('sky')` then `engine.look.env.set({ intensity, rotation })`; `replace(false)` turns it off |
137
+ | `engine.weather.define(field, spec)` | `engine.look.weather.replace({ [field]: spec })` |
138
+ | `engine.post.add(effect)` | `engine.look.post.add(effect, { owner })` (one pass, returns `{ remove() }`), `engine.look.post.patch(name, { glsl })` (a color effect) or `engine.look.post.replace([...effects])` (the whole chain) |
139
+ | `engine.post.enable(name, on)`, handle `.set` / `.enable` / `.remove` | `engine.look.post.set({ 'bloom.enabled': on })`, `engine.look.post.set({ 'bloom.strength': 0.6 })`; MSAA: `engine.post.setAntialias(on)` |
140
+ | `engine.look.clouds` | `engine.look.cloudShadow` |
141
+ | `engine.cameraOverride = { owner }` | `const cam = engine.takeCamera('owner', { focus })`; `cam.remove()` releases it |
142
+ | `engine.views.define(name, { pos })` | `engine.views.define(name, { position: [x, y, z] })` |
143
+ | failure `result.reason` (`ops.run` / `can` / `undo`) | `result.code` (reading `reason` throws) |
144
+ | `style.character.create` / `.model` / `.colors` (a body from the style pack) | bodies are assets: `createPlayer({ model: 'humanoid' })` with a pack's `assets` registered, a GLB asset name, or `{ rig }`; part colors are material roles `cloth` / `skin` / `trousers` / `hair`, or `{ colors }` per character ([13-animation](13-animation.md)) |
145
+
146
+ Not renamed (still the way to do it): per-call `makeMaterial(role, params)` keys win for that one material; `applyEffects(mat, { patches })` is the low-level form of `look.materials.patch(name, spec, { roles })`; `style.terrain.*`, `style.wind.*` and `style.lighting` are the style layer of `look.ground` / `look.wind` / `look.surface`.
@@ -0,0 +1,58 @@
1
+ # The ground up close: options and diagnosis
2
+
3
+ Not a standard recipe. Several looks are right for different games, and none is the default. **Decide from the reference images first**: is the
4
+ ground flat color shapes, a painted surface, a photographic texture, or a few lit polygons? Then pick a row. If the ground already looks wrong,
5
+ jump to the symptoms.
6
+
7
+ ## Approaches (pick by the look you want)
8
+ | Look | How | Typical values |
9
+ |---|---|---|
10
+ | Flat color blocks, no detail (minimal, flat illustration; on purpose) | `shading: 'flat'` or `'smooth'`, `colors` / `biomeColors`, no `detail`; a few `variation.patches` with `levels` | `resolution: 16`; `patches: { size: 90, levels: 3, strength: 0.15 }` |
11
+ | Color map + detail layer + near grass (soft variation, crisp borders) | `terrain({ shading: 'texture', colorResolution })`, `style.terrain.detail`, grass with `vegetation.add(name, { nearOnly: true })` | `colorResolution: 128`; `detail: { noise: 'dabs', scale: 0.5, strength: 0.25, normal: 0.03 }` |
12
+ | Tiling or triplanar textures (your own painted, photographed or generated images) | material spec `map` + `repeat`, or `detail: { texture: 'name' }` (`projection: 'triplanar'` on slopes and rocks) | `repeat: 8`; `detail: { texture, scale: 0.5, strength: 0.6 }` |
13
+ | Vertex color + toon lighting | vertex colors from `colors` and `variation.jitter`, `type: 'toon'` with a `ramp`; detail optional | `jitter: { size: 2, min: 0.9, range: 0.15 }`; `ramp: [0.4, 0.75, 1]` |
14
+ | Your own shader or plain three.js | `terrain({ material })`, or recipe 40 section 8 (what you give up) | any |
15
+
16
+ Detail noises (recipe 43): `grain` fine speckle, `paper` fibres, `stroke` directional streaks (stretched on purpose), `dabs` soft oval dabs with
17
+ no direction. `fade` (on by default) removes the detail where its pattern is smaller than a pixel. At run time: `look.ground.set`,
18
+ `look.surface.set({ detail })`, `look.surface.patch('detail', glsl)` (recipe 52).
19
+
20
+ Where each key is defined: `variation` (blend, jitter, patches) recipe 36; `shading`, `colorResolution`, `normals`, `normalFn`, heights from a
21
+ grid recipe 37; `detail` keys recipe 43; run-time changes `look.ground` recipe 52; terrain basics recipe 28.
22
+
23
+ ## Symptom, causes, options
24
+ **Brushed metal at grazing angles.** Cause: `stroke` stretches one axis (`stretch` 6) and `world` projection looks straight down, so a flat
25
+ ground seen at a low angle shows the stretch as long streaks. Options: `noise: 'dabs'` or `'grain'` (no stretch); `stretch: 1`; a smaller
26
+ `strength`; `projection: 'triplanar'` only on slopes; no detail at all if the reference is flat.
27
+
28
+ **Slopes show terraces or creases.** Causes: heights from sparse data with linear (bilinear) interpolation show the data grid as kinks along
29
+ its cell lines (`terrain({ heightmap })` always reads its image bilinearly; `sampleGrid` defaults to `interp: 'linear'`); a coarse mesh
30
+ `resolution` (16 per 64 m chunk = one height every 4 m); `shading: 'flat'`, which lights each triangle on its own so every facet shows.
31
+ Options, any of them: more height samples (a larger image or table), or the data smoothed before the terrain reads it; `sampleGrid(...,
32
+ { interp: 'cubic' })` for smooth heights everywhere outside the terrain module (placement, gameplay; recipe 37 section 7; a terrain `height`
33
+ function runs in a worker and cannot capture a sampler); a finer `resolution` (more triangles, collision and edit cells); `shading: 'smooth'`,
34
+ or `normals: 'smooth'` with `shading: 'texture'`; `diagonal: 'adaptive'` against zigzag ridges; or noise in the `height` function (`n.fbm`; ridges from
35
+ folding it) instead of a sparse table. Terraces can also be the look you want: `interp: 'nearest'`, or a stepped `height`.
36
+
37
+ **Blurry up close.** Cause: the color map is `colorResolution + 2` pixels per 64 m chunk side; 128 is 0.5 m per pixel, which is soft when the
38
+ camera is within a few meters. It does not depend on the mesh `resolution`. On a `low` tier the default is 64 (twice as coarse) unless you set
39
+ it. Options: `colorResolution: 256` (0.25 m; four times the image memory and worker time); a detail layer on top (it is computed per screen
40
+ pixel, so it stays sharp); near grass over the ground; or accept soft color and let a texture carry the fine part.
41
+
42
+ **One flat green.** Cause: not resolution. Color comes from `colors` / `biomeColors` per ground type (`groundType`), `variation.blend`
43
+ (wavelength and `strength` of the two-color noise) and `steep`. One color with no `biomeColors` and a flat blend is one green. Options: two
44
+ colors in `biomeColors` for the type; `blend.strength` 1.5; `variation.patches` with a `tint`; more ground types.
45
+
46
+ **Dark blotches.** Cause: usually cloud shadows (`style.clouds.shadow` above 0), not texture; they drift with `speed`, and bigger clouds mean
47
+ bigger blotches. Test by setting `clouds.shadow: 0` (live: `look.cloudShadow`); if they vanish, lower it or change `scale`. Blotches that
48
+ never move are `variation.patches` or a strong `detail`.
49
+
50
+ **Shimmer far away.** Cause: a pattern smaller than a pixel aliases. `detail.fade` (default) fades it out; `fade: false` keeps it. In your own
51
+ `glsl`, read `threedogDetailFootprint` (one pixel in pattern units; 1 = one cell per pixel) and fade yourself. A `variation.jitter.size` below a
52
+ pixel shimmers the same way; use a few meters, or `shading: 'texture'` (mipmapped).
53
+
54
+ **Near-only vegetation fades out by distance.** Any `nearOnly` species (grass, flowers, pebbles, twigs, snow tufts, debris ...) is placed per chunk ring
55
+ (`maxRing`), whose edge would be a visible line. By default instances shrink toward their base over a band that ends at `maxRing x chunk size` from the
56
+ player (start at 65% of it), so nothing pops per chunk. Tune with `fade: { start: 20, end: 45 }` (metres), or `fade: false` for a hard edge
57
+ (e.g. a species hidden in fog anyway). It is part of the species' own material (no extra draw call or program), keeps wind sway and shadows in step, and is skipped
58
+ when `effects: false`. A larger `maxRing`, fog, or a ground color near the species' base color still help for stylized looks with strong silhouettes.
@@ -3,7 +3,7 @@
3
3
  > Generated by `npm run map` by scanning this folder; paths are relative to it. Pages: /action.html, entry `main.js`.
4
4
  > Content data is in `content/*.js` (condition/effect syntax: `node_modules/threedog/docs/recipes/20-content-actions-save.md`), which main.js hands to the engine with `engine.content.load()`; for the engine API read `node_modules/threedog/docs/API.md` (index) first, then only the module pages listed below.
5
5
 
6
- Content: actions 4 · audio 1 · items 1 · places 1 · props 8 (from templates 8) · templates 4
6
+ Content: actions 4 · audio 1 · items 1 · places 1 · props 8 (from templates 8) · templates 4 · views 2
7
7
 
8
8
  ## Design decisions (hand-written, from DESIGN.md)
9
9
 
@@ -24,14 +24,13 @@ Content: actions 4 · audio 1 · items 1 · places 1 · props 8 (from templates
24
24
 
25
25
  - world: `node_modules/threedog/docs/recipes/18-world.md` · `node_modules/threedog/docs/api/world.md`
26
26
  - sky: `node_modules/threedog/docs/recipes/08-weather-sky.md` · `node_modules/threedog/docs/api/sky.md`
27
- - collision: `node_modules/threedog/docs/recipes/10-blender-level.md` · `node_modules/threedog/docs/api/collision.md`
27
+ - collision: `node_modules/threedog/docs/recipes/12-navmesh.md` · `node_modules/threedog/docs/api/collision.md`
28
28
  - characters: `node_modules/threedog/docs/recipes/12-navmesh.md` · `node_modules/threedog/docs/api/characters.md`
29
29
  - settings: `node_modules/threedog/docs/recipes/26-ui-parts.md` · `node_modules/threedog/docs/api/settings.md`
30
30
  - interactions: `node_modules/threedog/docs/recipes/20-content-actions-save.md` · `node_modules/threedog/docs/api/interactions.md`
31
31
  - inventory: `node_modules/threedog/docs/recipes/03-items-pickups.md` · `node_modules/threedog/docs/api/inventory.md`
32
- - content: `node_modules/threedog/docs/recipes/10-blender-level.md` · `node_modules/threedog/docs/api/content.md`
32
+ - content: `node_modules/threedog/docs/recipes/01-new-game.md` · `node_modules/threedog/docs/api/content.md`
33
33
  - hud: `node_modules/threedog/docs/recipes/04-quests.md` · `node_modules/threedog/docs/api/hud.md`
34
- - debug: `node_modules/threedog/docs/api/debug.md`
35
34
 
36
35
  Not used yet (check these before writing the system yourself):
37
36
 
@@ -46,13 +45,14 @@ content/*.js is content data: how to write it in `node_modules/threedog/docs/rec
46
45
  |---|---|---|
47
46
  | content/actions.js | 9 | |
48
47
  | content/audio.js | 10 | |
49
- | content/index.js | 10 | |
48
+ | content/index.js | 11 | |
50
49
  | content/items.js | 5 | |
51
50
  | content/places.js | 5 | |
52
51
  | content/props.js | 12 | |
53
52
  | content/templates.js | 11 | |
53
+ | content/views.js | 7 | |
54
54
  | look.js | 6 | This example's look, as a style part merged over the lowpoly pack (createEngine({ style: [lowpoly, … |
55
- | main.js | 138 | @ts-check Action example: one room, one player, one slime, one drop. Shows how an action game wires… |
55
+ | main.js | 139 | @ts-check Action example: one room, one player, one slime, one drop. Shows how an action game wires… |
56
56
  | models.js | 26 | Models this example builds in code (floor, wall, pillar, enemy), registered by name in main.js and … |
57
57
 
58
58
  ## NPCs (content/npcs.js)
@@ -119,7 +119,7 @@ Code that breaks saves or manages world models: none (rule R33).
119
119
  - Save slots: slot1
120
120
  - Save entries the game registers itself: ' +
121
121
  'action
122
- - Content-related saves handled by the engine: story flags and counters (engine.vars), inventory, quest progress, timers (clock, after registered by event name), pickups (world), felled trees (vegetation)
122
+ - Saved parts of the engine modules (vars, inventory, quests, timers, world...): `npx threedog catalog` (saves per module)
123
123
 
124
124
  ## Style pack keys
125
125
 
@@ -5,5 +5,6 @@ import actions from './actions.js';
5
5
  import templates from './templates.js';
6
6
  import props from './props.js';
7
7
  import audio from './audio.js';
8
+ import views from './views.js';
8
9
 
9
- export default { places, items, actions, templates, props, audio };
10
+ export default { places, items, actions, templates, props, audio, views };
@@ -0,0 +1,6 @@
1
+ // Named fixed camera views of the room (engine.content.load -> engine.views.define). Same name = same framing every time, so two screenshots
2
+ // differ only by time, style or code: npm run shot -- action --view corner (the page is action.html; add --compare before.png to diff a change).
3
+ export default {
4
+ corner: { position: [7, 5, -8], target: [0, 1, 0], fov: 55 }, // the whole room from a corner, a little above
5
+ door: { position: [0, 2.2, 9], target: [0, 1.2, 0] }, // from the far side looking back at the spawn
6
+ };
@@ -3,7 +3,7 @@
3
3
  // main.js holds rules only: modules, ops (attack, damage, enemy attack, death), fixed-step logic, presentation. The room, the slime and its stats are
4
4
  // content (content/templates.js + props.js, rule R33). The engine has no health, damage or death: all of that is below, as plain game state and ops.
5
5
  import { createEngine, openWorld, followCamera, presets, interactions, inventory, content, hud, toast } from '../../index.js';
6
- import lowpoly from '@threedog/style-lowpoly'; // optional style pack; ?style=none runs with the engine's gray placeholders
6
+ import lowpoly, { assets as lowpolyAssets } from '@threedog/style-lowpoly'; // optional style pack + its asset pack (the humanoid body); ?style=none runs with the engine's gray placeholders
7
7
  import look from './look.js';
8
8
  import data from './content/index.js';
9
9
  import { models } from './models.js';
@@ -30,7 +30,8 @@ engine.use(openWorld({ camera: followCamera({ ...presets.camera.overShoulder, ya
30
30
  const m = models(engine); // the names content/templates.js uses, written out so `npm run check` can see them
31
31
  engine.assets.manifest({ name: 'action', models: { floor: m.floor, wall: m.wall, pillar: m.pillar, enemy: m.enemy } });
32
32
  engine.audio.register('blip', (a, p, out) => { a.tone({ freq: (p.freq ?? 440) * p.pitch, dur: 0.12, out }); return 0.12; }); // content/audio.js names it
33
- engine.characters.createPlayer({ ...presets.player.aim, spawn: TUNE.spawn }); // face where the camera looks: a swing goes where you aim
33
+ if (style) engine.assets.manifest(lowpolyAssets); // the 'humanoid' body; style=none keeps the gray capsule
34
+ engine.characters.createPlayer({ ...presets.player.aim, model: style ? 'humanoid' : null, spawn: TUNE.spawn }); // face where the camera looks: a swing goes where you aim
34
35
  engine.content.load(data, { places: { room: { x: 0, z: 0 } } });
35
36
 
36
37
  // ---------- Game state: plain values, described and saved (one player, so it is not keyed by actor) ----------
@@ -22,11 +22,10 @@ None yet, write them in `DESIGN.md` (why it is designed this way, what not to ch
22
22
  - vegetation: `node_modules/threedog/docs/recipes/10-blender-level.md` · `node_modules/threedog/docs/api/vegetation.md`
23
23
  - sky: `node_modules/threedog/docs/recipes/08-weather-sky.md` · `node_modules/threedog/docs/api/sky.md`
24
24
  - weather: `node_modules/threedog/docs/recipes/08-weather-sky.md` · `node_modules/threedog/docs/api/weather.md`
25
- - collision: `node_modules/threedog/docs/recipes/10-blender-level.md` · `node_modules/threedog/docs/api/collision.md`
25
+ - collision: `node_modules/threedog/docs/recipes/12-navmesh.md` · `node_modules/threedog/docs/api/collision.md`
26
26
  - characters: `node_modules/threedog/docs/recipes/12-navmesh.md` · `node_modules/threedog/docs/api/characters.md`
27
27
  - settings: `node_modules/threedog/docs/recipes/26-ui-parts.md` · `node_modules/threedog/docs/api/settings.md`
28
- - content: `node_modules/threedog/docs/recipes/10-blender-level.md` · `node_modules/threedog/docs/api/content.md`
29
- - debug: `node_modules/threedog/docs/api/debug.md`
28
+ - content: `node_modules/threedog/docs/recipes/01-new-game.md` · `node_modules/threedog/docs/api/content.md`
30
29
 
31
30
  Not used yet (check these before writing the system yourself):
32
31
 
@@ -99,7 +98,7 @@ Code that breaks saves or manages world models: none (rule R33).
99
98
  ## Saves
100
99
 
101
100
  - Save prefix saveKey: threedog-sheepisland
102
- - Content-related saves handled by the engine: story flags and counters (engine.vars), inventory, quest progress, timers (clock, after registered by event name), pickups (world), felled trees (vegetation)
101
+ - Saved parts of the engine modules (vars, inventory, quests, timers, world...): `npx threedog catalog` (saves per module)
103
102
 
104
103
  ## Style pack keys
105
104
 
@@ -28,11 +28,11 @@ None yet, write them in `DESIGN.md` (why it is designed this way, what not to ch
28
28
  - sky: `node_modules/threedog/docs/recipes/08-weather-sky.md` · `node_modules/threedog/docs/api/sky.md`
29
29
  - weather: `node_modules/threedog/docs/recipes/08-weather-sky.md` · `node_modules/threedog/docs/api/weather.md`
30
30
  - water: `node_modules/threedog/docs/recipes/44-water-weather-look-hooks.md` · `node_modules/threedog/docs/api/water.md`
31
- - collision: `node_modules/threedog/docs/recipes/10-blender-level.md` · `node_modules/threedog/docs/api/collision.md`
31
+ - collision: `node_modules/threedog/docs/recipes/12-navmesh.md` · `node_modules/threedog/docs/api/collision.md`
32
32
  - rigid: `node_modules/threedog/docs/recipes/11-vehicles.md` · `node_modules/threedog/docs/api/rigid.md`
33
33
  - characters: `node_modules/threedog/docs/recipes/12-navmesh.md` · `node_modules/threedog/docs/api/characters.md`
34
34
  - ambience: `node_modules/threedog/docs/recipes/31-audio.md` · `node_modules/threedog/docs/api/ambience.md`
35
- - …8 more modules: their pages are in `node_modules/threedog/docs/api/`
35
+ - …7 more modules: their pages are in `node_modules/threedog/docs/api/`
36
36
 
37
37
  Not used yet (check these before writing the system yourself):
38
38
 
@@ -126,7 +126,7 @@ Code that breaks saves or manages world models: none (rule R33).
126
126
  ## Saves
127
127
 
128
128
  - Save prefix saveKey: threedog-styletest
129
- - Content-related saves handled by the engine: story flags and counters (engine.vars), inventory, quest progress, timers (clock, after registered by event name), pickups (world), felled trees (vegetation)
129
+ - Saved parts of the engine modules (vars, inventory, quests, timers, world...): `npx threedog catalog` (saves per module)
130
130
 
131
131
  ## Style pack keys
132
132
 
@@ -2,7 +2,7 @@
2
2
  export default {
3
3
  guide: {
4
4
  name: 'Guide',
5
- colors: { body: 0x4f6d8f, legs: 0x5b4a3a, hair: 0xd8d4cc },
5
+ model: 'humanoid', colors: { body: 0x4f6d8f, legs: 0x5b4a3a, hair: 0xd8d4cc },
6
6
  start: { place: 'stage', x: 2.5, z: 4 }, behavior: 'wander', mind: { radius: 0 },
7
7
  },
8
8
  };
@@ -42,9 +42,9 @@ engine.use(openWorld({ camera: fixedCamera(), seed: SEED, terrain: terrainPreset
42
42
 
43
43
  engine.assets.manifest(lowpolyAssets);
44
44
  engine.assets.manifest({ name: 'styletest', models: { woodBlock, stoneBlock, metalBall, glassPanes, shadowStage, room } }); // the names content/templates.js uses
45
- engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: { x: stage.x + 0.5, z: stage.z + 6 } });
45
+ engine.characters.createPlayer({ ...presets.player.thirdPerson, model: params.style === 'none' ? null : 'humanoid', spawn: { x: stage.x + 0.5, z: stage.z + 6 } }); // style=none: the gray capsule
46
46
  engine.content.load(data, { places: { stage, water } });
47
- if (params.env) { engine.sky.setEnvironment({ source: 'sky', intensity: 0.8 }); engine.sky.modify('env', { ambient: 0.6 }); } // soft ambient from the sky: lower the hemisphere ambient so shadows stay
47
+ if (params.env) { engine.look.env.replace('sky'); engine.look.env.set({ intensity: 0.8 }); engine.sky.modify('env', { ambient: 0.6 }); } // soft ambient from the sky: lower the hemisphere ambient so shadows stay
48
48
 
49
49
  // ---------- 2. The room's lamp: emissive plus one pooled light, on from 18:00 to 06:00 ----------
50
50
  const lampPos = [stage.x + 14, engine.surface(stage.x + 14, stage.z - 2) + 2.7, stage.z - 2];