threedog 1.4.0 → 2.1.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 (184) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +13 -7
  3. package/bin/threedog.mjs +42 -0
  4. package/core/assets/assetEntry.js +1 -1
  5. package/core/assets/assetPart.js +1 -1
  6. package/core/base/Events.js +7 -1
  7. package/core/base/errorCodes.js +1 -1
  8. package/core/base/events.generated.js +2 -2
  9. package/core/engine/Engine.js +11 -7
  10. package/core/engine/copies.js +1 -1
  11. package/core/engine/moduleTypes.js +1 -1
  12. package/core/engine/modules.js +23 -6
  13. package/core/engine/page.js +1 -0
  14. package/core/engine/services.js +5 -3
  15. package/core/engine/startup.js +4 -1
  16. package/core/inspect/DebugOverrides.js +2 -2
  17. package/core/inspect/InspectPerf.js +1 -1
  18. package/core/inspect/describeRender.js +0 -7
  19. package/core/inspect/metadata.generated.js +139 -50
  20. package/core/inspect/pictureChecks.js +2 -27
  21. package/core/ops/control.js +3 -3
  22. package/core/ops/holds.js +8 -3
  23. package/core/ops/sharedPoint.js +11 -2
  24. package/core/saves/saveApply.js +3 -3
  25. package/core/saves/session.js +20 -4
  26. package/core/scene/adaptive.js +5 -2
  27. package/core/scene/pixelRatio.js +39 -17
  28. package/core/scene/sceneMethods.js +1 -1
  29. package/core/scene/things.js +3 -2
  30. package/core/scene/tier.js +2 -16
  31. package/core/scene/view.js +14 -0
  32. package/core/time/skip.js +1 -1
  33. package/docs/AI.md +2 -2
  34. package/docs/CODEMAP.md +8 -8
  35. package/docs/COMMANDS.md +2 -2
  36. package/docs/CONVENTIONS.md +1 -0
  37. package/docs/THREE.md +1 -1
  38. package/docs/api/ambience.md +2 -2
  39. package/docs/api/cameraRig.md +7 -0
  40. package/docs/api/engine.md +6 -3
  41. package/docs/api/events.md +3 -3
  42. package/docs/api/particles.md +1 -1
  43. package/docs/api/photo.md +5 -0
  44. package/docs/api/pickups.md +1 -1
  45. package/docs/api/post.md +1 -1
  46. package/docs/api/rigid.md +1 -1
  47. package/docs/api/sky.md +11 -1
  48. package/docs/api/terrain.md +19 -0
  49. package/docs/api/tools.md +1 -1
  50. package/docs/recipes/01-new-game.md +1 -1
  51. package/docs/recipes/03-items-pickups.md +1 -1
  52. package/docs/recipes/05-props-bake.md +1 -1
  53. package/docs/recipes/06-clock-events.md +3 -10
  54. package/docs/recipes/07-flow-scenes-pause.md +3 -4
  55. package/docs/recipes/09-materials-lights-models.md +1 -1
  56. package/docs/recipes/10-blender-level.md +2 -2
  57. package/docs/recipes/{11-vehicles.md → 11-physics.md} +13 -5
  58. package/docs/recipes/12-navmesh.md +3 -3
  59. package/docs/recipes/14-custom-module.md +6 -5
  60. package/docs/recipes/15-perf.md +1 -1
  61. package/docs/recipes/16-dev-bridge.md +1 -1
  62. package/docs/recipes/18-world.md +1 -1
  63. package/docs/recipes/20-content-actions-save.md +0 -1
  64. package/docs/recipes/21-camera.md +11 -1
  65. package/docs/recipes/26-ui-parts.md +2 -2
  66. package/docs/recipes/27-net.md +1 -1
  67. package/docs/recipes/29-grid.md +1 -1
  68. package/docs/recipes/34-environment-lighting.md +5 -3
  69. package/docs/recipes/40-scene.md +1 -1
  70. package/docs/recipes/44-water-weather-hooks.md +1 -1
  71. package/docs/recipes/45-cascaded-shadows.md +6 -3
  72. package/docs/recipes/51-capability-catalog.md +1 -1
  73. package/docs/recipes/52-around-the-picture.md +8 -8
  74. package/docs/recipes/53-ground-up-close.md +2 -2
  75. package/docs/recipes/55-mods-time-wrap.md +6 -8
  76. package/docs/recipes/57-control.md +1 -1
  77. package/docs/recipes/59-depth-post-effects.md +1 -1
  78. package/docs/recipes/60-judge-the-picture.md +7 -7
  79. package/docs/recipes/62-picture-code.md +13 -17
  80. package/examples/action/GAMEMAP.md +4 -2
  81. package/examples/action/picture/lights.js +3 -2
  82. package/examples/perf-island/GAMEMAP.md +2 -1
  83. package/examples/perf-island/picture/lights.js +3 -2
  84. package/examples/styletest/GAMEMAP.md +2 -2
  85. package/examples/styletest/picture/env.js +1 -2
  86. package/examples/techniques/contact-shadows/README.md +1 -1
  87. package/examples/techniques/day-night-grade/picture/lights.js +3 -1
  88. package/examples/techniques/interior-light/README.md +1 -1
  89. package/examples/techniques/interior-light/picture/lights.js +4 -2
  90. package/examples/techniques/modular-building/picture/lights.js +3 -2
  91. package/examples/techniques/night-lights/README.md +1 -1
  92. package/examples/techniques/night-lights/picture/lights.js +3 -1
  93. package/examples/techniques/night-lights/picture/post.js +2 -2
  94. package/examples/techniques/outlines-and-rim/README.md +1 -1
  95. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -2
  96. package/examples/techniques/procedural-animation/README.md +1 -1
  97. package/examples/techniques/procedural-animation/picture/lights.js +3 -1
  98. package/examples/techniques/procedural-surface/README.md +1 -1
  99. package/examples/techniques/procedural-surface/picture/lights.js +3 -1
  100. package/examples/techniques/stylized-shading/picture/lights.js +3 -1
  101. package/examples/techniques/wet-road/README.md +1 -1
  102. package/examples/techniques/wet-road/picture/lights.js +3 -1
  103. package/examples/webgpu-tsl/GAMEMAP.md +4 -2
  104. package/examples/webgpu-tsl/picture/lights.js +3 -1
  105. package/examples/world/GAMEMAP.md +4 -3
  106. package/examples/world/picture/lights.js +3 -1
  107. package/examples/world/picture/post.js +2 -2
  108. package/llms.txt +33 -7
  109. package/modules/camera/common.js +22 -20
  110. package/modules/camera/contract.js +1 -1
  111. package/modules/characters/Character.js +2 -2
  112. package/modules/characters/NPC.js +7 -8
  113. package/modules/characters/index.js +8 -8
  114. package/modules/characters/mover.contract.js +1 -1
  115. package/modules/characters/movers/rapier.js +7 -9
  116. package/modules/characters/npcAvoid.js +2 -2
  117. package/modules/characters/player.js +11 -15
  118. package/modules/characters/playerStrings.js +1 -2
  119. package/modules/characters/seat.js +1 -1
  120. package/modules/collision/Collision.js +1 -1
  121. package/modules/collision/grid.js +1 -1
  122. package/modules/content/index.js +4 -3
  123. package/modules/content/models.js +1 -1
  124. package/modules/content/templates.js +3 -2
  125. package/modules/flow/index.js +8 -8
  126. package/modules/gameplay/Dialogue.js +1 -1
  127. package/modules/gameplay/Inventory.js +3 -3
  128. package/modules/gameplay/Quests.js +1 -0
  129. package/modules/gameplay/inventory.contract.js +1 -1
  130. package/modules/gameplay/pickups.js +1 -1
  131. package/modules/gameplay/questLog.js +0 -1
  132. package/modules/grid/index.js +1 -1
  133. package/modules/grid/tiles.js +6 -3
  134. package/modules/hud/index.js +2 -2
  135. package/modules/level/contract.js +2 -2
  136. package/modules/level/index.js +1 -1
  137. package/modules/music/Music.js +1 -1
  138. package/modules/nav/index.js +1 -1
  139. package/modules/net/sync.js +1 -1
  140. package/modules/particles/Particles.js +12 -5
  141. package/modules/particles/effect.js +17 -3
  142. package/modules/photo/pathTrace.js +1 -1
  143. package/modules/rigid/RigidBodies.js +23 -9
  144. package/modules/rigid/ragdoll.js +1 -1
  145. package/modules/rigid/sync.js +14 -0
  146. package/modules/settings/Settings.js +3 -2
  147. package/modules/settings/apply.js +4 -3
  148. package/modules/settings/sections.js +1 -1
  149. package/modules/sky/Sky.js +9 -4
  150. package/modules/sky/environment.js +5 -3
  151. package/modules/terrain/index.js +1 -2
  152. package/modules/timeline/Timeline.js +9 -6
  153. package/modules/vegetation/Vegetation.js +1 -1
  154. package/modules/vegetation/index.js +1 -1
  155. package/modules/weather/weatherDraw.js +1 -2
  156. package/modules/world/World.js +1 -0
  157. package/modules/world/index.js +1 -0
  158. package/modules/world/persist.js +1 -1
  159. package/package.json +6 -2
  160. package/render/PostFX.js +17 -12
  161. package/render/fx/postWebGPU.tsl.js +2 -1
  162. package/render/lightmap.js +1 -1
  163. package/render/lights.js +1 -2
  164. package/render/neutral.js +1 -1
  165. package/render/patches.js +3 -3
  166. package/render/probes.js +27 -2
  167. package/render/shaderErrors.js +1 -1
  168. package/render/shadows.js +1 -3
  169. package/types/core.d.ts +16 -9
  170. package/types/gameplay.d.ts +8 -3
  171. package/types/generated/modules/sky/Sky.d.ts +4 -4
  172. package/types/generated/render/PostFX.d.ts +2 -2
  173. package/types/generated/ui/UI.d.ts +2 -1
  174. package/types/physics.d.ts +1 -1
  175. package/types/world.d.ts +4 -2
  176. package/ui/UI.js +18 -14
  177. package/ui/cursor.js +2 -2
  178. package/examples/action/.threedog/content-index.json +0 -1
  179. package/examples/perf-island/.threedog/content-index.json +0 -1
  180. package/examples/plain-picture/.threedog/content-index.json +0 -1
  181. package/examples/rc2d/.threedog/content-index.json +0 -1
  182. package/examples/styletest/.threedog/content-index.json +0 -1
  183. package/examples/webgpu-tsl/.threedog/content-index.json +0 -1
  184. package/examples/world/.threedog/content-index.json +0 -1
