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
@@ -1,6 +1,6 @@
1
1
  # engine.characters — characters(opts?: CharactersOptions)
2
2
 
3
- Characters: createPlayer() (characters() module)
3
+ Characters: addPlayer() (characters() module)
4
4
 
5
5
  - Options `CharactersOptions`:
6
6
  - `npcs?: boolean` Whether to enable NPCs (engine.npcs), default true
@@ -10,13 +10,13 @@ Characters: createPlayer() (characters() module)
10
10
 
11
11
  ## Methods and properties
12
12
  - `characters.findSpawn(position?: PositionLike, opts?: FindSpawnOptions) → Vector3` — Find a spawn point: searches outward from position (default origin) for walkable (not steep, no obstacle), non-water ground, without assuming terrain height; e.g. findSpawn(v, { minH: 3, maxH: 20 }). Returns a Vector3 (y is the ground height)
13
- - `characters.createPlayer(opts: PlayerOptions) → Character` — Create the player and set engine.player; control is required (no default feel), e.g. createPlayer({ ...presets.player.thirdPerson, spawn }). An existing player is deleted first
13
+ - `characters.addPlayer(opts: PlayerOptions) → Character` — Create the player and set engine.player; control is required (no default feel), e.g. addPlayer({ ...presets.player.thirdPerson, spawn }). An existing player is deleted first
14
14
  - `characters.moveInput(seat?: Seat) → { x, z, run }` — The 'camera' player control as a value: keys / stick relative to the camera, the 'run' action if bound, input.autopilot. Reused object; call it inside your own control function to wrap it
15
15
  - `characters.addVehicle(vehicle: any) → { remove(): void }` — Join the vehicles a saved rider can be seated in again, before or after the load
16
16
  - `characters.support(object: any, opts?: { id?, safe?, carry?, inherit? }) → { id: string; remove(): void }` — Something characters stand on and ride (moving platform, lift, raft). Move the object any way (onFixed before or after the player, a timeline, physics): riders follow how its matrix changed, so the order does not matter. safe: false = never a respawn spot; carry 'position+yaw' turns riders with it; inherit: false = jumping off keeps none of its speed. With mover 'rapier' give it a collider too. Example: `const lift = engine.characters.support(liftMesh); engine.onFixed(() => { liftMesh.position.y = 2 + Math.sin(engine.time.now('real')); });`
17
17
  - `characters.removePlayer(id?: string)` — (experimental) Delete the current player (exits the vehicle first, stops responding to keys, fully deletes the model). The player save (key player) carries the position and the vehicle; loading an on-foot save exits the vehicle first
18
18
  - `characters.findPath(from: PositionLike, to: PositionLike, opts?: FindPathOptions & { detailed?: false }) → NavPathPoint[] | null` / `findPath(from: PositionLike, to: PositionLike, opts: FindPathOptions & { detailed: true }) → PathResult` — Pathfinding (the single entry point): uses the navmesh when nav is installed and ready, otherwise the A* fallback. Returns a path [{ x, y, z }...], or null if unreachable
19
- - `characters.findPathAsync(from: PositionLike, to: PositionLike, done: (path, status) => void, opts?: { radius?, step?, maxNodes? }) → { remove(): void }` — findPath for many callers (NPC crowds, AI squads): solved in engine.threads workers; done(path, status) runs on a fixed step a few steps later (same paths with threads on or off). Recipe 12 section 4
19
+ - `characters.findPathAsync(from: PositionLike, to: PositionLike, done: (path, status) => void, opts?: { radius?, passes?, step?, maxNodes? }) → { remove(): void }` — findPath for many callers (NPC crowds, AI squads): solved in engine.threads workers; done(path, status) runs on a fixed step a few steps later (same paths with threads on or off). Recipe 12 section 4
20
20
  - Properties:
21
21
  - `material: Material` The three.js material of every placeholder capsule. Set it to swap the look of all of them at once; used as given, with no patches added. A character with colors.body draws with a copy of it in that color. A model's own materials are the model's. Example: `engine.characters.material = new THREE.MeshToonMaterial({ color: 0xd9a066 });`
22
22
  - `kit: { beginMove, groundAt, endMove, ownState }` What a game's mover calls to take part in contact, each optional (recipe 57): a mover calling none owns contact itself (beginMove() groundAt() endMove() ownState())
@@ -35,7 +35,7 @@ Characters: createPlayer() (characters() module)
35
35
  - `player.playAction(name: string)` — Play a one-shot action (e.g. 'wave'); skipped if the model has no such clip
36
36
  - `player.onPose(fn: (character, dt) => void) → { remove(): void }` — Run fn(character, dt) every frame right after the animation pose is applied (model clips or procedural rig): attach things to bones or adjust bones. h.remove() stops it. Presentation only. Example: `const h = player.onPose(() => sword.position.copy(hand.getWorldPosition(v)));`
37
37
  - `player.dispose()` — Fully delete this character: exits the vehicle first, releases animation and movement, removes it from the scene and releases geometry and materials (used by npcs.remove / removePlayer)
38
- - `player.jump(opts?: { air?: boolean })` — Request a jump (buffered for jumpBuffer s): the ground jump on the ground or in coyote time, else an air jump while maxJumps allows; air: false = ground only. Example: `createPlayer({ ...presets.player.thirdPerson, maxJumps: 2 }) // double jump`
38
+ - `player.jump(opts?: { air?: boolean })` — Request a jump (buffered for jumpBuffer s): the ground jump on the ground or in coyote time, else an air jump while maxJumps allows; air: false = ground only. Example: `addPlayer({ ...presets.player.thirdPerson, maxJumps: 2 }) // double jump`
39
39
  - `player.placeAt(position: PositionLike)` — Put it on the ground at position (Vector3 / object / [x, y, z] / { x, z })
40
40
  - `player.syncRecord()` — After moving root yourself (a cutscene path, a scripted pose): write position and motion back to its world record (the player's), so a save right after has it
41
41
  - `player.walkTo(target: Vector3 | { x: number; z: number } | [number, number, number] | …, opts?: { speed?, arrive?, turnRate?, stuckSeconds?, maxRepaths?, run? }) → Promise<{ status: 'arri… & { remove(): void }` — Walk to a point along characters.findPath on fixed steps; never rejects. One walk per character: a new walkTo, dispose() or a save load ends the old one with 'cancelled'. Transient: not saved, not fast-forwarded by engine.skip. Holds the character's control on layer 'script' (owner 'walkTo'): the player's keys / an NPC's schedule pause meanwhile, a cutscene pauses the walk, and another script owner on it is control-conflict
@@ -45,7 +45,7 @@ Characters: createPlayer() (characters() module)
45
45
  - `player.saveMotion(out?: CharacterMotion) → CharacterMotion` — (experimental) Copy the motion state into a plain object (velocity, vertical velocity, heading, movement amount, grounded, swimming) to store in world data; after the model is rebuilt or a save is loaded, loadMotion continues from it with identical results
46
46
  - `player.loadMotion(m: CharacterMotion | null | undefined)` — (experimental) Restore the motion state from the plain object of saveMotion
47
47
  - Properties:
48
- - `root: Object3D` Root node: add it to the scene with engine.add(character.root) when you built the Character yourself; add children, change visible and scale on it
48
+ - `root: Object3D` Root node, the character's model (there is no character.model; the loaded glTF is a child of root): add it to the scene with engine.add(character.root) when you built the Character yourself; add children, change visible and scale on it
49
49
  - `position: Vector3` Position (= root.position)
50
50
  - `velocity: Vector2` Horizontal velocity (x, y map to world x, z). Writable: a write is an impulse the mover steers back toward the input (lasting knockback: push(); full control: mover 'manual')
51
51
  - `facing: number` Heading (radians): 0 faces +Z, forward = (sin facing, cos facing); increasing turns toward +X (rotation about the Y axis, consistent with root.rotation.y)
@@ -69,6 +69,7 @@ Characters: createPlayer() (characters() module)
69
69
  - `jumpBuffer: number` (experimental)
70
70
  - `fall: false | { belowY }` (experimental) Fall check (see CharacterOptions.fall); a plain property
71
71
  - `channel: string` Time channel the engine drives it on (see CharacterOptions.channel)
72
+ - `passes: readonly string[] | undefined` Collider layers it goes through (the passes option, sorted); undefined = stopped by every collider. Plain: a write counts from its next step and path
72
73
  - `id: string` The character's id, the one form engine.mod / time.local take: its world record id ('player', an NPC's record id), else the id option, else a generated one
73
74
  - `support: { kind, object, id, safe, velocity }` What it stands on, read-only (reused object); 'platform' = a registered support (characters.support), which carries it
74
75
  - `safeGround: Vector3 | null` Last spot it stood still on safe ground (where a fall returns it); null until it first stands. Saved with the motion
@@ -119,7 +120,7 @@ Characters: createPlayer() (characters() module)
119
120
  - `at: number`
120
121
  - `x: number`
121
122
  - `z: number`
122
- - **PlayerOptions** (extends CharacterOptions) Parameters of createPlayer()
123
+ - **PlayerOptions** (extends CharacterOptions) Parameters of addPlayer()
123
124
  - `id?: string` A further local player's id and world record; left out, the one player (engine.player)
124
125
  - `input?: Seat` The seat that drives this player (engine.input.seat); default engine.input
125
126
  - `spawn?: PositionLike` Spawn point (meters, { x, z } / Vector3 / object); flat ground is found automatically if omitted
@@ -131,7 +132,7 @@ Characters: createPlayer() (characters() module)
131
132
  - `runSpeed?: number` Running speed (m/s), default 7
132
133
  - `radius?: number` Collision radius (meters), default 0.4
133
134
  - `water?: CharacterWater` What water deeper than swimDepth does: 'swim' (default: floats, state 'swim') / 'block' (never enters it) / 'wade' (walks the bottom) / a function deciding per spot (a swim skill, a boat, depth). character:water fires on each change
134
- - `states?: CharacterStates | null` The game's own states on top of the built-in ones (crouch, climb, glide, dash, roll): run after the mover's state each step, return a state name or null to keep facts.base. The state picks the clip like any other (clips: { crouch: 'Crouch' }); speed changes stay engine.mod('move.speed'). Example: `createPlayer({ ..., clips: { crouch: 'Crouch' }, states: (c, f) => f.grounded && engine.input.down('crouch') ? 'crouch' : null })`
135
+ - `states?: CharacterStates | null` The game's own states on top of the built-in ones (crouch, climb, glide, dash, roll): run after the mover's state each step, return a state name or null to keep facts.base. The state picks the clip like any other (clips: { crouch: 'Crouch' }); speed changes stay engine.mod('move.speed'). Example: `addPlayer({ ..., clips: { crouch: 'Crouch' }, states: (c, f) => f.grounded && engine.input.down('crouch') ? 'crouch' : null })`
135
136
  - `swimDepth?: number` Water depth (meters) at which water counts as deep, default 1
136
137
  - `swimSpeed?: number` Swimming speed multiplier, default 0.45
137
138
  - `turnSpeed?: number` How fast it turns, default 10
@@ -147,7 +148,8 @@ Characters: createPlayer() (characters() module)
147
148
  - `jumpBuffer?: number` How long a jump() pressed early waits for the ground (seconds), default 0.12
