threedog 0.8.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/CHANGELOG.md +223 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -10,7 +10,7 @@ Quests (quests() module)
10
10
  ## Methods and properties
11
11
  - `quests.define(id: string, def: QuestDef)` — Define a quest (chainable)
12
12
  - `quests.start(id: string)` — Start a quest
13
- - `quests.state(id: string) → { step, steps, done, failed, active } | null` — One quest's progress (a copy): step index, step count, done, failed, active; null before it starts
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
15
  - `quests.isDone(id: string) → boolean` — (experimental)
16
16
  - `quests.isActive(id: string) → boolean` — Started, not done and not failed
@@ -25,11 +25,13 @@ Quests (quests() module)
25
25
  - `title: string` Title
26
26
  - `desc?: string` Description
27
27
  - `steps: (QuestStep | QuestParallelStep)[]` Steps (completed in order); a step may be parallel goals { all: [...] }
28
- - `reward?: (e: Engine) => void` Called on completion (give rewards)
28
+ - `reward?: (e: Engine) => any` Called on completion (give rewards). Returning a failure ({ ok: false, code }, e.g. what e.content.run or e.inventory.add answer) means it was not paid: see onUnpaid
29
+ - `onUnpaid?: (e, answer) => void` The game's decision for a reward not given, with the failure as answer. Without it the items that did not fit stay owed (list().owed, saved) and go into the bag when there is room
29
30
  - `fail?: (e: Engine) => boolean` Checked while active; true fails the quest (quest:fail; start(id) can begin it again). Example: `fail: e => e.vars.flag('caravanLost')`
30
31
  - `onFail?: (e: Engine) => void` Called when the quest fails
31
32
  - **QuestStep** One quest step: text is the displayed text, done the completion condition (checked every half second), target the objective (a marker is shown when hud is installed)
32
33
  - `id?: string` Stable id: saves store progress by it, so steps can be inserted or reordered later (default: the step's position)
33
34
  - `text: string`
34
35
  - `done: (e: Engine) => boolean`
36
+ - `next?: string | false | ((e: Engine) => string | false | undefined)` The step after this one: a step id, or e => id asked when this step is done (a branch); false finishes the quest here. Default: the next step in the list. steps already passed are in quests.state(id).visited
35
37
  - `target?: HudTarget` Objective: a place name (content.place), object, character, { x, z }, { nearest: itemId } or a function returning an objective; with the hud module the current step shows a marker automatically
package/docs/api/rays.md CHANGED
@@ -19,6 +19,8 @@
19
19
  - `normal: Vector3 | null`
20
20
  - `object: Object3D | null`
21
21
  - `face: any`
22
+ - `instanceId?: number` Which instance of an InstancedMesh was hit, as in a three.js intersection
23
+ - `batchId?: number` Which item of a BatchedMesh was hit, as in a three.js intersection
22
24
  - `entry?: any`
23
25
  - `kind?: string`
24
26
  - `thing?: HitThing` Point -> thing, computed when read: the world record the hit belongs to (a batched instance resolves to its original), where it was authored and what to edit. Example: `const t = engine.pick(0, 0)?.thing; // { id: 'chest-home', kind: 'chest', template: 'chest', definedAt: 'content/props.js:14', ... }`
package/docs/api/rigid.md CHANGED
@@ -13,12 +13,13 @@ Real physics, Rapier (rigid() module, needs collision)
13
13
  - `treeColliderHeight?: number` (experimental) Height (meters) of vegetation collision pillars (tree trunks), default 6
14
14
  - `treeRadius?: number` (experimental) Trunks get collision cylinders only in chunks within this many meters of the player or a moving rigid body (the rest are covered by engine.collision for characters), default 16
15
15
  - `playerCapsule?: { halfHeight: number; radius: number }` (experimental) Player capsule size (meters), default computed from engine.movement radius / height
16
+ - `fallbackFloor?: boolean` The flat plane at y = 0 when the ground has no collision of its own, default true. false: only your own bodies and colliders are there (a sky of islands)
16
17
 
17
18
  ## Methods and properties
18
19
  - `rigid.addBox(mesh: Object3D, opts?: RigidBoxOptions) → RigidEntry | null` — Add a box (crate). Physics is ready after engine.start() (or on engine:ready): called before, it throws in development, a release build warns once and returns null
19
20
  - `rigid.addBall(mesh: Object3D, opts?: RigidBallOptions) → RigidEntry | null` — (experimental) Add a ball; null only as in addBox: a release build, called before physics is ready
20
21
  - `rigid.addHull(mesh: Object3D, opts?: RigidBodyOptions) → RigidEntry | null` — (experimental) Add a convex hull (irregular objects such as rocks and barrels); null only as in addBox: a release build, called before physics is ready
21
- - `rigid.ragdoll(who: any, opts?: RagdollOptions) → Ragdoll | null` — (experimental) Turn a skinned character limp in one call; rd.remove() returns it to animation. who: a Character, an NPC handle, a character id or a skinned Object3D. Its mover, animator, capsule and camera yield until then; calling again on the same one pushes it again and returns the same ragdoll. Not saved: any load ends it. A skeleton it cannot read throws, naming the missing parts.
22
+ - `rigid.ragdoll(who: any, opts?: RagdollOptions) → Ragdoll | null` — (experimental) Turn a skinned character limp in one call; rd.remove() returns it to animation. who: a Character, an NPC handle, a character id or a skinned Object3D. Its mover, animator, capsule and camera yield until then; calling again on the same one pushes it again and returns the same ragdoll. Not saved: any load ends it. A skeleton it cannot read throws, naming the missing parts. The rule 'ragdoll.graph' (per character id) gives the parts: 'humanoid' (default), Record<string, RagdollPart> for any other body, a function (facts: { character, root, mesh }, engine) => one of those, or false for no ragdoll (returns null).
22
23
  - `rigid.impulse(entry: RigidEntry, impulse: Vec3Like)` — Give it a push: impulse vector impulse (Vector3 / [x, y, z] / { x, y, z }), e.g. impulse(ball, [0, 3, 5])
23
24
  - `rigid.setPosition(entry: RigidEntry, position: PositionLike)` — Teleport to position (velocity is zeroed)
24
25
  - `rigid.addWheeled(mesh: Object3D, opts: VehicleOptions) → Vehicle | null` — Turn a model into a wheeled vehicle (Rapier ray-cast vehicle controller: cars, karts, carts); remove it with vehicle.remove() (anyone inside gets out first). Before physics is ready it throws in development (release: warns, null), like addBox. Boats, mounts and mechs are the game's own objects with the same seat interface
@@ -92,4 +93,4 @@ Real physics, Rapier (rigid() module, needs collision)
92
93
  - `passengers: Character[]`
93
94
  - `hideDriver: boolean`
94
95
  - `seatPosition(seat?: number) → Vector3` — World position of a seat (default 0, the driver's)
95
- - `exitPosition(seat?: number) → Vector3` — Where to get out of a seat (outside the door on that seat's side, world coordinates)
96
+ - `exitPosition(seat?: number, n?: number) → Vector3` — Where to get out of a seat (outside the door on that seat's side, world coordinates)
package/docs/api/saves.md CHANGED
@@ -1,18 +1,18 @@
1
1
  # engine.saves (Saves) — engine.saves handles saving
2
2
 
3
- - `saves.register(key: string, provider: SaveProvider)` — 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). A part registered after a save was loaded (a module installed later) is handed its data from that save at once. atomic: true joins this part to atomic ops: it is copied before an atomic op runs and put back if the op fails (plain data only; afterLoad does not run on rollback). 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. Example: `await engine.saves.putAttachment('replay', 'run-1', blob, { score: 12 });`
5
- - `saves.removeAttachment(group: string, id: string) → Promise<void>` — (experimental) Delete an attachment; no such id is fine
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 });`
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');`
8
8
  - `saves.flush() → Promise<void>` — Wait for all queued disk writes to finish (for tests and before the page closes)
9
- - `saves.collect() → { format, savedAt, versions, parts }` — Collect the data of every part (does not write to the browser): { format, savedAt, versions, parts }. A part whose save() throws is left out and reported (engine.error in dev); save() instead refuses to write such a save.
9
+ - `saves.collect() → { format, savedAt, versions, parts }` — Collect the data of every part (does not write to the browser): { format, savedAt, versions, parts }. A part whose save() throws is left out and reported (engine.error in dev); save() instead refuses to write such a save. Throws while a load is under way: what it would return is half of each state. saves.save waits instead.
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
- - `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. If any part's save() throws, 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`
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
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');`
14
14
  - `saves.list() → { slot: string; savedAt: number }[]` — All slots, newest first (synchronous, reads the in-memory index)
15
- - `saves.remove(slot: string) → Promise<void>` — Delete a slot. Returns a Promise (disk write done); awaiting is optional
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)
17
17
  - `saves.import(text: string, slot?: string) → Promise<boolean>` — Import text from export() into a slot (default 'imported'); checked like importFile and written before it resolves. Resolves true once stored (save:imported fires), false when the text is not a save or the write failed. It does not load the slot.