@@ -135,7 +135,7 @@ The shape of an item on the ground is a model name from an asset pack, built thr
135
135
  else a model named `pickup:<item id>`, else one named `pickup`, else a neutral gray box. A generator that returns bare geometry is drawn with
136
136
  `engine.pickups.material` in the item's own `color`.
137
137
  ```js
138
- engine.use(pickups({ color: 0xd8c070, size: 0.3, lift: 0.5 })); // default color, placeholder box, height above the ground
138
+ engine.use(world(), pickups({ color: 0xd8c070, size: 0.3, lift: 0.5 })); // default color, placeholder box, height above the ground
139
139
  engine.pickups.material = new THREE.MeshStandardMaterial({ metalness: 0.8, roughness: 0.3 }); // swaps every box and geometry-only model; used as given
140
140
  ```
141
141
  A pickup or item with its own `color`, and a vertex-colored geometry, draw with a copy of that material carrying the color. For one object of the game's own pass
@@ -124,7 +124,7 @@ has keys, unless its bake entry says `source: 'file'`.
124
124
 
125
125
  Very detailed models (faces, sculpted shapes, hand-painted textures) are faster in Blender: export a GLB and register it (recipe 46).
126
126
 
127
- ## 2b. Many copies of one model: automatic batching
127
+ ## 2b. Many copies of one model: automatic batching (thousands of trees and rocks)
128
128
  Nothing to write for what the engine places: `engine.batching` (core) covers world record views (props, templates, grid items, `world.present`),
129
129
  `stream` builds and level files. When the same geometry + material (+ shadow flags) appears at least 8 times in one cell (256 m by default), those meshes are
130
130
  drawn by one real `THREE.InstancedMesh` per cell; fewer stay plain meshes. Each placed object stays in the scene with its own userData, record,
@@ -16,20 +16,13 @@ engine.onFixed(dt => moveEnemies(dt), { channel: 'enemies' }); // this dt is al
16
16
  `engine.mod(target, { owner, mul | add | set | clamp, for, clock })` is the one entry for every quantity several systems share (time channels,
17
17
  `'clock.rate'`, `'freeze'`, your own from `engine.stacks.define(name, { base })`). It returns `{ remove() }`; `remove()` ends only this owner's entry.
18
18
  Details, only when you need them:
19
- - One entry per owner: the same owner modding again updates its entry. Ending one recomputes from the base and the entries left, so effects can end
20
- in any order (bullet time ending under a stopwatch never "restores" a stale value).
21
- - Combine order and conflicts: `55-mods-time-wrap.md` (one layer table for every shared value; a stopwatch `set: 0, layer: 'effect'` beats any
22
- slow-down; two owners `set` on one layer is an error in development).
19
+ - One entry per owner, layers and conflicts: `55-mods-time-wrap.md`.
23
20
  - `for: seconds` ends it by itself, counted on `clock`: `'real'` (default; real seconds, which stop while frozen, so a pause menu does not use up a
24
- bullet time) or a channel name (`clock: 'enemies'`: a slow that lasts 3 enemy seconds lasts longer in bullet time). Each end emits `mod:end`
21
+ bullet time) or a channel name (`clock: 'enemies'`: slowed by bullet time too). Each end emits `mod:end`
25
22
  `{ target, owner, id }`. Saved with the time left; `engine.skip` ends them at the right point of the jump.
26
23
  - One record only: `engine.mod('time.local', { owner: 'stopwatch', id: 'slime_3', set: 0, layer: 'effect' })` (its speed = channel x local).
27
24
  `world.remove(id)` drops that record's entries.
28
- - Reading: `engine.time.scale('enemies', id?)`, `engine.time.now('enemies')`, `engine.clock.rate`; `describe().time.channels` lists speeds and
29
- holders. Saved: entries below `'system'`; `system` / `debug` ones (menus, debug panel) are screen state and are taken again after a load.
30
- - Freeze is not speed 0: a frozen engine runs no fixed step, so no channel moves, no `for` runs down and input is not read.
31
- - Plain JS keeps working: your own fields and `onFixed(dt => ...)` logic need none of this. Use `engine.mod` for quantities more than one system writes.
32
- - Order inside a fixed step: `onFixed(fn)` runs before the modules (player not moved yet), `onFixed(fn, { phase: 'late' })` after them. Stacks, `input.gate` and `engine.wrap` together: recipe 55.
25
+ - Reading: `engine.time.scale(ch, id?)`, `engine.time.now(ch)`; `describe().time.channels` lists speeds and holders. Saved: entries below `'system'`; `system` / `debug` ones (menus, debug panel) are screen state and are taken again after a load.
33
26
 
34
27
  ## The time table (the single source; other docs link here)
35
28
  **One time source.** `engine.time` counts one thing, `engine.time.tick` (fixed steps run). Every other time is a
@@ -90,7 +90,7 @@ page's saves, so the title offers no Continue; on a running page it also ends th
90
90
  advances only on `engine.step`, so a `weather.set(name, { seconds: 0.1 })` made after `start()` is still changing (use `seconds: 0`), and an `onFrame` copy of a sky
91
91
  color is one frame old (share `engine.uniforms.uSkyHorizon` instead, recipe 08).
92
92
 
93
- ## 2. Changing scene / teleporting
93
+ ## 2. Changing scene / teleporting / spawning at a chosen spot (testing)
94
94
  ```js fragment
95
95
  // A level-based game: switch to another map
96
96
  await engine.flow.transition(async () => {
@@ -113,8 +113,8 @@ is a builder in the assets manifest (recipe 66, "Two areas built in code"); a `l
113
113
 
114
114
  Saves live in the browser's IndexedDB (falling back to localStorage, with one notice). `save()` / `remove()` / `load()` return a Promise (a failed write shows a notice), while
115
115
  `list()` / `export()` are synchronous (saves are read into memory at startup). Attachments, file backup and `storageKey`: `../api/saves.md`.