148
149
  - `fall?: false | { belowY }` Falling out of the level: below belowY (or when belowY(character) is true) character:fall fires and the rule 'fall' decides: back to safeGround by default, engine.mod('fall', { owner, id, set: false }) leaves it to the game. false (default) = off
149
150
  - `channel?: string` Time channel its movement and animation follow when the engine drives it (player default 'player', others 'world')
150
- - `model?: Object3D | string | null` The body, one path for every kind: the name of a registered model asset, or what engine.assets.model() returned. A procedural builder name (from an asset pack) is built at once; a file model name shows a gray capsule and swaps in a copy when it loads (Character.ready / whenReady, event 'character:model'). Example: `engine.assets.manifest(yourAssets); engine.characters.createPlayer({ model: 'yourBody' }) // a generator or GLB name from an asset pack`
151
+ - `passes?: string[]` Collider layers it walks through, e.g. ['gate'] (collision.addBox { layer: 'gate' }): its walking, walkTo and NPC paths, navmesh included, follow it. Default: stopped by every collider
152
+ - `model?: Object3D | string | null` The body, one path for every kind: the name of a registered model asset, or what engine.assets.model() returned. A procedural builder name (from an asset pack) is built at once; a file model name shows a gray capsule and swaps in a copy when it loads (Character.ready / whenReady, event 'character:model'). Example: `engine.assets.manifest(yourAssets); engine.characters.addPlayer({ model: 'yourBody' }) // a generator or GLB name from an asset pack`
151
153
  - `rig?: CharacterRig | null` A ready procedural body (CharacterRig), used instead of model (a hand-built guard / pet)
152
154
  - `id?: string` Id for engine.mod / time.local entries of a character without a world record (read it back as character.id); the player is 'player', an NPC its record id
153
155
  - `clips?: { idle?, walk?, run?, swim?, jump?, fall?, … } | null` Action name mapping { idle, walk, run, swim, jump, fall } (shorthand for animation)
@@ -13,14 +13,14 @@ Lightweight collision (collision() module): no clipping while walking, the camer
13
13
  ## Methods and properties
14
14
  - `collision.addCircle(position: PositionLike, opts?: CircleColliderOptions) → Handle` — Add a circle collider (pillar, campfire): position is the center, e.g. addCircle(mesh, { radius: 1 }). Returns a handle { remove() }
15
15
  - `collision.addBox(position: PositionLike, opts?: BoxColliderOptions) → Handle` — Add a box collider (house, fence): position is the center, e.g. addBox(house, { halfWidth: 3, halfDepth: 2, rotation: 0.3 }). Returns a handle { remove() }