18
18
  - `saves.exportFile(slot?: string, opts?: { files?: boolean }) → Promise<boolean>` — (experimental) Download a save file (.json): the save plus every binary attachment (as data: text, so the file is larger; { files: false } exports the save only). Restores everything when browser data is wiped on a phone. Returns Promise<boolean>. Example: `engine.saves.exportFile('slot1');`
@@ -27,9 +27,10 @@
27
27
  ## Data structures
28
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)
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
- - `load: (data: any) => 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
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
31
  - `first?: boolean` Load before the other parts (such as the level)
32
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
33
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)
34
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
35
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
@@ -1,9 +1,8 @@
1
1
  # engine.stream (Stream) — engine.stream builds on demand by space: only entries near the focus get built
2
2
 
3
3
  - `stream.add(def: StreamEntryOptions) → StreamHandle` — Register something to stream in (not built at once); an object returned by build with no parent is added to the scene automatically. Example: `engine.stream.add({ position: [40, 0, 12], radius: 6, build: () => makeHouse() });`
4
- - `stream.setRadius(m: number)` — (experimental) Set the build radius in meters
5
4
  - `stream.source(position: any, opts?: StreamSourceOptions) → StreamSource` — (experimental) Add a stream source: the world around position is loaded (terrain chunks, colliders, nearby models, stream entries) until remove() or until. position may be live (an Object3D or Vector3 that moves) or a function. detail 'simple' loads only terrain and hlod proxies (a far view); physics defaults to true for 'full'; pass false for a camera that only needs a picture. radius caps every loader's range (default: each loader's own range). until: a Promise (removed when it settles) or a function checked every frame (removed when it returns true). Example: `const dest = engine.stream.source([800, 0, 300], { radius: 64 }); await dest.whenReady; engine.player.placeAt([800, 0, 300]); dest.remove();`
6
- - `stream.teleport(position: any, opts?: { radius?, move?, timeout? }) → Promise<void>` — (experimental) Load the destination first, then move: resolves after the player (engine.focus without one) is placed. Until the destination is ready (terrain chunks, collision, nearby models) the player stays where it is. move replaces the default placement (for a vehicle or a custom character). timeout (seconds of frame time, default 60; Infinity waits forever): when the destination is still not ready, the Promise rejects (code stream-timeout, naming the loaders still waiting) and the player is not moved. Example: `await engine.stream.teleport([800, 0, 300]);`
5
+ - `stream.teleport(position: any, opts?: { radius?, move?, timeout? }) → Promise<void>` — (experimental) Load the destination first, then move: resolves after the player (engine.focus without one) is placed. Until the destination is ready (terrain chunks, collision, nearby models) the player stays where it is. move replaces the default placement (for a vehicle or a custom character). timeout (seconds of frame time, default 60; Infinity waits forever): when the destination is still not ready, the Promise rejects (code stream-timeout, naming the loaders still waiting) and the player is not moved. Ready means nothing is pending, not that everything built: a stream entry or world model whose build failed is reported and left out, and the trip still lands. A terrain chunk that failed stays not ready, as there is no ground to stand on, so that trip ends in stream-timeout. A game that needs a thing built checks it itself (handle.built, engine.world.view(id)). Example: `await engine.stream.teleport([800, 0, 300]);`
7
6
  - `stream.addReadyCheck(name: string, fn: (source: StreamSource) => boolean) → { remove(): void }` — (experimental) Register a readiness check for loaders: fn(source) returns whether this loader finished what that source asks for. For module authors whose loader reads stream sources; games only read source.ready. Example: `engine.stream.addReadyCheck('props', s => s.detail !== 'full' // props.queued === 0)`
8
7
  - `stream.sources(pick?: { detail?, physics? }) → StreamSource[]` — (experimental) Sources with fresh positions, filtered: { detail: 'full' } for models and stream entries, { physics: true } for colliders, no filter for terrain
9
8
  - Properties:
@@ -12,8 +11,8 @@
12
11
  - `player: StreamSource` Built-in source at the player (engine.focus without one): full detail and physics
13
12
  - `camera: StreamSource` Built-in source at the camera focus engine.focus: full detail, no physics
14
13
  - `activeRadius: number` (experimental) The build radius actually in use, in meters
15
- - `radius: number | null` Build radius in meters around each full-detail stream source (a source radius caps it); null = follow the terrain view distance (the uViewDistance signal without terrain). Writing it takes effect like setRadius.
16
- - `ready: boolean` Everything registered within radius is built (start() waits for it before the loading screen goes away)
14
+ - `radius: number | null` Build radius in meters around each full-detail stream source (a source radius caps it); null = follow the terrain view distance (the uViewDistance signal without terrain).
15
+ - `ready: boolean` No build within radius is still waiting (start() waits for it before the loading screen goes away). Nothing pending, not everything built: a build that failed is reported and left out; a game that needs a thing built checks it itself (handle.built)
17
16
  - `stats: { entries: number; built: number; queued: number }` entries is the registered count, built the built count, queued the queued count
18
17
 
19
18
  ## Data structures
@@ -21,7 +20,7 @@
21
20
  - `position: PositionLike` Position (Vector3 / object / [x, y, z] / { x, z }; only the horizontal coordinates count)
22
21
  - `radius?: number` Object size (meters); larger ones are built earlier
23
22
  - `build: () => Object3D | Promise<Object3D>` Generate the object (called when entering range, run spread over frames through engine.jobs)
24
- - `dispose?: (obj: Object3D) => void` Unload (called when leaving range), default engine.remove (frees what nothing else in the scene uses); write your own when the object is reused (e.g. engine.detach)
23
+ - `dispose?: (obj: Object3D) => void` Unload (called when leaving range), default engine.remove (frees what nothing else in the scene uses); write your own when the object is reused (e.g. obj.removeFromParent())
25
24
  - `keep?: boolean` Do not unload even when out of range
26
25
  - `priority?: number` Build order: larger first (nearer first within the same priority), default 0
27
26
  - **StreamHandle** Handle returned by stream.add(): object is the generated object (null while not generated)
@@ -6,6 +6,7 @@ Procedural terrain, data part (terrain() module: chunks, heights, edits, collisi
6
6
  - `viewChunks?: number` View distance (in chunks), default 4
7
7
  - `density?: number` Vegetation density multiplier, default 1
8
8
  - `viewFog?: boolean` true: the signal engine.uniforms.uViewDistance follows the view distance, so a game's fog can read it and fade the far chunk edge out (openWorld() sets true)
9
+ - `part?: boolean` true: do not take the ground slot; compositeGround({ parts: [{ of: 'terrain' }] }) does and reads terrain.ground (so a terrain and a level can both run)
9
10
  - `material?: Material | ((engine: Engine) => Material)` Ground material (default neutral gray with vertex colors); chunks have position, normal, color and uv = world xz / chunk size. Cloud shadows, season tint and detail are added
10
11
  - `effects?: boolean` With material: false = draw it exactly as given, no cloud shadow / season / detail patch
11
12
  - `detail?: MaterialDetail | null` Detail layer over the ground: a noise, a texture asset name or your own glsl; defaults scale 0.25, strength 0.35, top-down world projection, multiply. Change it with engine.terrain.recolor({ detail })
@@ -13,8 +14,6 @@ Procedural terrain, data part (terrain() module: chunks, heights, edits, collisi
13
14
 
14
15
  ## Methods and properties
15
16
  - `terrain.recolor(o?: TerrainRecolor)` — Change at run time what terrain({...}) baked in. colors, biomeColors, steep, variation, shading, normals rebuild every chunk (edits stay); detail only patches the engine's material. Throws under a draw part that replaced 'terrain-draw'. Example: `engine.terrain.recolor({ colors: { grass: 0x6a8a3a }, biomeColors: { meadow: ['grass'] } });`
16
- - `terrain.setViewChunks(n: number)` — (experimental) Change the view distance (in chunks); camera far plane and, with viewFog, uViewDistance adjust too
17
- - `terrain.setDensity(d: number)` — (experimental) Change the vegetation density: plants are placed again on the loaded chunks; the ground and its collision stay
18
17
  - `terrain.view(hooks: { add?, change?, remove?, show? }) → { remove(): void }` — Draw these chunks: the hooks a draw part that replaces 'terrain-draw' uses. add(c): generated (c.data holds pos / nor / col / uv / tex arrays, c.cx / c.cz the chunk); change(c): an edit rewrote c.data (the vertex count can differ on the rim of a shape with diagonal 'adaptive'); remove(c): released; show(c, visible): in view or not. Chunks already loaded are added at once. Returns { remove() } (ctx.track it). Example: `ctx.track(engine.terrain.view({ add(c) { draw(c) }, remove(c) { undraw(c) } }))`
19
18
  - `terrain.retry() → number` — Send chunks that failed every try (terrain:chunkFailed) again, e.g. after fixing what their rule reads. Returns how many were queued
20
19
  - `terrain.rebuild()` — Rebuild all chunks
@@ -27,8 +26,8 @@ Procedural terrain, data part (terrain() module: chunks, heights, edits, collisi
27
26
  - `chunkSize: number` Chunk edge length (meters), the same value as the chunkSize option and ground.chunkSize
28
27
  - `voidY: number` terrain({ shape }) only: below this height the player or a moving rigid body has fallen out of the world (one terrain:void per fall). shape.voidY, else 50 m under the lowest island chunk loaded so far; -Infinity without a shape. Example: `engine.events.on('terrain:void', ({ who }) => { if (who === engine.player) engine.player.placeAt(home); });`
29
28
  - `chunks: Map<string, TerrainChunk>` Loaded chunks: 'cx,cz' → chunk
30
- - `viewChunks: number` (experimental) View distance (in chunks); writing it takes effect like setViewChunks
31
- - `density: number` Vegetation density multiplier; writing it takes effect like setDensity
29
+ - `viewChunks: number` (experimental) View distance (in chunks). Writing it moves the camera far plane out too, and with viewFog uViewDistance
30
+ - `density: number` Vegetation density multiplier. Writing it places plants again on the loaded chunks: it thins plants without a collider, blocking plants stand at every density, so collision does not change
32
31
  - `applyBudgetMs: number` Time budget (milliseconds) for uploading chunks per frame
33
32
  - `stats: { builtThisFrame, applyMs, queued, failed, visible?, loaded?, … }` Statistics (for the debug panel); failed = chunks that failed every try (terrain:chunkFailed)
34
33
  - `cellSize: number` Grid spacing (meters) = chunkSize / resolution: edits snap to it, paint colors whole cells of this size
@@ -1,4 +1,4 @@
1
- # engine.terrainDraw — terrainDraw()
1
+ # engine.terrainDraw — terrain(opts?: TerrainOptions)
2
2
 
3
3
  (experimental) Draws the terrain chunks (terrain()'s drawing module, slot 'terrain-draw'; undefined when a game replaced it)
4
4
 
@@ -5,8 +5,8 @@ Cutscenes, tweens (timeline() module)
5
5
  - Options `TimelineOptions`
6
6
 
7
7
  ## Methods and properties
8
- - `timeline.tween(target: any, to: TweenTo, opts?: { duration?: number; ease?: Ease }) → TweenPromise` — General tween (the only entry point for tweens in the engine): await engine.timeline.tween(mesh, { 'position.y': 2 }, { duration: 1, ease: 'outCubic' }); duration in seconds (default 1), ease default 'inOutCubic'; tween(mesh, to, 1) throws in dev. Returns a Promise (with finish() / remove())
9
- - `timeline.play(steps: TimelineStep | TimelineStep[], opts?: TimelinePlayOptions) → Promise<{ skipped: boolean }>` — Play a timeline; resolves with { skipped } when it ends
8
+ - `timeline.tween(target: any, to: TweenTo, opts?: { duration?: number; ease?: Ease }) → TweenPromise` — General tween (the only entry point for tweens in the engine): await engine.timeline.tween(mesh, { 'position.y': 2 }, { duration: 1, ease: 'outCubic' }); duration in seconds (default 1), ease default 'inOutCubic'; tween(mesh, to, 1) throws in dev. Returns a Promise (with finish() / remove()); a write that throws ends the tween and rejects it
9
+ - `timeline.play(steps: TimelineStep | TimelineStep[], opts?: TimelinePlayOptions) → Promise<{ ending: "finished" | "s…` — Play a timeline; resolves with { ending, error? } when it ends: 'finished', 'skipped', 'dropped' (a load, a new game or dispose took its state) or 'failed' (a step threw; error says what)
10
10
  - `timeline.skip(run?: any)` — Skip all (or one) playing timelines
11
11
  - Properties:
12
12
  - `skipAll: boolean` (experimental) Skip every cutscene immediately (set by scenario param cutscene=skip)
package/docs/api/tools.md CHANGED
@@ -1,7 +1,6 @@
1
1
  # Utility functions (imported from threedog)
2
2
 
3
3
  - `PICTURE_SLOTS: Readonly<Record<PictureSlot, { readonly what: str…` — The picture slots: what each one is and which describe('picture').picture.writers names it covers (a name ending in '.' covers everything under it)
4
- - `weather(opts?: WeatherOptions) → [ModuleDef<Weather>, ModuleDef<im…` — Weather: two modules for one engine.use: the state (engine.weather, type 'world') and its picture (engine.weatherDraw, type 'picture'; sky optional)
5
4
  - `presets: { weather, calendar, player, interactions, bindings, camera }` — Opt-in gameplay presets: named option objects a game picks on purpose (the engine never applies one itself). Each only bundles options the game could write; spread and override: weather({ ...presets.weather.temperate, autoPool: ['clear', 'rain'] })
6
5
  - `world(opts?: { cellSize?, radius?, farEvery?, farMaxPerTick?, buildPerFrame? }) → import("../../../core").ModuleDef…` — World data module: installed as engine.world. Put things here that must be saved, survive level changes and keep changing while far away; models are only built while nearby
7
6
  - `net(opts?: { role, transport, sync?, syncEvery?, keepAlive?, rate?, … }) → import("../../../core").ModuleDef…` — (experimental) Optional co-op multiplayer: one host owns the state, clients mirror it and ask for changes through ops. Installed as engine.net. Host: peers' requests run as `ops.run(name, args, { source: 'net', actor })` only for ops defined with net: 'peer', with the op's args shape checked, the optional owner check, and a per-peer rate limit; the result comes back after the state diff that contains it. State: world records, containers, vars and the other save parts are sent as a snapshot on join and as diffs every syncEvery steps. Client: ops.run of a peer op returns { ok: true, pending: true, seq } (watch state or the net:result event, not the return value); its own avatar moves locally and is sent to the host (clamped to maxSpeed); other avatars glide between updates.
@@ -58,6 +57,9 @@
58
57
  - `behind: boolean`
59
58
 
60
59
  ## Other exported classes and functions
60
+ - `pixelGrid(options: { camera, pixelsPerMeter }) → PixelGrid` — The art pixel grid of an orthographic camera. Pure math.
61
+ - `pixelSprite(options: PixelSpriteOptions) → Mesh` — A plain THREE.Mesh: a vertical plane that turns around Y with the camera's forward direction, stretched so one texel is one art pixel. Works as a character's `model`. mesh.position stays exact; only what is drawn is rounded.
62
+ - `spriteFrame(mesh: Mesh, frame: number, flip?: boolean) → Mesh` — Show a sheet frame (left to right, top to bottom); flip mirrors it, left out it stays as it was
61
63
  - `wind(position: Node, origin: Node, amplitude: Node | number) → Node` — (experimental) GLSL vec3 threedogWind(vec3 position, vec3 origin, float amplitude): object-space sway offset, higher vertices sway more. position: object space before the instance transform (positionGeometry); origin: the object's world origin (objectOrigin()); amplitude: metres per metre of height. Reads uTime, uWind, uWindFreq.
62
64
  - `cloudShadow(worldPos: Node) → Node` — (experimental) GLSL float threedogCloudShadow(vec3 worldPos): light factor 0-1 under the drifting clouds (1 = no shadow). Reads uTime, uWeatherCloud, uCloudShadow*, uCloudShadowSpeed.
63
65
  - `season(color: Node, kind: Node | 0 | 1) → Node` — (experimental) GLSL vec3 threedogSeason(vec3 color, int kind): kind 0 foliage, 1 ground; tints by uFoliageTint / uGroundTint (mix mode when uFoliageMix / uGroundMix > 0). A vec4 color is read as its rgb.
@@ -31,6 +31,8 @@ Trigger zones (triggers() module)
31
31
  - `who?: string | Vector3 | Object3D | { x, y, z } | (() => Array<string | Obje…) | null` Who can trigger it: engine.actor by default; or an actor id, a position, an object (its position is used), or a function returning an array of those (several actors: () => [e.actor, ...e.net.peers.map(p => p.actor)])
32
32
  - `cooldown?: number` Seconds after leaving during which entering does not fire again, default 0
33
33
  - `userData?: Record<string, any>` Custom data
34
+ - `occupancy?: 'zone' | 'each'` 'zone' (default): one enter when the first actor arrives, one exit when the last leaves. 'each': an enter, stay and exit per actor (a door counting entrants); inside is true while anyone is in
35
+ - `volume?: { contains, bounds? }` Your own region instead of a shape: the plain volume addWaterBody takes. bounds ({ min, max }) lets the zone be indexed and drawn in the debug view; without it the zone is checked every step
34
36
  - **Trigger** A trigger zone (the return value of add())
35
37
  - `shape: 'cylinder' | 'sphere' | 'box'`
36
38
  - `x: number` Position (meters)
@@ -1,4 +1,4 @@
1
- # engine.vegetationDraw — vegetationDraw()
1
+ # engine.vegetationDraw — vegetation(opts?: VegetationModuleOptions)
2
2
 
3
3
  (experimental) Draws the plants (vegetation()'s drawing module, slot 'vegetation-draw'; undefined when a game replaced it)
4
4
 
package/docs/api/water.md CHANGED
@@ -22,8 +22,12 @@ Water surface (water() module)
22
22
 
23
23
  ## Data structures
24
24
  - **WaterBodyOptions** Parameters of engine.addWaterBody(): position center, level water surface height (meters); give radius for a circle, halfWidth / halfDepth for a rectangle
25
- - `position: PositionLike`
26
- - `level: number`
25
+ - `position?: PositionLike`
26
+ - `level?: number`
27
+ - `query?: (x: number, z: number, y?: number) => number | null` Your own water (the engine draws nothing): level at (x, z) for a body at height y, or null where this body has none
28
+ - `bounds?: { min, max }` Box3-like { min, max } that lets waterAt skip the query outside it
29
+ - `mesh?: Object3D` The mesh you draw for it (kept for reference; add it to the scene yourself)
30
+ - `volume?: { contains, bounds? }` A plain volume with contains({ x, y, z }); with level it is water inside the volume
27
31
  - `radius?: number`
28
32
  - `halfWidth?: number`
29
33
  - `halfDepth?: number`
@@ -1,11 +1,26 @@
1
- # engine.weather — weather()
1
+ # engine.weather — weather(opts?: WeatherOptions)
2
2
 
3
- Weather state (weather() module): the table, current values, set / setAuto, save, events
3
+ Weather state (weather() module): the table, current values, set / auto, save, events
4
4
 
5
+ - Options `WeatherOptions`:
6
+ - `start?: WeatherName` Starting weather, default 'clear' (or the first of the game's types when it has no 'clear')
7
+ - `auto?: boolean` Automatic weather changes
8
+ - `particles?: number` Rain / snow particle count, default 6000
9
+ - `rain?: WeatherParticles` Rain particles (default streaks: color 0xc8c8c8, opacity 0.55, length 0.7 m, speed 22 m/s, slant 1); a texture or a sprite shape draws drops
10
+ - `snow?: WeatherParticles & { cover?: SnowCover }` Snow particles (default round sprites: color 0xffffff, opacity 0.9, size 20, maxSize 5 px, speed 1.6 m/s, sway 1.5 m), plus the cover it leaves
11
+ - `lightning?: (flash: number, engine: Engine) => number` Strike picture: flash (1 at the strike, fading in a third of a second) -> sky flash amount; default flickers. Return 0 and draw your own bolt on the weather:lightning event for a whole replacement. Example: `lightning: f => f * f * 0.8`
12
+ - `lightningBrightness?: number` Multiplies the sky flash of every strike, default 1
13
+ - `overcastColor?: ColorLike` Color the sky turns as a weather type raises grey, default 0x8c8c8c
14
+ - `types?: Record<string, Partial<WeatherPreset> & Record<string, numb…` The game's weather table, the whole list (default only a calm 'clear'; seven temperate ones in presets.weather.temperate.types, extend them with { ...presets.weather.temperate.types, dust: {...} }). Left-out fields are calm; extra numeric fields of the game's own blend too and show in weather.current
15
+ - `autoPool?: string[]` Candidates for automatic changes (repeat an entry for higher probability)
16
+ - `autoInterval?: number[]` Interval between automatic changes [shortest, longest] seconds
17
+ - `transition?: number` Transition seconds of automatic changes, default 25
18
+ - `area?: number` Rain / snow coverage (meters)
19
+ - `lightningFirst?: number` Seconds to the first bolt once a type with lightning > 0.5 holds, default 5
20
+ - `lightningInterval?: number[]` Seconds between later bolts [shortest, longest], default [6, 20]
5
21
 
6
22
  ## Methods and properties
7
23
  - `weather.defineField(field: string, spec: WeatherParticles | null) → WeatherParticleSystem | null` — Draw a field of the weather table with particles: your own (ash, petals, sparks) or rain / snow in place of the built-in ones. The amount each frame is weather.current[field], so they fade with the weather. spec takes the keys of weather({ rain }), or { create(engine, { area, count }) => { object, update?(amount, { camera, time, wind }) } } for a system of your own; null gives rain / snow back to weather({ rain, snow }) and removes any other field. Defining a field again replaces it. A field no type has throws with the table's fields. Example: `engine.weather.defineField('ash', { shape: 'soft', color: 0x555555, size: 14, speed: 0.8, sway: 3 });`
8
- - `weather.setAuto(on: boolean)` — Automatic weather on/off
9
24
  - `weather.set(name: WeatherName, opts?: { seconds?: number })` — Switch weather. seconds: transition seconds, default 15; 0 switches at once (current is the new weather before the next step, so a screenshot or test right after shows all of it). Options in an object like every other engine call: set('rain', 20) throws [module-params] in dev (the old positional form). Example: `engine.weather.set('rain', { seconds: 20 })`
10
25
  - `weather.label(name?: string) → string` — Display name of a weather (string table weather.<name>, falls back to the name itself); defaults to the current weather
11
26
  - Properties:
@@ -21,4 +36,4 @@ Weather state (weather() module): the table, current values, set / setAuto, save
21
36
  - `lightningBrightness: number` Multiplies the sky flash of every strike; write it at any time
22
37
  - `overcastColor: THREE.Color` Color the sky turns as a weather type raises grey: a THREE.Color, overcastColor.set(0x667788) changes it live
23
38
  - `particles: Record<string, WeatherParticleSystem>` The particle systems drawn now, by field: rain and snow when the table has them, plus what defineField() added. Example: `engine.weather.particles.rain.spec.speed = 30;`
24
- - `auto: boolean` Automatic weather on/off. Writing it takes effect like setAuto.
39
+ - `auto: boolean` Automatic weather on/off.
@@ -1,4 +1,4 @@
1
- # engine.weatherDraw — weatherDraw()
1
+ # engine.weatherDraw — weather(opts?: WeatherOptions)
2
2
 
3
3
  (experimental) Weather drawing (installed by weather(); sky is optional): rain / snow particle systems, lightning flash, the weather's effect on sun, fog and sky
4
4
 
package/docs/api/world.md CHANGED
@@ -9,7 +9,7 @@ World data (world() module): things that must be saved, survive level changes an
9
9
  - `world.idOf(obj: any) → string | null` — (experimental) The id of the record whose model contains obj (obj itself or one of its parents is a built model), else null. A ray hit on a model names its record this way. Example: `const h = engine.pick(0, 0); const id = h && engine.world.idOf(h.object);`
10
10
  - `world.get(id: string) → WorldRecord | undefined` — Get a record by id (undefined if missing, like a Map)
11
11
  - `world.set(id: string, patch: Record<string, any>) → WorldRecord` — Merge fields into a record and emit the world:change event; a position in patch also moves it. Returns the record. For discrete changes (chest opened, growth stage, picked up); if present has show, it is re-evaluated after the change. id / kind cannot be changed. Example: `engine.world.set('crate_1', { opened: true })`
12
- - `world.move(id: string, position: any)` — Move a record (no event; use it in simulate for things that move every step); still saved (saves diff against content). The model of a positionFrom 'record' (default) record follows this frame; to do something else with the position in presentation, compare in update. Example: `engine.world.move(rec.id, { x: rec.position.x + 1, z: rec.position.z })`
12
+ - `world.move(id: string, position: any)` — Move a record (no event; use it in simulate for things that move every step); still saved (saves diff against content). The model of a positionFrom 'record' (default) record follows this frame; to do something else with the position in presentation, compare in update. On a live character (the player, an NPC with a model) this is its placeAt: the character owns its position, so it goes there and the record says where it stands. A seated rider gets out to go there (placeAt ends a ride); a write equal to where it sits only follows the seat. Example: `engine.world.move(rec.id, { x: rec.position.x + 1, z: rec.position.z })`
13
13
  - `world.remove(id: string)` — Remove a record (its model is torn down too) and emit the world:remove event. Does nothing if the id does not exist. Removing an initial record is saved, so it stays gone after loading
14
14
  - `world.query(opts?: { kind?, near?, radius?, where?, zone? }) → WorldRecord[]` — Query records; returns an array. With near only nearby cells are scanned and results are sorted nearest first (radius defaults to 30 m); where filters further. For neighbor queries every step use forEachNear. Example: `engine.world.query({ kind: 'zombie', near: engine.player, radius: 30, where: z => !z.dead })`
15
15
  - `world.forEachNear(center: any, radius: number, fn: (rec, d2) => void)` — Call fn(rec, d2) for each record within radius meters (horizontal distance) of center; d2 is the squared distance. Unsorted, no allocation: use it for per-step neighbor queries (hundreds of zombies avoiding each other). Don't add / remove / move in the callback (moving into a cell not yet visited visits it again): record the change and apply it after the loop. Example: `engine.world.forEachNear(rec.position, 5, (o, d2) => { if (o !== rec && o.kind === 'zombie') n++; })`
@@ -28,7 +28,7 @@ The canvas is the one you gave `createEngine({ canvas })`, also `engine.renderer
28
28
  - The comments in `main.js` list further gameplay modules you can add; usage is in `../api/<module>.md`.
29
29
  - To change the starting point of new games, edit the real files in `packages/tools/templates/game/` (`templates/openworld/` for `--open-world`).
30
30
  - `DESIGN.md` is a form to fill in with the game's design, `STATUS.md` holds progress, and `CLAUDE.md` holds the working rules, a table cut from AI.md and the reading order.
31
- - There is no `tests/`: when `tests/specs/` does not exist, `npm test -w games/my-game` runs a smoke test automatically.
31
+ - There is no `tests/`: a smoke test runs until you add `tests/specs/`.
32
32
 
33
33
  ## 1. Creating the files by hand (to learn what each file is, or when the template doesn't fit)
34
34
  | File | Content |
@@ -60,7 +60,7 @@ The template's `tsconfig.json` checks the game files only (`checkJs`), with `lib
60
60
  `games/my-game/main.js`: the opening lines are written out once, in [recipe 63](63-third-person-start.md) §1 (the blank template's `main.js` has the same opening with `world(), content(), settings()` and the camera placed by hand). What an open-world game with a few gameplay modules changes in it:
61
61
  ```js
62
62
  // my-game: ... (this first comment line appears in the file table of GAMEMAP.md)
63
- // The opening stays as in recipe 63 §1: createEngine({ canvas, lights: false, ui, saveKey, bindings }), createPicture(engine) after engine.use,
63
+ // The opening stays as in recipe 63 §1: createEngine({ canvas, lights: false, ui, saveKey, bindings }), engine.use(createPicture()) after engine.use,
64
64
  // Object.assign(window, { engine, picture }) (tests, screenshots and the console rely on it), await engine.start().
65
65
  import { presets, openWorld, interactions, dialogue, inventory, pickups, quests, content } from 'threedog';
66
66
  import { terrainPreset } from '@threedog/terrain-noise'; // optional terrain generator (nor a world shape)
@@ -121,7 +121,7 @@ refuse to guess: `createPlayer()` throws `[player-control]` without `control`, `
121
121
  `openWorld()` throws `[open-world-camera]` without `camera`. The core key table holds only movement and menu confirm / cancel; run, jump and interact
122
122
  keys come from the game. `presets` holds named option objects a game picks on purpose; each only bundles options you could write yourself, so spread
123
123
  and override:
124
- ```js
124
+ ```js fragment
125
125
  import { presets, weather, calendar, sky, followCamera, interactions } from 'threedog';
126
126
  engine.use(calendar(presets.calendar.fourSeasons), sky(), weather({ ...presets.weather.temperate, autoPool: ['clear', 'rain'] }), followCamera(presets.camera.overShoulder));
127
127
  engine.use(interactions({ ...presets.interactions.facing })); // nearest / facing / aim, each with E
@@ -99,8 +99,7 @@ The behavior name and `mind` (the behavior's parameters and memory) are in the N
99
99
  carries on with the new behavior. A wrong behavior name throws and lists the registered ones. NPCs in content can also write `behavior` + `mind`
100
100
  directly (see the cat above); to change behavior at runtime use `npc.setBehavior`.
101
101
 
102
- **An enemy that chases the player**: the `chase` behavior below is the example; in `near`, after your own `character.move`, call
103
- `engine.npcs.avoid.push(rec, npc.character, dt)` once so several enemies don't pile into one clump (see "Avoidance" below). Things that are not NPCs
102
+ **An enemy that chases the player**: the `chase` behavior below is the example; the push in "Avoidance" below keeps several from piling into one clump. Things that are not NPCs
104
103
  (monsters, crops) are written as world data, see recipe 18 section 5.
105
104
 
106
105
  To write your own: `engine.npcs.behavior(name, { near(rec, dt, npc), far(rec, dt) })`, with the same rules as `world.simulate`: `near` is called once
@@ -136,7 +135,7 @@ engine.npcs.avoid.set(false); // turn off (ghosts, cro
136
135
  ```
137
136
  - Far away (no model) NPCs are simulated from data without per-NPC avoidance; a few steps after a model is built on approach they get pushed apart.
138
137
  - `nav({ crowd: true })` replaces this push with Recast crowd agents: they route around obstacles along the navmesh but do not guarantee identical
139
- results after a load. The push routes around nothing and only keeps NPCs from overlapping. For replays and saves use the push; for crowds going
138
+ results after a load, and the player is no agent, so crowd NPCs walk through the player. The push routes around nothing and only keeps NPCs from overlapping. For replays and saves use the push; for crowds going
140
139
  around big obstacles use crowd.
141
140
  - Behaviors you write are not avoided automatically: after your own `character.move`, call `engine.npcs.avoid.push(rec, npc.character, dt)` once
142
141
  (inside `near`, before writing back to the data).
@@ -153,7 +152,7 @@ A walk holds the character's control on layer `script` ([57-control](57-control.
153
152
  walk, and an escort quest that wants the same NPC takes control itself (`engine.control.take(npc, { owner: 'escort', step })`) instead of
154
153
  editing its record.
155
154
 
156
- ```js
155
+ ```js fragment
157
156
  const guard = new Character(engine, { rig: { root: myGuardMesh } });
158
157
  engine.add(guard.root);
159
158
  guard.placeAt(post);
@@ -5,12 +5,12 @@
5
5
 
6
6
  ## Pick and count: meshes you built, no bag
7
7
  Shells on a beach, four kinds of flowers, letters to collect: things the player takes and a number goes up. `interactions()`, `hud()` and a key (`createEngine({ bindings: presets.bindings.interact })`: E) are enough:
8
- ```js
8
+ ```js fragment
9
9
  engine.hud.counter('shells', { label: 'Shells', value: 0, max: 4 }); // at setup, not on session:start
10
10
  shells.forEach((shell, i) => engine.interactions.add(shell, { id: `shell-${i}`, label: 'Pick up', once: true, counter: 'shells', onUse: () => engine.audio.sfx('pick') }));
11
11
  ```
12
- `once` hides the mesh after a use (`onUse` returning `{ ok: false }` leaves it); `counter` adds 1 through `engine.hud.bump(name, n)`, and does nothing without
13
- `hud()`. Both are saved and go back on a new game. The save knows a thing by `id`, else `mesh.name`: development throws when it has neither, or shares one with another once item.
12
+ `once` hides the mesh after a use (`onUse` returning `{ ok: false }` leaves it; an async `onUse` is judged when it settles, and a throw leaves it too); `counter` adds 1 through `engine.hud.bump(name, n)`, and does nothing without
13
+ `hud()`. Both are saved and go back on a new game. The save knows a thing by `id`, else `mesh.name`: `interactions.add` throws when it has neither, or shares one with another once item.
14
14
  A hidden mesh is only hidden: a collider it had is yours to remove in `onUse`. To add up without a thing to take, call `engine.hud.bump('score', 10)` yourself.
15
15
 
16
16
  | Use | When |
@@ -50,15 +50,13 @@ Remember to `import items, { startItems } from './items.js'` and `import pickups
50
50
 
51
51
  **Data and stable ids**: each pickup is a plain `kind: 'pickup'` record in `engine.world` (needs `world()`, which `openWorld()` includes); the model
52
52
  is built only near the player and removed when far.
53
- Id: if you write an `id` it is used; otherwise it is `pickup:<item>:<index in the pickups array>`, the same every time for the same content, and
54
- distinguishes the same item placed at the same coordinates. **Write an `id` if the content will keep changing** (inserting a new one in the middle
55
- shifts the later indices).
53
+ Id: write an `id`; without one it is `pickup:<item>:<index in the pickups array>`, which moves when an entry is inserted above it (recipe 30, "Ids").
56
54
  When picked up, the record is removed from world; one with `respawn` stays and gets an `until` (calendar seconds); while waiting it has no model,
57
55
  and at that time (also when far away with no model) it returns to the ground. Pickups in content are initial data, like props (recipe 18 §4).
58
56
  `engine.world.remove(id)` deletes one directly.
59
57
 
60
58
  ## 2. In code (dynamic drops, custom models, instant effects)
61
- ```js
59
+ ```js fragment
62
60
  engine.inventory.define('gem', { name: 'Gem', icon: '💎', color: 0x66ccff }); // shape: model: 'gemModel' (an asset name), else an asset named 'pickup:gem' / 'pickup', else a gray box (spawn { mesh } puts one object of the game's own down instead)
63
61
  const gem = engine.pickups.spawn(engine.player.position, { give: 'gem', count: 1 }); // returns a handle; gem.remove() deletes data and model together
64
62
  // opts.id writes a stable id (spawning again with the same id reuses the existing one)
@@ -82,10 +80,12 @@ I.define('sword', { name: 'Sword', stack: 1 });
82
80
  const { key } = I.add('sword', 1, { data: { durability: 80, level: 3 } }); // 'sword#7' (add returns { ok: false, code: 'full' } when it does not fit)
83
81
  // change it inside an op or fixed step (data objects are frozen: always pass a new one; the key stays the same)
84
82
  const s = I.get(key); I.setData(key, { ...s.data, durability: s.data.durability - 1 });
83
+ I.container('chest-1', { capacity: 8 });
85
84
  I.transfer('player', 'chest-1', key); // exactly this sword; it keeps its data and key
86
- I.remove(key); // exactly this one; I.remove('sword') takes plain ones first, then the oldest
87
- I.add('tomato', 5, { data: { quality: 2 } }); // stackable: equal data joins the same entry
88
- I.setData('tomato#4', { quality: 1 }, 2); // only 2 of that stack change: they split off under a new key (returned)
85
+ I.container('chest-1').remove(key); // exactly this one; I.remove('sword') takes plain ones first, then the oldest
86
+ I.define('tomato', { name: 'Tomato' });
87
+ const t = I.add('tomato', 5, { data: { quality: 2 } }); // stackable: equal data joins the same entry
88
+ I.setData(t.key, { quality: 1 }, 2); // only 2 of that stack change: they split off under a new key (returned)
89
89
  ```
90
90
  Data and keys are saved with the container. Which piece a player means is chosen by key (a click on a row of `list()`), so ops take `item` as an id or a key.
91
91
 
@@ -103,7 +103,7 @@ Both act on `ctx.actor`'s container (`'player'` by default).
103
103
 
104
104
  **Replace an item when the bag is full**: `inventory.trade` takes A and gives B as one all-or-nothing step (it checks that B fits once A is gone), and
105
105
  can be undone.
106
- ```js
106
+ ```js fragment
107
107
  const r = engine.ops.run('inventory.trade', { take: 'rusty_key', give: 'gold_key' }); // also takeN / giveN; take may be an entry key ('sword#3')
108
108
  if (!r.ok) say(r.code); // 'notEnough' (A missing) | 'full' (B does not fit even after A leaves)
109
109
  engine.ops.undo('inventory.trade', { take: 'rusty_key', give: 'gold_key' }, r.value); // gives A back (with its data), takes B away
@@ -69,6 +69,8 @@ engine.quests.start('slimes3');
69
69
  engine.vars.bump('slimes'); // each time one is defeated
70
70
  engine.events.on('quest:done', ({ id }) => { /* quest completed */ }); // there are also quest:start, quest:step, quest:part and quest:fail
71
71
  ```
72
+ A failed reward (full bag, refused `{ op }`, a function returning `{ ok: false, code }`) still finishes the quest and fires `quest:unpaid`. Items that did not fit stay owed (`quests.list()`, saved) until there is room, unless the game decides itself with `onUnpaid` (effect words, or `(e, answer) => ...`).
73
+
72
74
  To turn off automatic markers: `hud({ questMarkers: false })`. To add a marker by hand: `const m = engine.hud.marker('gate', { label: 'Gate' }); m.remove();`;
73
75
  content effects can add them too: `{ marker: 'gate' }` / `{ clearMarker: 'gate' }`. A counter in the screen corner:
74
76
  `engine.hud.counter('slimes', { label: 'Slimes', value: 2, max: 3 })`; `anchor: 'top-right'` (or `top`, `bottom`, `bottom-left`...) puts a counter
@@ -47,7 +47,7 @@ during development and say how to fix it).
47
47
  Inserting a new entry in the middle shifts the later indexes, so moves / deletions in old saves no longer match. **Give an `id` to any prop whose
48
48
  content may still change.**
49
49
  Get them in code, move or delete them (all saved with the game):
50
- ```js
50
+ ```js fragment
51
51
  engine.world.query({ kind: 'prop' }); // all prop data { id, position, model, rot, scale, collide ... }
52
52
  engine.world.move('prop:rock:3', { x: 12, z: -4 }); // move: model, collision and ray registration follow; height is recomputed from the ground
53
53
  engine.world.set('prop:rock:3', { rot: 1.2, scale: 1.5 }); // change rotation / size
@@ -70,7 +70,7 @@ If a model fails to generate, world reports it once in the console, does not blo
70
70
  ## 2. Large code-generated models and baking
71
71
  Big things assembled in code, such as a city block or a whole house, are written as a function, registered in the manifest and fetched by name. During
72
72
  development they are cached automatically (.threedog/cache) and recomputed when the code changes:
73
- ```js
73
+ ```js fragment
74
74
  import { buildBlock } from './block.js';
75
75
  engine.assets.manifest({ models: { 'city-block': buildBlock } }); // the function returns an Object3D or a geometry
76
76
  const block = await engine.assets.model('city-block');
@@ -106,6 +106,7 @@ it by name, and use the name everywhere. Later a `.glb` registered under the sam
106
106
  `receiveShadow` on any of its meshes keeps its own flags (a rug that receives but does not cast); one that set none casts and receives
107
107
  everywhere. The same rule holds for `assets.model(name)` and content props.
108
108
  - It runs once per name + params; every placement is a clone sharing geometry and materials (`engine.assets.model(name)` and content props alike).
109
+ - Who frees what: a copy from `assets.model` holds its original until `engine.remove`. `release` and `trim` skip what a copy still holds, and `describe().assets` counts `leases` and `waiting`. A generated model stays cached for good, and a content prop's prototype keeps one copy.
109
110
  - Cache key = name + the generator's source (its file and imports) + params + `engine.assets.palette`. Values it reads from outer variables must go in
110
111
  `params`, or a change keeps the stale model. In dev a build slower than `assets.cacheMinMs` (20 ms) is stored as GLB in `.threedog/cache` and
111
112
  read back next time; `npm run bake` writes the same GLB to `public/models/baked/` (section 2). Neither is needed: unbaked generators run in the
@@ -148,7 +149,7 @@ Objects your code makes and adds (`engine.scene.add(mesh)`, `engine.add(mesh)`,
148
149
  `THREE.Raycaster`, scene walks and material swaps see exactly the meshes you made. Many static copies of your own mesh (fence posts, tiles, coins)
149
150
  opt in with one flag on the root you add, set before adding it (or call `engine.batching.refresh(obj)` after). In dev, `engine.inspect.perf()` and
150
151
  `describe().perf.batching.hint` say so when many identical meshes of yours draw one by one.
151
- ```js
152
+ ```js fragment
152
153
  for (const p of postSpots) { const m = new THREE.Mesh(postGeo, woodMat); m.position.copy(p); m.userData.batch = true; engine.scene.add(m); }
153
154
  ```
154
155
  ```js
@@ -186,9 +187,8 @@ props repeated across the level), think through the parts and their proportions
186
187
  - **Tune numbers live**: declare `params` (section 2a); the dev panel's models folder (`?panel=1`) shows them and every drag rebuilds the
187
188
  copies (`engine.assets.setParams(name, values)`). "write back", then `threedog tune write` (dry run; `--apply`) puts the values into the
188
189
  schema's `default` where the model is registered.
189
- - **Review all at once**: `?gallery=1` on the dev page, or `threedog gallery`, puts every registered model and texture on a turntable under three neutral lights;
190
- `--shots` writes one page of pictures, `--mode silhouette,value` adds outline and grayscale shots with measurements in `index.json` (`fill`, `boxFill`, `aspect`,
191
- luminance `p5` / `p50` / `p95`). They are measurements, not grades: a shape the player must recognize at play distance usually still reads as a silhouette, and a
190
+ - **Review all at once**: `?gallery=1` on the dev page, or `threedog gallery`, puts every registered model and texture on a turntable;
191
+ `--shots` writes one page of pictures, `--mode silhouette,value` adds outline and grayscale shots with measurements (`../COMMANDS.md`). They are measurements, not grades: a shape the player must recognize at play distance usually still reads as a silhouette, and a
192
192
  narrow p5-p95 spread means hue carries the form; compare assets that must be told apart with each other rather than with a fixed number.
193
193
  - **Compare with the reference**: `threedog picture compare <reference.png> .threedog/gallery/<name>-midday.png --out diff.png` gives numbers
194
194
  for one asset against its reference crop, the same way as for a whole screenshot (`recipes/35-picture-from-reference.md`).
@@ -207,7 +207,7 @@ the DESIGN.md "Asset sources" row, and every source ends up the same way, as a n
207
207
 
208
208
  **Does it fit?** Every library entry has one card, measured at `lib add` (needs, provides, shared three.js values it writes, size, style, usage); `threedog lib list <word> --card` prints it. Tag a style with `--style` in your own words: only tags can say that, and two entries with no tag in common are reported. After pulling several pieces, `threedog lib check` says what is missing and what clashes. Nothing is forced: fix a clash in your copy, or leave a note you meant.
209
209
 
210
- **Your own library.** `threedog lib add <file|folder|exportName> -w earlier-game` keeps a piece of a finished game in `~/.threedog/library`, `threedog lib list [words]` searches it, `threedog lib pull <name>` copies it into this game (code goes to `plugins/<name>/`, plus a wiring file `plugins/<name>.js`); flags in `../COMMANDS.md`. Look here before writing an effect from scratch. A pulled entry is a copy with no link back and no update: change it to fit this game rather than keeping it as it was, or every game ends up looking alike.
210
+ **Your own library.** `threedog lib add <file|folder|exportName> -w earlier-game` keeps a piece of a finished game in `~/.threedog/library`, `threedog lib list [words]` searches it, `threedog lib pull <name>` copies it into this game; flags and where each kind lands in `../COMMANDS.md`. Look here before writing an effect from scratch. A pulled entry is a copy with no link back and no update: change it to fit this game rather than keeping it as it was, or every game ends up looking alike.
211
211
 
212
212
  **Rules (correctness and licensing):**
213
213
  - Read the license of every asset you did not make, on the page you downloaded it from, before it goes into the game; a library can mix
@@ -246,7 +246,7 @@ Every asset load is a task in `engine.loading` (so are module init / `isReady`,
246
246
  phase (`queued` → `download` → `decode` → `upload` / `build` → `done` | `failed`), progress, the error (file, HTTP status, a texture or `.bin` the
247
247
  model references but could not load) and its source (which manifest, which path, file version, animation names).
248
248
  Decide per entry what a failure means:
249
- ```js
249
+ ```js fragment
250
250
  engine.assets.manifest({
251
251
  name: 'forest', // the source label in engine.loading (default 'manifest#1')
252
252
  models: {
@@ -296,6 +296,6 @@ engine.assets.manifest({ name: 'ui-fonts', base: '/fonts/', fonts: { pixel: 'pix
296
296
  - Baking: `npm run bake` prints each item's size; related test `threedog test 烘焙`. To look at the picture: `npm run shot -- / --pos x,z`.
297
297
 
298
298
  ## 5. Deleting objects
299
- `engine.remove(obj)` deletes an object and frees its GPU memory; `engine.detach(obj)` only takes it off for a while (add it back with `engine.add`).
299
+ `engine.remove(obj)` deletes an object and frees its GPU memory; `obj.removeFromParent()` only takes it off for a while (add it back with `engine.add`).
300
300
  Don't call `obj.removeFromParent()` or `scene.remove()` on meshes you built: their geometry and materials would leak.
301
301
  (`thing.remove` (`40-scene.md`) deletes a registered object so that an undo can bring it back; `engine.remove` is final.)
@@ -84,18 +84,19 @@ call `after` in code.
84
84
 
85
85
  ```js
86
86
  import { parseClock, formatClock } from 'threedog';
87
+ const lamp = new THREE.PointLight();
87
88
 
88
89
  // Time-window switch: lamps on from 18:00 to 06:00 (crosses midnight). On registration, at start, after loading a save, applyState, or turning the time back, it aligns to the current time immediately (returns a handle; lampHours.remove() cancels)
89
90
  const lampHours = engine.calendar.between('18:00', '06:00', { on: () => lamp.visible = true, off: () => lamp.visible = false });
90
91
 
91
92
  // An event when a clock time is crossed (an "action" once per day): open the market at 12:00
92
- engine.calendar.at('12:00', day => market.open(), { days: [1, 3, 5] }); // only on days 1, 3, 5; a function also works: day => day % 7 === 6
93
+ engine.calendar.at('12:00', day => engine.vars.bump('marketDays'), { days: [1, 3, 5] }); // only on days 1, 3, 5; a function also works: day => day % 7 === 6
93
94
 
94
95
  // After how long: pass an event name to make it saveable (still fires after loading a save); a function cannot be saved
95
96
  engine.clock.after(120, 'bread:ready', { data: { oven: 1 } });
96
- engine.events.on('bread:ready', ({ oven }) => engine.inventory?.add('bread', 1));
97
+ engine.events.on('bread:ready', ({ oven }) => engine.vars.bump('bread'));
97
98
 
98
- engine.clock.every(30, () => spawnBird()); // every 30 calendar seconds (not 30 clock seconds)
99
+ engine.clock.every(30, () => engine.vars.bump('birds')); // every 30 calendar seconds (not 30 clock seconds)
99
100
  engine.calendar.daily(day => console.log('day', day)); // every day at 00:00
100
101
  engine.calendar.onSeason('winter', () => engine.weather?.set('snow', { seconds: 20 })); // needs seasons (presets.calendar.fourSeasons) and a 'snow' weather (presets.weather.temperate)
101
102
 
@@ -120,7 +121,7 @@ For "which time" or "has this been done" in a story, use `engine.vars.bump / set
120
121
 
121
122
  ## 1b. Smooth movement between fixed steps: `engine.stepBlend`
122
123
  The game runs in fixed steps and the screen draws at its own rate, so most frames fall between two steps. Something you move in `onFixed` and draw at its latest position jumps from step to step and stutters, the more so on a fast screen. Keep where it was before the step and where it is now, and draw between them. `engine.stepBlend` says how far this frame is from the last step to the next, from 0 to 1:
123
- ```js
124
+ ```js fragment
124
125
  const body = { x: 0, lastX: 0 };
125
126
  engine.onFixed(dt => { body.lastX = body.x; body.x += speed * dt; }); // the rules read body.x
126
127
  engine.onFrame(() => { mesh.position.x = body.lastX + (body.x - body.lastX) * engine.stepBlend; }); // the picture only
@@ -148,7 +149,7 @@ What catches up, and how:
148
149
  - Input is locked and gameplay frozen for the whole skip (keys pressed during the fade do nothing). With `fade: 0` (default) the time has moved when
149
150
  `skip` returns; with a fade the Promise resolves after the fade in, which needs frames (in a halted test keep calling `engine.step`).
150
151
  - A stopped calendar (`clock.rate` 0) skips as if at 1x. The jump itself is the op `time.skip { seconds }` (logged and replayable; it refuses `seconds <= 0`).
151
- - A module that keeps its own time implements the hook `skip(dt, e, done)` (called once per segment; `done` on the last one).
152
+ - A module that keeps its own time implements the hook `skip` (recipe 49, item 3).
152
153
 
153
154
  ### Order inside one frame
154
155
  Each rendered frame runs: input poll -> the fixed steps due (`commits` applied first, then `onFixed`, module `fixed` hooks, `onFixed` `{ phase: 'late' }`, clock timers) -> `onFrame`
@@ -171,4 +172,3 @@ When a game has several systems, a default that keeps this order in one place: o
171
172
  or a settling physics body always differs: ignore those parts and read the rest. It leaves the world at the stepped state, so run it on a scratch playthrough or in a test. A diff usually means a
172
173
  module with its own time lacks a `skip` hook. `await engine.checkSave()` does the same for save -> load (a diff names a save part whose `load` does not restore what `save` wrote).
173
174
  - Why did it fire (or not)? `engine.events.traceSize = 200` records each event with the event or op that caused it: `events.trace('item:add').at(-1).chain`. Failed ops, sight queries and NPC state changes are entries too (with `code`); `events.note(name, { obj, code, data })` adds your own and `events.traceFocus(id)` makes one object verbose (the ring is bounded; size 0 costs nothing). Details: recipe 23 section 12.
174
- - Related tests: `threedog test 游戏时钟 SKIP`.