116
- For just a fade-to-black, without locking input or saving: `await fadeScreen(engine, 1, { seconds: 0.5 }); ...; await fadeScreen(engine, 0, { seconds: 0.5 });` (import from `threedog`).
117
- Fades inside a cutscene use the timeline steps `{ fade: 0.5 }`, `{ fade: 0.5, to: 0 }`.
116
+ For just a fade-to-black, without locking input or saving: `await fadeScreen(engine, 1, { seconds: 0.5 }); ...; await fadeScreen(engine, 0, { seconds: 0.5 });` (import from `threedog`). `{ owner }` names who holds the cover (default 'game'); a transition or a cutscene does not clear a cover the game holds.
117
+ Fades inside a cutscene use the timeline steps `{ fade: 0.5 }`, `{ fade: 0.5, to: 0 }`. A cutscene that ends dark hands its cover to the scene change: the next `flow.transition` lifts it (to lift it yourself, `fadeScreen(engine, 0, { owner: 'flow' })`).
118
118
 
119
119
  ## 2b. Input contexts (menus, vehicles, build mode)
120
120
  Who declares an action and who binds its keys: recipe 58.
@@ -170,4 +170,3 @@ One place listens to window focus, tab visibility, mouse lock and the WebGL cont
170
170
  `page:pointerlock { locked, byEngine }` (cameras lock again on the next click; a lock the player ended counts as Esc, because the browser keeps that key), `page:contextlost` / `page:contextrestored` (the same freeze, and the player
171
171
  sees a message; three.js restores the context).
172
172
  - `engine.step()` still advances while away (tests, dev bridge). Held keys are released by Input.
173
- - Tests: `threedog test "Session:" "Window:"`.
@@ -26,7 +26,7 @@ thing that only changes pixels is a write on the module's three.js material. The
26
26
  separate package, `@threedog/terrain-noise`, because the shape of the world is gameplay. Post effects such as `bloom` / `ao` / `outline` come from
27
27
  `@threedog/post-effects` and go in as `plugins/` files (recipe 40 §1, chain order: recipe 52).
28
28
 
29
- ## 1. Materials are plain three.js
29
+ ## 1. Materials are plain three.js: which kind for which look
30
30
  `new THREE.MeshStandardMaterial(...)`, `MeshToonMaterial`, your own shading in TSL (WebGPU, recipe 56) or GLSL (WebGL only, recipe 43): all work as in any three.js project, and a plain material gets fog and
31
31
  cascaded shadows by itself. Keep them in `picture/materials.js` by name, and let other code ask for `picture.materials.wall`, so a change of picture touches one folder.
32
32
 
@@ -24,8 +24,8 @@ hierarchy are kept; faces are not reduced. Only changed files are processed; `--
24
24
 
25
25
  ## 3. Putting it in the game (main.js)
26
26
  ```js fragment
27
- import { presets, level, collision, followCamera, characters, interactions, dialogue, triggers, content, hlod } from 'threedog';
28
- engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), characters(), interactions({ ...presets.interactions.nearest }), dialogue(), triggers(), content(), hlod());
27
+ import { presets, level, world, collision, followCamera, characters, interactions, dialogue, triggers, content, hlod } from 'threedog';
28
+ engine.use(level({ url: '/models/town.glb' }), world(), collision(), followCamera(), characters(), interactions({ ...presets.interactions.nearest }), dialogue(), triggers(), content(), hlod());
29
29
  engine.events.once('level:loaded', () => { // once: level:loaded fires again on every level change
30
30
  engine.characters.addPlayer({ ...presets.player.thirdPerson, spawn: engine.level.spawn });
31
31
  engine.content.load(data); // a place in content can be a marker name directly: { place: 'npc_shopkeeper' }
@@ -3,12 +3,12 @@
3
3
  > **Covers:** rigid bodies, pushing, joints, vehicles, boarding and driving, ragdolls.
4
4
  > **Use when:** crates that tumble, doors on hinges, a car or a boat.
5
5
  > **Shortest:** `engine.rigid.addBox(mesh, { id })` with `rigid()` installed (§3).
6
- > **Sections:** 1 Build a car · 2 Boarding and driving · 3 Rigid bodies saves · 3b Ragdoll experimental) · 4 Verify
6
+ > **Sections:** 1 Build a car · 2 Boarding and driving · 3 Rigid bodies saves · 3b Ragdoll experimental) · 3c Explosions, stacks, solver · 4 Verify
7
7
 
8
8
  Any physics body (crates the player pushes, balls, doors on hinges, ropes): §3, read it first when the game has no car. Cars and
9
9
  boarding: §1–2.
10
10
 
11
- Required modules: `collision()` + `rigid()` (Rapier physics; the vehicle controller lives there) + `characters()`. With
11
+ Required modules: `collision()` + `rigid()` (Rapier, with the vehicle controller) + `world()` + `characters()` (the player and NPCs are world records). With
12
12
  `interactions({ ...presets.interactions.nearest })` installed, a "board/exit" prompt (E key) appears automatically near a vehicle.
13
13
  Convention: **the front of the car faces the model's +Z**, and a wheel's `position` is relative to the body origin (meters). Rapier has to be
14
14
  downloaded and initialized, so build the car after `engine:ready`.
@@ -59,7 +59,7 @@ This section covers every `engine.rigid` body (crates, balls, hulls, vehicles),
59
59
  ahead. The mover leaves dynamic bodies out of its own collision, so a body is pushed instead of stopping the player; how hard it resists is
60
60
  its `mass` and friction. A body that should stop the player is `{ fixed: true }` with `mover: 'rapier'` (that mover collides with fixed bodies).
61
61
  A puzzle reads the result from the body (`entry.body.translation()` in `onFixed`, or a trigger zone) and gives the body an `id`, so a save keeps
62
- where it was pushed. Test: `threedog test "rigid push"` (both movers).
62
+ where it was pushed.
63
63
 
64
64
  **Far bodies freeze.** On chunked terrain only the chunks within `rigid({ terrainRing })` of the player (default 1 ring) have terrain colliders. A
65
65
  body outside them stops (`entry.enabled` is false, `describe().rigid.frozen` counts them) instead of falling through the ground, and goes on when
@@ -93,8 +93,7 @@ stay). Removing a body removes its joints (Rapier does that).
93
93
 
94
94
  **Determinism**, the one place this is stated (replay, `engine.step`, saves and net link here):
95
95
  - Same build, same machine, same inputs and the same number of fixed steps give bit-identical bodies, in a fresh page and at any frame rate.
96
- Physics only advances in fixed steps. Test: `threedog test "rigid determinism"`: stacked boxes knocked over, a rolling ball, a driving car, the
97
- `mover: 'rapier'` player, two fresh pages, `frameEvery` 1 / 2 / 4.
96
+ Physics only advances in fixed steps.
98
97
  - A load restores each saved body exactly. Rapier's contact and warm-start caches and its solver order are not saved, so the run after a load
99
98
  is not bit-identical to the run that went on without the load: a toppling stack can end some centimetres away. Bodies at rest stay at rest.
100
99
  - Across machines: the engine uses `@dimforge/rapier3d-compat`, which Rapier does not promise to be cross-platform deterministic (that is the
@@ -127,6 +126,15 @@ engine.clock.after(4, () => rd.remove(), { channel: 'real' }); // back to anima
127
126
  Without `id` it covers every body; a function `(facts, engine) => graph` picks per body; `false` makes `ragdoll()` return null.
128
127
  - **Left out:** partial or blended ragdoll (an arm thrown by a hit while the rest animates); `remove()` cuts to the animation.
129
128
 
129
+ ## 3c. Explosions, stacks and solver settings (when to add bodies)
130
+
131
+ **When.** Calls that return a Rapier body (`addBox`, `addBall`, `addHull`, `addWheeled`, `ragdoll`) run after `await engine.start()`; `collider3d.addSolid` works before.
132
+
133
+ **Explosion.** Loop over `engine.rigid.bodies` and call `engine.rigid.impulse(b, dirFromBlast * falloff)`: it wakes a sleeping body first.
134
+ **Stacks.** The collider is exactly `size`; resting boxes overlap a little (soft contacts: ~0.7 cm a layer, ~5 cm under a body 50x heavier),
135
+ the same at 4, 8 or 16 solver iterations: keep touching masses close. Iterations (joint chains): `engine.rigid.world.integrationParameters.numSolverIterations`
136
+ (default 4), kept through newGame and a load.
137
+
130
138
  ## 4. Verify
131
139
  - In a test (no real key presses): `engine.player.enter(car); engine.input.autopilot = { x: 0, y: 1 }; engine.step(3)`,
132
140
  then `describe().player.vehicle.speed` is above 0 and the car has moved; after `engine.player.exit()`, `engine.player.vehicle` is null and the
@@ -14,8 +14,8 @@ There is a single pathfinding entry point: `engine.characters.findPath(from, to)
14
14
  ## 1. Install (main.js)
15
15
  A level is a file or a `THREE.Object3D` built in code: `level({ scene: group })`, its meshes named as in `10-blender-level.md`.
16
16
  ```js fragment
17
- import { level, collision, followCamera, characters, nav } from 'threedog';
18
- engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), characters(),
17
+ import { level, world, collision, followCamera, characters, nav } from 'threedog';
18
+ engine.use(level({ url: '/models/town.glb' }), world(), collision(), followCamera(), characters(),
19
19
  nav({ agentRadius: 0.4, agentHeight: 1.8, maxClimb: 0.45, maxSlope: 45, debug: false })); // debug: true draws the navmesh