16
- - `collision.addSegment(a: PositionLike, b: PositionLike, opts?: { thickness?, height?, y?, occluder? }) → Handle` — Add a thin wall along a -> b (fence). Options: thickness (default 0.3), height, y, occluder (as in addBox). A gap between segments is a gate. Returns a handle { remove() }
16
+ - `collision.addSegment(a: PositionLike, b: PositionLike, opts?: { thickness?, height?, y?, occluder?, layer? }) → Handle` — Add a thin wall along a -> b (fence). Options: thickness (default 0.3), height, y, occluder, layer (as in addBox). A gap between segments is a gate. Returns a handle { remove() }
17
17
  - `collision.addBlocked(fn: (x: number, z: number) => boolean, opts?: { bounds? }) → Handle` — Mark ground impassable where fn(x, z) is true (river, lava); fn must be pure (no side effects, same answer for the same (x, z)); reading engine.ground in it is fine. findPathAsync caches the answers, so after the ground or your own state changes, remove() and add the field again. bounds { minX, maxX, minZ, maxZ } (world metres, the field's x / z extent) skips fn outside it; give it to keep findPathAsync's ground sampling cheap. Returns a handle { remove() }
18
18
  - `collision.blockedAt(x: number, z: number, radius?: number) → boolean` — (experimental) Is a character of this radius touching addBlocked ground at (x, z)
19
- - `collision.addObject(obj: Object3D, opts?: { pad?: number; occluder?: boolean }) → Handle` — Add a collider from an object's bounding box, pad expands outward (meters), occluder as in addBox. Returns a handle { remove() }
19
+ - `collision.addObject(obj: Object3D, opts?: { pad?, occluder?, layer? }) → Handle` — Add a collider from an object's bounding box, pad expands outward (meters), occluder and layer as in addBox. Returns a handle { remove() }
20
20
  - `collision.forEachStatic(fn: (type, data) => void)` — (experimental) Iterate all static colliders added by hand
21
21
  - `collision.mirror(fns: { add, remove }) → { sync, clear, size }` — (experimental) Keep an outside copy of the static colliders in step (physics colliders, navmesh obstacles): add builds one piece, remove drops one; sync() diffs only when colliders changed and returns whether it compared; clear() forgets every piece without remove (the outside world was thrown away)
22
- - `collision.walkable(position: PositionLike, opts?: { radius?: number }) → boolean` — Whether someone can stand at this position (for pathfinding): not in water, not too steep, not inside an obstacle. radius is the character radius (meters, default engine.movement.radius)
23
- - `collision.walkableAt(x: number, z: number, radius?: number) → boolean` — walkable with plain numbers, allocating nothing (A* inner loops); radius defaults to engine.movement.radius
22
+ - `collision.walkable(position: PositionLike, opts?: { radius?, passes? }) → boolean` — Whether someone can stand at this position (for pathfinding): not in water, not too steep, not inside an obstacle. radius is the character radius (meters, default engine.movement.radius), passes the collider layers it goes through
23
+ - `collision.walkableAt(x: number, z: number, radius?: number, y?: number, passes?: readonly string[]) → boolean` — walkable with plain numbers, allocating nothing (A* inner loops); radius defaults to engine.movement.radius; y picks the floor; passes as in walkable
24
24
  - `collision.lineClear(a: PositionLike, b: PositionLike, opts?: { radius?, who? }) → boolean` — Line of sight with height: is the 3D segment a -> b free of boxes, circles and terrain trees? radius fattens the line; addBlocked water is ignored. Give eye heights in a / b
25
25
  - Properties:
26
26
  - `maxClimb: number` (experimental)
@@ -36,6 +36,7 @@ Lightweight collision (collision() module): no clipping while walking, the camer
36
36
  - `radius?: number` Radius, default 0.5
37
37
  - `height?: number` Height, default 6
38
38
  - `occluder?: boolean` false: walkers are still stopped but the follow camera's occlusion check ignores it (forest trunks the camera may pass through). Default true
39
+ - `layer?: string` A name: movers whose passes list names it go through it (walking, paths, navmesh), every other mover is stopped, e.g. a gate only some characters use. Omitted: it stops every mover. Sight lines and the camera ignore it
39
40
  - **BoxColliderOptions** Parameters of addBox() (meters, radians)
40
41
  - `halfWidth?: number` Half width (X direction), default 1
41
42
  - `halfDepth?: number` Half depth (Z direction), default 1
@@ -43,3 +44,4 @@ Lightweight collision (collision() module): no clipping while walking, the camer
43
44
  - `height?: number` Height, default 6
44
45
  - `y?: number` Bottom height of the box; if omitted it sits on the ground (give it for walls placed on platforms in a level)
45
46
  - `occluder?: boolean` false: walkers are still stopped but the follow camera's occlusion check ignores it (forest trunks the camera may pass through). Default true
47
+ - `layer?: string` A name: movers whose passes list names it go through it (walking, paths, navmesh), every other mover is stopped, e.g. a gate only some characters use. Omitted: it stops every mover. Sight lines and the camera ignore it
@@ -8,9 +8,9 @@
8
8
  - `antialias?: boolean` MSAA anti-aliasing (kept with post effects on), default on for desktop and off for low-tier devices; with a renderer of your own, its own antialias. It is fixed with the canvas: a player's settings row changes it at the next launch
9
9
  - `pixelRatio?: number` Render resolution, default min(device pixel ratio, 1.5); the low tier uses at least 0.75 x device pixel ratio (never below 1). describe().render.scale reports it
10
10
  - `pixelSize?: number` Real screen pixels per art pixel, a whole number from 1 up: art pixels of exactly one size at any display scale, through page zoom and moves to another display. Sets image-rendering: pixelated, antialias defaults to off, adaptive resolution stops, and the last few real pixels (fewer than k) at the right and bottom stay empty. Example: `createEngine({ canvas, pixelSize: 3 })`
11
- - `adaptiveResolution?: boolean` Automatically lower resolution when the frame rate is too low, default true. Never silent: a dev warning once, and describe().render.scale.autoLowered
11
+ - `adaptiveResolution?: boolean` Automatically lower quality when frames cost too much (resolution, and post effects that declare a cheaper or skippable form; engine.adaptive.steps), default true. Never silent: a dev warning once, and engine.budget.notice()
12
12
  - `targetFps?: number` Target frame rate for automatic resolution lowering, default 55
13
- - `ui?: UIOptions` All screen UI: replace or turn off any part (loading, toast, title, hud.marker, hud.counter, hud.bar; the default title screen is off), and the look of the default parts (theme, css, fonts, templates). Example: `createEngine({ canvas, ui: { loading: { title: 'My Game' }, title: { title: 'My Game' }, toast: false } })`
13
+ - `ui?: UIOptions` All screen UI: replace or turn off any part (loading, toast, title, hud.marker, hud.counter, hud.bar, hud.button; the default title screen is off), and the look of the default parts (theme, css, fonts, templates). Example: `createEngine({ canvas, ui: { loading: { title: 'My Game' }, title: { title: 'My Game' }, toast: false } })`
14
14
  - `audio?: AudioConfig` Volume of each channel, 0–1
15
15
  - `fov?: number` Camera field of view (degrees), default 55
16
16
  - `near?: number` Camera near clipping plane (meters), default 0.3
@@ -19,6 +19,7 @@
19
19
  - `bindings?: Readonly<Record<string, string | readonly string[]>>` The game's keys per action (keyboard, 'Mouse0', gamepad 'PadA' in one list), owner 'game': replaces the basics (move / confirm / cancel / UI cursor) and binds every other action, e.g. { interact: ['KeyE', 'PadX'], ...presets.bindings.dialogNumbers }. Same as engine.input.bind(map)
20
20
  - `saveKey?: string` Save name prefix; must differ when several games share one site, default 'game'
21
21
  - `joystick?: 'auto' | boolean` On-screen joystick: 'auto' (only on touch devices) / true / false
22
+ - `blockBrowserKeys?: boolean` While playing (no menu, not paused), keys the game binds do not reach the browser, e.g. Ctrl+S; true by default. In dev builds F5, Ctrl+R, F12 stay the browser's (recipe 58)
22
23
  - `headless?: boolean` Headless mode: no real-time loop and no per-frame rendering, advances only on step() (for tests and screenshots). Adding ?threedog-headless to the URL also turns it on
23
24
  - `validate?: boolean` (experimental) Check parameter names at runtime and warn on misspelled names (the console prints "did you mean xxx"), default true; a release build can write false to turn it off
24
25
  - `decoders?: string` (experimental) Directory of Draco/KTX2 decoders (a URL containing draco/ and basis/), for when they live on a CDN. Normally not needed: the decoders bundled with three are packed by vite automatically
@@ -33,15 +34,15 @@
33
34
 
34
35
  ## engine methods
35
36
  - `engine.actorPosition(id?: string) → { x, y, z } | null` — Where an actor is now (default engine.actor): the player's position for 'player' (engine.focus without a player), else its model or world record position; null when unknown. Example: `engine.actor = 'boat_1'; engine.actorPosition()`
36
- - `engine.catalog(id?: string | { find?: string }) → any` — What this game can do, read from the existing registrations (modules, ops, save parts, describe, params schemas). No argument: the short list, an ARRAY of { id, kind, label, ops, saves, ... } (read .id, not Object.keys); a module id / op name: that entry expanded (null if unknown); { find }: the short list filtered. recipes/51-capability-catalog.md. Example: `engine.catalog().map(s => s.id); engine.catalog('shop').ops[0].failures // ['soldOut', 'noMoney']`
37
+ - `engine.catalog(id?: string | { find?: string }, o?: { offered?: any[] }) → any` — What this game can do, read from the existing registrations (modules, ops, save parts, describe, params schemas). No argument: the short list, an ARRAY of { id, kind, label, ops, saves, ... } (read .id, not Object.keys); a module id / op name: that entry expanded (null if unknown); { find }: the short list filtered. 'picture': the picture menu, one row per capability (on now, runs here, cost class, one way on, recipe, main limit) and the combination checks; o.offered adds effects not in the chain yet (factories with .about). 'module:<id>' / 'op:<name>' / 'capability:<id>' pick the kind (a bare name tries picture, post, shadows first). recipes/51-capability-catalog.md. Example: `engine.catalog().map(s => s.id); engine.catalog('shop').ops[0].failures // ['soldOut', 'noMoney']`
37
38
  - `engine.takeCamera(owner: string | ({ owner: string } & Partial<CameraOverride>), opts?: Partial<CameraOverride>) → OwnerHandle` — Take the camera over (camera modules leave it alone) until remove(); the latest holder is in charge, releasing hands it back to the previous one
38
- - `engine.mod(name: string, opts: import('./gameplay').ModOptions) → import('./gameplay').ModHandle` — (experimental) The one way several systems change a shared quantity: an entry per owner, combined by layer, ended by its handle; nothing remembers an old value. Example: `engine.time.channel('enemies'); engine.mod('time.enemies', { owner: 'bullet-time', mul: 0.35, for: 2 }) // bullet time on a channel the game made`
39
+ - `engine.mod(name: string, opts: import('./gameplay').ModOptions) → import('./gameplay').ModHandle` — The one way several systems change a shared quantity: an entry per owner, combined by layer, ended by its handle; nothing remembers an old value. Example: `engine.time.channel('enemies'); engine.mod('time.enemies', { owner: 'bullet-time', mul: 0.35, for: 2 }) // bullet time on a channel the game made`
39
40
  - `engine.wrap(target: T, method: string, fn: (next, args) => any, opts?: { owner?: string }) → Handle` — (experimental) The one way to change what a module's public method does without copying the module: fn(next, ...args) runs instead of it; call next(...args) for the method (do work before, after, or skip it). Several wrappers compose (the last wrapped runs first); remove() takes one out; listed in describe().wraps. Private (_) methods throw. The methods a module promises are its contract.js api. Example: `engine.wrap(engine.inventory, 'add', (next, id, n = 1, o) => carried() + weightOf(id) * n > 30 ? false : next(id, n, o), { owner: 'weight' })`
40
41
  - `engine.setCamera(kind: CameraKind, opts?: object) → CameraRig` — Switch the camera at runtime between kinds, once a camera module is installed (openWorld installs followCamera; with none it throws camera-none naming the module to install, e.g. engine.use(fixedCamera({ position, lookAt }))): the target and horizontal heading carry over; the first-person camera hides the character body automatically (the shadow stays) and locks / releases the mouse; the camera switched out is kept, with its parameters, for switching back. Passing opts rebuilds this kind of camera with the new parameters. A wrong kind throws and lists the available options. Example: `engine.onFrame(() => { if (engine.input.pressedRaw('toggleView')) engine.setCamera(engine.cameraRig.kind === 'follow' ? 'firstPerson' : 'follow'); });`
41
42
  - `engine.use(...mods: (ModuleInput | { replaces })[])` — Install one or more modules (in order; dependencies must be installed first). A last argument { replaces: 'slot' } swaps the module that holds that exclusive slot: it is unloaded first (its handles, changes and dispose) and put back if the new install fails. Example: `engine.use(myInventory(), { replaces: 'inventory' })`
42
43
  - `engine.unuse(name: string)` — Unload one installed module: its tracked handles, its slots and ctx.mod entries, its dispose. What it added some other way stays (dev reports a picture module's leftovers). Throws while another module still requires it. To swap a holder use engine.use(mine(), { replaces: 'slot' }). Example: `engine.unuse('rain');`
43
44
  - `engine.has(name: string) → boolean` — Whether a module of this name, or a provider of this capability, is installed. Installed only: engine.explain({ module: name }) says whether it is running
44
- - `engine.setGround(g: Partial<Ground>)` — Set the ground (called by the terrain and level modules); missing parts fall back to flat ground
45
+ - `engine.setGround(g: Partial<GroundProvider>)` — Set the ground (called by the terrain and level modules); missing parts fall back to flat ground
45
46
  - `engine.surface(x: number, z: number, refY?: number) → number` / `surface(at: PositionLike, refY?: number) → number` — Ground height (meters) at (x, z); a position or object also works: engine.surface(mesh.position). For multi-layer ground (bridges, caves, interiors) pass a reference height refY: returns the highest layer not above refY + one step (0.45 m), so standing under a bridge gives the ground and standing on it gives the deck; without it the highest layer is used (as before). Procedural terrain and flat ground have one layer and ignore refY. Off the outline of terrain({ shape }) it is -Infinity (no ground there; engine.ground.has(x, z) says so as a boolean)
46
47
  - `engine.slope(x: number, z: number, refY?: number) → number` / `slope(at: PositionLike, refY?: number) → number` — Slope at (x, z); a position or object also works
47
48
  - `engine.groundType(x: number, z: number, refY?: number) → string` / `groundType(at: PositionLike, refY?: number) → string` — Ground type at (x, z) (for footsteps, particles); a position or object also works. 'void' off the outline of terrain({ shape })
@@ -53,9 +54,9 @@
53
54
  - `engine.thing(idOrObj: string | Object3D) → Thing` — What a thing is and what a save keeps: a world record id, an engine.add id or name, or any Object3D (its registered ancestor). object is the live Object3D (not enumerable). Throws with the closest id when nothing matches. Change it with ops.run('thing.set' / 'thing.remove', { id, ... }). Example: `engine.thing('windmill').saved // 'code'`
54
55
  - `engine.remove(...objs: Object3D[])` — Fully delete an object (use it when you no longer want the object): removes it from its parent, unregisters rays, and releases the geometry and materials of it and its children (textures and geometry / materials shared by assets are not released)
55
56
  - `engine.onFixed(fn: (dt: number) => void, opts?: { channel?, phase? }) → Handle` — Fixed-step logic (60 times per second, dt in fixed seconds): movement, physics, cooldowns, and gameplay keys (read pressed() here: a per-step snapshot, independent of frame rate). dt is real seconds (always 1/60) unless { channel } names a time channel: then the channel's scaled dt. phase 'early' (default) runs before every module fixed hook (the player has not moved yet this step); 'late' after them, before the clock (hit checks, reading this step's result). Returns a handle { remove() }. Example: `engine.onFixed(() => checkHits(engine.player.position), { phase: 'late' })`
56
- - `engine.onFrame(fn: (dt: number) => void) → Handle` — Once per frame (dt in frame seconds): animation, camera, UI and UI keys (menus read this frame's latest input). Gameplay keys belong in onFixed. Returns a handle { remove() }
57
- - `engine.onRender(fn: (ctx) => void, opts?: { when?: 'before' | 'after' }) → Handle` — Around the main frame render, after the camera update and batching. when 'before' (default): render into your own render target here (mirror, minimap, portal, picking); the render target is reset to the screen afterwards. 'after': right after the frame (read pixels). The main frame render itself stays the engine's (post chain). Returns a handle { remove() }. Example: `const rt = new THREE.WebGLRenderTarget(256, 256); engine.onRender(({ renderer, scene }) => { renderer.setRenderTarget(rt); renderer.render(scene, mapCam); });`
58
- - `engine.renderOnce(target?: import('three').RenderTarget | null, camera?: import('three').Camera)` — Draw one picture now, outside the loop, on either renderer. `renderOnce()`: the frame the player sees, onto the canvas through engine.post (read the canvas in the same task, as photo mode does). `renderOnce(target)`: that frame through engine.post into a render target (the canvas's pixels). `renderOnce(target, camera)` with another camera: the scene from that camera, without post. On WebGPURenderer each call is a fresh node frame, so two calls in one task give two pictures (a RenderPipeline draws its scene pass once per frame). Example: `engine.renderOnce(); const url = engine.renderer.domElement.toDataURL('image/png'); engine.renderOnce(rt, mapCamera); // a minimap / thumbnail into your own render target`
57
+ - `engine.onFrame(fn: (dt: number) => void) → Handle` — Once per frame (dt in frame seconds, capped at the fixed step's 0.1 s; 0 on the frame back from a hidden tab): animation, camera, UI and UI keys (menus read this frame's latest input). Gameplay keys belong in onFixed. Returns a handle { remove() }
58
+ - `engine.onRender(fn: (ctx) => void, opts?: { when?: 'before' | 'after' }) → Handle` — Around the main frame render, after the camera update and batching. when 'before' (default): render into your own render target here (mirror, minimap, portal, picking); the render target is reset to the screen afterwards. 'after': right after the frame (read pixels). The main frame render itself stays the engine's (post chain). fn gets { renderer, scene, camera, dt }: dt is this frame's seconds, the same value onFrame gets (no performance.now() bookkeeping needed). Returns a handle { remove() }. Example: `const rt = new THREE.WebGLRenderTarget(256, 256); engine.onRender(({ renderer, scene }) => { renderer.setRenderTarget(rt); renderer.render(scene, mapCam); });`
59
+ - `engine.renderOnce(target?: import('three').RenderTarget | null, camera?: import('three').Camera)` — Draw one picture now, outside the loop, on either renderer. `renderOnce()`: the frame the player sees, onto the canvas through engine.post (read the canvas in the same task, as photo mode does). `renderOnce(target)`: that frame through engine.post into a render target (the canvas's pixels: tone mapped, in the output color space, display values). `renderOnce(target, camera)` with another camera: the scene from that camera, without post, as three draws into a target: linear and not tone mapped (right as a texture on a material, which three then tone maps and encodes; read back as image pixels it looks dark). On WebGPURenderer each call is a fresh node frame, so two calls in one task give two pictures (a RenderPipeline draws its scene pass once per frame). Example: `engine.renderOnce(); const url = engine.renderer.domElement.toDataURL('image/png'); engine.renderOnce(rt, mapCamera); // a minimap / thumbnail into your own render target`
59
60
  - `engine.bakeProbes(opts: { bounds, spacing, resolution?, include?, owner? }) → Promise<ProbeSet>` — (experimental) Bake a grid of light probes from the scene as it is now: three's probe grid renders a cube at every grid point and keeps spherical harmonics, and every lit pixel inside the grid then takes its own interpolated light, on WebGL and WebGPU alike. The grid adds to whatever ambient light the scene has (hemi, environment), which the bake also saw: lower those where the probes take over (a warning and describe().render.probes say so). Outside the grid there is no probe light. A load-time cost, not per frame: 6 renders per probe, a few probes per task so the page keeps drawing; ship the result with `toJSON()` + `engine.loadProbes(json)` instead of baking at every start. Adding a grid recompiles the lit materials once: bake at start-up, not mid-play. Example: `const probes = await engine.bakeProbes({ bounds: { min: [-20, 0, -20], max: [20, 6, 20] }, spacing: 4, include: o => !o.userData.moving }); saveFile('probes.json', JSON.stringify(probes.toJSON()));`
60
61
  - `engine.loadProbes(json: ProbeData, opts?: { owner?: string }) → ProbeSet` — (experimental) A probe set from a file made by `handle.toJSON()` (no baking), on either renderer whichever one baked it. A wrong shape is refused with code `probes-data` and nothing is added. Example: `const probes = engine.loadProbes(await (await fetch('probes.json')).json());`
61
62
  - `engine.loadLightmap(file: string | ArrayBuffer, opts?: { owner?: string }) → Promise<Lightmap>` — (experimental) Put a baked lightmap on the scene: `threedog bake light` wrote the file from the meshes the game marked `userData.static = true`; this rebuilds each with its second UV set and sets plain `material.lightMap`, on WebGL and WebGPU alike. Call it once the level is built, with its lights as they will be played. Nothing runs per frame. Keep the sun real-time; the ambient light the bake saw (hemisphere, environment) has to go, or it counts twice. A wrong file is refused with code `lightmap-data` and nothing is changed. `material.lightMapIntensity` is yours. describe().render.lightmap says what was skipped, moved or doubled. Example: `const light = await engine.loadLightmap('light/level.lightmap');`
@@ -68,14 +69,14 @@
68
69
  - `engine.start() → Promise<this>` — Start: initialize modules, preload assets, wait for the world to be ready
69
70
  - `engine.haltLoop(owner?: string | { owner?: string }) → OwnerHandle` — Pause the real-time loop: the picture stops and even rendering stops, only step() advances (for tests and screenshots). Use freeze() for a game menu pause
70
71
  - `engine.nextFixed(fn: () => T) → Promise<T>` — Run fn at the start of the next fixed step (via commits); a Promise of fn's value
71
- - `engine.freeze(owner?: string | { owner?, kind?, ambient? }, opts?: { kind?, ambient? }) → OwnerHandle` — Gameplay pause (menu, flow's paused): fixed steps are skipped entirely (onFixed, module fixed, tick and every time view but ambient stop), frame hooks and rendering continue and the UI works. So gameplay logic (movement, timing, quest checks, cutscene waits) belongs in fixed, or check engine.frozen first in frame. owner is the freezer's name, default 'game'. uniforms.uTime (wind, water, clouds), skeletal animation and particles keep moving while frozen; { ambient: true } stops them too (a still)
72
+ - `engine.freeze(owner?: string | { owner?, kind?, still? }, opts?: { kind?: 'title'; still?: boolean }) → OwnerHandle` — Gameplay pause (menu, flow's paused): fixed steps are skipped entirely (onFixed, module fixed, tick and every time view but ambient stop), frame hooks and rendering continue and the UI works. So gameplay logic (movement, timing, quest checks, cutscene waits) belongs in fixed, or check engine.frozen first in frame. owner is the freezer's name, default 'game'. uniforms.uTime (wind, water, clouds), skeletal animation and particles keep moving while frozen; { still: true } stops them too (a still)
72
73
  - `engine.step(seconds: number, opts?: { render?, frameEvery?, describe? }) → GameState | null` — Advance seconds of fixed-step time synchronously; seconds must be a finite number >= 0: 0 advances nothing (no step, no render), negative or non-finite throws (code step-seconds), any positive value runs at least one fixed step (60Hz; time channels and the calendar clock.now / sky time of day run at their own speeds; frame hooks run once every frameEvery fixed steps, default 2; describe: false returns null instead of building describe()). jobs ignore real time and finish every frame; results of stream's synchronous build are attached to the scene before returning. When render is true (default) one frame is rendered at the end. Returns the describe() result after advancing
73
74
  - `engine.skip(opts: SkipOptions) → Promise<{ seconds: number; clock:…` — Skip game time forward (sleep until morning, wait an hour) without stepping every fixed step. clock.after / every, sky.at / daily / between, day:start and season:change fire in time order as if stepped (each crossing once); world records with far catch up the span in one far(rec, dt). onFixed, module fixed hooks, physics and near simulation do not run; every time view (tick, real, ambient, channels, calendar) moves as if stepped. Input is locked and gameplay frozen during the skip; emits time:skip. fade 0 (default): the time has moved when skip returns. fade > 0: fade out, jump, save, fade in; the Promise resolves after the fade in (it needs frames). session.newGame / load / quit cancel a running skip: it resolves null. Example: `await engine.skip({ to: '06:00' })`
74
75
  - `engine.checkSkip(seconds: number, opts?: { ignore?: string[] }) → Promise<{ ok: boolean; code?: 'fr…` — Consistency check: engine.skip({ seconds }) vs stepping the same span in fixed steps; compares the saved state. Leaves the world at the stepped state (use a scratch playthrough or a test). Example: `const r = await engine.checkSkip(600); if (!r.ok) console.log(r.diffs);`
75
76
  - `engine.checkSave(opts?: { ignore?: string[] }) → Promise<{ ok: boolean; diffs: { p…` — Consistency check: save -> load gives the same saved state back (nothing is written to the browser). Example: `const r = await engine.checkSave(); if (!r.ok) console.log(r.diffs);`
76
77
  - `engine.describeText(opts?: { radius?, full?, path? }) → string` — The same information as English text, summary first: at most 30 lines (standard lines, the 5 nearest things, the game's describe.add sections, one line per module with its key counts, the engine tables such as shared / slots / owned as one count line), ending with how to expand. { path: 'world.byKind' } returns one part of describe() as JSON; { full: true } returns everything (all nearby things, every module's full data). Example: `engine.describeText() engine.describeText({ path: 'quests' }) engine.describeText({ full: true })`
77
78
  - `engine.explain(q: { op, args?, actor? } | { value: string } | { thing } | …) → { ok, code?, text, detail?, recent?, events?, … }` — Why something is the way it is. { op, args?, actor? }: text says whether it can run now, and if not the reason and the op's note on fixing it (reason first); detail has the last attempt and the events around it; recent / events are the raw last 5 attempts and event names within a step of the last one. { value }: who last wrote a watched value, with its history. { thing: id }: where the id comes from; detail is the whole ThingExplanation. { module } / { capability }: whether it runs and what blocks it. Other keys are answered by modules (definition field explain: { key(e, value, query) { return { ok, text } } }); the quests module answers { quest: id }. Example: `engine.explain({ op: 'shop.buy', args: { shop: 'bakery', item: 'bread' } }).text // 'shop.buy {...} cannot run now: noMoney (Not enough gold)'`
78
- - `engine.profile(on: boolean)` / `profile() → Record<string, number> | null` — Module hook timing: pass true to turn on, false to turn off (returns the engine); with no argument returns { moduleName: average milliseconds per rendered frame } and resets, or null when not on
79
+ - `engine.profile(on: boolean)` / `profile() → Record<string, { ms: nu… | null` — Module hook timing, on by default in dev builds: pass true to turn on afresh, false to turn off (returns the engine); with no argument returns { moduleName: { ms (median), mean, p95 } } per frame over the last 300 frame-hook cycles, or null when off. Only the module's own hooks count; fixed hooks count one fixed step per frame, its dearest (a slow frame's catch-up steps are not the module's cost)
79
80
  - `engine.dispose(opts?: { keepContext?: boolean })` — Destroy the engine: stop the main loop, call each module's dispose(e) in reverse install order, then reclaim listeners, timers, audio, UI and GPU memory (scene, assets cache, post-processing, renderer). After that no callbacks fire and step() returns null. Safe to call repeatedly. Don't use it for level changes; use level.track(handle). The engine's own renderer gives its WebGL context back (browsers keep about 16 live ones), so that canvas cannot host a new engine; keepContext: true keeps it. A renderer passed to createEngine({ renderer }) is never released.
80
81
  - `engine.counts() → EngineCounts` — Counts for leak hunting: they should not keep growing after repeatedly entering / leaving levels or opening / closing windows. geometries / textures come from three.js renderer.info.memory (counted only after rendering)
81
82
 
@@ -89,7 +90,7 @@
89
90
  - `focus: Vector3` Camera focus, updated every frame by the camera module: terrain, models etc. load around it. The center of gameplay simulation is world.anchor (the player by default), which does not follow the camera
90
91
  - `ground: Ground` Current ground
91
92
  - `movement: Readonly<MovementProfile>` Shared parameters for whether a character can walk somewhere (set by createEngine({ movement }), read-only); same-named options of individual modules are only overrides
92
- - `player: Character | null` The player (exists only after characters.createPlayer()). Its position belongs to the character's mover: other systems request movement (placeAt / move / vehicle enter), don't modify position directly
93
+ - `player: Character | null` The player (exists only after characters.addPlayer()). Its position belongs to the character's mover: other systems request movement (placeAt / move / vehicle enter), don't modify position directly
93
94
  - `actor: string` World record id of the one the local user controls (default 'player'): interactions, trigger zones, marker distances, the world simulation center and ops (ctx.actor) use it. Set it to hand control to a vehicle or squad member
94
95
  - `phase: 'constructed' | 'starting' | 'loading' | 'ready' | 'running' | 'disposed'` Where the engine is in its life: 'constructed' (start() not called) -> 'starting' (modules init) -> 'loading' (assets and the world; in both frame hooks only, no fixed step, so no game time passes and every machine opens at tick 0) -> 'ready' (world built: fixed steps run, engine:ready fires) -> 'running' (start() resolved) -> 'disposed'.
95
96
  - `ready: boolean` phase is 'ready' or 'running': the world is built and the loading screen is gone (every "is it ready" in the engine is such a boolean property)
@@ -126,7 +127,6 @@
126
127
  - `plugins: { add, off, on, list }` The plugins folder: files in the game's plugins/ plugged at start by what they export (core/engine/plugins.js); describe().slots lists them (add() off() on() list())
127
128
  - `rays: Rays` Ray registry (what engine.raycast hits)
128
129
  - `jobs: Jobs` Frame-spread job scheduler
129
- - `commits: Commits` (experimental) Background results that affect gameplay take effect on a fixed tick (chunk collision, spread jobs with apply...), see Commits
130
130
  - `threads: Threads` (experimental) Worker pool (createEngine({ threads })): lane() for your own worker script, pure() for self-contained functions, array() for shared typed arrays. Results that affect gameplay go through commits
131
131
  - `ops: Ops` One entry point for actions players and NPCs decide to do: define / run / can / list / recent, see Ops and recipes/23-ops.md
132
132
  - `views: Views` Named fixed camera views for repeatable screenshots: define / show / release (recipes/46-blender-art-route.md)
@@ -136,17 +136,17 @@
136
136
  - `startup: StartupReport | null` Startup timing report (null until start() completes)
137
137
  - `uniforms: EngineUniforms` This engine's shader uniforms, read by the built-in effects (wind, clouds, season, water, sky, rain). Share these objects in your own ShaderMaterial or patch instead of making your own uTime. Weather and sky write them; uTime is engine.time.now('ambient'). Example: `new THREE.ShaderMaterial({ uniforms: { uTime: engine.uniforms.uTime }, vertexShader, fragmentShader });`
138
138
  - `waterLevel: number` Global water level (meters); -Infinity when there is no water
139
- - `debug: DebugOverrides & { panel: DebugPanel | null }` Diagnostic overrides and view modes with an owner (override / clear / view: core, always there); panel is the F3 panel, null without the debug() module
139
+ - `debug: DebugApi` Diagnostic overrides and view modes with an owner (override / clear / view: core, always there); panel is the F3 panel, null without the debug() module
140
140
  - `shadows: Shadows` Shadow engineering on lights you hand in: enabled, cascades, box, budget, include (recipes/45): core, always there
141
141
  - `autoView: View` The camera and drawing-buffer values the engine changes on its own: manual() takes one (recipes/52): core, always there
142
142
  - `shaderTerms: Terms` Your own cloud shadow or season tint in place of the engine's (recipes/52): core, always there
143
- - `stateApplied: boolean` (experimental) Scenario is ready: start() completed, and the URL parameters / the latest applyState have all been applied. Tests and screenshots wait for it: page.waitForFunction(() => window.engine?.stateApplied)
143
+ - `stateApplied: boolean` Scenario is ready: start() completed, and the URL parameters / the latest applyState have all been applied. Tests and screenshots wait for it: page.waitForFunction(() => window.engine?.stateApplied)
144
144
  - `stateRefused: { key: string, value: any, reason: string }[]` (experimental) What the URL parameters or the latest applyState could not do, e.g. ?weather=typo. Read it after stateApplied
145
145
  - `headless: boolean` Whether in headless mode (createEngine({ headless: true }))
146
146
  - `halted: boolean` Whether the real-time loop is stopped: only step() advances the game (headless mode starts this way)
147
147
  - `fps: number` Smoothed frame rate
148
148
  - `frozen: boolean` Is anyone freezing gameplay?
149
- - `still: boolean` True while a freeze asked for a full still (freeze(owner, { ambient: true })): frame code that moves things reads this, as animation and particles do
149
+ - `still: boolean` True while a freeze asked for a full still (freeze(owner, { still: true })): frame code that moves things reads this, as animation and particles do
150
150
  - `describe: { add }` Call engine.describe(opts?: { radius?: number }) to get the current game state (a plain object, JSON.stringify-able); radius is how far counts as "nearby" (meters, default 30).
151
151
  - `inspect: { scene, materials, perf }` What is around an actor or a spot, and what that actor can do now (each op offer checked with can, possible first, at most 8; failed ones carry code and the op's reasons note). at: a world record id (that actor), [x, z] / { x, z } (a spot, ops as the player), or nothing (the player). radius default 10 m. Example: `engine.inspect(); // { actor: 'player', at: { x, z }, near: [...], ops: [{ op: 'shop.buy', args, ok: false, code: 'noMoney', why: 'Not enough gold' }] }`
152
152
 
@@ -180,7 +180,7 @@
180
180
  - `describe(e: Engine, ctx: DescribeContext) → any` — Optional: add state to engine.describe(). The (JSON-able) return value goes into the result keyed by the module name; nothing is added if it returns nothing. It may also fill in the standard fields of ctx.out, or use ctx.near() to report "nearby things"
181
181
  - `counts(e: Engine) → number | Record<string, number>` — Optional: leak-hunting counts for engine.counts(), put there under the module name (a number or an object of numbers that should not keep growing)
182
182
  - `applyState(e: Engine, params: StateParams) → void | PositionLike | { refused } | Promise<void>` — Optional: handle the keys of engine.applyState that this module owns (e.g. calendar handles time and season); for at, return the place's position; return { refused: { key: reason } } for a value it cannot apply
183
- - `dispose(e: Engine)` — Optional: called on engine.dispose() (in reverse install order). Only clean up what the core cannot: Workers, the physics world, real-time timers, Audio nodes you connected yourself. Events, onFixed / onFrame, clock timers, jobs, stream, ray registrations and GPU memory in the scene are reclaimed by the core; DOM listeners attached to engine.signal and UI attached to engine.uiRoot are cleaned up automatically too
183
+ - `dispose(e: Engine)` — Optional: called on engine.dispose() (in reverse install order). Only clean up what the core cannot: Workers, the physics world, real-time timers, Audio nodes you connected yourself. Events, onFixed / onFrame, clock timers, jobs, stream and ray registrations are reclaimed by the core. GPU memory is its creator's: free what you put in the scene with ctx.track({ remove: () => engine.remove(mesh) }) (design.md 6.2); DOM listeners attached to engine.signal and UI attached to engine.uiRoot are cleaned up automatically too
184
184
 
185
185
  ## createEngine({ ui })
186
186
  - **UIOptions** createEngine({ ui }): the look of the default parts (theme, css, fonts, templates); every other key is a part name
@@ -24,6 +24,7 @@
24
24
  - `ui:close` [id: string] A window was closed
25
25
  - `settings:shadows` [on: boolean] Shadows were toggled
26
26
  - `settings:change` [values: Record<string, any>] A value in the settings menu changed (the argument is all setting values)
27
+ - `post:add` [name: string] A post effect was added (its name)
27
28
  - `water:add` [body: WaterBody] A water body was added
28
29
  - `water:remove` [body: WaterBody] A water body was removed
29
30
  - `day:start` [day: number] A new day (the argument is the day number, starting at 1; needs the calendar module)
@@ -93,10 +94,10 @@
93
94
  - `net:close` [{}] Client (net): connection lost
94
95
  - `net:sync` [{ tick: number; full: boolean }] Client (net): host state applied (full: a whole snapshot, else a diff); redraw UI from state here
95
96
  - `net:result` [{ seq: number; name: string; ok: boolean; code: string | null; value… Client (net): the host's answer to an op request (seq from ops.run's return value; tick is the host's), sent after the state it caused
96
- - `engine:error` [EngineError] A gameplay error in development / testing; gameplay is frozen (error severity levels, see engine.error)
97
+ - `engine:error` [EngineError] A gameplay error: in development / testing gameplay is frozen; a release build keeps running and sends it once per site (engine.error holds the first; error severity levels, see engine.error)
97
98
  - `module:disabled` [{ name: string; message: string }] A picture or ui module errored and was disabled (the game continues)
98
99
  - `module:restored` [{ modules: any[] }]
99
- - `state:replaced` [{ undone: boolean }]
100
+ - `op:rolledBack` [{ op: string; parts: number }] An atomic op failed and its parts were put back (its own events already went out and stay): read derived state again. Not sent for a load's rollback (that ends in state:replaced)
100
101
  - `vehicle:enter` [{ character: Character; vehicle: Rideable }] A character boarded a vehicle
101
102
  - `vehicle:exit` [{ character: Character; vehicle: Rideable }] A character exited a vehicle
102
103
  - `flow:change` [{ from: string; to: string }] Game flow state changed
@@ -1,8 +1,9 @@
1
- # engine.ground (Ground) — Ground: whoever provides the ground height is the "terrain" (terrain module, level module, or the default flat y=0)
1
+ # engine.ground (GroundProvider) — Ground provider: whoever provides the ground height is the "terrain" (terrain module, level module, or the default flat y=0)
2
2
 
3
- - `ground.height(x: number, z: number, refY?: number) → number` — Ground height (meters) at (x, z). For multi-layer ground (bridges, caves) pass refY: takes the highest layer not above refY + one step (0.45 m); without it the highest layer is used. Single-layer ground ignores refY
4
- - `ground.slope(x: number, z: number, refY?: number) → number` — Slope at (x, z) (height difference / horizontal distance)
5
- - `ground.type(x: number, z: number, refY?: number) → string` — Ground type at (x, z) (landform name, e.g. 'meadow')
3
+ - `ground.height(x: number, z: number, refY?: number) → number` — Ground height (meters) at (x, z). For multi-layer ground (bridges, caves) pass refY: takes the highest layer not above refY + one step (0.45 m); without it the highest layer is used. Single-layer ground ignores refY. A game reads it with engine.surface(x, z)
4
+ - `ground.slope(x: number, z: number, refY?: number) → number` — Slope at (x, z) (height difference / horizontal distance). A game reads it with engine.slope
5
+ - `ground.type(x: number, z: number, refY?: number) → string` — Ground type at (x, z) (landform name, e.g. 'meadow'). A game reads it with engine.groundType
6
+ - `ground.water(x: number, z: number, refY?: number) → number` — Optional: water surface height at (x, z) when it differs per point (-Infinity = none); replaces waterLevel there. A game reads engine.waterAt
6
7
  - `ground.has(x: number, z: number) → boolean` — Is there ground at (x, z). Always true except off the outline of terrain({ shape }), where height is -Infinity and slope 0. Example: `if (engine.ground.has(x, z)) engine.snapToGround(chest);`
7
8
  - `ground.voidY() → number` — Height below which something has fallen out of the world (terrain:void): engine.terrain.voidY with terrain({ shape }), else -Infinity
8
9
  - `ground.forEachCollider(x: number, z: number, range: number, fn: (cx, cz, r) => void)` — Optional: iterate the circular colliders (tree trunks etc.) within range meters of (x, z)
@@ -11,5 +12,5 @@
11
12
  - `ground.staticTrimeshes() → { positions, indices }[]` — (experimental) Optional: static triangle mesh (the level module provides it for physics)
12
13
  - `ground.staticVersion() → number` — (experimental) Optional: version number of the static mesh; rebuild when it changes
13
14
  - Properties:
14
- - `waterLevel: number` Global water level (meters); -Infinity when there is no water
15
+ - `waterLevel: number` Global water level (meters); -Infinity when there is no water. A game reads engine.waterLevel
15
16
  - `chunkSize?: number` Optional: chunk edge length (meters)
package/docs/api/hud.md CHANGED
@@ -7,11 +7,13 @@ Objective markers, counters, progress bars (hud() module)
7
7
 
8
8
  ## Methods and properties
9
9
  - `hud.marker(target: HudTarget, opts?: HudMarkerOptions) → HudMarker` — Add an objective marker: target is an object, position or place name
10
- - `hud.counter(id: string, opts: { label?, icon?, value?, max?, anchor? })` — Counter or text status (calling again with the same id = update; calling every frame is fine): counter('fish', { label: '鱼', value: 2, max: 5 }), counter('clock', { value: '08:30' }); no value = the label alone, no label = the value alone (the id is not shown)
10
+ - `hud.addCounter(id: string, opts: { label?, icon?, value?, max?, anchor? }) → { id, set, remove }` — Counter or text status, returns { set(value), remove() } (calling again with the same id = update; calling every frame is fine): addCounter('fish', { label: '鱼', value: 2, max: 5 }), addCounter('clock', { value: '08:30' }); no value = the label alone, no label = the value alone (the id is not shown)
11
11
  - `hud.bump(id: string, n?: number) → number` — Add n (default 1) to a number counter, return the new value; one not declared yet starts at 0 with its id as the label
12
12
  - `hud.value(id: string) → number | string | undefined` — Current value of a counter or bar (number or text), undefined when there is none; reads what interactions.add({ counter }) has added up
13
13
  - `hud.bar(id: string, opts: { value, max?, label?, anchor? })` — Progress bar (calling again with the same id = update; calling every frame is fine, the DOM is untouched when the value is unchanged), value/max 0–max
14
- - `hud.remove(id: string)` — Delete a counter or progress bar
14
+ - `hud.button(id: string, opts: { label, run, icon?, anchor?, action? })` — Clickable button (calling again with the same id = update): label is text or an i18n key, run() is called on a click / tap. The press never reaches the game and focus goes back to it; a locked mouse has no cursor, so free it first (Esc)
15
+ - `hud.hint(id: string, opts: { action, label?, anchor? })` — (experimental) Key hint "E · Talk" (same id = update): the key text is engine.input.label(action) (the input.noKey text when the action needs a key and has none, as in the prompt), so it follows rebinding and keyboard / pad switching; label is text or an i18n key. A button with `action` shows its key too
16
+ - `hud.remove(id: string)` — Delete a counter, progress bar, button or key hint
15
17
  - Properties:
16
18
  - `markers: HudMarker[]` All markers
17
19
 
package/docs/api/input.md CHANGED
@@ -1,20 +1,20 @@
1
1
  # engine.input (Input) — Input: read by "action", not by "key"
2
2
 
3
- - `input.action(name: string, o?: { context?, label?, optional?, keys?, owner? }) → { name: string; remove(): void }` — Declare an action: its context and display name, never its keys (the game binds those). Modules call ctx.input.action (owned by the module, removed with it); a game's own action can pass keys to declare and bind in one line. context: the input context it is read in (default 'walk'); readable only while that context is on the stack and not shadowed, see push(). optional: true = the module works without it (number keys for dialogue choices), so reading it unbound is silent. A second owner declaring the same action with another context throws input-action-context. Example: `ctx.input.action('choice1', { context: 'dialog', label: 'dialogue.choice', optional: true }); // in a module: no keys`
3
+ - `input.define(name: string, o?: { context?, label?, optional?, keys?, owner? }) → { name: string; remove(): void }` — Declare an action: its context and display name, never its keys (the game binds those). Modules call ctx.input.define (owned by the module, removed with it); a game's own action can pass keys to declare and bind in one line. context: the input context it is read in (default 'walk'); readable only while that context is on the stack and not shadowed, see push(). optional: true = the module works without it (number keys for dialogue choices), so reading it unbound is silent. A second owner declaring the same action with another context throws input-action-context. Example: `ctx.input.define('choice1', { context: 'dialog', label: 'dialogue.choice', optional: true }); // in a module: no keys`
4
4
  - `input.bind(name: string | Readonly<Record<string,…, keys?: string | readonly string[], { owner }?: { owner?: string }) → { owner: string; remove(): void }` — Bind keys to an action (the game's choice; owner 'game'). Takes one action or a whole map, e.g. a preset: bind(presets.bindings.rtsRotate). Binding again as the same owner replaces; a DIFFERENT owner binding the same action throws input-bound-twice in dev (release: the later wins). An action nobody declared yet is created in context 'walk' (a module declaring it later sets its context; order does not matter). Example: `engine.input.bind('jump', ['Space', 'PadA']);`
5
5
  - `input.touchButton(action: string, labelKey: string) → { remove(): void }` — Touch button (appears only on touch devices); pressing it triggers the action. labelKey is the string-table key of the button text (updates when the language changes). Returns { remove() }: a module tracks it, so the button leaves with the module
6
6
  - `input.simulate(action: string, down?: boolean)` — Press (down true) or release an action from code, through the same path as a real key: tests, AI drivers, replays. Presses the action's first bound key and holds it until simulate(action, false), so the player walks like with a held key. Takes action names (moveForward, moveLeft, run, interact, ...; engine.input.actions lists them), not keys; an unknown name throws unknown-name with the closest one. Example: `engine.input.simulate('moveForward'); engine.step(1); engine.input.simulate('moveForward', false)`
7
- - `input.seat(opts?: { pad?, keys? }) → Seat` — A local player's share of the input on a shared screen: its own keys and gamepad, read like engine.input (axis, down, pressed, released). Pass it to createPlayer({ id, input }). pad: gamepad index; that pad leaves engine.input and answers the game's pad bindings here. keys: { action: keys } for this seat alone. Two seats on one pad or key throw `input-seat`. Example: `const two = engine.input.seat({ pad: 1, keys: { moveForward: 'KeyI', moveBack: 'KeyK', moveLeft: 'KeyJ', moveRight: 'KeyL', jump: 'KeyU' } });`
7
+ - `input.seat(opts?: { pad?, keys? }) → Seat` — A local player's share of the input on a shared screen: its own keys and gamepad, read like engine.input (axis, down, pressed, released). Pass it to addPlayer({ id, input }). pad: gamepad index; that pad leaves engine.input and answers the game's pad bindings here. keys: { action: keys } for this seat alone. Two seats on one pad or key throw `input-seat`. Example: `const two = engine.input.seat({ pad: 1, keys: { moveForward: 'KeyI', moveBack: 'KeyK', moveLeft: 'KeyJ', moveRight: 'KeyL', jump: 'KeyU' } });`
8
8
  - `input.rebind(action: string, keys: string | string[] | null)` — The player's rebinding (the settings menu calls this and saves it): replaces the game's keys on the settings layer of 'input.keys'. keys null takes the player's choice away (the game's or the default keys show again). Works before the action is declared (a saved binding is restored at start, the module declaring the action comes later). Example: `engine.input.rebind('jump', ['KeyJ']); engine.input.rebind('jump', null); // back to the game's keys`
9
9
  - `input.rebound() → Record<string, string[]>` — The player's rebindings now in effect: { action: keys } (what the settings menu saves)
10
- - `input.keysOf(action: string) → readonly string[]` — (experimental) All keys bound to an action: the player's rebinding, else the game's bind, else the default preset (basics only); plus its touch button
10
+ - `input.keysOf(action: string) → readonly string[]` — All keys bound to an action: the player's rebinding, else the game's bind, else the default preset (basics only); plus its touch button
11
11
  - `input.isUnbound(action: string) → boolean` — True when an action needs a key and has none, so no player input can fire it. Not for an optional action, and not for one bound to [] on purpose (a mouse-only game): "no key at all" is the fault, whichever key the game or the player chose is not. Example: `if (engine.input.isUnbound('interact')) engine.input.bind(presets.bindings.interact);`
12
12
  - `input.label(action: string) → string` — Key name shown in the UI, e.g. "E"
13
13
  - `input.down(action: string) → boolean` — Held (a snapshot of this step in fixed, the latest state in frame)
14
14
  - `input.pressed(action: string) → boolean` — Just pressed. Read in onFixed / module fixed: pressed since the previous fixed step, true only for this step (counted once however the frame rate varies, never lost); read in onFrame / module frame: pressed this frame (UI keys only). Read gameplay keys in fixed. Example: `engine.onFixed(() => { if (engine.input.pressed('jump')) player.jump(); });`
15
- - `input.released(action: string) → boolean` — (experimental) Just released (which copy is read is the same as pressed; for things like release-to-fire after charging). Example: `if (engine.input.released('fire')) shoot(charge);`
15
+ - `input.released(action: string) → boolean` — Just released (which copy is read is the same as pressed; for things like release-to-fire after charging). Example: `if (engine.input.released('fire')) shoot(charge);`
16
16
  - `input.pressedRaw(action: string) → boolean` — Just pressed, ignoring input contexts (for menus and dialogue themselves, which run while a context blocks the game)
17
- - `input.push(name: string, opts?: { pass?: boolean; owner?: string }) → { name: string; remove(): void }` — Push an input context (an action group, like a Unity Action Map). The top context shadows lower actions bound to the same key. Opaque by default (nothing below is readable: menus, dialogue, cutscenes); { pass: true } lets unrelated lower actions keep working (vehicle, build mode). Applies at the start of the next fixed step; actions it blocks lose their held state (no stuck keys after a menu closes). Join a context with input.action(name, { context }); menu keys: pressedRaw. Example: `const h = engine.input.push('vehicle', { pass: true }); // vehicle-context actions (brake) work, and shadow gameplay actions on the same key h.remove();`
17
+ - `input.push(name: string, opts?: { pass?: boolean; owner?: string }) → { name: string; remove(): void }` — Push an input context (an action group, like a Unity Action Map). The top context shadows lower actions bound to the same key. Opaque by default (nothing below is readable: menus, dialogue, cutscenes); { pass: true } lets unrelated lower actions keep working (vehicle, build mode). Applies at the start of the next fixed step; actions it blocks lose their held state (no stuck keys after a menu closes). Join a context with input.define(name, { context }); menu keys: pressedRaw. Example: `const h = engine.input.push('vehicle', { pass: true }); // vehicle-context actions (brake) work, and shadow gameplay actions on the same key h.remove();`
18
18
  - `input.describe() → { stack, unbound, rebound }` — describe().input: the context stack, declared actions nobody bound (unbound: isUnbound) and the player's rebindings
19
19
  - `input.gate(action: string, owner?: string | { owner?, for?, clock? }) → { owner: string; remove(): void }` — Close one action while anyone holds its gate (stun: no jump; a tutorial: no attack yet), without a whole input context. Same rules as every engine.mod stack (it is the shared point 'input.gate', one entry per owner and action): only the owner opens it, { for } ends it by itself. A closed action reads as not down / pressed / released; describe().holds.gates lists the owners. Example: `const stun = engine.input.gate('jump', { owner: 'stun', for: 1.5 }); // no jumping for 1.5 s; stun.remove() reopens it early`
20
20
  - Properties:
@@ -9,7 +9,7 @@ Particles (particles() module)
9
9
  ## Methods and properties
10
10
  - `particles.define(name: string, opts?: ParticleOptions) → ParticleEffect` — Define an effect (same name replaces it, and emitters attached to it move to the new definition); params sit on top of particles({ effects, default }). Returns the effect object: .points is its THREE.Points (a Sprite on WebGPURenderer); .material is its plain three.js material (set your own and it is drawn as given, null gives the engine's back); .uniforms are the engine material's { value } objects (uMap, uHasMap, uScale, uMaxPx), which a ShaderMaterial of yours can share. A material of yours lasts until the effect is defined again. Example: `engine.particles.define('sparks', { blending: 'additive' }).material = myMaterial;`
11
11
  - `particles.has(name: string) → boolean` — Whether this effect has been defined
12
- - `particles.emit(name: string, position: PositionLike, opts?: { count?, overrides? })` — Burst: emit count particles at once (default 10) at position (Vector3 / Object3D / [x, y, z] / {x, y, z}). overrides affect this batch only (color, speed, direction...; max/texture/blending/soft cannot be changed temporarily)
12
+ - `particles.emit(name: string, position: PositionLike, opts?: { count?, overrides? })` — Burst: emit count particles at once (default 10) at position (Vector3 / Object3D / [x, y, z] / {x, y, z}). overrides affect this batch only (color, speed, direction...; max/texture/blending/soft/lit cannot be changed temporarily)
13
13
  - `particles.attach(name: string, object3d: THREE.Object3D, opts?: { rate?, ratePerMeter?, offset?, overrides? }) → ParticleEmitter` — Keep emitting while following an object: rate per second, ratePerMeter per meter it moves (spread along the path, on top of rate), offset in the object's local coordinates [x, y, z] (meters). Returns a handle { remove(), rate, ratePerMeter, active } (active = false pauses)
14
14
  - `particles.count(name?: string) → number` — Live particle count (no name = all)
15
15
  - `particles.clear(name?: string)` — Clear one effect's (or all) particles
@@ -40,6 +40,7 @@ Particles (particles() module)
40
40
  - `maxPixels?: number` Largest on-screen size of one particle in pixels (smoke drifting past the camera stays bounded), default 512
41
41
  - `ratePerMeter?: number` (experimental) Default particles per meter the emitter moves for attach, on top of rate, spread along the path it moved; default 0
42
42
  - `soft?: number` (experimental) Meters over which a particle fades where it meets what writes depth; default 0, off. Set at define, not in overrides. On WebGLRenderer it costs one depth-only draw of the scene per render while such an effect is on screen
43
+ - `lit?: boolean` (experimental) The scene's lights tint each particle's color (dust a lamp lights): point, spot, directional, ambient, hemisphere, as a matte card facing each light. No shadows, environment map or probes. Default false (the color is drawn as given). Set at define, not in overrides; costs live particles x lights per frame on the CPU, the same on both renderers
43
44
  - **ParticleEmitter** (extends Handle) Continuous emitter returned by attach() (a handle)
44
45
  - `rate: number` Particles per second (can be changed at any time)
45
46
  - `ratePerMeter: number` (experimental) Particles per meter the object moves, on top of rate (can be changed at any time)
package/docs/api/photo.md CHANGED
@@ -4,12 +4,15 @@ Photo mode (photo() module)
4
4
 
5
5
  - Options `PhotoOptions` (also includes the fields of PhotoTakeOptions):
6
6
  - `maxAlbum?: number` (experimental) How many photos the album keeps at most, default 50
7
+ - `pathTracer?: (() => Promise<any>) | null` (experimental) The game's import of its optional path tracer, called on the first photo.trace(): () => import('three-gpu-pathtracer/webgpu')
7
8
 
8
9
  ## Methods and properties
9
10
  - `photo.take(opts?: PhotoTakeOptions) → PhotoShot` — Capture a photo now without checks. Gameplay takes photos through the op: engine.ops.run('photo.take') (checks canTake, logged)
11
+ - `photo.trace(opts?: PhotoTakeOptions & { samples?, seconds? }) → Promise<PhotoShot>` — (experimental) A path-traced photo (WebGPU backend or a WebGLRenderer; the game's photo({ pathTracer })): samples (whole, >= 1, default 128) accumulate on a snapshot while the game runs, until seconds (>= 1, default 60); resolves to the shot, rejects naming why. scale defaults to 1 here. The op photo.trace starts it (r.value is this Promise)
10
12
  - `photo.subject() → { name, kind, distance } | null` — (experimental) What is in the middle of the frame (NPC, entity, named object, vegetation), null if nothing; this is the subject of take()
11
13
  - Properties:
12
14
  - `album: PhotoShot[]` Album (newest first)
13
15
  - `canTake: () => boolean | string` The op photo.take's can: return true, or false / a reason string to refuse (e.g. () => engine.inventory.has('film') // 'noFilm')
14
16
  - `format: string` (experimental)
15
17
  - `maxAlbum: number` (experimental)
18
+ - `tracing: { samples: number; of: number } | null` (experimental) While a path-traced photo accumulates: samples per pixel so far and the target; null otherwise
package/docs/api/post.md CHANGED
@@ -2,10 +2,11 @@
2
2
 
3
3
  - `post.object() → any` — (experimental) What the chain runs in, for reading, or null while no post work has run yet (built the first time an effect is on; it is not built here, so asking never costs a render target). WebGLRenderer: the three.js EffectComposer (pass list, sizes, its targets). WebGPURenderer: { pipeline, scenePass }, three's RenderPipeline and the scene's pass() node. Read-only by rule, not by lock: the engine owns it, rebuilds the chain whenever the list changes and disposes it with the engine. To add a pass use post.add, to own the whole chain post.own() (recipe 52). Why public: a game reading the chain had to dig into an internal field (review 2026-11-03)
4
4
  - `post.targets() → { renderTarget1, renderTarget2, readBuffer, writeBuffer } | null | …` — (experimental) The composer's render targets, for reading (sample the last frame's color or depth in a game pass, check formats / samples), or null while there is no composer, and always on WebGPURenderer (its pass nodes own their targets: post.object().scenePass). renderTarget1 / renderTarget2 are the ping-pong pair. During the chain readBuffer is a pass's input and writeBuffer its output; EffectComposer swaps them after every pass with needsSwap (most passes; the scene RenderPass does not). The last pass draws to the canvas and still swaps, so after the frame (engine.onRender(fn, { when: 'after' })) neither target holds the final picture: writeBuffer holds the input of that last pass (readBuffer when the last pass does not swap) and readBuffer is stale. For the final image, render into a target of your own.
5
- - `post.add(x: any, o?: { name?, slot?, order? }) → PostHandle` — The one way to add a post effect. x is a three.js Pass (WebGL), a TSL node function (input, ctx) => node (WebGPU), or an effect { name, create / node / fuse, slot, order, params, needsDepth, needsBuffers, backend, skipOnLowTier, facts } (both renderers when it gives create and node, or a fuse). A wrong shape throws with nothing added. needsDepth, needsBuffers ('normal' / 'diffuse' / 'velocity', WebGPU), backend ('webgpu': not on the WebGL2 backend), skipOnLowTier (held when engine.tier is 'low') and facts (shown by describe().render.post) are explained on PostEffect. A Pass that draws engine.scene takes the 'scene' slot, FXAA / SMAA / TAA 'final', any other 'hdr' after the effects already there, or 'ldr' once an OutputPass was added. A RenderPass of engine.scene and an OutputPass are the engine's own stages: skipped and said once (an OutputPass still marks where display color starts). Example: `const glow = engine.post.add(new UnrealBloomPass(size, 0.6, 0.4, 0.85), { name: 'glow' }); glow.enabled = false;`
6
- - `post.get(name: string) → PostHandle | undefined` — (experimental) An added effect's handle (as add() returns it), or undefined. Example: `engine.post.get('bloom').set({ strength: 0.6 });`
5
+ - `post.add(x: any, o?: { name?, slot?, order? }) → PostHandle` — The one way to add a post effect. x is a three.js Pass (WebGL), a TSL node function (input, ctx) => node (WebGPU), or an effect { name, create / node / fuse, slot, order, params, needsDepth, needsBuffers, backend, skipOnLowTier, cheaper, facts } (both renderers when it gives create and node, or a fuse). A wrong shape throws with nothing added. needsDepth, needsBuffers ('normal' / 'diffuse' / 'velocity' / 'metalRough', WebGPU), backend ('webgpu': not on the WebGL2 backend), skipOnLowTier (held when engine.tier is 'low') and facts (shown by describe().render.post) are explained on PostEffect. A Pass that draws engine.scene takes the 'scene' slot, FXAA / SMAA / TAA 'final', any other 'hdr' after the effects already there, or 'ldr' once an OutputPass was added. Example: `const glow = engine.post.add(new UnrealBloomPass(size, 0.6, 0.4, 0.85), { name: 'glow' }); glow.enabled = false;`
6
+ - `post.get(name: string) → PostHandle | undefined` — An added effect's handle (as add() returns it), or undefined. Example: `engine.post.get('bloom').set({ strength: 0.6 });`
7
+ - `post.byRole(role: string, name?: string) → PostHandle[]` — (experimental) The added effects that declare this role in about.acts ('glow', 'ao', 'exposure'): found by what they do, never by name; the settings rows and photo follow every one of them. Only when NO effect declares the role does the effect named `name` stand in (a game's own 'bloom' written before roles existed); with no `name` that case gives [].
7
8
  - `post.own(on?: boolean)` — (experimental) Hand the built chain to the game: the engine stops rebuilding it, so the composer's passes (post.object().passes) or the WebGPU pipeline's outputNode are the game's to edit. own(false) gives it back and rebuilds from the list. describe().owned shows who has it. Example: `engine.post.own(); engine.post.object().passes.reverse();`
8
- - `post.list() → { name, slot, order, enabled }[]` — (experimental) Effects in render order: [{ name, slot, order, enabled }]
9
+ - `post.list() → { name, slot, order, enabled }[]` — Effects in render order: [{ name, slot, order, enabled }]
9
10
  - `post.render(dt: number, target?: any)` — Draw the frame through the chain. target: a render target to draw the finished picture into instead of the canvas (engine.renderOnce(target)); it gets the canvas's pixels (tone mapped, output color space). Why a target argument and not "set the render target first": the WebGL chain's last pass always writes to the canvas (EffectComposer renderToScreen); the WebGPU pipeline draws into whatever target is set.
10
11
  - Properties:
11
12
  - `antialias: boolean` (experimental) MSAA on or off in the post chain's render targets, for what runs through the chain. It is a render setting, not a drawing part. With no effect on nothing runs through the chain: the canvas's own MSAA shows, fixed when the context was made (createEngine({ antialias })). Example: `engine.post.antialias = false;`
@@ -21,9 +22,11 @@
21
22
  - `order?: number`
22
23
  - `enabled?: boolean`
23
24
  - `needsDepth?: boolean`
24
- - `needsBuffers?: ("normal" | "diffuse" | "velocity")[]`
25
+ - `needsBuffers?: ("normal" | "diffuse" | "velocity" | "metalRough")[]`
25
26
  - `backend?: "webgpu"`
26
27
  - `skipOnLowTier?: boolean`
28
+ - `cheaper?: Record<string, any>`
27
29
  - `facts?: () => Record<string, any> | null`
30
+ - `about?: Record<string, any>`
28
31
  - `params?: Record<string, any>`
29
32
  - `update?: (impl: any, params: Record<string, any>) => void`
@@ -12,9 +12,9 @@ Quests (quests() module)
12
12
  - `quests.start(id: string)` — Start a quest
13
13
  - `quests.state(id: string) → { step, steps, done, failed, active, visited } | null` — One quest's progress (a copy): step index, step count, done, failed, active; null before it starts
14
14
  - `quests.advance(id: string) → boolean` — Finish the current step from code (its done() is not asked) and go on; the last step completes the quest. false when not active
15
- - `quests.isDone(id: string) → boolean` — (experimental)
15
+ - `quests.isDone(id: string) → boolean` — Finished (done, not failed)
16
16
  - `quests.isActive(id: string) → boolean` — Started, not done and not failed
17
- - `quests.isFailed(id: string) → boolean` — (experimental) Its fail condition held (start(id) begins it again)
17
+ - `quests.isFailed(id: string) → boolean` — Its fail condition held (start(id) begins it again)
18
18
  - `quests.check()` — Check completion conditions once immediately
19
19
  - `quests.list() → { id, title, desc?, done, failed, steps }[]` — Quest list (for custom UI)
20
20
  - Properties:
package/docs/api/rays.md CHANGED
@@ -1,7 +1,6 @@
1
1
  # engine.rays (Rays) — engine.rays is the ray registry (engine.raycast hits whatever is registered here)
2
2
 
3
- - `rays.addStatic(obj: THREE.Object3D | THREE.Object3D[], opts?: { occluder?: boolean }) → Handle` — Register a static object and every mesh under it (an array also works; meshes over 256 triangles get a BVH); occluder: true also blocks the camera. Returns a handle { remove() }. Only visible objects are hit. Something that is merely not drawn is still hit: batched originals, far hlod originals and the full model of a far assets.lod sit on a reserved layer, with their visible true. Unregisters automatically on geometry dispose or engine.remove. Example: `engine.rays.addStatic(house, { occluder: true });`
4
- - `rays.forget(obj: THREE.Object3D)` — (experimental) Unregister every mesh under the object (engine.remove calls this automatically)
3
+ - `rays.addStatic(obj: THREE.Object3D | THREE.Object3D[], opts?: { occluder?: boolean }) → Handle` — Register a static object and every mesh under it (an array also works; meshes over 256 triangles get a BVH); occluder: true also blocks the camera. Returns a handle { remove() }. Matrices are read once per tick and frame: a registered mesh moved between two rays of one step needs updateMatrixWorld() first. Only visible objects are hit. Something that is merely not drawn is still hit: batched originals, far hlod originals and the full model of a far assets.lod sit on a reserved layer, with their visible true. Unregisters automatically on geometry dispose or engine.remove. Example: `engine.rays.addStatic(house, { occluder: true });`
5
4
  - `rays.addProvider(fn: RayProvider) → Handle` — (experimental) A module merges its own hits (rigid adds rigid bodies; asked only when targets is 'all'). Returns a handle { remove() }
6
5
  - Properties:
7
6
  - `statics: Map<THREE.Object3D, { refs: number; occ: number }>` (experimental) Registered mesh -> { refs: registration count, occ: camera-blocker registration count }
package/docs/api/saves.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # engine.saves (Saves) — engine.saves handles saving
2
2
 
3
- - `saves.register(key: string, provider: SaveProvider) → { remove }` — Register "how to save and load"; key is this part's name in the save. Parts with first: true load first (the level); a load returning a Promise makes later parts wait. version (default 1): raise it by 1 whenever what save() returns changes shape, and add migrate[oldVersion] = data => newData; load sees only the current shape. A save whose part is newer than this build's version is refused as a whole (load returns false, the save is kept). load(data, turn): turn is this replacement's identity. Pass it on, level.load(x, { turn }) or content.load(x, { turn }): those wait for a running load to end, except with its turn. A part registered after a save was loaded (a module installed later) is handed its data from that save: at once when idle, else right after the replacement under way. Example: `engine.saves.register('garden', { save: () => garden.toJSON(), load: d => garden.fromJSON(d) }); // later the format gains beds: version 2, and a step that upgrades version-1 data engine.saves.register('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save: () => garden.toJSON(), load: d => garden.fromJSON(d) });`
4
- - `saves.putAttachment(group: string, id: string, blob: Blob | (() => Promise<Blob>), meta?: any) → Promise<void>` — (experimental) Store a binary attachment outside the world save (a photo, a replay). It rides in the queue of save writes, so flush() waits for it, and exportFile() carries it. Pass a function to make the bytes when the write runs: flush() then waits for that too. Without IndexedDB it is not kept. Rejects with save-stale, changing nothing, when another tab wrote this id since this tab last saw it; attachments(group) is how a tab looks. Example: `await engine.saves.putAttachment('replay', 'run-1', blob, { score: 12 });`
3
+ - `saves.define(key: string, provider: SaveProvider) → { remove }` — Define "how to save and load"; key is this part's name in the save. Parts with first: true load first (the level); first may be a number, lower loads earlier, true counts as 0 (zones that need the level: 1); a load returning a Promise makes later parts wait. version (default 1): raise it by 1 whenever what save() returns changes shape, and add migrate[oldVersion] = data => newData; load sees only the current shape. A save whose part is newer than this build's version is refused as a whole (load returns false, the save is kept). load(data, turn): turn is this replacement's identity. Pass it on, level.load(x, { turn }) or content.load(x, { turn }): those wait for a running load to end, except with its turn. A part registered after a save was loaded (a module installed later) is handed its data from that save: at once when idle, else right after the replacement under way. Example: `engine.saves.define('garden', { save: () => garden.toJSON(), load: d => garden.fromJSON(d) }); // later the format gains beds: version 2, and a step that upgrades version-1 data engine.saves.define('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save: () => garden.toJSON(), load: d => garden.fromJSON(d) });`
4
+ - `saves.putAttachment(group: string, id: string, blob: Blob | (() => Promise<Blob>), meta?: any) → Promise<void>` — (experimental) Store a binary attachment outside the world save (a photo, a replay). It rides in the queue of save writes, so flush() waits for it, and exportFile() carries it. Pass a function to make the bytes when the write runs: flush() then waits for that too. Without IndexedDB it is not kept: it rejects with save-write. Rejects with save-stale, changing nothing, when another tab wrote this id since this tab last saw it; attachments(group) is how a tab looks. Example: `await engine.saves.putAttachment('replay', 'run-1', blob, { score: 12 });`
5
5
  - `saves.removeAttachment(group: string, id: string) → Promise<void>` — (experimental) Delete an attachment; no such id is fine. Rejects with save-stale as putAttachment does
6
6
  - `saves.attachments(group: string) → Promise<{ group: string; id: stri…` — (experimental) The attachments of a group, once storage is ready. Empty without IndexedDB.
7
7
  - `saves.storageKey(name: string) → string` — A localStorage key for what belongs to this game but is not a save (settings, a last-used tab): it shares the game's name, so two games on one site stay apart, and stays out of list(). Example: `localStorage.setItem(engine.saves.storageKey('lastTab'), 'map');`
@@ -10,7 +10,7 @@
10
10
  - `saves.check(slot?: string) → null | "missing" | "corrupt" | "tooNew" | "migrate"` — Can this slot be loaded? null when it can, else why not (checked without touching the game): 'missing' / 'corrupt' (unreadable) / 'tooNew' (a newer save format or part) / 'migrate' (an upgrade step is missing or throws). Example: `if (engine.saves.check('slot1') === 'tooNew') showUpdateHint();`
11
11
  - `saves.apply(data: any, slot?: string) → Promise<boolean>` — Apply a save's data (an object from collect(), or save text) onto the running game. Resolves true when every part loaded. Refused before anything changes (false, toast) when the data is corrupt, from a newer build or cannot be migrated. After every part loaded it runs the modules' afterLoad hooks (gameplay frozen until they resolve), for saves.load, session.newGame / quit and direct calls alike. If a part's load throws, a listener of an event it emits while loading (world:load) throws, or a module's afterLoad throws, the game is rolled back to how it was before (every part reloads its pre-load state) and it resolves false; the error goes through the error tiers. "While loading" lasts until the result settles, past every await of an async load(); a listener that throws in that window for any reason fails this load.
12
12
  - `saves.save(slot?: string) → Promise<boolean>` — Save into a slot (default 'auto'). Returns Promise<boolean> (resolves after the write to IndexedDB: true on success, false with a toast and console error on failure). The in-memory save updates immediately, so a following load / list / export sees it at once; the 'save:written' event fires only after the write succeeds. Asked for while a load, newGame or quit is under way, it waits for that to end and saves the result: a save never holds half of each state. If any part's save() throws, or its data holds NaN or Infinity at any depth (the message names the part and the path), nothing is written and the slot keeps its previous save (false). A failed write keeps the previous save too. Show "saved" only after the result is true. Example: `if (await engine.saves.save('slot1')) toast(engine, 'Saved'); // on false the engine already showed why`
13
- - `saves.load(slot?: string) → Promise<boolean>` — Load a slot onto the running playthrough (a quick load: what the game added during play stays) and resolve true on success; the 'save:loaded' event fires on success. A missing slot resolves false; a corrupt / too new / unmigratable save resolves false with a toast and changes nothing; a part whose load throws rolls the game back. To continue or retry with nothing of the current playthrough left over, use engine.session.load(slot). Example: `if (!(await engine.saves.load('quick'))) toast(engine, 'No quick save');`
13
+ - `saves.load(slot?: string, { turn }?: { turn?: object }) → Promise<boolean>` — Load a slot onto the running playthrough (a quick load: what the game added during play stays) and resolve true on success; the 'save:loaded' event fires on success. A missing slot resolves false; a corrupt / too new / unmigratable save resolves false with a toast and changes nothing; a part whose load throws rolls the game back. To continue or retry with nothing of the current playthrough left over, use engine.session.load(slot). Example: `if (!(await engine.saves.load('quick'))) toast(engine, 'No quick save');`
14
14
  - `saves.list() → { slot: string; savedAt: number }[]` — All slots, newest first (synchronous, reads the in-memory index)
15
15
  - `saves.remove(slot: string) → Promise<void>` — Delete a slot. Returns a Promise (disk write done); awaiting is optional. A newer save another tab wrote meanwhile is kept: the slot lists again, with a toast (save-stale). A delete the store refused lists the slot again too, with a toast.
16
16
  - `saves.export(slot?: string) → string` — (experimental) Export as a piece of text (can be copied as a backup; synchronous, without binary attachments)
@@ -25,12 +25,12 @@
25
25
  - `versions: Record<string, number>` The save versions this build reads, per part: { world: 1, clock: 1, ... }. A save whose part is newer is refused; an older one is migrated.
26
26
 
27
27
  ## Data structures
28
- - **SaveProvider** Save provider: save() returns JSON-able data, load(data) reads it back (may return a Promise, e.g. for changing level; later parts wait for it to finish before loading). first: true providers load first (parts such as the level, where the rest only makes sense after it is loaded)
28
+ - **SaveProvider** Save provider: save() returns JSON-able data, load(data) reads it back (may return a Promise, e.g. for changing level; later parts wait for it to finish before loading). first: true providers load first (parts such as the level, where the rest only makes sense after it is loaded); first may be a number, lower loads earlier, true counts as 0
29
29
  - `save: () => any` This part's data now: plain data (structuredClone can copy it; no functions, DOM nodes or three objects). It may be the live object the part keeps: the engine copies it for its rollback point before a load, so a load() that writes into that same object can still be undone.
30
30
  - `load: (data: any, turn: SaveTurn) => void | Promise<void>` Read data back; may return a Promise (later parts wait). Listener errors of events it emits count as the load throwing, also after an await. turn: this replacement's identity. Pass it on as level.load(x, { turn }) / content.load(x, { turn }): awaited without it, those wait for this load, so for ever (dev warns after 3 s, save-nested)
31
- - `first?: boolean` Load before the other parts (such as the level)
32
- - `atomic?: boolean` Join atomic ops: copied before an atomic op runs, put back if it fails (plain data; afterLoad does not run on rollback)
33
- - `notAtomic?: string` Why an atomic op leaves this part alone. Every engine part gives atomic: true or this (rule R66); a game's part may
31
+ - `first?: boolean | number` Load before the other parts (such as the level)
32
+ - `atomic?: boolean` Join atomic ops: copied before an atomic op runs, put back if it fails (plain data; afterLoad does not run on rollback; load() must be synchronous: an async function is refused at define, a returned Promise at rollback as engine-misuse)
33
+ - `notAtomic?: string` Why an atomic op leaves this part alone. Every engine part gives atomic: true or this (rule R67); a game's part may
34
34
  - `checkNewGame?: (data: any) => void` Dev only: called once start() finished with this part's data in the new-game state, to warn about what should not be there yet (world: records placed by code)
35
35
  - `version?: number` This part's format version, default 1: raise it by 1 when what save() returns changes shape. A save with a newer version is refused
36
36
  - `migrate?: Record<number, (data: any, save: { parts: Record<string, an…` Upgrade steps: old version -> data => data in the next version's shape, e.g. { 1: d => ({ ...d, beds: [] }) }. The second argument is the whole save as read ({ parts, versions }, read only), for a step that depends on another part