threedog 1.1.0 → 1.3.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 (370) hide show
  1. package/CHANGELOG.md +893 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +187 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +17 -7
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +8 -7
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +50 -28
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +36 -15
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +47 -4
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +17 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +30 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +24 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +7 -2
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +75 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +10 -9
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +72 -79
  180. package/docs/recipes/63-third-person-start.md +48 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/.threedog/content-index.json +1 -1
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/.threedog/content-index.json +1 -1
  189. package/examples/perf-island/GAMEMAP.md +3 -3
  190. package/examples/perf-island/picture/lights.js +2 -1
  191. package/examples/plain-picture/GAMEMAP.md +1 -1
  192. package/examples/rc2d/GAMEMAP.md +1 -1
  193. package/examples/styletest/.threedog/content-index.json +1 -1
  194. package/examples/styletest/GAMEMAP.md +2 -2
  195. package/examples/styletest/main.js +1 -1
  196. package/examples/techniques/interior-light/README.md +3 -3
  197. package/examples/techniques/interior-light/interiorLight.js +2 -4
  198. package/examples/techniques/interior-light/picture/lights.js +2 -1
  199. package/examples/techniques/modular-building/picture/lights.js +3 -1
  200. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  201. package/examples/techniques/procedural-animation/README.md +1 -1
  202. package/examples/techniques/procedural-animation/main.js +1 -1
  203. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  204. package/examples/world/.threedog/content-index.json +1 -1
  205. package/examples/world/GAMEMAP.md +2 -3
  206. package/examples/world/art/humanoid.js +1 -1
  207. package/examples/world/main.js +6 -3
  208. package/index.d.ts +2 -2
  209. package/llms.txt +101 -0
  210. package/modules/ambience/Ambience.js +21 -5
  211. package/modules/calendar/index.js +9 -5
  212. package/modules/calendar/schedule.js +23 -8
  213. package/modules/camera/FirstPersonCamera.js +3 -1
  214. package/modules/camera/FollowCamera.js +10 -5
  215. package/modules/camera/RtsCamera.js +4 -3
  216. package/modules/camera/common.js +70 -8
  217. package/modules/camera/contract.js +1 -1
  218. package/modules/characters/Character.js +16 -10
  219. package/modules/characters/NPC.js +31 -19
  220. package/modules/characters/assetModel.js +14 -9
  221. package/modules/characters/astar.js +6 -1
  222. package/modules/characters/contract.js +2 -2
  223. package/modules/characters/index.js +34 -22
  224. package/modules/characters/movers/manual.js +1 -1
  225. package/modules/characters/movers/rapier.js +17 -2
  226. package/modules/characters/movers/simple.js +1 -1
  227. package/modules/characters/movers/support.js +16 -7
  228. package/modules/characters/npcAvoid.js +2 -2
  229. package/modules/characters/npcSim.js +3 -2
  230. package/modules/characters/pathAsync.js +24 -8
  231. package/modules/characters/pathJob.js +1 -1
  232. package/modules/characters/player.js +10 -9
  233. package/modules/characters/playerStrings.js +5 -5
  234. package/modules/characters/proceduralRig.js +5 -5
  235. package/modules/characters/useModel.js +6 -0
  236. package/modules/characters/walkTo.js +1 -1
  237. package/modules/collision/Collision.js +29 -18
  238. package/modules/collision/grid.js +22 -4
  239. package/modules/content/index.js +3 -1
  240. package/modules/content/loader.js +1 -1
  241. package/modules/content/models.js +82 -33
  242. package/modules/content/props.js +2 -1
  243. package/modules/content/rules.js +11 -5
  244. package/modules/content/templates.js +3 -3
  245. package/modules/content/words.js +2 -2
  246. package/modules/debug/DebugPanel.js +9 -9
  247. package/modules/flow/index.js +9 -6
  248. package/modules/gameplay/Dialogue.js +34 -20
  249. package/modules/gameplay/Interactions.js +19 -15
  250. package/modules/gameplay/Inventory.js +9 -4
  251. package/modules/gameplay/Quests.js +12 -10
  252. package/modules/gameplay/pickups.js +23 -11
  253. package/modules/grid/index.js +1 -1
  254. package/modules/grid/preview.js +2 -2
  255. package/modules/grid/tiles.js +1 -1
  256. package/modules/hlod/index.js +4 -1
  257. package/modules/hud/index.js +47 -10
  258. package/modules/hud/parts.js +28 -9
  259. package/modules/level/geometry.js +8 -3
  260. package/modules/level/index.js +10 -5
  261. package/modules/level/load.js +4 -2
  262. package/modules/lights/sources.js +1 -1
  263. package/modules/music/Music.js +22 -4
  264. package/modules/nav/index.js +20 -10
  265. package/modules/particles/Particles.js +31 -14
  266. package/modules/particles/effect.js +20 -5
  267. package/modules/particles/lit.js +72 -0
  268. package/modules/photo/Photo.js +72 -28
  269. package/modules/photo/pathTrace.js +106 -0
  270. package/modules/rigid/RigidBodies.js +23 -14
  271. package/modules/rigid/Vehicles.js +3 -13
  272. package/modules/rigid/sync.js +2 -1
  273. package/modules/settings/Settings.js +52 -20
  274. package/modules/settings/apply.js +23 -9
  275. package/modules/settings/sections.js +39 -6
  276. package/modules/settings/strings.js +2 -0
  277. package/modules/settings/view.js +19 -3
  278. package/modules/sky/dome.js +15 -3
  279. package/modules/sky/environment.js +28 -12
  280. package/modules/sky/fog.js +1 -1
  281. package/modules/sky/frame.js +6 -1
  282. package/modules/sky/shader.js +4 -3
  283. package/modules/sky/skyModule.js +8 -4
  284. package/modules/swarm/Swarm.js +1 -1
  285. package/modules/terrain/ChunkManager.js +61 -15
  286. package/modules/terrain/chunkJob.js +2 -2
  287. package/modules/terrain/index.js +20 -5
  288. package/modules/terrain/terrainEdit.js +8 -4
  289. package/modules/terrain/terrainTexture.js +4 -2
  290. package/modules/timeline/Timeline.js +4 -3
  291. package/modules/timeline/Tween.js +3 -0
  292. package/modules/timeline/letterbox.js +1 -0
  293. package/modules/triggers/index.js +36 -17
  294. package/modules/vegetation/Vegetation.js +81 -19
  295. package/modules/vegetation/densityMap.js +13 -8
  296. package/modules/vegetation/draw.js +147 -24
  297. package/modules/vegetation/groundChunks.js +20 -5
  298. package/modules/vegetation/index.js +3 -3
  299. package/modules/vegetation/modelGeometry.js +9 -4
  300. package/modules/water/Water.js +11 -8
  301. package/modules/weather/Weather.js +7 -2
  302. package/modules/weather/shaders.js +25 -5
  303. package/modules/weather/weatherDraw.js +20 -6
  304. package/modules/world/World.js +2 -1
  305. package/modules/world/index.js +2 -2
  306. package/modules/world/persist.js +6 -2
  307. package/modules/world/views.js +15 -2
  308. package/package.json +5 -1
  309. package/presets.js +5 -5
  310. package/render/PostFX.js +102 -42
  311. package/render/backend.js +142 -16
  312. package/render/bindingLimits.js +59 -0
  313. package/render/cascades.js +3 -1
  314. package/render/cascades.tsl.js +2 -0
  315. package/render/daylight.js +7 -1
  316. package/render/detail.js +7 -4
  317. package/render/effects.js +27 -8
  318. package/render/fogLook.js +24 -0
  319. package/render/fuse.js +5 -2
  320. package/render/fx/compareLevel.tsl.js +23 -0
  321. package/render/fx/detail.tsl.js +9 -7
  322. package/render/fx/index.js +9 -2
  323. package/render/fx/library.tsl.js +1 -0
  324. package/render/fx/lightShaft.tsl.js +114 -0
  325. package/render/fx/noise.tsl.js +25 -8
  326. package/render/fx/objectOrigin.tsl.js +39 -10
  327. package/render/fx/particles.tsl.js +23 -6
  328. package/render/fx/patchNodes.tsl.js +17 -12
  329. package/render/fx/pcss.tsl.js +51 -0
  330. package/render/fx/postWebGPU.tsl.js +104 -29
  331. package/render/fx/sky.tsl.js +3 -9
  332. package/render/fxNumbers.js +10 -4
  333. package/render/impostor.tsl.js +107 -0
  334. package/render/lighting.js +33 -1
  335. package/render/lightmap.js +42 -28
  336. package/render/lights.js +19 -3
  337. package/render/materials.js +6 -4
  338. package/render/mergeCommon.js +4 -1
  339. package/render/occlusion.js +14 -4
  340. package/render/patches.js +79 -41
  341. package/render/postRuns.js +32 -0
  342. package/render/postWebGL.js +97 -10
  343. package/render/probes.js +10 -14
  344. package/render/shaderErrors.js +44 -7
  345. package/render/shadowCache.tsl.js +33 -5
  346. package/render/shadows.js +42 -16
  347. package/render/slots.js +8 -5
  348. package/render/vertexInputs.js +52 -0
  349. package/types/core.d.ts +115 -47
  350. package/types/gameplay.d.ts +56 -23
  351. package/types/generated/core/audio/Audio.d.ts +27 -1
  352. package/types/generated/core/base/Random.d.ts +1 -1
  353. package/types/generated/core/input/Input.d.ts +6 -8
  354. package/types/generated/core/input/inputSeat.d.ts +1 -1
  355. package/types/generated/core/inspect/Budget.d.ts +26 -0
  356. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  357. package/types/generated/core/saves/Saves.d.ts +10 -7
  358. package/types/generated/core/saves/session.d.ts +8 -2
  359. package/types/generated/core/scene/Rays.d.ts +1 -3
  360. package/types/generated/core/scene/Views.d.ts +17 -3
  361. package/types/generated/modules/particles/Particles.d.ts +1 -1
  362. package/types/generated/modules/world/World.d.ts +2 -1
  363. package/types/generated/render/PostFX.d.ts +35 -9
  364. package/types/physics.d.ts +796 -764
  365. package/types/pixel.d.ts +1 -1
  366. package/types/tsl.d.ts +62 -1
  367. package/types/world.d.ts +12 -3
  368. package/ui/Focus.js +7 -5
  369. package/ui/Parts.js +1 -1
  370. package/ui/touchPart.js +6 -3