20
20
  ```
21
21
  - Mesh source: the walkable meshes in the level (naming convention in `10-blender-level.md`). Walls = the level's `col_` boxes + every
@@ -56,7 +56,7 @@ engine.characters.pathsPerStep = 64; // requests sent per fixed step (default 3
56
56
  if either changes while a batch is in flight, that batch is recomputed on the main thread on the new state.
57
57
  - With A*, ground shape (height, water, slope) is sampled on a 1 m raster cached 5 s, every floor of it, so what stands under a bridge or a storey counts as it does for `findPath` (colliders and terrain trees are tested exactly), and the search stays inside
58
58
  the start-goal box plus a margin, so an async path can differ slightly from `findPath`'s.
59
- - A save taken while a request is in flight does not keep it: the NPC asks again after loading. Tests: `threedog test "paths:"`.
59
+ - A save taken while a request is in flight does not keep it: the NPC asks again after loading.
60
60
 
61
61
  ## 5. One source for "can walk there"
62
62
  `createEngine({ movement: { radius, height, maxSlope, stepHeight } })` sets it once; read it as `engine.movement`. Collision, the Rapier capsule, the
@@ -68,7 +68,7 @@ No subtypes: inside a type the differences are declarations (`provides`, `requir
68
68
  A module that does two kinds of thing is two definitions returned together (`weather()` returns the `weather` state and the `weatherDraw` drawing part;
69
69
  `engine.use(weather())` installs both). The warning comes once and refuses nothing: it names the module, its type, what it did, why not, and the fix. A game's own module may do what it needs; a split into two modules is usually the fix.
70
70
 
71
- ## 2. Hooks and order cheat sheet
71
+ ## 2. Hooks and order cheat sheet; who frees materials and textures when a module goes
72
72
  - `install(e, ctx)` returns the public object; `init(e, ctx)` (may be async) prepares at start; `ctx.track(handle)` ties a listener or timer to
73
73
  the module (next bullet but four); while `isReady(e)` returns false the loading screen waits for it
74
74
  (the hook is called isReady; `ready` is always a boolean property in the engine); `afterLoad(e, turn)` (may be async; recipe 20 says what `turn` is for) runs after a save loaded, to rebuild
@@ -101,8 +101,8 @@ A module that does two kinds of thing is two definitions returned together (`wea
101
101
  `engine.use` of the same module works; a save part's data stays in the save and goes back to the part when it registers again.
102
102
  - Listeners and timers the module adds go through `ctx.track(...)`: `ctx.track(e.events.on('item:add', fn))`, also `onFixed` / `onFrame` /
103
103
  `clock.after` / `audio.measure` / a `makeWindow` window, anything with `remove()`. They leave with the module: when its `engine.use(...)` batch
104
- rolls back, when its `init` fails, and on `engine.dispose()` before its `dispose` hook (the spec `threedog test "Lifecycle: every built-in"`
105
- checks every engine module). A class the module builds takes `ctx` as a constructor argument. DOM listeners use
104
+ rolls back, when its `init` fails, and on `engine.dispose()` before its `dispose` hook.
105
+ A class the module builds takes `ctx` as a constructor argument. DOM listeners use
106
106
  `addEventListener(type, fn, { signal: engine.signal })`, and UI elements attach to `engine.uiRoot` (not `document.body`); jobs and stream
107
107
  entries are collected by `engine.dispose()`; scene GPU memory is its creator's: `engine.dispose()` does not free the meshes, materials and textures you made, so track their removal: `ctx.track({ remove: () => engine.remove(mesh) })` (`engine.remove` disposes geometry and materials, not their textures: three's `material.dispose()` leaves its maps, so dispose a texture you made when nothing uses it). The `dispose(e)`
108
108
  hook frees the rest (Workers, the physics world, WASM objects, real-time timers), in reverse install order.
@@ -125,8 +125,9 @@ A module that does two kinds of thing is two definitions returned together (`wea
125
125
  on all three paths: save, load, and new game (a new game loads the state captured when `start()` finished), so there is nothing to reset by
126
126
  hand. What cannot be saved ends with its playthrough: a background result goes through `ctx.commits` (a load or new game drops old ones;
127
127
  keep `ctx.commits.epoch` on a queued request and drop it when that changed), and an effect of a running playthrough (an open dialogue, a
128
- running cutscene, the music playing) stops on `ctx.track(e.events.on('session:end', ...))`. What is derived from save parts is rebuilt on
129
- `'session:start'` and `'save:loaded'`, and what a rollback took down on `'session:failed'`. A `'session:end'` listener only stops things: it starts nothing for the next state. A module's `describe()` should show such state: the session spec (`threedog test "session fresh page"`) compares `describe()` after a new game with a fresh page, and the Lifecycle spec round-trips the engine's own.
128
+ running cutscene, the music playing) stops in `sessionEnd(e)`; derived state rebuilds in `worldLoad`, `afterLoad`, `sessionStart` (that order,
129
+ modules by `stage` / `before` / `after`, never install order; core/saves/session.js). Events are for game code; a rollback restores on
130
+ `'session:failed'`. `sessionEnd` only stops things. A module's `describe()` should show such state.
130
131
  - When you only need a per-frame callback and no module structure: `const h = engine.onFrame(dt => ...)` / `engine.onFixed`, and `h.remove()` cancels it.
131
132
 
132
133
  ## 3. Extra steps when it goes into the engine
@@ -127,7 +127,7 @@ tower.levels[1].object; // a plain THREE.LOD: read, replace, tower.addLevel(...
127
127
  then `skipOnLowTier` effects held off (a rebuild, so last; one that drops straight back waits longer). Your own knob: `{ name, down, up }`
128
128
  (down: false at its floor). `['resolution']` = scale only, `[]` = nothing.
129
129
  Only downward: what the game or player has off is no step, settings stay above it, `adaptive.on = false` puts every effect back.
130
- - `engine.setPixelRatio(p)` = the top it climbs back to; a direct `renderer.setPixelRatio` drops the resolution step; `pixelSize` stops it all (recipe 62 4b).
130
+ - `engine.setPixelRatio(p)` = the top it climbs back to, never above a ratio the player chose in settings below the device default (the slider, or a preset share under 1; `settings.reset('pixelRatio')` hands it back); a direct `renderer.setPixelRatio` drops the resolution step; `pixelSize` stops it all (recipe 62 4b).
131
131
  - `describe().render.scale`: `{ current, devicePixelRatio, upscaled, pixelSize, autoLowered, adaptive, floor, max }`. `upscaled: true` means current < devicePixelRatio, the picture
132
132
  is softer than the screen: if that looks wrong in a screenshot, check this before the style. Fixed quality: `pixelRatio: n` plus `adaptiveResolution: false`.
133
133
 
@@ -10,7 +10,7 @@ After changing code, ask the running game instead of writing a playwright script
10
10
  What the bridge changes lives in this session only: `op`, `step`, `state` and `js` alter the running game and its saves, never the level. To change
11
11
  the level, edit `content/*.js` (templates, props, npcs…) or the level model and reload the page.
12
12
 
13
- ## 1. Usage
13
+ ## 1. Usage: run a scripted check on the running game
14
14
  ```
15
15
  npm run dev -- my-game # terminal A: start the dev server first (for the engine example just npm run dev)
16
16
  threedog describe -w my-game # terminal B: look at the scene (inside the game folder you can omit -w)
@@ -152,7 +152,7 @@ function wander(rec, dt) {
152
152
  }
153
153
  ```
154
154
 
155
- ## 6. Near, far, camera, player
155
+ ## 6. Near, far, camera, player: a huge map that loads as you walk
156
156
  - **Near / far is decided by the gameplay anchor `world.anchor`**: by default the position of the player record (`engine.focus` when there is no
157
157
  player). A cutscene or photo mode moves the camera away, but the player's surroundings are still simulated as near: gameplay results do not depend
158
158
  on the camera. For a top-down strategy game centered on a base, set `W.anchor = baseObject`; set it back to `null` to restore the default.
@@ -222,4 +222,3 @@ A save is one envelope; `engine.saves.collect()` returns it and `export` / `expo
222
222
  progress by step ids (`steps: [{ id: 'talk-mayor', ... }]`, recipe 04). Content edits (a new step, a new prop) then never shift an old save.
223
223
  - The export file wraps the envelope:
224
224
  `{ threedog: 'save', format: 1, game, slot, savedAt, data: <envelope>, files: [{ group, id, at, meta, type, url: 'data:...' }] }`.
225
- - Tests: `threedog test "Save failure"`.
@@ -3,7 +3,7 @@
3
3
  > **Covers:** the four cameras (follow, first person, strategy, fixed), switching, framing, limits.
4
4
  > **Use when:** choosing or tuning how the player sees the game.
5
5
  > **Shortest:** `openWorld({ camera: 'firstPerson' })`.
6
- > **Sections:** 1 Press V to · 2 What the engine · 3 Other common things · 4 Over the shoulder · 4b Looking up, ground · 4c Chase camera behind · 5 Take over the · 6 Orthographic view, and · 7 Your own camera
6
+ > **Sections:** 1 Press V to · 2 What the engine · 3 Other common things · 4 Over the shoulder · 4b Looking up, ground · 4c Chase camera behind · 5 Take over the · 6 Orthographic view, and · 6b Screen shake and · 7 Your own camera
7
7
 
8
8
  Four cameras; the kind names are always: `'follow'` third-person follow · `'firstPerson'` first person · `'rts'` top-down strategy · `'fixed'` fixed shots.
9
9
  Pick one at the start: `openWorld({ camera: 'firstPerson' })`, or by hand `engine.use(followCamera({ distance: 10 }))` /
@@ -197,6 +197,16 @@ A camera module goes on placing the camera you assigned, and one assigned during
197
197
  engine.use(followCamera({ projection: 'orthographic', size: 15, yaw: 0, pitch: 0, lockPitch: true, distance: 40, ground: 'none', mouseLook: false }));
198
198
  ```
199
199
 
200
+ ## 6b. Screen shake and other camera offsets (the camera keeps following)
201
+
202
+ A direct camera write takes the camera (recipe 52); a shake is an offset on the drawn frame only:
203
+ ```js fragment
204
+ const pose = new THREE.Vector3(); let shake = 0; // yours: raise it on a hit, let it fall in onFrame
205
+ engine.onRender(({ camera }) => { pose.copy(camera.position); camera.position.y += (Math.random() - 0.5) * shake; });
206
+ engine.onRender(({ camera }) => { camera.position.copy(pose); camera.updateMatrixWorld(); }, { when: 'after' }); // back: no warning, picking sees the real pose
207
+ ```
208
+ Aim that should climb (recoil) is `cameraRig.pitch` (recipe 32).
209
+
200
210
  ## 7. Your own camera module
201
211
  Everything else in the engine reads only what `modules/camera/contract.js` lists from `engine.cameraRig`: `forward()` / `right()` (control: 'camera',
202
212
  faceMode 'camera', targeting), `follow(object, opts?)` (addPlayer, getting in and out of a vehicle), `focusPoint()` (photo, where the world loads)
@@ -14,7 +14,7 @@ Each name takes one value: `false` off · `true` default · `{ ...options }` def
14
14
  An end screen is a flow state (`engine.flow.define('gameOver', { freeze: true, lockInput: true })`, recipe 07 §1) showing a window with `closable: false` ("A window: results, game over", below).
15
15
  Only want different colors / layout? Use "Reskin" below, not a new part.
16
16
 
17
- ## Reskin: your picture on every default part, in one place
17
+ ## Reskin: change the look of every default part and menu, in one place
18
18
  The default parts are neutral gray on purpose. About ten lines give all of them the game's picture; do this before writing your own dialogue box or HUD:
19
19
  ```js
20
20
  const theme = { // picture/ui.js
@@ -193,7 +193,7 @@ const still = await engine.photo.trace({ samples: 128 }); // still.pathTraced.u
193
193
  ```
194
194
  HUD text follows the engine locale (`createEngine({ locale })`, default `'auto'` = the browser language): a game written in English sets `locale: 'en'`, or distance labels read `50 米` on a Chinese browser.
195
195
 
196
- ## 6. Settings menu: only the tabs the game needs
196
+ ## 6. Settings menu: only the tabs the game needs, quality options that turn off your pass
197
197
  ```js
198
198
  engine.use(settings({ sections: ['game', 'graphics', 'audio', 'controls', 'camera'] })); // default: graphics, audio, controls, language, saves
199
199
  // optional built-ins by name: 'game' (resume / load / back to title), 'camera' (sensitivity, invert Y, field of view; re-applied on 'camera:change')
@@ -75,7 +75,7 @@ engine.ops.define('cheat.gold', { args: { n: 'int' }, run: (e, { n }, ctx) => e.
75
75
  The host sends a full snapshot when a client joins (or after a lost message), then diffs every `syncEvery` fixed steps (default 3, 20 per second):
76
76
  world records, containers, `vars`, and every other save part (quests, clock, sky, weather...) except `random`, `level` and `rigid`. Choose explicitly with
77
77
  `sync: ['world', 'containers', 'vars', 'quests']`. Physics runs on each machine and is not synced, and machines need not agree on it
78
- (why: [11-vehicles.md, Determinism](11-vehicles.md#3-rigid-bodies-saves-joints-determinism)).
78
+ (why: [11-physics.md, Determinism](11-physics.md#3-rigid-bodies-saves-joints-determinism)).
79
79
  On a client the mirror is applied at the next fixed step; `world.simulate` does not run there (the host simulates). Other players glide between
80
80
  updates (kinds in `interpolate`, default `['player']`). The client moves its own avatar and reports its position; the host clamps it to `maxSpeed`
81
81
  (m/s, default 15).
@@ -15,7 +15,7 @@ Works on any ground: procedural terrain, a Blender level, an indoor floor. Heigh
15
15
  ## 1. Grids and items
16
16
  ```js
17
17
  import { grids, toast } from 'threedog';
18
- engine.use(grids());
18
+ engine.use(world(), grids());
19
19
  const board = engine.grids.add('board', { cell: 1, origin: [0, 0], size: [16, 12] }); // several grids may exist: a tower-defense board,
20
20
  const room = engine.grids.add('room', { cell: 0.5, origin: [-3, -3], size: [12, 12], zone: 'house' }); // a dungeon or house room,
21
21
  const plot = engine.grids.add('plot', { cell: 1, origin: [20, 0], size: [8, 8] }); // a garden plot