@@ -67,7 +67,7 @@ logic need none of this.
67
67
  | Change a picture value (light, fog, sky, water, tone, post) | write it in your `picture/` code on the three.js object or the module's `material` (recipe 62); a value the engine drives (camera far, fov, pixel ratio): write it directly, the engine yields; `engine.autoView.manual(key)` is for borrowing one and giving it back; a screen effect: `engine.post.add(x)` |
68
68
  | Write the picture yourself | plain three.js on `engine.scene / camera / renderer` (own material, `ShaderMaterial`, pass); a direct write takes that value over and the engine yields | `THREE.md` |
69
69
 
70
- **What can be replaced**: a slot with a contract file (inventory, interactions, dialogue, quests, flow, characters, calendar, cameraRig, particles, collision, level; nav only with a Recast-based implementation, see below) lists what a replacement must supply, and `runContract` checks it. `nav` is narrower than the others: the path search calls Recast's `findPath` and `findStraightPath` on `query` and `getOffMeshConnectionByRef` on `navMesh`, the path worker gives the bytes from `exportMesh` to Recast's `importNavMesh`, and NPC steering calls `addAgent` on `crowd`, so a replacement is Recast underneath (a different mesh build, say), not another navigation library. For a search of another kind, leave `nav()` out and call yours from game code. The slots below have no contract; a replacement must supply what the engine's own callers read:
70
+ **What can be replaced**: a slot with a contract file (inventory, interactions, dialogue, quests, flow, characters, calendar, cameraRig, particles, collision, level, nav) lists what a replacement must supply, and `runContract` checks it. A `nav` replacement must still be Recast underneath (path search, the path worker and NPC steering call Recast's `query`, `navMesh` and `crowd` methods listed in `modules/nav/contract.js`); for a search of another kind, leave `nav()` out and call yours from game code. The slots below have no contract; a replacement must supply what the engine's own callers read:
71
71
 
72
72
  | Slot | A replacement must supply |
73
73
  |---|---|
@@ -78,14 +78,11 @@ logic need none of this.
78
78
  | `rigid` | `vehicles`, a list of objects that meet `modules/characters/vehicle.contract.js`; `collider3d`, the three-axis slot (`modules/rigid/collider3d.contract.js`) |
79
79
  | `swarm` | nothing: no other module calls it |
80
80
 
81
- **Not replaceable**: `world` (saves, the shared id space, streaming and content stand on its records; it provides the slot so that `requires: ['world']` names a capability), and the player inside `characters` (a replacement of `characters` leaves a live player's `world` record behind, and `engine.player` is the engine's own character; steer it with `control.take`).
81
+ **Not replaceable**: `world` (saves, ids, streaming and content stand on its records; `requires: ['world']` names it as a capability), and the player inside `characters` (`engine.player` is the engine's own character; steer it with `control.take`).
82
82
 
83
- The starting picture comes from the game's `picture/` folder; what it builds as a factory can also be passed at the call site, and the
84
- call site wins (`terrain({ material })` and the like; the water surface is `engine.water.material`); a new style factory ships with its call-site option.
83
+ A picture factory can also be passed at the call site, which wins (`terrain({ material })` and the like; the water surface is `engine.water.material`).
85
84
 
86
- **Time channels**: most games use only the default (fixed `dt` in real seconds, `engine.clock` for calendar time). A channel exists so one group
87
- of things can run slower or faster than the rest (bullet time on enemies, haste on the player): `engine.onFixed(fn, { channel: 'enemies' })` gets
88
- that channel's scaled `dt`, and `engine.mod('time.enemies', { owner, mul })` scales it; units and which clock to use: `recipes/06-clock-events.md`.
85
+ **Time channels**: one group runs slower or faster than the rest (bullet time on enemies): `engine.onFixed(fn, { channel: 'enemies' })` gets that channel's scaled `dt`, `engine.mod('time.enemies', { owner, mul })` scales it (`recipes/06-clock-events.md`).
89
86
 
90
87
  ### One task, which entry
91
88
  Where a task has more than one entry they are layers of the ladder above, not alternatives: take the first, go down only for the reason given.
@@ -102,7 +99,7 @@ into, or a convenience for after.
102
99
  | Camera | install one: `openWorld({ camera })`, `engine.use(fixedCamera({ position, lookAt }))` | switch kinds at runtime: `setCamera(kind)`; a shot of your own: `takeCamera(owner)` |
103
100
  | Sky | `sky({ ... })` start values, tuned through `engine.uniforms` and `engine.sky` | a custom sky of your own (shader dome, skybox, painted backdrop): `engine.sky.replace(obj)` (recipe 08 "Your own sky object"); on WebGPU three's `SkyMesh` the same way |
104
101
  | Environment light | `engine.sky.environment({ into: engine.scene })`, or `scene.environment` | light that changes from place to place: `bakeProbes` |
105
- | Post effects | your own three.js Pass in the engine's chain: `engine.post.add(pass)`, the one way in (the engine renders through its composer) | ready-made effects as an optional convenience: `@threedog/post-effects` through the same call or a plugin file, tuned with its handle; a whole chain of your own: `engine.post.own()` |
102
+ | Post effects | your own three.js Pass in the engine's chain: `engine.post.add(pass)` | ready-made effects: `@threedog/post-effects` through the same call or a plugin file, tuned with its handle; a whole chain of your own: `engine.post.own()` |
106
103
  | Ambient occlusion | `engine.post.add(ao())` (screen space) | a model made in code: `bakeVertexAO(geometry)`; bounce light between places: `bakeProbes` |
107
104
  | Days, months and seasons that pass | `calendar()`, read `engine.calendar` (recipe 06) | one fixed moment: `sky({ time })` |
108
105
  | See through the hero's eyes | `firstPersonCamera()` (recipe 21) | switch at runtime: `setCamera(kind)` |
@@ -110,6 +107,7 @@ into, or a convenience for after.
110
107
  | Strategy view from above, edge scrolling | `rtsCamera()` (recipe 21) | a view of your own: a module writing `engine.camera` |
111
108
  | A person who walks, follows a path, is steered | `engine.characters` (recipe 13, 57) | a mover of your own: `characters.kit` |
112
109
  | Levels, items and quests written as data files | `content/` files, read by `engine.content` (recipe 20) | built at runtime: plain code in a module |
110
+ | Look at only the normals or overdraw of the picture to find what is wrong | `engine.debug.view('normals', { owner })`, then `view('off')` (recipe 15) | your own overlay: `engine.debug.defineView` |
113
111
  | Dev info on screen, a key that shows it | `debug()`: F3 opens the panel, `engine.debug` (recipe 15) | outside the page: `threedog describe` |
114
112
  | Far buildings or forests merged into one cheap mesh | `engine.hlod.add(root)` (recipe 15) | close objects: `engine.batching` |
115
113
  | Next map, next stage, change level | `engine.level.load(name)` (recipe 10) | a fade around it: `engine.flow` (recipe 07) |
@@ -125,10 +123,9 @@ into, or a convenience for after.
125
123
  | What each frame costs, against limits | `engine.budget` (recipe 15) | |
126
124
  | A cutscene takes the view for a moment | `engine.takeCamera(owner)`, read `engine.cameraOverride` | a whole shot list: `engine.timeline` |
127
125
  | Sweep a shape through solid things, overlap tests | `engine.collider3d` (recipe 11) | a line: `engine.rays` |
128
- | Spread mesh changes over frames so nothing hitches | `engine.commits` (recipe 15) | any other work: `engine.jobs` |
129
126
  | Message when the game crashes, the last error | `engine.error` and `.threedog/errors.log` (recipe 16) | |
130
127
  | Tell other systems something happened | `engine.events` (recipe 06) | |
131
- | Height of the floor under a point | `engine.ground.height(x, z)` (recipe 28) | |
128
+ | Height of the floor under a point | `engine.surface(x, z)` (recipe 28) | whether there is floor at all, or a fall out of the map: `engine.ground.has(x, z)` / `voidY()` |
132
129
  | Heavy work done bit by bit without freezing a frame | `engine.jobs` (recipe 15) | off the main thread: `engine.threads` |
133
130
  | Loading screen, progress bar while files load | `engine.loading` (recipe 07) | |
134
131
  | Pause when the browser tab is hidden | `engine.page` does it: gameplay freezes under owner `page` (recipe 07) | |
@@ -229,20 +226,19 @@ Workers are created only through `engine.threads.lane({ create, local })` (the s
229
226
  `new Worker` / `postMessage` elsewhere (`npm run check` rule R19). Worker files import only worker-safe code (a game:
230
227
  `import { serve } from 'threedog/worker'`; inside the engine `core/threads/threadServe.js`, `core/threads/threadPure.js`), never `core/threads/Threads.js` or three.js.
231
228
 
232
- ### Worker results that change gameplay: `engine.commits`
229
+ ### Worker results that change gameplay: `ctx.commits`
233
230
  A result that changes gameplay never takes effect "when it arrives"; it takes effect on a fixed tick decided when you ask (`engine.time.tick + lag`,
234
231
  default 30 steps), so threads on or off, fast or slow machine, give the same state.
235
232
  ```js
236
- const t = engine.commits.request({
237
- apply: r => { state.path = r; }, // runs on the due tick, with the worker result or the fallback result
238
- fallback: () => computePath(from, to), // required: the SAME computation on the main thread
239
- valid: () => state.gen === myGen, // still wanted? checked on the due tick
233
+ const t = ctx.commits.request({
234
+ apply: r => { state.path = r; }, // runs on the due tick, with the worker result or the fallback result
235
+ fallback: () => computePath(from, to), // required: the SAME computation on the main thread
236
+ valid: () => state.gen === myGen, // still wanted? checked on the due tick
240
237
  });
241
- lane.run(job).then(r => t.resolve(r)); // when the worker replies; t.remove() if you no longer want it
238
+ lane.run(job).then(r => t.resolve(r)); // when the worker replies; t.remove() if you no longer want it
242
239
  ```
243
- - **The worker result has not come back by the due tick**: the main thread calls `fallback()` right then, `apply` gets that result, and
244
- `engine.commits.stats.late` goes up by 1. A worker reply that arrives afterwards is ignored. So `fallback` must give the same result as the worker
245
- (use one function for both) and must be fast enough to run inside one fixed step.
240
+ - **No worker result by the due tick**: `fallback()` runs then, `apply` gets its result, `ctx.commits.stats.late` goes up, and a later reply is ignored. So `fallback`
241
+ must give the same result as the worker (one function for both) and fit inside one fixed step.
246
242
  - **Dropping an old result**: `t.remove()`, or `valid()` returning false on the due tick. A save load (`saves.apply`) or `level.load` drops pending
247
243
  commits that have no `valid` (they were requested for the old world), including `jobs.add(work, { apply })` started before it (`jobs.add` also takes
248
244
  `valid`); a request with `valid` decides itself.
@@ -258,26 +254,24 @@ engine.world.simulate('crop', { far: (rec, dt) => { rec.growth += dt * RATE; },
258
254
  // right: the constant lives inside, or on the record (rec.rate)
259
255
  engine.world.simulate('crop', { far: (rec, dt) => { rec.growth = Math.min(1, rec.growth + dt / 600); }, worker: true });
260
256
  ```
261
- What is checked when: at registration (`threads.pure` / `simulate`) it checks that the function can be recompiled (not native, not async, parseable).
262
- Outside variables are also scanned at registration and reported by name with the fix (a heuristic scan: it may miss a few forms such as variables
263
- inside template strings, which then throw on the first call).
257
+ Registration (`threads.pure` / `simulate`) checks that the function recompiles and names outside variables with the fix (a heuristic: a variable inside a template string throws on the first call instead).
264
258
 
265
259
  ## Interface conventions (one style across the engine)
266
260
  - **A position is one argument**: any API that takes a position takes it as a single argument: Vector3, Object3D (its position), `[x, y, z]` or
267
261
  `{ x, z }` all work. Size, radius and count go in the options object after it: `collision.addBox(house, { halfWidth: 3, halfDepth: 2 })`,
268
262
  `particles.emit('dust', p, { count: 20 })`, `world.query({ near: p, radius, kind })`. A position key inside an options object is always `position`
269
- (`stream.add({ position, build })`). The only exceptions are ground sampling `engine.surface / slope / groundType / waterAt(x, z)` and
270
- `ground.height(x, z)`; `{ place, x, z }` in content data is a data form.
263
+ (`stream.add({ position, build })`). The only exceptions are ground sampling `engine.surface / slope / groundType / waterAt(x, z)`;
264
+ `{ place, x, z }` in content data is a data form.
271
265
  - **Registrations return a handle**: anything that registers a listener, timer, continuing effect or registration (`events.on/once`,
272
266
  `onFixed/onFrame`, `clock.after/every`, `calendar.at/between/daily/onSeason`, `collision.addBox/...`, `interactions.add`, `rays.addStatic`, `stream.add`,
273
- `triggers.add`, `hud.marker`, `hlod.add`, `particles.attach`, `pickups.spawn`, `rigid.addBox/...`, `audio.addBus`, `defineState`, `ops.define`, `saves.register`, `ui.define`) returns a
274
- handle `{ owner?, remove() }`; `h.remove()` undoes it, the only give-back form (no `null` / `false` hand-back calls)
275
- (safe to call repeatedly, and it removes only its own registration, so `ctx.track` takes any of them), never a bare function. `remove()` undoes what that call did: models it created itself are deleted with it (such as a
267
+ `triggers.add`, `hud.marker`, `hlod.add`, `particles.attach`, `pickups.spawn`, `rigid.addBox/...`, `audio.addBus`, `defineState`, `ops.define`, `saves.define`, `ui.define`) returns a
268
+ handle `{ owner?, remove() }`, never a bare function; `h.remove()` is the only give-back form (safe to repeat, removes only its own registration, so `ctx.track` takes any). `remove()` undoes what that call did: models it created itself are deleted with it (such as a
276
269
  pickup); objects you passed in are not. APIs that add an object or change business data return what their own signature says: `engine.add(obj)`
277
- returns the added object, `inventory.add` returns a result, `world.add` a record; delete those with `engine.remove(obj)` / their own remove call.
270
+ returns the added object, `inventory.add` a result, `world.add` a record; delete those with `engine.remove(obj)` / their own remove call.
271
+ Exceptions to the verb rules (each with its reason in the table of check rule R69, which checks this line): `add`, `characters.addPlayer`, `world.add`, `inventory.add`, `settings.addSection`, `i18n.add`, `plugins.add`, `plugins.on`, `jobs.add`, `grids.add`, `player.addJumps`, `input.bind`, `particles.attach`, `saves.putAttachment`, `ui.create`; giving back is the verb remove, and these are the only other verbs for it (clear / forget / release / unload / dispose, each does what remove cannot): `triggers.clear`, `debug.clear`, `particles.clear`, `level.unload`, `assets.release`, `views.release`, `page.releaseLock`, `control.forget`, `player.dispose`, `nav.dispose`, `dispose`.
278
272
  A definition by name (`inventory.define`, `quests.define`, `settings.define`) is data, not a registration: it returns its own object, and defining the name again replaces it.
279
- - **Verbs**: defining a kind is `define` (`vegetation.define`, `particles.define`, `grids.define`, `ops.define`); placing one is `add` / `spawn`;
280
- hooking up a provider the engine calls back is `register` (`saves.register(key, { save, load })`: it defines no kind and places nothing).
273
+ - **Verbs** (AI.md "Three rules"): a named kind or rule is `define` (`vegetation.define`, `ops.define`, `saves.define(key, { save, load })`); placing one is `add` / `spawn`;
274
+ then `set`, `remove`, `describe`.
281
275
  One timer entry: `engine.clock.after(seconds, fn, { data, channel })` (calendar seconds, or `'real'` / a time channel's seconds with `channel`);
282
276
  one queue, so `remove()` is immediate: a removed timer never fires, not even later in the same step.
283
277
  - **Unknown options throw**: every options bag goes through a `readParams` schema (one schema gives the check, the defaults and the catalog entry); an
@@ -290,15 +284,13 @@ inside template strings, which then throw on the first call).
290
284
  `core/time/time.js` adds to them (a spec checks). Always name the unit, real, channel or calendar seconds; `recipes/06-clock-events.md` defines them (and the calendar's time of day) and has
291
285
  the table of which one to use for movement, action timelines, cooldowns, hit-stop, crop growth, calendar and UI, and what pause / freeze /
292
286
  `clock.rate` 2 do to each. Speeds change only through `engine.mod` (the "Customization ladder" above).
293
- - **Input**: gameplay keys (attack, jump, interact...) are read in the fixed step (`onFixed` / module `fixed`), where `pressed / down / released` give
294
- a snapshot taken at the start of the step, so the result does not depend on frame rate and a press is never lost. UI keys (menus, toggling a view, a
295
- HUD button) are read in `onFrame` / module `frame`, which gives this frame's latest state. Never read `pointer.clicked` for gameplay; bind a `Mouse0` action.
296
- Modules declare actions and their context (`ctx.input.action`) and never name a key; the game binds (`createEngine({ bindings })`,
287
+ - **Input**: gameplay keys are read in the fixed step (`onFixed` / module `fixed`), where `pressed / down / released` are a snapshot from the step's start (no frame-rate
288
+ dependence, no lost press); UI keys (menus, a view toggle) in `onFrame` / module `frame`. Never read `pointer.clicked` for gameplay; bind a `Mouse0` action.
289
+ Modules declare actions and their context (`ctx.input.define`) and never name a key; the game binds (`createEngine({ bindings })`,
297
290
  `input.bind`, `presets.bindings.*`); only the basics (move, confirm, cancel, UI cursor) have default keys (`recipes/58-input.md`).
298
291
  - **Module names**: `collision()` installs as `engine.collision` (lightweight collision: walking, camera); `rigid()` installs as `engine.rigid` (real
299
292
  physics with Rapier).
300
- - **Presets**: `openWorld()` installs only world, environment and basic modules; gameplay modules (interactions, dialogue, inventory, pickups, quests...) are
301
- added by the game with `engine.use`; pass `false` for items you don't want; the camera has no default and must be named, e.g.
293
+ - **Presets**: `openWorld()` installs only world, environment and basic modules; the game adds gameplay modules with `engine.use`; `false` drops an item; the camera has no default and must be named, e.g.
302
294
  `openWorld({ camera: 'firstPerson' })` (`'follow'` / `'rts'` / `'fixed'`, a camera module, or `false`).
303
295
  - **Errors say how to fix it**: passing an old form (a numeric position, etc.) throws and explains the fix.
304
296
 
@@ -312,33 +304,29 @@ inside template strings, which then throw on the first call).
312
304
  - **One source for "can walk there"**: `engine.movement`, and a character's position belongs to its mover (recipe 12 section 5).
313
305
  Who calls `move` is the character's control holder (`engine.control`, `recipes/57-control.md`): one per step; anyone else is `[control-bypass]`.
314
306
  - Units are meters, Y is up, north is -Z. Characters and vehicles face the model's +Z; `facing` 0 = +Z, forward = (sin f, cos f).
315
- - Never call `requestAnimationFrame` or `renderer.render` yourself. **Game logic always uses real seconds or calendar seconds** (the hook's `dt`,
316
- `engine.clock`; see the time table in `recipes/06-clock-events.md`); no `setTimeout` / `setInterval` / `performance.now()`: they ignore pause,
317
- freeze and `engine.step` fast-forward, so they can't be tested or saved.
318
- - To be saved, call `engine.saves.register(key, { save, load })` (`load` may return a Promise); `saves.save / load` always return `Promise<boolean>`,
307
+ - Never call `requestAnimationFrame` or `renderer.render` yourself. **Game logic uses real or calendar seconds** (the hook's `dt`, `engine.clock`; `recipes/06-clock-events.md`),
308
+ never `setTimeout` / `setInterval` / `performance.now()`: they ignore pause, freeze and `engine.step`.
309
+ - To be saved, call `engine.saves.define(key, { save, load })` (`load` may return a Promise); `saves.save / load` always return `Promise<boolean>`,
319
310
  so `await` them. Saved data names things by stable ids, never positions; when it changes shape raise `version` and add a `migrate` step
320
311
  (`recipes/20-content-actions-save.md` "Save format").
321
312
  - Day / night in gameplay comes from the calendar: read `calendar.isDay`, use `calendar.daylight` (0-1) for fades (they work with no sky); don't judge by clock text yourself.
322
313
  - A game's own picture parameters (colors, materials) can live anywhere plain three.js code lives; its `picture/` folder keeps them in one place (recipe 62).
323
- - Vegetation `rule` must not contain functions (it is sent to a Worker).
324
314
  - Terrain is editable: `engine.terrain.edit(pos, { lower|raise|flatten|paint })`, only inside an op or fixed step; custom
325
315
  `terrain({ height, groundType })` must be pure functions.
326
316
  - Loading follows the `engine.stream` sources (player + camera focus by default); display, physics and world data are separate: unloading a model
327
317
  never removes its world record.
328
318
  - Window blur, tab hidden, pointer lock and WebGL context loss are listened to only in `core/engine/page.js`; modules read `engine.page` or listen to
329
319
  `page:*`. Show "saved" only after `saves.save` returns true.
330
- - Character bodies are assets: `createPlayer({ ...presets.player.thirdPerson, model: 'humanoid' | 'hero' })` (a procedural builder is built
320
+ - Character bodies are assets: `addPlayer({ ...presets.player.thirdPerson, model: 'humanoid' | 'hero' })` (a procedural builder is built
331
321
  now; a file shows a gray capsule and is swapped in when it loads: `await player.whenReady`, event `character:model`), or `{ rig }`; a name no model
332
322
  asset has throws. Per-character colors: `colors: { body, skin, legs, hair }` on meshes marked `userData.part`.
333
- - Importing the engine makes `Mesh.prototype.customDepthMaterial` / `customDistanceMaterial` default to a depth material carrying the mesh material's
334
- vertex patches, so wind-swayed meshes cast swaying shadows with nothing to set up; assigning your own value still wins. Shader time, wind and cloud
335
- cover are per engine in `engine.uniforms` (share them in your own `ShaderMaterial`); with two engines on a page, pass the engine to
336
- `applyEffects(mat, { engine })`.
323
+ - Wind-swayed meshes cast swaying shadows with nothing to set up (`shadow-accessors` in `THREE.md`). Shader time, wind and cloud cover are per engine in
324
+ `engine.uniforms`; with two engines on a page, pass the engine to `applyEffects(mat, { engine })`.
337
325
 
338
326
  ## Failures: which shape
339
327
  A runtime "can't" (not enough money, shelf empty) is returned as `{ ok: false, code, facts, nextActions }` (ops.run / can / undo, and direct calls such as `container.trade`, which a module builds by returning that shape, or a code string from an op's `can`). Misuse (a wrong call, a typo) is a thrown `codedError`. Documented exceptions: `checkSkip` / `checkSave` return `{ ok, diffs }`, `walkTo` returns `{ status }`. Read `code` (there is no `reason` field). Predicates (op `can`, `grid.can()`) may return a plain code string.
340
328
 
341
- Inside the engine a failure takes one of three forms, so every one reaches the reader with a code, a fix and a page: misuse throws `codedError(code, message)` with an `ERROR_CODES` entry (`core/base/errorCodes.js`: what to change, which page to read); a recoverable problem warns once with `warnOnce(coded(code, message))`; a game or module callback that threw goes to `reportError`. Check rule R45 rejects a plain `throw new Error` and a bare `console.warn` / `console.error` in engine code.
329
+ Inside the engine a failure takes one of three forms, so every one reaches the reader with a code, a fix and a page: misuse throws `codedError(code, message)` with an `ERROR_CODES` entry (`core/base/errorCodes.js`: what to change, which page to read); a recoverable problem warns once with `warnOnce(coded(code, message))` (dev lists each in `describe().warnings`; a code ending `-clamped`, `-fallback`, `-ignored` or `-replaced` says the engine used something other than what the game gave); a game or module callback that threw goes to `reportError`. Check rule R45 rejects a plain `throw new Error` and a bare `console.warn` / `console.error` in engine code.
342
330
 
343
331
  ## Stability
344
332
 
@@ -349,8 +337,8 @@ Inside the engine a failure takes one of three forms, so every one reaches the r
349
337
  - **Objects from other libraries**, which follow that library's version: `rigid.rapier / world / playerBody / playerCollider`, `nav.navMesh / query / tileCache / crowd / helper`, `assets.gltf / draco / ktx2`, `post.object / targets`, `shadows.csm`.
350
338
  - **Effects still moving with three.js**: all of `threedog/tsl` and `@threedog/post-effects/tsl`.
351
339
  - **Names nothing uses yet**: a public name no game, recipe, example or template used at 0.8 stays marked until one does; `docs/api-surface.txt` lists them.
352
- - **Coordination no test game has used**: `engine.stacks`, `engine.wrap`, `engine.mod`, `time.channel / channels`.
353
- - **Systems still settling**: `net()`, `engine.threads`, `engine.commits`, `grids()`, `hlod()`, `swarm()`, `stream.source / teleport / addReadyCheck / sources`, `post.get / own / antialias / list`, `world.simulate({ worker })`, `terrain.edit`, `ops.guard / allow`, `terrainDraw`, `vegetationDraw`, `weatherDraw`, `engine.bakeProbes / loadProbes / loadLightmap`.
340
+ - **Coordination no test game has used**: `engine.stacks`, `engine.wrap`, `time.channel / channels`.
341
+ - **Systems still settling**: `net()`, `engine.threads`, `grids()`, `hlod()`, `swarm()`, `stream.source / teleport / addReadyCheck / sources`, `post.own / antialias`, `world.simulate({ worker })`, `terrain.edit`, `ops.guard / allow`, `terrainDraw`, `vegetationDraw`, `weatherDraw`, `engine.bakeProbes / loadProbes / loadLightmap`.
354
342
  - **Flat content**: an entry's `source`, `content stamp`, `content capture`.
355
343
  - **Tuning and readings**: `engine.moduleOrder / moduleStates`, `player.saveMotion / loadMotion`, `jobs.loadingMs / maxSteps / slowStepMs`, `stream.unloadFactor`, `batching.held`, `world.steps`, `level.heightfield`.
356
344
  - **Commands.** Only the `--json` and MCP shapes are an interface; printed text keeps changing for AI readers. An error's `code` string is frozen, its message is not.
@@ -54,7 +54,7 @@ These do not fail loudly, so search for them.
54
54
  | `assets.reportText(name)` | `assets.report(name)` |
55
55
  | `assets.users(name)` | no replacement: it was internal |
56
56
  | `player.object`, `character.object` | `.root`, the same object (`npc.object` stays) |
57
- | `character.addTo()` | `engine.add(character.root)` for a `new Character` of your own; `createPlayer` still adds the player |
57
+ | `character.addTo()` | `engine.add(character.root)` for a `new Character` of your own; `addPlayer` still adds the player |
58
58
  | `engine.rigid.R` | `engine.rigid.rapier` |
59
59
  | `collision.circles`, `collision.boxes` | `collision.forEachStatic((type, data) => ...)` |
60
60
  | `engine.stream.readyCheck(name, fn)` | `engine.stream.addReadyCheck(name, fn)` |
@@ -71,7 +71,7 @@ These do not fail loudly, so search for them.
71
71
  | `engine.adaptive.paused` | `engine.adaptive.on = false` |
72
72
  | `settings.removeSection(id)` | List the tabs you want: `settings({ sections: [...] })` |
73
73
  | `sky({ moonSize })`, `sky({ starScale })`, `sky({ gradientCurve })`, `sky({ orbitTilt })`, `sky({ orbitSway })` | Write `engine.uniforms.uMoonSize.value`, `uStarScale.value`, `uSkyCurve.value`, `engine.sky.orbit.tilt`, `engine.sky.orbit.sway` (plain values after `engine.use(sky())`; defaults unchanged) |
74
- | `saves.register(key, { movedFrom })` | No replacement. Only the calendar used it: the time and day of a 0.2 save, kept under the old `sky` part, are no longer read, and such a save starts from `calendar({ time })` |
74
+ | `saves.define(key, { movedFrom })` | No replacement. Only the calendar used it: the time and day of a 0.2 save, kept under the old `sky` part, are no longer read, and such a save starts from `calendar({ time })` |
75
75
  | The old keys of `sky()` and `water()` (`sky({ fog })`, `sky({ sun })`, `sky({ layers })`, `sky({ dayLength })`, `water({ color })`, `water({ glsl })` and the like) | They are ordinary unknown options now: an error with a did-you-mean in development, one warning in a build. Recipes 08, 44 and 62 say where each value lives |
76
76
  | `calendar.daysPerSeason` (the field) | Nothing read it and writing it did nothing. The option `calendar({ daysPerSeason })` stays |
77
77
  | `ground.navGeometry` on a ground API of your own | Nothing read it: the navmesh comes from `staticTrimeshes()` |
@@ -27,7 +27,7 @@ First run `threedog doctor --fix`, then `npm run check`: a removed name shows up
27
27
  | `preventDefault is not a function` in a `character:fall` listener | Falling is one rule, `fall`, for characters and rigid bodies | Remove the call. `engine.mod('fall', { owner: 'game', id: 'player', set: false })` leaves the fall to the game; a function `(facts, engine) => 'rescue' \| false` decides per fall |
28
28
  | `nothing explains 'picture' (did you mean 'value'?)` | `explain({ picture })` is now `explain({ value })`, which also gives the short history | Rename the key. On the command line: `threedog explain value fog.far` |
29
29
  | `explain is not a function` on a thing | `engine.explain` is the one way to ask why | `engine.thing(id).explain()` becomes `engine.explain({ thing: id }).detail`, and `threedog thing <id>` becomes `threedog explain thing <id> --full` (MCP: `explain` with `about: 'thing'`) |
30
- | `[save-key-taken]` from `saves.register` | A second register on a held key used to take the part from its owner with nothing said, and that owner stopped being saved | Use another key, or `remove()` the first handle before registering again |
30
+ | `[save-key-taken]` from `saves.define` | A second register on a held key used to take the part from its owner with nothing said, and that owner stopped being saved | Use another key, or `remove()` the first handle before registering again |
31
31
  | `[skip-busy]` from `engine.skip` | A second skip during a first one's fade used to resolve and unfreeze the game mid-fade. The doc always said it rejects | Await the first skip, then skip again |
32
32
  | `[save-busy]` from `saves.collect` | A load is running. `saves.save` waits for it, `collect` cannot | Collect after the load. Do not await `saves.apply` or `saves.load` inside a part's `load()` or an `afterLoad`: dev warns `save-nested`, because it would wait forever |
33
33
  | `setViewChunks is not a function` or `setDensity is not a function` | One entry each: `terrain.viewChunks` and `terrain.density` take effect when written | `terrain.setViewChunks(n)` becomes `terrain.viewChunks = n`; `terrain.setDensity(d)` becomes `terrain.density = d`. Plants that block stand at every density |
@@ -44,7 +44,7 @@ First run `threedog doctor --fix`, then `npm run check`: a removed name shows up
44
44
  | `[module-params] triggers.add({ radius })` | A NaN or negative radius used to sit in the zone list and never match | Pass a finite number >= 0 |
45
45
  | `[grids-misuse] grids.add` | A cell, origin or size that is no valid number is refused | Cell > 0, a finite origin, size whole numbers > 0 or left out |
46
46
  | `[quest-step] ... next` | A step's `next` must be a step of that quest or a function | Fix the id the message quotes |
47
- | `[save-version]` at `saves.register` | A `migrate` key must be a whole version below the current one | Rename the key |
47
+ | `[save-version]` at `saves.define` | A `migrate` key must be a whole version below the current one | Rename the key |
48
48
  | `saves.save` answers false with `[save-part-threw]` | A part's `save()` returned a function, a symbol, NaN or an infinity, which a save cannot hold | Return plain data, or null for nothing |
49
49
  | `[save-write]` from `saves.putAttachment` | Only a Blob is stored | Pass a Blob |
50
50
  | `[terrain-option]` from a terrain edit | An edit that would touch more than about four million points is refused | Use a smaller radius or several edits |
package/docs/THREE.md CHANGED
@@ -24,9 +24,8 @@ yourself: `engine.plugins.add(import.meta.glob('./plugins/*.js', { eager: true }
24
24
 
25
25
  ## three.js idioms and who writes the value
26
26
 
27
- Write the three.js first; it works. `renderer.toneMapping = THREE.ACESFilmicToneMapping` is a complete answer. What you need to know is which values the
28
- engine **writes on its own** (every frame or on a timer): a direct write to one of those hands it to you (the engine stops writing it and warns once with the
29
- explicit call); the full list is recipe 52 "Who writes it". The engine route is optional on top: `engine.mod(point, ...)` adds owners and layers where several
27
+ Write the three.js first; it works. What you need to know is which values the engine **writes on its own** (every frame or on a timer): a direct write
28
+ to one hands it to you (the engine stops and warns once with the explicit call); the full list is recipe 52 "Who writes it". Optional on top: `engine.mod(point, ...)` adds owners and layers where several
30
29
  systems share a value (recipe 55); `engine.autoView.manual(key)` takes a value without the warning (`manual(key, false)` gives it back);
31
30
  `engine.describe('picture').picture` says what three.js holds now; `describe().owned` who writes each engine-driven value now.
32
31
 
@@ -52,13 +51,15 @@ Contact shadows are no engine feature: `threedog examples pull contact-shadows`
52
51
 
53
52
  ## What the engine changes in three.js (Global changes)
54
53
  Everything else in three is untouched. Every change below is listed in `describe().threePatches` (`{ id, what, scope, on, offable, lost }`);
55
- an offable one is undone page-wide with `threePatches.off(id)` (`import { threePatches } from 'threedog'`), call it before creating the objects
56
- that should not see it. It is page-wide: every engine on the page loses the change, and `engine.dispose()` does not undo it (disposing one engine never touches a change another engine or library relies on). A wrapper another library put on `Object3D.prototype.add` stays when `scene-add-hook` is turned off. `lost` says what stops working; a change that cannot be undone says why and `off` throws.
54
+ an offable one is undone page-wide with `threePatches.off(id)` (`import { threePatches } from 'threedog'`) before creating the objects that should not
55
+ see it, for every engine on the page; `engine.dispose()` does not undo a change. A wrapper another library put on `Object3D.prototype.add` stays when `scene-add-hook` is turned off. `lost` says what stops working; a change that cannot be undone says why and `off` throws.
57
56
 
58
57
  | id | Change | Effect on your code | Off |
59
58
  |---|---|---|---|
60
59
  | `occlusion-layers-test` | `layers.test` of a mesh `engine.occlusion` hides, an own property while it is hidden | `engine.camera` skips the mesh; every other camera, shadows and rays see it. `mask`, `visible` and clones stay yours | no; `engine.occlusion.enabled = false` removes it |
61
60
  | `shadow-accessors` | `Mesh.prototype.customDepthMaterial / customDistanceMaterial` become accessors | Unassigned, they return a shadow material only for a mesh whose material carries a vertex-moving engine patch (wind), so its shadow sways too; otherwise `undefined` as in three. An assignment always wins | yes |
61
+ | `fog-linear` | `ShaderChunk.fog_pars_fragment`, `tonemapping_fragment` and `fog_fragment` (page-wide, WebGL) | Fog is mixed once, in linear space before the tone curve and the output encoding, on the canvas, under the composer and on WebGPU alike (three mixes after both, so far fog changed colour when the first effect turned on). Adds the GLSL helpers threedogFogColor and threedogFogFactor and the define `THREEDOG_FOG_DONE`; a material `fog` slot patch replaces this mix. A shader without the fog chunks keeps three's code | yes: `threePatches.off('fog-linear')` turns off only the engine's mix (distant fog mixes after tone mapping again); the helpers and the guard stay, so a fog slot patch keeps working |
62
+ | `compare-sample-level` | `WGSLNodeBuilder.prototype.generateTextureCompare` wrapped | WebGPU only: a shadow map compare is written as `textureSampleCompareLevel` (no screen derivative, same picture), so one inside a loop compiles on D3D's FXC (`sunShafts`); a mipmapped compare texture keeps three's call. | yes |
62
63
  | `node-setup-position` | `NodeMaterial.prototype.setupPosition` wrapped | WebGPU only: runs the engine's vertex-moving patches (wind) first; other node materials unchanged | yes |
63
64
  | `scene-add-hook` | `Object3D.prototype.add / remove` wrapped (page-wide) | None to the call itself; the engine sees what enters and leaves its scene at any depth (adopting `scene.add`, cascades, cloud shadow, light counts). Another library wrapping the same methods stacks with it | yes (`scene.add` no longer adopted) |
64
65
  | `mesh-material-accessor` | `material` on each object entering the engine's scene: an own get / set on that object (a class accessor, e.g. troika text, still runs) | In devtools `mesh.material` shows as an accessor; `mesh.material = other` works as in three and is seen | yes (new objects) |
@@ -66,14 +67,17 @@ that should not see it. It is page-wide: every engine on the page loses the chan
66
67
  | `renderer-render` | `engine.renderer.render` (that instance only) wrapped | Counts your full-canvas draws so the engine yields the frame; a scissored / smaller-viewport / `autoClear = false` layer (minimap, HUD) does not count | yes |
67
68
  | `shader-chunks` | `THREE.ShaderChunk.threedog_*` added (new names, nothing replaced) | None until you `#include` one | no (the engine's patches include them) |
68
69
  | `light-idle-shadow` | `shadow.autoUpdate` of your shadow-casting point / spot lights: off while intensity is 0, back on when lit | Only lights whose autoUpdate was on; writing autoUpdate yourself hands the light back; `light.userData.idleShadow = false` opts one out; `describe().render.lights` shows `shadowIdled` | yes |
70
+ | `ray-bvh` | `geometry.boundsTree` and an own `mesh.raycast` on meshes of 256+ triangles in `engine.rays.addStatic` | Your `Raycaster` gets the BVH too; your own raycast is kept; the last unregister gives the raycast back and drops a tree the engine built | yes |
69
71
  | `shadow-cache` | `light.shadow.shadowNode` of a light handed to `engine.shadows.cache`: a `ShadowNode` subclass with float depth, a second depth map and a draw filter | Only that light, only after the call; the handle's `remove()` puts three's node back |
70
72
  | `batching-draw-walk` | `children` of a parent holding batched meshes: those meshes leave the array during the engine's own draw and come back right after | None outside the draw: your code, raycasts and `scene.traverse` see the scene as built. A scene change made inside a render (`onBeforeRender`) on such a parent is lost | yes (three walks every batched original twice a frame again) |
71
- | `picture-writers` | Dev server only (absent from bundles and release builds): an own get / set on the picture values of objects in the engine's scene (light intensity / color / position, `scene.fog` and its values, tone and exposure, environment, background, material color / emissive / opacity), on the values in `describe().owned` that are plain properties (the camera, `view.far`, the shadow target), on values named with `engine.debug.watch`, and on the components of those colors, vectors and rotations | Every read and write goes through unchanged; in devtools these show as accessors. A write records who made it for `describe('picture').writers` and `engine.explain({ value })` | yes: `threePatches.off('picture-writers')`, accessors stay and only pass values through |
73
+ | `picture-writers` | Dev server only (not in bundles or release builds): an own get / set on the picture values of objects in the engine's scene (light intensity / color / position, `scene.fog` and its values, tone and exposure, environment, background, material color / emissive / opacity), on plain-property values in `describe().owned` (the camera, `view.far`, the shadow target), on values named with `engine.debug.watch`, and on the components of those colors, vectors and rotations | Reads and writes pass through unchanged; devtools shows accessors. A write records who made it for `describe('picture').writers` and `engine.explain({ value })` | yes: `threePatches.off('picture-writers')`, accessors stay and only pass values through |
72
74
  | `post-shadow-hold` | `render` of the first pass of the WebGL post chain wrapped (it may be your own Pass) | None to what the pass draws; shadow maps redraw once a frame | yes |
73
75
  | `post-background-tone` | `onBeforeRender` of three's own background mesh, while the engine draws straight to the canvas | A texture background is tone-mapped as it is through the post chain; your own `renderer.render` keeps three's rule | yes |
74
76
  | `node-twin-dress` | `renderer.library.fromMaterial` of a WebGPURenderer wrapped | WebGPU only: the node twin of a classic material gets its patches | no (patched materials would lose their picture on WebGPU) |
75
77
  | `node-builder-hook` | `renderer.debug.onNodeBuilderCreated` of a WebGPURenderer wrapped | WebGPU only: your own hook still runs; a later write of yours replaces the engine's | yes |
78
+ | `pipeline-internal-scope` | `createRenderPipeline` of the renderer's GPUDevice wrapped | WebGPU only: an 'internal' error scope around the call; a pipeline the driver refuses is named, its post effect held | yes |
76
79
  | `device-lost-hook` | `renderer.onDeviceLost` of a WebGPURenderer wrapped | WebGPU only: three's hook still runs; a later write of yours replaces the engine's | yes |
80
+ | `page-exit-pointer-lock` | `document.exitPointerLock` wrapped (one wrapper for all live engines, gone with the last) | a game-requested unlock reads as the player pressing Esc | yes |
77
81
  | `occlusion-readback` | `resolveOccludedAsync` of the WebGPU backend (that one instance), once `engine.occlusion` is on | WebGPU only: an AbortError from a buffer destroyed with the renderer is dropped; any other error still reaches you | no (disposing an engine while occlusion answers are on their way would report an unhandled rejection) |
78
82
  | `lod-view-camera` | `update` and `clone` of the `THREE.LOD` objects `assets.lod` and a prop's `lod` make | Only the engine camera moves the level, and far off the full model waits on the batch layer with `visible` still true, so rays reach it | yes |
79
83
  | `webgpu-record-sweep` | A `'dispose'` event sent to objects drawn earlier that have left every Scene for a few seconds, found through WebGPURenderer's private record list | WebGPU only: your `'dispose'` listener on such an object runs; drawing it again rebuilds its record | yes |
@@ -97,7 +101,7 @@ that should not see it. It is page-wide: every engine on the page loses the chan
97
101
  | Vehicles, navigation, character controller | `engine.rigid.addWheeled(mesh, ...)` returns `{ body, controller }`; `engine.nav.navMesh / query / tileCache / crowd` (they are destroyed and replaced on rebuild; code that caches them compares `engine.nav.version`); `engine.player.mover.controller` (mover: 'rapier') |
98
102
  | glTF / compression decoders | `engine.assets.gltf` (GLTFLoader, Meshopt installed), `assets.draco` (DRACOLoader), `assets.ktx2` (KTX2Loader); the last two are created the first time compressed data is met and are null before that |
99
103
  | Rays | `engine.raycast(origin, direction)` / `engine.pick(ndcX, ndcY)` return three hits (`object` is the mesh, `face` and `point` unchanged); `{ targets: 'all' }` hits rigid bodies too (the hit carries `entry` and `kind: 'rigid'`); the underlying `engine.rays.ray` (THREE.Raycaster, `firstHitOnly` on) |
100
- | Ray acceleration (BVH) | three-mesh-bvh, without touching three's prototypes: a static mesh the engine registers (from 256 triangles up) gets `mesh.geometry.boundsTree` and its own `mesh.raycast`, so any ray on that mesh is fast, your own `new THREE.Raycaster()` too; every other mesh is plain three. Page-wide BVH for your rays: three-mesh-bvh's documented setup (`Mesh.prototype.raycast = acceleratedRaycast`, ...) |
104
+ | Ray acceleration (BVH) | three-mesh-bvh, without touching three's prototypes: only on meshes in `engine.rays.addStatic` (`ray-bvh` above); every other mesh is plain three. Page-wide BVH for your rays: three-mesh-bvh's documented setup (`Mesh.prototype.raycast = acceleratedRaycast`, ...) |
101
105
  | Streamed-in objects | `.object` of the handle returned by `engine.stream.add({ position, build })` (the Object3D that build returned; null before it is built) |
102
106
  | Post-processing | `engine.post.add(pass)`, the one way in (a Pass, or an effect `{ name, slot, create: ctx => pass }` plus its twin for the other renderer, recipe 56; slots `scene` / `hdr` / `tone` / `ldr` / `final`; on / off and params with its handle); `engine.post.own()` hands over the whole chain |
103
107
  | Where the mouse points | Ground: `screenToGround(engine, input.pointer.ndcX, ndcY)` -> Vector3; objects: `engine.pick(input.pointer.ndcX, ndcY)` (registered static objects; for any object pass `{ targets: [object] }`) |
@@ -107,34 +111,25 @@ Anywhere a position is accepted it is **one argument**: Vector3 / Object3D / `[x
107
111
 
108
112
  ## Engine conventions when using three.js
109
113
 
110
- 1. **Materials**: `new THREE.MeshStandardMaterial(...)` is the way; afterwards change `.map`, `.transparent` as usual.
111
- Your own shader code works as in three.js: `ShaderMaterial`, `onBeforeCompile` (also on an engine material: yours runs first, the engine's
112
- wind / clouds / season patches after it). The engine adds effects only to materials it made; yours opt in with `applyEffects(mat, { wind: 0.03 })`.
114
+ 1. **Materials**: `new THREE.MeshStandardMaterial(...)` is the way. Your own shader code works as in three.js: TSL on WebGPU (recipe 56),
115
+ `ShaderMaterial` / `onBeforeCompile` on WebGL (table above). The engine adds effects only to materials it made; yours opt in with `applyEffects(mat, { wind: 0.03 })`.
113
116
  One exception, named: with cascaded shadows on (`engine.shadows.cascades(light)`) every built-in lit material gets the `csm` patch, or it would
114
117
  be lit N times; a lit `ShaderMaterial` of yours joins with `engine.shadows.include(mat)` (recipe 45).
115
- 2. **Adding to the scene**: `engine.scene.add(obj)` is all it takes: every root under the scene is registered (`engine.thing(obj)` says what it
116
- is and what a save keeps). `engine.add(obj, { id })` is only for a stable id, so `thing.set` changes to it are saved (`recipes/40-scene.md`). To attach to a character use `player.root.add(hat)`.
118
+ 2. **Adding to the scene**: `engine.scene.add(obj)` registers every root (`engine.thing(obj)` says what a save keeps); `engine.add(obj, { id })` only adds a stable id (`recipes/40-scene.md`). To attach to a character: `player.root.add(hat)`.
117
119
  3. **Per-frame logic goes in `engine.onFrame(dt => ...)`** (movement and timing use `engine.onFixed`); it returns a handle, cancel with `h.remove()`.
118
- Don't start your own `requestAnimationFrame` loop: the engine owns pausing, fast-forward in tests and ordering. Rendering the canvas
119
- yourself (own `EffectComposer`) takes the frame over: the engine stops drawing it and its post chain, adaptive resolution and photo mode stop applying. Rendering into your own render target is fine: `engine.onRender`, in the table above.
120
+ Don't start your own `requestAnimationFrame` loop: the engine owns pausing, fast-forward in tests and ordering. Rendering the whole canvas yourself takes the frame over
121
+ (post chain, adaptive resolution and photo mode stop applying); a render target of your own goes in `engine.onRender` (table above).
120
122
  4. **Snap to ground**: get ground height with `engine.surface(x, z)`, or `engine.snapToGround(obj, heightAboveGround)`. Don't raycast the terrain.
121
123
  **Rays** always go through `engine.raycast / pick`: level meshes are registered automatically; register your own static objects with
122
124
  `engine.rays.addStatic(obj)` or `assets.model(name, { static: true })`.
123
- 5. **Deleting**: when you no longer need an object use `engine.remove(obj)`: it removes it, unregisters it from `engine.rays` and frees the geometry
124
- and materials (`obj.removeFromParent()` / `scene.remove` leak GPU memory). To take it off only temporarily and `add` it back later use
125
- `obj.removeFromParent()`. A copy from `assets.model()` shares resources with other copies (`remove` skips them); they are freed together by
126
- `assets.release(name)`.
127
- 6. **The sky lights nothing**: it computes signals and draws the dome, and your `picture/` code writes the lights, the fog and the exposure (recipe 62); weather gives `uWeatherLight` / `uWeatherFog` to multiply in. Every engine-written value: recipe 52
128
- "Who writes it". Adding your own point lights (street lamps, campfires) is fine.
125
+ 5. **Deleting**: `engine.remove(obj)` (recipe 05 §5; it also unregisters rays). A copy from `assets.model()` shares resources with other copies (`remove` skips them); `assets.release(name)` frees them together.
126
+ 6. **The sky lights nothing**: it computes signals and draws the dome; your `picture/` code writes lights, fog and exposure (recipe 62).
129
127
  7. **Camera**: `engine.camera` is a three.js camera: change its properties, or assign your own real `THREE.PerspectiveCamera` or `THREE.OrthographicCamera` (`engine.camera = cam`, keep the old value to swap back). Rendering, post, picking, shadows, audio and an installed camera module all go on with it; any other class, a subclass too, is refused. Aspect, frustum and a rig's `projection`: recipe 21. `engine.setCamera('follow')` swaps the camera *module*, not the object. When a camera
130
128
  module is installed it places the camera every frame; to control the view yourself take it with `const cam = engine.takeCamera('me')` and `cam.remove()` it
131
129
  (`engine.cameraOverride` is read-only: it shows the holder in charge, or `null`).
132
130
  8. Collision: the player only respects `engine.collision` (`addCircle / addBox / addObject(mesh)`); a mesh alone does not block anyone.
133
- 9. **Big code-generated things** (a city block, a whole group of houses): write them as a function registered in the manifest
134
- `assets.manifest({ models: { block: buildBlock } })` and fetch with `assets.model('block')`; in development it is cached automatically, after
135
- `npm run bake` it reads the file.
136
- Things needed only nearby use `engine.stream.add({ position, build })`; put long loops in `engine.jobs.add(function* () { ...; yield; })` so they
137
- are spread over frames and the start does not stall.
131
+ 9. **Big code-generated things**: a generator in the manifest, fetched by name (recipe 05 §2). Things needed only nearby: `engine.stream.add({ position, build })`;
132
+ long loops: `engine.jobs.add(function* () { ...; yield; })`, spread over frames.
138
133
  10. **One copy of the engine and of three per page**: `resolve: { dedupe: ['threedog', 'three'] }` in vite.config.js. A second engine copy
139
134
  (a pack that lists threedog under `dependencies` instead of `peerDependencies`, a linked plus an installed copy) breaks shadows of wind and
140
135
  cascaded-shadow materials; the engine warns once at load, naming both paths [engine-two-copies].
@@ -144,22 +139,22 @@ The same windmill as a template with an id, saved and editable without code, is
144
139
 
145
140
  ```js
146
141
  import { THREE } from 'threedog';
147
- const mill = new THREE.Group(), blades = new THREE.Group(); // plain three.js: meshes and materials as usual
142
+ const mill = new THREE.Group(), blades = new THREE.Group(); // plain three.js: meshes and materials as usual
148
143
  mill.add(blades);
149
144
  mill.position.set(20, 0, -10);
150
- engine.snapToGround(mill); // snap to ground
151
- engine.scene.add(mill); // registered like engine.add; engine.add(mill, { id: 'mill' }) also keeps thing.set changes in saves
145
+ engine.snapToGround(mill); // snap to ground
146
+ engine.scene.add(mill); // registered like engine.add; engine.add(mill, { id: 'mill' }) also keeps thing.set changes in saves
152
147
  engine.collision?.addCircle(mill, { radius: 1.3 }); // block the player (when the collision module is installed)
153
148
  engine.onFrame(dt => { blades.rotation.z += dt * 1.5; });
154
149
  ```
155
150
 
156
151
  ## Example: your own rain (three.js drops, a plain call or a module)
157
- `weather({ rain })` is there if it fits. Your own effect of any kind is the same few steps: three.js builds it, a call adds it, a module only when something must clean up or swap it.
152
+ `weather({ rain })` is there if it fits. Your own effect: three.js builds it, a call adds it, a module only when something must clean up or swap it.
158
153
 
159
154
  ```js
160
155
  import { THREE } from 'threedog';
161
156
  function makeRain({ count = 2000, area = 40, height = 20, speed = 18 } = {}) {
162
- const pos = new Float32Array(count * 6); // one short line per drop
157
+ const pos = new Float32Array(count * 6); // one short line per drop
163
158
  for (let i = 0; i < count; i++) pos.set([(i * 0.618 % 1 - 0.5) * area, i * 0.31 % 1 * height, (i * 0.754 % 1 - 0.5) * area], i * 6);
164
159
  const geo = new THREE.BufferGeometry().setAttribute('position', new THREE.BufferAttribute(pos, 3));
165
160
  const drops = new THREE.LineSegments(geo, new THREE.LineBasicMaterial({ color: 0x9fb8d0, transparent: true, opacity: 0.5 }));
@@ -192,14 +187,14 @@ engine.use(rainEffect({ count: 4000 }));
192
187
  The engine then does the rest: `engine.unuse('rain')`, a failed install or `{ replaces }` runs what `ctx.track` holds, and two modules of one name or two owners of one slot are refused with the fix. A value that others change too (rain slowing the player) goes through `ctx.mod`.
193
188
 
194
189
  ## Example: wet stone in rain (the engine gives the signal, the game decides)
195
- The weather module knows how hard it rains. It does not know what your stone looks like wet, or whether wet stone is slick: those are this game's look and this game's rule.
190
+ The weather module knows how hard it rains, not what your stone looks like wet or whether it is slick: that is the game's look and rule.
196
191
 
197
192
  ```js
198
193
  import { THREE } from 'threedog';
199
194
  const stone = new THREE.MeshStandardMaterial({ color: 0x777066, roughness: 0.9 });
200
- engine.onFrame(() => { stone.roughness = 0.9 - 0.6 * engine.uniforms.uRain.value; }); // the look: the game's material reads the rain
195
+ engine.onFrame(() => { stone.roughness = 0.9 - 0.6 * engine.uniforms.uRain.value; }); // the look: the game's material reads the rain
201
196
 
202
- let slick = null; // the rule, if the game wants one: in game time, through the shared value
197
+ let slick = null; // the rule, if the game wants one: in game time, through the shared value
203
198
  engine.onFixed(() => {
204
199
  const wet = (engine.weather?.current.rain ?? 0) > 0.5 && engine.groundType(engine.player.position) === 'stone';
205
200
  if (wet && !slick) slick = engine.mod('move.speed', { owner: 'wet-stone', id: 'player', mul: 0.8 });
@@ -218,14 +213,14 @@ import { mergeGeometries, mergeVertices } from 'three/addons/utils/BufferGeometr
218
213
  import { SimplexNoise } from 'three/addons/math/SimplexNoise.js';
219
214
  import { bakeVertexAO } from 'threedog';
220
215
 
221
- const rng = engine.random.seeded(7), simplex = new SimplexNoise({ random: () => rng.next() }); // seeded noise: the same shape every load
216
+ const rng = engine.random.seeded(7), simplex = new SimplexNoise({ random: () => rng.next() }); // seeded noise: the same shape every load
222
217
  // weld first, or the noise opens cracks; mergeVertices compares every attribute, so drop normal and uv (their seams would stay unwelded)
223
218
  const rock = mergeVertices(new THREE.IcosahedronGeometry(1, 3).deleteAttribute('normal').deleteAttribute('uv'));
224
219
  const p = rock.attributes.position, v = new THREE.Vector3();
225
220
  for (let i = 0; i < p.count; i++) { v.fromBufferAttribute(p, i); v.multiplyScalar(1 + 0.25 * simplex.noise3d(v.x, v.y, v.z)); p.setXYZ(i, v.x, v.y, v.z); }
226
221
  rock.computeVertexNormals();
227
222
  const slab = new THREE.CylinderGeometry(1.2, 1.4, 0.3).translate(0, -0.9, 0).deleteAttribute('uv');
228
- const model = mergeGeometries([rock, slab]); // same attributes (position, normal), both indexed
223
+ const model = mergeGeometries([rock, slab]); // same attributes (position, normal), both indexed
229
224
  bakeVertexAO(model, { samples: 32, strength: 0.7, occluders: [new THREE.PlaneGeometry(6, 6).rotateX(-Math.PI / 2).translate(0, -1.05, 0)] });
230
225
  ```
231
226
 
@@ -9,13 +9,13 @@
9
9
  - `assets.model(nameOrUrl: string, opts?: { castShadow?, receiveShadow?, static? }) → Promise<Object3D>` — Get a model copy (name or path; geometry and materials are shared with other copies). static: true registers it in engine.rays (builds ray acceleration)
10
10
  - `assets.lod(nameOrUrl: string, opts?: { distances?, hysteresis?, castShadow?, receiveShadow?, static? }) → Promise<import('three').LOD>` — (experimental) A model copy as a plain THREE.LOD: the full model near, the levels of `threedog assets optimize --lod` far away. Default distances follow the model's size; distances (rising meters) replace them, hysteresis is the share of a distance that stops flicker at the line (default 0.1). Rays, collision and saves keep using the full model. A LOD object is never batched. Without levels it warns in dev and draws in full. Example: `const tower = await engine.assets.lod('tower', { distances: [40, 120] }); engine.add(tower); tower.levels[1].object;`
11
11
  - `assets.modelNow(nameOrUrl: string, opts?: { castShadow?, receiveShadow?, static? }) → Object3D | null` — (experimental) A model copy right now if it has already loaded, else null (never starts a load, never waits): lets code that rebuilds often skip the frame an await costs. Code-built models (a build function in the manifest) count too: they are null until one await model(name) or an entry with preload: true ran (dev warns [asset-not-loaded]). Example: `const m = engine.assets.modelNow('villager') ?? await engine.assets.model('villager');`
12
+ - `assets.onModel(fn: (model, name) => void) → { remove(): void }` — The game's setup for every model the engine hands out (assets.model / modelNow / lod, content props and templates, pickups, character bodies, a code-built vegetation model named in define, a level file): runs once per copy, before it is added or drawn. Synchronous; one per engine (a second throws); leaves the root's transform to its placer (dev throws). Copies share materials: map each original to one of yours. Example: `const mine = new Map(); engine.assets.onModel(m => m.traverse(o => { if (o.isMesh) o.material = mine.get(o.material) ?? mine.set(o.material, myLook(o.material)).get(o.material); }));`
12
13
  - `assets.geometry(nameOrUrl: string) → Promise<BufferGeometry>` — Get the geometry of the first mesh in a model
13
14
  - `assets.gridFromImage(nameOrUrl: string, opts?: { channel?, range?, bits? }) → Promise<{ data: Float32Array; wid…` — An image as grid data for sampleGrid: PNG at 8 or 16 bits (jpg / webp 8). channel 'r' (default) 'g' 'b' 'a' or 0-3; range maps pixels to [min, max] (default [0, 1])
14
15
  - `assets.texture(nameOrUrl: string, opts?: { color?, pixelated?, repeat? }) → Promise<Texture>` — Get a texture (.ktx2 compressed textures also work)
15
16
  - `assets.useTexture(nameOrUrl: string, use: (texture: Texture) => void, o?: { where?, instead?, opts? }) → Promise<boolean>` — Fetch a texture for something that already shows a stand-in: use(texture) runs when it arrives; a failed load is one asset-load dev warning naming `where` and what shows `instead`, and resolves false (an error inside use() is not swallowed). opts are texture()'s options
16
17
  - `assets.release(name: string)` — Release a resource and return its memory. Not released while copies of the model are still in the scene; it is released when the last copy is removed with engine.remove. A sound (name or path) plays on where it is playing and loads again on next use. A load still running ends and its result is thrown away; code awaiting it gets a fresh load, never freed data. A name that fell back holds no data of its own: release the name it fell back to
17
18
  - `assets.trim() → string[]` — Release every model that has no copy in use and every long decoded sound (music, long loops; short effects stay; a sound still playing plays on), unless marked preload (called automatically after level changes). Models whose shared geometry was taken by geometry() and code-generated models are not released automatically. Returns the released names
18
- - `assets.forget(obj: Object3D)` — (experimental) Called when an object is fully removed (engine.remove already calls it, normally you don't need to): decrements the use count of the model copies under it
19
19
  - `assets.animate(root: Object3D, config?: AnimatorOptions) → Animator` — Create an animation state machine for a skinned model (without config it is simple play-by-name). A copy of a manifest model whose entry has `animation` starts from that mapping; config wins per state
20
20
  - `assets.mapping(root: Object3D) → AnimatorOptions | null` — The manifest entry's animation mapping for a model copy, or null (not a manifest copy, or no mapping)
21
21
  - `assets.report(nameOrRoot: string | Object3D) → AssetReport` — Import report of a loaded model (by name, or a copy from model()): materials, textures with colorSpace, clips, colliders, templates, and issues for what the file has but the scene lost
@@ -63,4 +63,6 @@
63
63
  - `sync(state: string | null, t?: number) → any` — Gameplay drives the clock: show state at gameplay time t (fixed-step seconds) through its timing. The clip never advances or ends by itself and go() leaves it alone; sync(null) hands control back
64
64
  - `describe() → AnimatorInfo` — What is showing: state, clip, clip time, progress, driven, weights
65
65
  - `check(actions?: string[]) → string[]` — Check the mapping against the action names the game plays: each problem as text with its fix ([] = all will play). Example: `anim.check(['idle', 'walk', 'attack', 'hurt'])`
66
+ - `addAim(opts: { bones, target?, limit?, speed?, weight?, fade?, … }) → AimLayer` — Look-at IK, the last layer on the clips: a bone or a chain from the body out turns toward target, within limit degrees of the animated pose. Weight 0 leaves the pose exactly; target null looks ahead; forward: the last bone's own front axis when the bind pose does not say (recipe 13 §3e). Example: `const look = npc.anim.addAim({ bones: ['Neck', 'Head'], target: engine.player.root, limit: 70 });`
67
+ - `addFeet(opts?: { legs?, hips?, reach?, far?, speed?, weight?, … }) → FeetLayer` — Feet on the ground: each [upper, lower, foot] leg bends onto the model's own ground (a Character's includes platforms; off while it jumps or swims, beyond far from the camera, while hidden); the hips lower for the foot that reaches down. legs: bone names when they are not recognised. Example: `const feet = engine.player.anim.addFeet();`
66
68
  - `dispose()` — Stop the per-frame update when no longer needed
package/docs/api/audio.md CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  - `audio.addBus(name: string, opts?: { level?: number; owner?: string }) → { owner?: string; remove(): void }` — Add a bus of your own (routed to master). It gets a settings slider like the others (label key settings.vol.<name>) until the handle is removed (the one give-back form, like every other handle). A name that is already a bus throws: two owners of one bus could not both remove it. Example: `const voice = engine.audio.addBus('voice', { level: 1 }); engine.audio.sfx('line-01', { bus: 'voice' }); voice.remove();`
4
4
  - `audio.setVolume(bus: string, v: number)` — Set a bus volume 0-1 ('master' for the total). Example: `engine.audio.setVolume('music', 0.3);`
5
+ - `audio.reverb(opts: { wet?, decay?, size?, sends?, fade? } | null)` — (experimental) The one reverb: a send/return any bus can feed (a cave, a hall, a bathroom). Off until called: nothing is built or heard before. Each call changes only the keys given (sends merge per bus; 0 stops one); null turns it off. The echo of a bus follows its slider and its ducks, and comes back through master. The impulse is generated (decaying noise, no file): changing size or decay rebuilds it, wet and sends only fade. Called before the first click it waits for audio to unlock. Places: an ambience rule { reverb: 0.6, when: { zone: 'cave' } } sets wet while it holds (recipes/31 §9). Example: `engine.audio.reverb({ sends: { sfx: 0.5, ambience: 0.8 }, decay: 3, size: 0.8, wet: 0.4 });`
5
6
  - `audio.duck(levels: Record<string, number>, opts?: { fade?: number }) → { remove(fade?: number): void }` — Lower buses until the handle is removed (dialogue, pause menu, a cutscene). Several ducks stack (their levels multiply). Example: `const d = engine.audio.duck({ music: 0.3, ambience: 0.5 }); engine.events.once('dialogue:end', () => d.remove());`
6
7
  - `audio.condition(name: string, test: (value: any, e: any) => boolean) → { remove(): void }` — Add a condition key for music / ambience rule lists: `when: { [name]: value }` calls test(value, engine). Modules add theirs (calendar: time, weather: weather, triggers: zone); the engine has `state` (engine.audio.state). Example: `engine.audio.condition('inside', v => engine.vars.flag('indoors') === v);`
7
8
  - `audio.measure(name: string, fn: (e: any) => number) → { remove(): void }` — Add a measure: a number rule data compares (`when: { daylight: { gt: 0.15 } }`; gt / gte / lt / lte) and adds up (`volume: { add: { wind: 0.08 } }`). calendar adds daylight, weather rain / snow / wind, ambience nearWater / altitude. A name is a condition or a measure, not both. Example: `engine.audio.measure('danger', e => e.vars.counter('alarm') / 10); // data: when: { danger: { gt: 0.5 } } Measures are not only for sound: render/daylight.js reads 'daylight' for night glow, so the calendar (or the sky without one) registers it once and nothing else has to know which module tells day from night. remove() drops only this registration (a later one under the name stays).`
@@ -21,7 +22,7 @@
21
22
  - `master: any` The master GainNode (every bus ends here)
22
23
  - `noise: any` 2 s of white noise, reused by synthesized sounds
23
24
  - `running: boolean` (experimental) Is audio usable (the player has clicked/pressed a key)?
24
- - `info: { running, state, levels, ducks, voices }` What is playing (describe().audio shows it while something is ducked or playing): bus levels, the duck multiplier per bus, live voices per sound name. ducks is the level the active ducks ask for (1 = not lowered), read at once even while a fade is still ramping or the audio clock does not run (headless page). Example: `engine.audio.duck({ music: 0.3 }); engine.audio.info.ducks.music // 0.3`
25
+ - `info: { running, state, levels, ducks, voices, reverb? }` What is playing (describe().audio shows it while something is ducked or playing): bus levels, the duck multiplier per bus, live voices per sound name. ducks is the level the active ducks ask for (1 = not lowered), read at once even while a fade is still ramping or the audio clock does not run (headless page). Example: `engine.audio.duck({ music: 0.3 }); engine.audio.info.ducks.music // 0.3`
25
26
 
26
27
  ## Data structures
27
28
  - **AudioConfig** The game's sound config: createEngine({ audio }), read back as engine.audio.config (merged with content packs' ContentAudio).
@@ -42,8 +43,9 @@
42
43
  - `loop?: boolean`
43
44
  - `distance?: { ref?: number; max?: number; rolloff?: number }` 3D falloff for sfx(name, { at }): ref meters at full volume (2), max meters (60), rolloff (1)
44
45
  - **AmbienceRule** One ambience rule: while `when` holds, `sound` plays at `volume`. With `every` it is a one-shot repeated at random gaps, else a loop
45
- - `sound: string`
46
+ - `sound?: string` A name from audio.sounds; required unless the rule is a reverb rule
46
47
  - `when?: AudioCondition`
48
+ - `reverb?: number | AudioVolumeData | ((e, ambience) => number)` (experimental) Instead of a sound: the reverb's wet (0-1, or the volume forms) while `when` holds; the highest holding one wins, none gives engine.audio.reverb's own wet back. Not with sound / volume / every / bus
47
49
  - `volume?: number | AudioVolumeData | ((e, ambience) => number)` 0-1, data { base, add: { measure: factor }, min, max }, or a function of the moment (e, ambience) => 0-1 (code only)
48
50
  - `fade?: number` Fade seconds when the rule turns on / off (1)
49
51
  - `every?: number[]` One-shot: [shortest, longest] seconds between plays
@@ -7,11 +7,14 @@
7
7
  - `budget.report() → BudgetReport | null` — Budget report; null when off. In the real-time loop it returns the last second's result; in step() mode it is computed on demand
8
8
  - `budget.checkStartup(s: { totalMs, modules }) → { category, value, limit, top }[]` — (experimental) Called by the engine when startup finishes: warns if startupMs / moduleMs is exceeded and returns the offenders (empty array if none)
9
9
  - `budget.values() → Record<string, number>` — Current value per category (fps/low1/cpuMs exist only once there are frame times)
10
+ - `budget.record() → { where, values }` — This run's numbers in the shape baseline keeps: { where, values: { drawCalls, triangles, cpuMs (live runs), modules: { name: median ms, 0 too } } }. threedog shot / verify --save-baseline write it into the game's .threedog/perf-baseline.json (this machine's, not committed)
11
+ - `budget.notice() → string | null` — One line when something is off, null when all is fine: over a limit the game declared (only when the budget is on; the engine's own reference limits never), slower than the baseline recorded at this spot on this machine (medians, past a noise margin), a module with spikes (p95 over 3x its median and over 2 ms), or what adaptive quality lowered (resolution, effects). threedog shot, verify and describeText print it. Example: `engine.budget.notice() // 'Perf: over budget drawCalls 312 (limit 250, +25%); slower than baseline: modules.terrain 1.4 ms (was 0.6, +133%) -> threedog inspect perf'`
10
12
  - `budget.byTag() → BudgetTagStat[]` — Estimate draw calls and triangles by userData.budgetTag (visible meshes inside the frustum; shadow casters count a second shadow draw). Returns [{ tag, drawCalls, triangles }], largest first. Called only on overrun (at most once a second) or when debugging
11
13
  - Properties:
12
14
  - `enabled: boolean` Is it on?
13
15
  - `limits: BudgetLimits` (experimental) Current limits
14
16
  - `cost: ApplyCost` Cost of applying background results, split in stages (see ApplyCost)
17
+ - `baseline: Record<string, any> | null` The recorded run to compare against: { [where]: { drawCalls, triangles, cpuMs?, modules: { name: ms } } } as record() makes it. threedog shot / verify load the game's .threedog/perf-baseline.json (this machine's) here when the game set none (and write it with --save-baseline). null = no comparison
15
18
 
16
19
  ## Data structures
17
20
  - **BudgetLimits** Budget limits: only the given categories are checked. fps/low1 are lower bounds (frame rate must not drop below), the rest are upper bounds
@@ -21,6 +24,7 @@
21
24
  - `cpuMs?: number` CPU milliseconds per frame
22
25
  - `triangles?: number` Triangle count
23
26
  - `textures?: number` Texture count
27
+ - `gpuMemoryMB?: number` GPU memory in MB as three counts it (WebGPURenderer only: an estimate, not driver VRAM)
24
28
  - `chunkApplyMs?: number` Terrain chunk upload milliseconds per frame
25
29
  - `rigidBodies?: number` Rigid body count
26
30
  - `lights?: number` Lit point + spot lights, a game's own and pooled ones (default limit 8)
@@ -34,6 +38,7 @@
34
38
  - `applyStreamMs?: number`
35
39
  - `startupMs?: number` Time from opening to playable (milliseconds); when exceeded, the slowest module is named
36
40
  - `moduleMs?: number` Single module startup (init + wait for ready, milliseconds); when exceeded, that module is named
41
+ - `modules?: Record<string, number>` Hook ms per frame of one module, { terrain: 1.5 } (median of engine.profile(), on in dev builds); reported as category 'modules.<name>'
37
42
  - **BudgetReport** Budget report: ok means everything is within budget
38
43
  - `ok: boolean`
39
44
  - `over: BudgetOver[]`