@@ -63,7 +63,7 @@ engine.renderer.toneMapping = THREE.NeutralToneMapping; // the curve; materials
63
63
  ```
64
64
  The engine picks no curve: `renderer.toneMapping` stays three.js's default (`NoToneMapping`) until your code writes it. A curve of your own is a post effect in the `'tone'` slot (recipe 52).
65
65
 
66
- Exposure that adapts like an eye (WebGPU): `engine.post.add(autoExposure({ min: 0.25, max: 4 }))` from `@threedog/post-effects/tsl` measures the average brightness on the GPU and eases toward `key`. It multiplies after everything that adds light, before tone mapping (`toneMappingExposure` still applies on top). Bloom runs before it, so in bright daylight large areas glow and are then darkened: raise bloom's `threshold` or give it an `order` above 800. Narrow `min` / `max` for an authored look; `speedUp` / `speedDown` set the speed, on `engine.time`; a chain rebuild keeps the adapted value. It measures a 64x64 sample: a small, very bright thing can nudge it.
66
+ Exposure that adapts like an eye (WebGPU): `engine.post.add(autoExposure({ min: 0.25, max: 4 }))` from `@threedog/post-effects/tsl` eases the average GPU-measured brightness toward `key`. It multiplies after everything that adds light, before tone mapping (`toneMappingExposure` still applies on top). Bloom runs before it (bright daylight glows, then darkens): raise bloom's `threshold` or give it an `order` above 800. Narrow `min` / `max` for an authored look; `speedUp` / `speedDown` (on `engine.time`); a chain rebuild keeps the adapted value. It measures a 64x64 sample: a small, very bright thing nudges it.
67
67
 
68
68
  ## Environment maps
69
69
  `scene.environment` is plain three.js and stays `null` until your code writes it. The background (the sky dome or a skybox) and the environment lighting are two separate fields.
@@ -86,11 +86,13 @@ On `renderer: 'webgpu'` take `PMREMGenerator` from `three/webgpu`. A map you mad
86
86
  - With `into`, that object's `.environment` gets the map at each rebuild. A map you write there yourself stays: the rebuilds go on, but only `handle.texture` follows them.
87
87
  - The dome is rendered into a cube (at least 256 px a face) and prefiltered with `PMREMGenerator`, rebuilt only when sky colors, sun direction or cloud cover changed
88
88
  AND `interval` seconds passed (default 1, 4 on a low tier; yours stands). A fixed time of day builds once; a call before the first frame waits for it. A second call replaces the first.
89
+ A rebuild is one cube render; no material builds again, so a moving day can light the scene with its sky.
89
90
  - An asset map is a fixed photo: it does not dim at night. Write `scene.environmentIntensity` from your own frame code reading `engine.uniforms.uDaylight`.
90
91
 
91
92
  ### What a MeshLambertMaterial does with it (three 0.187)
92
- The engine's neutral materials are Lambert: they get soft ambient light colored by the environment by direction, and no specular (reflections need Standard / Physical).
93
- The hemisphere light still adds on top, so lower it when the environment comes on. The first frame with an environment recompiles every Lambert program once: do it at start-up.
93
+ The engine's neutral materials are Lambert: soft ambient light colored by the environment by direction, no specular (reflections need Standard / Physical).
94
+ Both renderers alike; a `MeshLambertNodeMaterial` you build reads only its own `envMap`.
95
+ A hemisphere light adds on top: lower it. The first frame with an environment recompiles every Lambert program once: do it at start-up.
94
96
  - Toon, Basic and ShaderMaterial surfaces ignore it.
95
97
 
96
98
  ## Light probes (baked indirect light)
@@ -13,7 +13,7 @@ Every root added with `engine.add` or `engine.scene.add` is registered: an id, w
13
13
  keeps. World records (template instances, props, pickups, NPCs, level nodes) share the same id space and the same query, so one question works for a
14
14
  plain three.js mesh and for a template instance alike. Only `engine.add(obj, { id })` gives it a stable id.
15
15
 
16
- ## 1. Two doors into one scene
16
+ ## 1. Two doors into one scene: add a mesh the save remembers, or plain scene.add
17
17
  A scene object comes in either of two ways, and both end up in the same scene:
18
18
 
19
19
  - **Plain three.js.** Build a mesh or group, `engine.scene.add(obj)` (or `engine.add(obj)`, the same registration). Nothing else is required. This is the right way for anything your code rebuilds
@@ -114,7 +114,7 @@ m.colorNode = mix(color(0x2a5a7a), mirror, 0.6); // 0 = water color, 1 = pure r
114
114
  engine.water.material = m;
115
115
  ```
116
116
  - Cost: the whole scene drawn once more per frame per water mesh at `textureWidth` x `textureHeight` (shadows are not re-rendered). Use 256-512
117
- on phones; on `engine.tier === 'low'` keep the default material instead.
117
+ on phones; on `engine.tier` 'low' keep the default material instead; again on `'tier:change'`.
118
118
  - One mirror plane: the material is shared, so water bodies at other levels need `water({ sea: false })` or their own mirror. The Reflector's
119
119
  shader has no waves or fog; for both, copy its `fragmentShader` into a `MeshPhongMaterial` patch that samples `tDiffuse` with `textureMatrix`.
120
120
  - three's `Refractor` addon (next to `Reflector`) reads `matrixWorld` as an XY plane too, so the same adapter applies (not covered by a test).
@@ -9,7 +9,8 @@
9
9
  const sun = new THREE.DirectionalLight('#fff4e0', 3);
10
10
  sun.position.set(40, 80, 30);
11
11
  sun.castShadow = true;
12
- sun.shadow.mapSize.setScalar(engine.tier === 'low' ? 1024 : 2048);
12
+ const fit = () => engine.shadows.mapSize(sun, engine.tier === 'low' ? 1024 : 2048);
13
+ fit(); engine.events.on('tier:change', fit);
13
14
  engine.scene.add(sun);
14
15
  if (engine.lights.sun) engine.lights.sun.castShadow = false; // WebGL: cascades must be the only shadowing DirectionalLight (or createEngine({ lights: false }))
15
16
 
@@ -73,7 +74,7 @@ It works with and without a sky, on both renderers (WebGPU needs `import 'threed
73
74
  `light.position` and `light.target` hold that placement: writes to `light.position` or a new `light.target` still set the direction, and
74
75
  `remove()` puts both back as you left them, with the shadow camera box. A `light.target` you assigned (your player, say) is never moved.
75
76
  - `engine.tier === 'low'` gets one map unless you pass `low: { count: 2 }`. That map covers `maxFar / count` each way, so its texels are as small as an average cascade's: the low tier
76
- saves shadow passes and draws shadows less far, not blurrier (one map over all of `maxFar` has `count` times the texels, and the PCF blur is `radius` x texel). On a game's light it follows the
77
+ saves shadow passes and draws shadows less far, not blurrier, rebuilt on a tier change. On a game's light it follows the
77
78
  camera, shifted half its size ahead of the view, and never stops at the origin; like cascades it places the light, so `engine.shadows.box` on that light is refused. On `engine.lights.sun` the
78
79
  one map stays the engine's own box around the focus, sized the same way. `count: 1` (one map on every tier) covers all of `maxFar`. `handle.csm` is null while there is one map.
79
80
  - An engine draws one set of cascades: a second handle throws. A box on the same light throws too, except the engine's own box on `engine.lights.sun`, which waits
@@ -174,9 +175,11 @@ engine.renderer.shadowMap.type = THREE.VSMShadowMap; // BasicShadowMap | PCFSha
174
175
  const sun = new THREE.DirectionalLight(0xffffff, 2);
175
176
  sun.shadow.radius = 3; sun.shadow.blurSamples = 8; // softness (pcf, vsm); blur quality (vsm)
176
177
  sun.shadow.bias = -0.0001; sun.shadow.normalBias = 0.03;
177
- sun.shadow.mapSize.setScalar(2048); // before the first frame; later also sun.shadow.map?.dispose(); sun.shadow.map = null;
178
+ engine.shadows.mapSize(sun, 2048); // any time: after the first frame it reallocates the map
178
179
  ```
179
180
 
181
+ Soft shadows on three 0.187: `PCFSoftShadowMap` is gone (it logs a warning and gives `PCFShadowMap`). Keep `PCFShadowMap` and widen `light.shadow.radius`; `VSMShadowMap` blurs more.
182
+
180
183
  PCF's `radius` is in shadow texels, so the blur in meters is `radius x 2 x extent / mapSize`: halve the map (a low-tier size) and keep the radius, and the blur doubles. Scale them
181
184
  together, `sun.shadow.radius = Math.max(Math.min(R, 2), R * size / 2048)` for a radius `R` tuned on the 2048 map, as the engine's own sun does (`R` = 3): under about 2 texels PCF shows the map's stair steps.
182
185
 
@@ -9,7 +9,7 @@
9
9
  that already exist: module definitions (`requires`, `optional`, `stage`, hooks), `engine.ops.define`, `engine.saves.define`,
10
10
  `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.
11
11
 
12
- ## 1. Ask
12
+ ## 1. Ask: which effects, modules and ops exist and can be turned on
13
13
  ```js
14
14
  engine.catalog(); // short list: [{ id: 'sky', kind: 'module', state: 'running', stage: 'environment', ops: [], saves: ['sky'], time: 'fixed+skip' }, ...]
15
15
  engine.catalog('shop'); // one module expanded (below)
@@ -22,7 +22,7 @@ Which knob changes what on screen, and how to judge it for your picture: [recipe
22
22
  since it faces up), and three divides by π, so a total near π shows mid-tone albedos at roughly their own value under `AgXToneMapping`. AgX darkens light colors and pales saturated ones,
23
23
  so a pale or vivid palette needs more, or exposure. Walls and faces away from the sun get only their `N·L` share, and the environment (`scene.environment`) adds on top for Standard / Physical materials.
24
24
 
25
- ## Atmosphere: fog, sky
25
+ ## Atmosphere: fog, sky, view distance and field of view
26
26
 
27
27
  Fog and the placeholder lights: [recipe 34](34-environment-lighting.md). The sky: plain values and calls on `engine.sky`, [recipe 08](08-weather-sky.md). Shadows: `engine.shadows` and three.js, recipe 45. Water and weather: recipe 44.
28
28
 
@@ -46,7 +46,7 @@ engine.shaderTerms.season(kind => ({ glsl: 'diffuseColor.rgb = mix(diffuseColor.
46
46
  - `engine.shaderTerms.cloudShadow(spec)` and `engine.shaderTerms.season(spec)` put your own patch (`{ glsl, tsl, uniforms?, pars?, slot? }`, slot `lighting` / `color` by default) in place of the engine's on every material that carries the term, including ones built earlier; `false` removes the term; the handle's `remove()` gives the engine's back. The signals stay bound: `uWeatherCloud, uCloudShadow*` and `threedogCloudShadow(worldPos)`; `uFoliageTint` / `uGroundTint` / `uFoliageMix` / `uGroundMix`, `uGroundCover` (cover amount alone, x foliage, y ground) and `threedogSeason(color, kind)` (TSL: `season(color, kind)`). `season` also takes `kind => spec` (`'foliage'` | `'ground'`). A missing renderer form throws by name.
47
47
  - Cloud shadow values are signals: `engine.uniforms.uCloudShadow` (darkest, 0 = none), `uCloudShadowScale`, `uCloudShadowSpeed`. The term sits on engine materials and on what you pass to `applyEffects(mat)`; your own shader calls `threedogCloudShadow(worldPos)` (GLSL) or `cloudShadow(positionWorld)` (`threedog/tsl`). The engine adds it to no other material.
48
48
 
49
- ## Post effect chain
49
+ ## Post effect chain: your own pass, extra render passes
50
50
 
51
51
  Post-processing is an ordered list of named effects, and **`engine.post.add(x, { name, slot, order })` is the one way an effect gets
52
52
  in**: game code and the game's `plugins/` folder (a file that exports the Pass or effect) go through it, so every
@@ -59,19 +59,19 @@ effect has a name, a handle and a row in `describe().slots` and `describe().rend
59
59
 
60
60
  Each runs in a slot, then by `order` (low first): `scene` (replaces the scene render, one at a time, e.g. pixelation) -> `hdr` (linear color: outline, AO, bloom) -> `tone` (replaces the tone-mapping output, one at a time; it must output display color) -> `ldr` (sRGB: LUT, palette, grain, vignette) -> `final` (FXAA / SMAA).
61
61
 
62
- A plain Pass is placed by its kind: one that renders `engine.scene` itself (`RenderPixelatedPass`, `SSAARenderPass`, `TAARenderPass`) goes in `scene` and replaces the engine's scene render (a second one throws), FXAA / SMAA / TAA in `final`, any other in `hdr` after the effects already there (`ldr` when you added it after an OutputPass); a RenderPass of `engine.scene` and an OutputPass are skipped (the engine has them). Without `{ name }` it is listed by class or shader name (`CopyShader#1`); its `remove()` does not dispose it.
62
+ A plain Pass is placed by its kind: one that renders `engine.scene` itself (`RenderPixelatedPass`, `SSAARenderPass`, `TAARenderPass`) goes in `scene` and replaces the engine's scene render (a second one throws; your own Pass that draws the scene says so with `{ slot: 'scene' }`). Passes that hold `scene` and `camera` only to read the scene render (`GTAOPass`, `SAOPass`, `SSAOPass`, `SSRPass`, `BokehPass`) are ordinary `hdr` passes, FXAA / SMAA in `final`, any other in `hdr` after the effects already there (`ldr` when you added it after an OutputPass); a RenderPass of `engine.scene` and an OutputPass are skipped (the engine has them). AO, bloom and outline are `ao()`, `bloom()`, `outline()` of `@threedog/post-effects`. Without `{ name }` it is listed by class or shader name (`CopyShader#1`); its `remove()` does not dispose it.
63
63
 
64
64
  To read the chain: `engine.post.object()` and `engine.post.targets()`; both stay the engine's (it rebuilds, resizes, disposes), so change the chain through `engine.post`, or take it over with `engine.post.own()` (`own(false)` gives it back). A game that renders the canvas itself (its own composer) takes the frame: the engine stops drawing and warns once `[own-frame]`.
65
65
  ```js fragment
66
- import { bloom, outline, vignette, lut } from '@threedog/post-effects'; // shared effects come from the add-on
66
+ import { bloom, outline, vignette, lut, grain } from '@threedog/post-effects'; // shared effects come from the add-on
67
67
  import { LUTPass } from 'three/addons/postprocessing/LUTPass.js';
68
68
  const line = engine.post.add(outline({ thickness: 1.5 })); engine.post.add(vignette());
69
69
  line.enabled = false; // pauses it in place; a settings restriction above this still holds it off
70
70
  engine.post.get('vignette').set({ strength: 0.6 }); // params by name; an unknown name throws
71
- if (engine.tier !== 'low') engine.post.add(bloom()); // the heavy ones are the game's call on weak devices
71
+ engine.post.add({ ...bloom(), skipOnLowTier: true }); // held while engine.tier is 'low', following a change
72
72
  engine.post.add({ name: 'myLut', slot: 'ldr', params: { lut: myLut }, create: ({ params }) => new LUTPass({ lut: params.lut }) });
73
- // a plugin file brings the same effect with no main.js line: plugins/10-bloom.js
74
- export default bloom({ strength: 0.2 });
73
+ // a plugin file adds one with no main.js line: plugins/10-grain.js (a new game adds ao and bloom in picture/post.js)
74
+ export default grain({ amount: 0.04 });
75
75
  ```
76
76
  - `bloom({ strength, radius, threshold })`, defaults 0.35, 0.5, 0.85 (glow added, spread 0 to 1, brightness a pixel needs to glow). It reads linear color before the tone curve, so a
77
77
  surface brighter than 1 glows hard however small: if the frame washes out, raise `threshold` or dim that surface before lowering `strength`. On the WebGPU route three's own `BloomNode` is also open to you through `engine.post.add({ node })`.
@@ -129,7 +129,7 @@ Each of them is registered once (`core/ops/owned.js`), and every one behaves the
129
129
  | `view.far` | view | terrain view range (`terrain.viewChunks`) | `engine.autoView.manual('far')` | - |
130
130
  | `view.fov` | view | the settings menu fov slider, camera modules (first person / rts fov, fixed shots, back to the install fov on a switch) | `engine.autoView.manual('fov')` | - |
131
131
  | `view.pixelRatio` | view | adaptive resolution, about once a second while slow | `engine.autoView.manual('pixelRatio')` | `engine.setPixelRatio(1.5)` |
132
- | `camera` (position, rotation) | view | the camera module, every frame | `const cam = engine.takeCamera('me')` (`cam.remove()` gives it back) | - |
132
+ | `camera` (position, rotation) | view | the camera module, every frame | `const cam = engine.takeCamera('me')` (`cam.remove()` gives it back) | shake / offset: recipe 21 §6b |
133
133
  | `post.chain` | post | whenever the effect list changes (add / remove / on / off, MSAA): the engine rebuilds the composer passes (WebGL) or `pipeline.outputNode` (WebGPU) | `engine.post.own()`: the built chain stays as you left it in `engine.post.object()`; `own(false)` rebuilds it from the list. A write to `object()` without `own()` does not yield: the next chain change replaces it | `engine.post.get('bloom').set({ strength: 0.6 })` |
134
134
  | `shadow.csm` (not a property: a list) | shadow | while cascades are on: the `csm` patch goes on every built-in lit material, yours too (else N times as bright) | - (`handle.remove()`); your ShaderMaterial is left alone until `engine.shadows.include(mat)` | - |
135
135
 
@@ -53,8 +53,8 @@ With a preset the same switch gives crisp banks without more triangles: `terrain
53
53
 
54
54
  Cost: the worker time per chunk is mostly your `groundType` called once per pixel, several times that of smooth at 128; 64 costs a quarter, 256 four times that.
55
55
  Memory is `(colorResolution + 2)^2 x 4` bytes per chunk plus mipmaps (about 90 KB at 128, 23 KB at 64). The first frames pay one shader compile and the uploads, not a cost per frame.
56
- On a low tier (`engine.tier === 'low'`) the default drops to 64 unless you set `colorResolution`. To skip the
57
- color map there, choose the shading yourself: `shading: engine.tier === 'low' ? 'smooth' : 'texture'`.
56
+ On a low tier the default drops to 64 unless set by `colorResolution` (follows tier). To skip the color map there,
57
+ choose the shading: `shading: engine.tier === 'low' ? 'smooth' : 'texture'`, read once at `terrain({})`.
58
58
 
59
59
  `variation` shapes *what* color a point gets; `shading` decides *where* it is evaluated. In vertex modes every variation is limited to cell size; in
60
60
  texture mode it is sampled per pixel, so `patches: { size: 20, levels: 4 }` gives hard-edged color blocks, and a `jitter.size` below the pixel size
@@ -8,7 +8,7 @@
8
8
  A shared value is something several owners change: the game, a module, an effect. Name it, say who you are, say how you change it:
9
9
 
10
10
  ```js
11
- engine.time.channel('enemies'); // a channel of your own exists once you name it (world, player and calendar are built in)
11
+ engine.time.channel('enemies'); // a channel of your own (built-in ones: recipe 06)
12
12
  const slow = engine.mod('time.enemies', { owner: 'bullet-time', mul: 0.35, for: 2 }); // bullet time; slow.remove() ends it early
13
13
  engine.mod('time.world', { owner: 'hitstop', set: 0, layer: 'system', for: 0.06 }); // decide on a higher layer: hides everything below
14
14
 
@@ -31,19 +31,17 @@ What to remember:
31
31
  - **`replaces` to swap an engine part** that `provides` a slot; a second provider without it is the error `shared-taken`. What the old part issued goes with it: read `engine.<slot>` where you use it, and keep the issuer beside any handle so you can compare (`if (from !== engine.rigid) { from = engine.rigid; crate = from.addBox(mesh); }`). Version numbers count per module, so they cannot tell two modules apart. The engine's own props, NPCs, pickups, cars and movers do this; a rider leaves a rigid car when rigid goes. `world` is the exception: it owns every record, so install your world before the modules that need it; once they are installed, or after `start()`, `replaces: 'world'` and `unuse('world')` are refused (`module-replaces`, `module-unuse`). A factory that gives two modules goes in whole: `engine.use(terrain(o), { replaces: 'terrain' })` swaps its drawing part too. A module of your own wraps `world.present`, `world.simulate`, `rays.addProvider`, `input.touchButton` and `assets.onSwap` in `ctx.track(...)`, so they leave with it.
32
32
  - Every handle ends with `h.remove()` (`engine.mod`, `ctx.mod`, `input.gate`, `wrap`, `freeze`, `takeCamera`); it drops only your own entry.
33
33
 
34
- Only things several parties commonly write are shared values: time speeds and the calendar rate, pause / freeze / camera holders, move stats,
35
- input gates; shadow on / quality and post parameters are on them too. Your own objects,
36
- materials and textures are plain three.js: never registered, never a conflict. Which tool to reach for: `../CONVENTIONS.md` "Customization ladder".
34
+ Only things several parties write are shared values (time speeds, holders, move stats, input gates, shadow and post parameters); your own
35
+ objects stay plain three.js. Which tool to reach for: `../CONVENTIONS.md` "Customization ladder".
37
36
 
38
37
  ```js
39
- engine.mod('time.player', { owner: 'haste', mul: 1.2, for: 5 }); // haste on the player
40
38
  const menu = engine.freeze('pause-menu'); /* ... */ menu.remove(); // pause menu: the picture, UI and ambient uTime (wind, water, clouds) keep running; { still: true } stops those too
41
39
  engine.input.gate('jump', { owner: 'stun', for: 1.5 }); // no jumping while stunned
42
40
  engine.wrap(engine.inventory, 'add', (next, id, n = 1, o) => // a weight rule on top of the engine's inventory
43
41
  carried() + weightOf(id) * n > 30 ? { ok: false, code: 'tooHeavy' } : next(id, n, o), { owner: 'weight' });
44
42
  ```
45
43
 
46
- ## The rules in full: `engine.mod(point, { owner, set | add | mul | clamp, layer?, for?, id? })`
44
+ ## The rules in full: `engine.mod(point, { owner, set | add | mul | clamp, layer?, for?, id? })`; which values are being changed now, `important` points
47
45
 
48
46
  | Layer (low to high) | Who writes it |
49
47
  |---|---|
@@ -111,11 +109,11 @@ checks that need this step's player position). The order never depends on which
111
109
  enter the bag wraps `add` and `transfer`.
112
110
  - Meant for public methods (the module's `contract.js` `api` list); a `_private` name warns once in dev and still works. `describe().wraps` lists `{ 'inventory.add': [owners] }`.
113
111
 
114
- ## Replacing a module
112
+ ## Replacing a module: swap in your own dialogue, camera or inventory system
115
113
 
116
114
  Two modules that each want to be "the" one (a sky, a tone-mapping stage, an inventory) declare an exclusive slot: `provides: ['inventory']`.
117
115
  Other modules `requires: ['inventory']` and work with whichever holds it. `engine.use(myInventory(), { replaces: 'inventory' })` unloads the
118
- holder (its tracked handles, its `ctx.mod` entries, its `dispose`) before the new install, and puts it back if that fails, with its save data and content sections. Either way the holder is a fresh install, so `module:restored` fires with the fresh modules once their `init` is done: content sections load again, as a `content.load` on a running game would (a newcomer with its own format may refuse a pack written for the old holder: that part stays out, with a warning naming the pack); game code redefines on that event what it defined by hand on the old holder. Level walls and solid props need no event: they go into whichever `collision` or `collider3d` is installed, also one that came late or came back.
116
+ holder (its tracked handles, its `ctx.mod` entries, its `dispose`) before the new install, and puts it back if that fails, with its save data and content sections. Either way the holder is a fresh install, so `module:fresh` fires with the fresh modules once their `init` is done: content sections load again, as a `content.load` on a running game would (a newcomer with its own format may refuse a pack written for the old holder: that part stays out, with a warning naming the pack); game code redefines on that event what it defined by hand on the old holder. Level walls and solid props need no event: they go into whichever `collision` or `collider3d` is installed, also one that came late or came back.
119
117
 
120
118
  Most replaceable modules have a contract (`modules/gameplay/*.contract.js`, `modules/*/contract.js`; object contract `modules/characters/vehicle.contract.js`; the rest and what cannot be replaced: CONVENTIONS.md "What can be replaced"): the api, fields, ops, events
121
119
  and save keys other code relies on, and nothing more (the engine's callers use only that surface). `await runContract(contract, () => myInventory(), { check })`
@@ -39,7 +39,7 @@ What to remember:
39
39
  - **Inside a module** use `ctx.control.take(ch, { ... })`: the owner defaults to the module, and everything it holds is handed back when the
40
40
  module goes (unloaded, rolled back, replaced).
41
41
 
42
- ## Who takes what
42
+ ## Who takes what: who drives the player body
43
43
 
44
44
  | Driver | Layer | Owner | Notes |
45
45
  |---|---|---|---|
@@ -8,7 +8,7 @@
8
8
  Fog you march through, light shafts, haze that thickens with distance, edge or focus effects: they all read the scene depth behind each pixel
9
9
  and turn it into a distance or a world position. This recipe writes one such effect with both forms, a three.js `Pass` (GLSL) for
10
10
  WebGLRenderer and a TSL node for WebGPURenderer, in one effect object. How effects are ordered, switched and tuned is recipe 52's
11
- [Post effect chain](52-around-the-picture.md#post-effect-chain); the TSL side in general is [recipe 56](56-webgpu-tsl.md#post-effects-as-nodes).
11
+ [Post effect chain](52-around-the-picture.md#post-effect-chain-your-own-pass-extra-render-passes); the TSL side in general is [recipe 56](56-webgpu-tsl.md#post-effects-as-nodes).
12
12
  For plain distance or height fog on materials, `engine.scene.fog` is enough (recipe 34).
13
13
 
14
14
  ## One effect, both renderers