threedog 1.0.1 → 1.2.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 (364) hide show
  1. package/CHANGELOG.md +90 -0
  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 +178 -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 +16 -6
  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 +5 -5
  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 +46 -27
  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 +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  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 +16 -11
  103. package/docs/COMMANDS.md +31 -33
  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 +28 -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/cameraRig.md +2 -2
  112. package/docs/api/characters.md +10 -8
  113. package/docs/api/collision.md +6 -4
  114. package/docs/api/engine.md +16 -16
  115. package/docs/api/events.md +3 -2
  116. package/docs/api/ground.md +6 -5
  117. package/docs/api/hud.md +4 -2
  118. package/docs/api/input.md +5 -5
  119. package/docs/api/particles.md +2 -1
  120. package/docs/api/photo.md +3 -0
  121. package/docs/api/post.md +7 -4
  122. package/docs/api/quests.md +2 -2
  123. package/docs/api/rays.md +1 -2
  124. package/docs/api/saves.md +7 -7
  125. package/docs/api/settings.md +2 -2
  126. package/docs/api/tools.md +3 -1
  127. package/docs/api/vars.md +1 -1
  128. package/docs/api/vegetation.md +4 -2
  129. package/docs/api/world.md +1 -1
  130. package/docs/recipes/01-new-game.md +16 -17
  131. package/docs/recipes/02-npc.md +22 -18
  132. package/docs/recipes/03-items-pickups.md +37 -35
  133. package/docs/recipes/04-quests.md +15 -10
  134. package/docs/recipes/05-props-bake.md +101 -95
  135. package/docs/recipes/06-clock-events.md +28 -28
  136. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  137. package/docs/recipes/08-weather-sky.md +52 -64
  138. package/docs/recipes/09-materials-lights-models.md +26 -17
  139. package/docs/recipes/10-blender-level.md +15 -10
  140. package/docs/recipes/11-vehicles.md +12 -7
  141. package/docs/recipes/12-navmesh.md +44 -26
  142. package/docs/recipes/13-animation.md +56 -45
  143. package/docs/recipes/14-custom-module.md +21 -18
  144. package/docs/recipes/15-perf.md +61 -55
  145. package/docs/recipes/16-dev-bridge.md +23 -33
  146. package/docs/recipes/18-world.md +36 -42
  147. package/docs/recipes/19-shooting-picking.md +20 -15
  148. package/docs/recipes/20-content-actions-save.md +48 -56
  149. package/docs/recipes/21-camera.md +45 -54
  150. package/docs/recipes/22-shop-gold.md +12 -7
  151. package/docs/recipes/23-ops.md +25 -23
  152. package/docs/recipes/26-ui-parts.md +67 -47
  153. package/docs/recipes/27-net.md +12 -7
  154. package/docs/recipes/28-terrain.md +24 -21
  155. package/docs/recipes/29-grid.md +32 -27
  156. package/docs/recipes/30-templates.md +21 -20
  157. package/docs/recipes/31-audio.md +39 -22
  158. package/docs/recipes/32-action-game.md +19 -14
  159. package/docs/recipes/33-stream-sources.md +15 -11
  160. package/docs/recipes/34-environment-lighting.md +126 -70
  161. package/docs/recipes/35-picture-from-reference.md +8 -8
  162. package/docs/recipes/36-ground-plants.md +27 -21
  163. package/docs/recipes/40-scene.md +19 -28
  164. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  165. package/docs/recipes/44-water-weather-hooks.md +34 -31
  166. package/docs/recipes/45-cascaded-shadows.md +35 -26
  167. package/docs/recipes/46-blender-art-route.md +6 -1
  168. package/docs/recipes/49-game-module-contract.md +13 -8
  169. package/docs/recipes/50-own-renderer.md +6 -2
  170. package/docs/recipes/51-capability-catalog.md +15 -8
  171. package/docs/recipes/52-around-the-picture.md +34 -32
  172. package/docs/recipes/53-ground-up-close.md +6 -1
  173. package/docs/recipes/55-mods-time-wrap.md +27 -19
  174. package/docs/recipes/56-webgpu-tsl.md +74 -43
  175. package/docs/recipes/57-control.md +18 -13
  176. package/docs/recipes/58-input.md +26 -16
  177. package/docs/recipes/59-depth-post-effects.md +8 -3
  178. package/docs/recipes/60-judge-the-picture.md +9 -8
  179. package/docs/recipes/61-deploy.md +5 -0
  180. package/docs/recipes/62-picture-code.md +70 -79
  181. package/docs/recipes/63-third-person-start.md +47 -45
  182. package/docs/recipes/64-particles.md +22 -10
  183. package/docs/recipes/65-swarm.md +18 -13
  184. package/docs/recipes/66-common-tasks.md +38 -35
  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/GAMEMAP.md +3 -3
  189. package/examples/perf-island/picture/lights.js +2 -1
  190. package/examples/plain-picture/GAMEMAP.md +1 -1
  191. package/examples/rc2d/GAMEMAP.md +1 -1
  192. package/examples/styletest/GAMEMAP.md +2 -2
  193. package/examples/styletest/main.js +1 -1
  194. package/examples/techniques/interior-light/README.md +3 -3
  195. package/examples/techniques/interior-light/interiorLight.js +2 -4
  196. package/examples/techniques/interior-light/picture/lights.js +2 -1
  197. package/examples/techniques/modular-building/picture/lights.js +3 -1
  198. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  199. package/examples/techniques/procedural-animation/README.md +1 -1
  200. package/examples/techniques/procedural-animation/main.js +1 -1
  201. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  202. package/examples/world/GAMEMAP.md +2 -3
  203. package/examples/world/art/humanoid.js +1 -1
  204. package/examples/world/main.js +6 -3
  205. package/index.d.ts +2 -2
  206. package/llms.txt +101 -0
  207. package/modules/ambience/Ambience.js +21 -5
  208. package/modules/calendar/index.js +9 -5
  209. package/modules/calendar/schedule.js +23 -8
  210. package/modules/camera/FirstPersonCamera.js +3 -1
  211. package/modules/camera/FollowCamera.js +10 -5
  212. package/modules/camera/RtsCamera.js +4 -3
  213. package/modules/camera/common.js +70 -8
  214. package/modules/camera/contract.js +1 -1
  215. package/modules/characters/Character.js +16 -10
  216. package/modules/characters/NPC.js +31 -19
  217. package/modules/characters/assetModel.js +14 -9
  218. package/modules/characters/astar.js +6 -1
  219. package/modules/characters/contract.js +2 -2
  220. package/modules/characters/index.js +34 -22
  221. package/modules/characters/movers/manual.js +1 -1
  222. package/modules/characters/movers/rapier.js +17 -2
  223. package/modules/characters/movers/simple.js +1 -1
  224. package/modules/characters/movers/support.js +16 -7
  225. package/modules/characters/npcAvoid.js +2 -2
  226. package/modules/characters/npcSim.js +3 -2
  227. package/modules/characters/pathAsync.js +24 -8
  228. package/modules/characters/pathJob.js +1 -1
  229. package/modules/characters/player.js +10 -9
  230. package/modules/characters/playerStrings.js +5 -5
  231. package/modules/characters/proceduralRig.js +5 -5
  232. package/modules/characters/useModel.js +6 -0
  233. package/modules/characters/walkTo.js +1 -1
  234. package/modules/collision/Collision.js +29 -18
  235. package/modules/collision/grid.js +22 -4
  236. package/modules/content/index.js +3 -1
  237. package/modules/content/loader.js +1 -1
  238. package/modules/content/models.js +82 -33
  239. package/modules/content/props.js +2 -1
  240. package/modules/content/rules.js +11 -5
  241. package/modules/content/templates.js +3 -3
  242. package/modules/content/words.js +2 -2
  243. package/modules/debug/DebugPanel.js +9 -9
  244. package/modules/flow/index.js +9 -6
  245. package/modules/gameplay/Dialogue.js +34 -20
  246. package/modules/gameplay/Interactions.js +19 -15
  247. package/modules/gameplay/Inventory.js +9 -4
  248. package/modules/gameplay/Quests.js +12 -10
  249. package/modules/gameplay/pickups.js +23 -11
  250. package/modules/grid/index.js +1 -1
  251. package/modules/grid/preview.js +2 -2
  252. package/modules/grid/tiles.js +1 -1
  253. package/modules/hlod/index.js +4 -1
  254. package/modules/hud/index.js +47 -10
  255. package/modules/hud/parts.js +28 -9
  256. package/modules/level/geometry.js +8 -3
  257. package/modules/level/index.js +10 -5
  258. package/modules/level/load.js +4 -2
  259. package/modules/lights/sources.js +1 -1
  260. package/modules/music/Music.js +22 -4
  261. package/modules/nav/index.js +20 -10
  262. package/modules/particles/Particles.js +31 -14
  263. package/modules/particles/effect.js +20 -5
  264. package/modules/particles/lit.js +72 -0
  265. package/modules/photo/Photo.js +72 -28
  266. package/modules/photo/pathTrace.js +106 -0
  267. package/modules/rigid/RigidBodies.js +23 -14
  268. package/modules/rigid/Vehicles.js +3 -13
  269. package/modules/rigid/sync.js +2 -1
  270. package/modules/settings/Settings.js +52 -20
  271. package/modules/settings/apply.js +23 -9
  272. package/modules/settings/sections.js +39 -6
  273. package/modules/settings/strings.js +2 -0
  274. package/modules/settings/view.js +19 -3
  275. package/modules/sky/dome.js +15 -3
  276. package/modules/sky/environment.js +28 -12
  277. package/modules/sky/fog.js +1 -1
  278. package/modules/sky/frame.js +6 -1
  279. package/modules/sky/shader.js +4 -3
  280. package/modules/sky/skyModule.js +8 -4
  281. package/modules/swarm/Swarm.js +1 -1
  282. package/modules/terrain/ChunkManager.js +61 -15
  283. package/modules/terrain/chunkJob.js +2 -2
  284. package/modules/terrain/index.js +20 -5
  285. package/modules/terrain/terrainEdit.js +8 -4
  286. package/modules/terrain/terrainTexture.js +4 -2
  287. package/modules/timeline/Timeline.js +4 -3
  288. package/modules/timeline/Tween.js +3 -0
  289. package/modules/timeline/letterbox.js +1 -0
  290. package/modules/triggers/index.js +36 -17
  291. package/modules/vegetation/Vegetation.js +81 -19
  292. package/modules/vegetation/densityMap.js +13 -8
  293. package/modules/vegetation/draw.js +147 -24
  294. package/modules/vegetation/groundChunks.js +20 -5
  295. package/modules/vegetation/index.js +3 -3
  296. package/modules/vegetation/modelGeometry.js +9 -4
  297. package/modules/water/Water.js +11 -8
  298. package/modules/weather/Weather.js +7 -2
  299. package/modules/weather/shaders.js +25 -5
  300. package/modules/weather/weatherDraw.js +20 -6
  301. package/modules/world/World.js +2 -1
  302. package/modules/world/index.js +2 -2
  303. package/modules/world/persist.js +6 -2
  304. package/modules/world/views.js +15 -2
  305. package/package.json +4 -1
  306. package/presets.js +5 -5
  307. package/render/PostFX.js +84 -41
  308. package/render/backend.js +137 -16
  309. package/render/cascades.js +3 -1
  310. package/render/cascades.tsl.js +2 -0
  311. package/render/daylight.js +7 -1
  312. package/render/detail.js +7 -4
  313. package/render/effects.js +27 -8
  314. package/render/fogLook.js +24 -0
  315. package/render/fuse.js +5 -2
  316. package/render/fx/detail.tsl.js +9 -7
  317. package/render/fx/index.js +7 -2
  318. package/render/fx/library.tsl.js +1 -0
  319. package/render/fx/lightShaft.tsl.js +114 -0
  320. package/render/fx/noise.tsl.js +25 -8
  321. package/render/fx/objectOrigin.tsl.js +39 -10
  322. package/render/fx/particles.tsl.js +23 -6
  323. package/render/fx/patchNodes.tsl.js +17 -12
  324. package/render/fx/pcss.tsl.js +51 -0
  325. package/render/fx/postWebGPU.tsl.js +89 -29
  326. package/render/fx/sky.tsl.js +3 -9
  327. package/render/fxNumbers.js +10 -4
  328. package/render/impostor.tsl.js +107 -0
  329. package/render/lighting.js +33 -1
  330. package/render/lightmap.js +42 -28
  331. package/render/lights.js +19 -3
  332. package/render/materials.js +6 -4
  333. package/render/mergeCommon.js +4 -1
  334. package/render/occlusion.js +14 -4
  335. package/render/patches.js +79 -41
  336. package/render/postRuns.js +32 -0
  337. package/render/postWebGL.js +97 -10
  338. package/render/probes.js +10 -14
  339. package/render/shaderErrors.js +2 -1
  340. package/render/shadowCache.tsl.js +33 -5
  341. package/render/shadows.js +42 -16
  342. package/render/slots.js +8 -5
  343. package/render/vertexInputs.js +52 -0
  344. package/types/core.d.ts +114 -46
  345. package/types/gameplay.d.ts +56 -23
  346. package/types/generated/core/audio/Audio.d.ts +27 -1
  347. package/types/generated/core/base/Random.d.ts +1 -1
  348. package/types/generated/core/input/Input.d.ts +6 -8
  349. package/types/generated/core/input/inputSeat.d.ts +1 -1
  350. package/types/generated/core/inspect/Budget.d.ts +26 -0
  351. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  352. package/types/generated/core/saves/Saves.d.ts +10 -7
  353. package/types/generated/core/saves/session.d.ts +8 -2
  354. package/types/generated/core/scene/Rays.d.ts +1 -3
  355. package/types/generated/modules/particles/Particles.d.ts +1 -1
  356. package/types/generated/modules/world/World.d.ts +2 -1
  357. package/types/generated/render/PostFX.d.ts +35 -9
  358. package/types/physics.d.ts +43 -11
  359. package/types/pixel.d.ts +1 -1
  360. package/types/tsl.d.ts +62 -1
  361. package/types/world.d.ts +12 -3
  362. package/ui/Focus.js +7 -5
  363. package/ui/Parts.js +1 -1
  364. package/ui/touchPart.js +6 -3
@@ -1,69 +1,74 @@
1
1
  # Performance investigation (F3, budget, profile, describe().perf)
2
2
 
3
- **In this recipe**: 1. Where things stand · 2. Set a budget · 3. Whose CPU is slow · 4. Common fixes · 4a. Less detail far away · 4b. Render scale · 5. Verify
3
+ > **Covers:** finding what makes the game slow, limits that warn, baselines, common fixes, less detail far away.
4
+ > **Use when:** the game is slow or you want limits that warn.
5
+ > **Shortest:** `createEngine({ budget: { drawCalls: 250, fps: 55 } })`, then `engine.budget.report()`.
6
+ > **Sections:** 1 Where things stand · 2 Set a budget · 2a Slower than before · 3 Whose CPU is · 4 Common fixes · 4a Less detail far · 4b Render scale and · 5 Verify once before
4
7
 
5
- Order: first use numbers to decide which category is over (frame rate? draw calls? CPU? startup?), then find who takes the most, and after changing,
6
- compare before/after with the same method.
7
- Which renderer measures: `threedog shot`, `perf`, `stress` and `gallery --shots` use the hardware GPU when headless can reach it (`threedog doctor` says whether it can; COMMANDS.md, `--gpu`). On a machine without one, ask the user to press F3 in the browser (bound by `createEngine({ bindings: { ...presets.bindings.debug } })`; the open-world template does).
8
+ Order: numbers first (which category is over: fps, draw calls, CPU, startup?), then who takes the most; after a change compare the same way (section 5).
9
+ Which renderer measures: `threedog shot`, `perf`, `stress` and `gallery --shots` use the hardware GPU when headless can reach it (`threedog doctor` says; `--gpu`). On a machine without one, ask the user to press F3 in the browser (bound by `createEngine({ bindings: { ...presets.bindings.debug } })`; the open-world template does).
8
10
  What this machine can carry: `threedog stress` (COMMANDS.md) prints where 16.7 / 33 ms are crossed for each kind of load. Turn the row for your target machine into `engine.budget` limits (section 2).
9
11
 
10
12
  ## 1. Where things stand
11
- - **One report with verdicts**: `engine.inspect.perf()` / `threedog inspect perf` (MCP `inspect` target `perf`): draw calls (shadow and post passes
12
- included), triangles, shader programs, texture memory (estimate: three.js does not report VRAM), JS ms per frame split by phase, compile stalls (frames
13
- in which three.js compiled new programs during play, worst ms; `startup.compileMs`), the costliest programs, and one line per budget, `✗` with the next
14
- call to make. Budgets are your `engine.budget` limits, else a reference (desktop, 60 fps; a reading aid, not enforced). Plain three.js:
15
- `renderer.info.render`, `renderer.info.programs.length`, `renderer.info.memory`. Textures in detail: `engine.inspect.materials()` (below).
16
- - **Which materials cost**: `engine.debug.view('shaderCost')` colors each material green -> red by its compiled program (fragment code lines + samplers,
17
- approximate; gray = not compiled yet); `engine.debug.view('overdraw')` shows pixels drawn many times over (bright = many layers: foliage cards, particles).
18
- `'off'` restores. For real GPU timings use `threedog capture` (Spector.js) or the browser's GPU profiler.
19
- - **Other view modes and the panel**: `debug.view('triggers')` shows hidden zones (`triggers({ debugColor, debugOpacity })` colors them); modules add their own modes (`engine.debug.defineView(name, { what, apply })`)
20
- and `engine.debug.viewModes()` lists every mode. `engine.debug.panel` is the F3 panel (dev builds; null without the `debug()` module).
21
- - **F3 panel** (`debug()` module; `openWorld` installs it in dev builds only, collapsed; the action `debugPanel` opens it, `presets.bindings.debug` binds F3): frame rate, CPU ms/frame, draw calls, triangles,
22
- chunks, vegetation instances, time of day; with a budget set also over-limit items and startup time.
13
+ - **One report with verdicts**: `engine.inspect.perf()` / `threedog inspect perf`: draw calls (shadow and post passes included), triangles, programs,
14
+ texture memory (estimate), JS ms per phase, the dearest modules, compile stalls during play (`startup.compileMs`), the costliest programs, one line per budget
15
+ (`✗` with the next call; your `engine.budget` limits, else a desktop 60 fps reference, not enforced). Plain three.js: `renderer.info`. Textures: `engine.inspect.materials()`.
16
+ - **Which materials cost**: `engine.debug.view('shaderCost')` colors materials green -> red by compiled program cost (gray = not compiled yet);
17
+ `engine.debug.view('overdraw')` shows pixels drawn many times over. `'off'` restores. Real GPU timings: `threedog capture` (Spector.js) or the browser's GPU profiler.
18
+ - **Other view modes**: `debug.view('triggers')` shows hidden zones (`triggers({ debugColor, debugOpacity })` colors them); modules add their own (`engine.debug.defineView(name, { what, apply })`);
19
+ `engine.debug.viewModes()` lists them.
20
+ - **F3 panel** (`engine.debug.panel`; `debug()` module, dev builds, null without it; action `debugPanel`): frame rate, CPU ms, draw calls, triangles,
21
+ chunks, vegetation instances, time of day; with a budget set, over-limit items and startup time.
23
22
  - **Text**: `engine.describe().perf` =
24
- `{ fps, cpuMs, cpu, apply, drawCalls, triangles, pixelRatio, budget, startup, stream, batching, jobs, commits, chunks?, vegetation? }`;
25
- the perf line of `npm run shot -- / --describe-only` (in headless mode fps/cpu are `-`; look at draw calls and triangles).
26
- - **CPU time of a frame**: `engine.inspect.perf().cpuMs` is the main-thread time from input to the end of the afterRender hooks; its `cpuPhases` splits it into
27
- `fixed` (input + fixed steps), `frame` (frame hooks, stream, jobs), `render` (draw submission, upload of new objects, shader compiles) and `afterRender`.
28
- GPU time is not in it. With `npm run perf -- --only=stream` the stream-in numbers below are measured for you.
29
- - **Applying background results** (`engine.budget.cost.report()`, also `describe().perf.apply` and the budget categories `applyBuildMs` ...): terrain
30
- chunks, vegetation, colliders and stream builds come back from workers or jobs and are paid for on the main thread, in stages: `transit` (worker round
31
- trip minus the worker's own compute: queueing and structured clone, an async wait, approximate), `build` (creating the three.js objects), `collider`
32
- (physics colliders), `upload` (extra render time of the frames that first draw new objects: GPU upload and shader compile, approximate), `stream`
33
- (the synchronous part of a `stream.add` build callback). Per stage: `n`, `totalMs`, `maxMs`, smoothed `frameMs`, and `bytes` (transit).
23
+ `{ fps, cpuMs, cpuFrames, cpu, apply, drawCalls, triangles, pixelRatio, gpuMemory, budget, notice, startup, stream, batching, jobs, commits, chunks?, vegetation? }`
24
+ (`cpuMs`: median of `cpuFrames` frames, as in `inspect.perf()` and F3; `cpu`: last frame by phase);
25
+ also the Perf line of `threedog shot --describe-only` (headless: fps and cpu are `-`).
26
+ - **One line when something is off**: `engine.budget.notice()` (`describe().perf.notice`, printed by `describeText`, `shot`, `verify`), null when all is fine:
27
+ `Perf: over budget drawCalls 312 (limit 250, +25%); slower than baseline: ...; spiky: ...; lowered automatically: reflections cheaper, resolution 1.5 -> 1.2 (...)`, against your own limits and baseline (2, 2a).
28
+ - **CPU time of a frame**: `engine.inspect.perf().cpuMs`, main thread from input to the afterRender hooks (no GPU time); `cpuPhases` splits it:
29
+ `fixed` (input + fixed steps), `frame` (frame hooks, stream, jobs), `render` (draw submission, uploads, shader compiles), `afterRender`.
30
+ `npm run perf -- --only=stream` measures the stream-in numbers below.
31
+ - **Applying background results** (`engine.budget.cost.report()`, `describe().perf.apply`, budget categories `applyBuildMs` ...): what the main thread
32
+ pays for chunks, vegetation, colliders and stream builds, in stages `transit` (worker round trip minus its compute, approximate), `build` (three.js
33
+ objects), `collider`, `upload` (readying streamed textures and shaders, plus the extra render time of frames that first draw new objects), `stream` (sync part of a `stream.add` build).
34
+ Per stage: `n`, `totalMs`, `maxMs`, smoothed `frameMs`, `bytes` (transit).
34
35
  - **Startup**: `engine.startup` = `{ totalMs, startMs, preloadMs, streamMs, compileMs, firstFrameMs, phases, modules: { name: { init, ready } } }`. `firstFrameMs` is page open to the first frame drawn after the loading screen, and `phases`
35
36
  splits it into parts that add up to it: `script` (page open until `createEngine`), `construct`, `setup` (game code until `start()`), `init` (saves,
36
37
  renderer, module init), `preload`, `world` (nearby builds), `compile` (shaders + hidden warm-up frame), `draw`. `inspect.perf().text` prints the line.
37
38
 
38
39
  ## 2. Set a budget (so going over reports itself)
39
- Off by default and costs nothing. The game gives the limits in `createEngine` (only the given categories are checked):
40
+ Off by default and costs nothing. Only the categories given are checked; `gpuMemoryMB` is three's own byte count (WebGPU only, not driver VRAM):
40
41
  ```js
41
- const engine = createEngine({ canvas, budget: { drawCalls: 250, fps: 55, low1: 30, triangles: 600000, chunkApplyMs: 3, rigidBodies: 300, startupMs: 5000 } });
42
+ const engine = createEngine({ canvas, budget: { drawCalls: 250, fps: 55, low1: 30, triangles: 600000, gpuMemoryMB: 512, rigidBodies: 300, startupMs: 5000 } });
42
43
  // or at runtime: engine.budget.enable({ drawCalls: 200 });
43
- const r = engine.budget.report(); // { ok, over: [{ category, value, limit, top }] }; going over also prints one console hint
44
+ const r = engine.budget.report(); // { ok, over: [{ category, value, limit, top }] }; going over also prints one console hint
44
45
  ```
45
46
  `top` lists the biggest draw-call users grouped by an object's `userData.budgetTag`. Tag your own things to see who it is:
46
47
  ```js fragment
47
- house.userData.budgetTag = 'houses'; // children inherit the parent's tag; untagged ones count as 'other'
48
- engine.budget.byTag(); // [{ tag, drawCalls, triangles }...], largest first
49
- engine.budget.metric('fishCount', () => fish.length, { limit: 50 }); // a module's own category
48
+ house.userData.budgetTag = 'houses'; // children inherit the parent's tag; untagged ones count as 'other'
49
+ engine.budget.byTag(); // [{ tag, drawCalls, triangles }...], largest first
50
+ engine.budget.metric('fishCount', () => fish.length, { limit: 50 }); // a module's own category
51
+ engine.budget.enable({ modules: { terrain: 1.5, vegetation: 2 } }); // ms per frame of one module (median of engine.profile(), section 3; a fixed-step module counts its dearest single step, catch-up steps are not added)
50
52
  ```
51
53
 
54
+ ## 2a. Slower than before (a baseline on this machine)
55
+ `threedog shot --save-baseline` (or `verify <name> --save-baseline`) writes `engine.budget.record()` (draw calls, triangles, module ms, live `cpuMs`) to
56
+ `.threedog/perf-baseline.json`, keyed by GPU, canvas size, pixel ratio, headless or live, camera pose. Runs with that key load it into `engine.budget.baseline`
57
+ and name what got slower (times +20% and +0.2 ms, new ones past 0.2 ms; counts +5%). Local to this machine, do not commit; save again after a change you accept.
58
+
52
59
  ## 3. Whose CPU is slow
53
60
  ```js
54
- engine.profile(true); // start timing each module's fixed/frame/afterRender
55
- // ...run for a few seconds (engine.step(3) in a test doesn't render; the real-time loop is more accurate: wait a few seconds)
56
- engine.profile(); // { terrain: 0.06, rigid: 0.23, ... } average milliseconds per rendered frame; cleared after reading
57
- engine.profile(false);
61
+ engine.profile(); // { terrain: { ms: 0.1, mean: 0.12, p95: 0.4 } } per frame, last 300 (ms: median); on in dev
62
+ engine.profile(true); // production: on (afresh); false: off
58
63
  ```
59
- `onFrame/onFixed` callbacks are not in the module timings; if you suspect them, temporarily turn them into a small module (see `14-custom-module.md`)
60
- and they get timed.
64
+ Only the module's own hooks count, not what it hands to `engine.jobs` or `engine.stream` loaders. Fixed hooks count one fixed step per frame, the dearest one: a slow frame runs several catch-up steps, and that is the frame's cost (`cpuMs`), not a spike of the physics module. `threedog inspect perf` lists the five dearest.
65
+ Browsers round time to 0.1 ms. `onFrame/onFixed` are not timed; to time one, make it a small module (`14-custom-module.md`).
61
66
 
62
67
  ## 4. Common fixes
63
68
  | Symptom | Fix |
64
69
  |---|---|
65
70
  | Many draw calls | Use `vegetation` / InstancedMesh for repeated objects; install `hlod()` for a block of buildings; share geometry and materials between copies of a model (`assets.model` shares by default) |
66
- | Expensive shadows | `engine.shadows.budget(light, { every: 3 })` (update every 3 frames), reduce `light.shadow.mapSize` / the box's `extent`; filter `renderer.shadowMap.type = THREE.BasicShadowMap` (hard edge, cheapest) / `THREE.PCFShadowMap` (default) / `THREE.VSMShadowMap` (softest, costliest), blur with `light.shadow.radius` (pcf and vsm only) and `.blurSamples` (vsm only); a switch recompiles materials, so avoid doing it every frame; the vegetation species option `shadowRing` (default 1) sets within how many chunk rings it casts shadows; change it while playing with `engine.vegetation.setShadowRing('tree', 0)` |
71
+ | Expensive shadows | `engine.shadows.budget(light, { every: 3 })` (update every 3 frames), reduce `light.shadow.mapSize` / the box's `extent`; filter `renderer.shadowMap.type`: Basic cheapest, PCF default, VSM softest and dearest (switching recompiles); vegetation `shadowRing` (default 1) is how many chunk rings cast (culled per camera: a shadow box or cascade draws only chunks inside it), `engine.vegetation.setShadowRing('tree', 0)` while playing; grass-scale species: `castShadow: false` (`content check` hints) |
67
72
  | Stutter while walking | Put generation work in `engine.jobs.add(function* () { ...; yield; })` or `engine.stream.add`; chunk upload budget `engine.terrain.applyBudgetMs` |
68
73
  | Slow start | Look at which is slowest in `engine.startup.modules`; `npm run bake` for large models; preload only the necessary assets |
69
74
  | Slow physics | Keep dynamic rigid bodies within a few hundred (the `rigidBodies` budget); `rigid({ terrainRing: 1 })` |
@@ -74,9 +79,9 @@ false = all on the main thread, same results.
74
79
  - Many far records: `world.simulate(kind, { far, worker: true })` (recipe 18 section 7).
75
80
  - Many paths per step (NPC crowds, AI squads): `engine.characters.findPathAsync(from, to, done)` (recipe 12 section 4); built-in NPCs already use it.
76
81
  - Your own worker script: `engine.threads.lane({ create: () => new Worker(new URL('./w.js', import.meta.url), { type: 'module' }), local: makeHandler })`;
77
- the worker file is `serve(makeHandler())` from `threedog/worker`. Results that change gameplay go through `engine.commits`.
82
+ the worker file is `serve(makeHandler())` from `threedog/worker`. Results that change gameplay go through `ctx.commits`.
78
83
 
79
- **Two worker limits**, with examples in `../CONVENTIONS.md`, "Worker limits": `engine.commits` runs your `fallback()` when the worker is late and does not clear pending requests on a load or level change, so give each a `valid()`; `threads.pure` functions are recompiled from source and capture nothing.
84
+ **Two worker limits**, with examples in `../CONVENTIONS.md`, "Worker limits": `ctx.commits` runs your `fallback()` when the worker is late and does not clear pending requests on a load or level change, so give each a `valid()`; `threads.pure` functions are recompiled from source and capture nothing.
80
85
 
81
86
  ## 4a. Less detail far away: which tool for which job
82
87
 
@@ -93,10 +98,10 @@ Four tools lower the cost of distant things, and each owns a different case. Pic
93
98
  // 1. once: writes public/optimized/tower.lod1.glb, .lod2.glb and lists them in assets.optimized.js
94
99
  // threedog assets optimize --lod (--lod-shares 0.5,0.2 sets the triangle share of each level)
95
100
  // 2. one line in the game; without it no level is ever downloaded
96
- const tower = await engine.assets.lod('tower'); // distances follow the model's size
97
- const gate = await engine.assets.lod('gate', { distances: [40, 120] }); // or your own, in meters
101
+ const tower = await engine.assets.lod('tower'); // distances follow the model's size
102
+ const gate = await engine.assets.lod('gate', { distances: [40, 120] }); // or your own, in meters
98
103
  // content/props.js: { model: 'tower', x: 10, z: 4, collide: 'box', lod: true } // or lod: [40, 120]; also on a template
99
- tower.levels[1].object; // a plain THREE.LOD: read, replace, tower.addLevel(...), tower.autoUpdate = false
104
+ tower.levels[1].object; // a plain THREE.LOD: read, replace, tower.addLevel(...), tower.autoUpdate = false
100
105
  ```
101
106
 
102
107
  - **Batching:** instances share one geometry, so a copy cannot change level alone. A LOD object is never batched, which means `lod` on a model placed many times can
@@ -107,24 +112,25 @@ tower.levels[1].object; // a plain THREE.LOD: read, replace, tower.addLevel(..
107
112
  - **Skipped by the tool, with the reason in its report:** skinned, morphing and animated models, and models under 1000 triangles. `assets.lod` still works on them: one level, and a
108
113
  dev warning.
109
114
  - **The level follows `engine.camera`** only, so a shadow pass does not change it. `delete tower.update`, while level 0 shows, restores the plain method; far rays then miss the full model.
110
- - **A narrow lens:** `camera.zoom` counts towards the distance, `camera.fov` does not. A sniper scope that narrows `fov` shows the far level up close, so use `zoom` or set
115
+ - **A narrow lens:** `camera.zoom` counts towards the distance, `camera.fov` does not: a scope narrowing `fov` shows the far level, so zoom, or set
111
116
  `tower.autoUpdate = false` while scoped.
112
117
  - **Check the last level up close once:** a low level can lose round details (a dial, a dome) that a few dozen pixels hide and a scope shows. If it shows, raise `--lod-shares` or move the distance out.
113
- - **Popping:** levels switch at once, softened by a hysteresis of 0.1 of the distance (`hysteresis` changes it). There is no crossfade; if a switch shows, move the distance out.
118
+ - **Popping:** no crossfade (only `hysteresis`); if a switch shows, move the distance out.
114
119
  - **Scale:** default distances follow a prop's `scale`. On `assets.lod` they follow the model as loaded, so give `distances` when you scale it yourself.
115
120
 
116
- ## 4b. Render scale (resolution) is never lowered silently
121
+ ## 4b. Render scale and effects are never lowered silently
117
122
  - Default render scale: `min(devicePixelRatio, 1.5)`; the low tier uses at least 0.75 x devicePixelRatio (a 2x laptop screen gets 1.5, not 1), never above 1.5.
118
- - Adaptive resolution (`createEngine({ adaptiveResolution, targetFps })`, default on, floor 0.6) lowers the scale by 0.1 per second while frames cost more
119
- than the target allows (main-thread time, plus GPU time where the browser has the timer query; without it, a low fps that is not just the display's own
120
- refresh). The first 3 s after ready and frames that compile shaders are not judged, and a display or power mode locked at 30 Hz is not overload. The first
121
- time it lowers, dev builds warn once: `render scale X -> Y because frames cost N ms ...; turn off with adaptiveResolution: false`. It is the only thing
122
- lowered automatically (shadows and post are never traded first). `engine.setPixelRatio(p)` sets the top it climbs back to, so a ratio the game chose stays; a direct
123
- `renderer.setPixelRatio` stops it altogether, and so does `pixelSize` (recipe 62 section 4b).
123
+ - Adaptive quality (`createEngine({ adaptiveResolution, targetFps })`, default on) lowers one step a second while frames cost more than the target allows
124
+ (CPU + GPU time where timed, else fps unless locked to the display); the first 3 s, compile frames and a 30 Hz lock are not judged.
125
+ Dev warns once; the perf notice (section 1) names what stays lowered. 4 s of cheap frames raise the last one back.
126
+ - `engine.adaptive.steps`, first lowered first. Default `null`: effects' own `cheaper` params (in place, no recompile), the resolution (0.1 a step, floor 0.6),
127
+ then `skipOnLowTier` effects held off (a rebuild, so last; one that drops straight back waits longer). Your own knob: `{ name, down, up }`
128
+ (down: false at its floor). `['resolution']` = scale only, `[]` = nothing.
129
+ Only downward: what the game or player has off is no step, settings stay above it, `adaptive.on = false` puts every effect back.
130
+ - `engine.setPixelRatio(p)` = the top it climbs back to; a direct `renderer.setPixelRatio` drops the resolution step; `pixelSize` stops it all (recipe 62 4b).
124
131
  - `describe().render.scale`: `{ current, devicePixelRatio, upscaled, pixelSize, autoLowered, adaptive, floor, max }`. `upscaled: true` means current < devicePixelRatio, the picture
125
132
  is softer than the screen: if that looks wrong in a screenshot, check this before the style. Fixed quality: `pixelRatio: n` plus `adaptiveResolution: false`.
126
133
 
127
134
  ## 5. Verify (once before and once after, under the same conditions)
128
135
  - `npm run perf` (native vs engine vs per-module cost of openWorld), run before and after on the same machine; differences under 10-30% are noise.
129
- - Compare a specific scenario: `npm run shot -- / --pos x,z --time 12:00 --describe-only` to see draw calls and triangles.
130
- - Attach the before/after numbers when reporting.
136
+ - One spot: `threedog shot --pos x,z --save-baseline` before, the same shot after (2a). Attach the numbers.
@@ -1,12 +1,11 @@
1
1
  # Dev bridge: operate the running game from the terminal (threedog describe / step / press / op...)
2
2
 
3
- **In this recipe**: 1. Usage · 2. Notes · 2b. A scripted playthrough, and three kinds of check · 3. Windows / PowerShell notes ·
4
- 3b. Speed, a session, and checks in one call · 4. Let describe see the game's own state · 5. Safety · 6. Reuse in scenario tests ·
5
- 7. Describe snapshots instead of screenshots · 8. Errors carry a code, a fix and a doc page · 9. Reusable scenarios · 10. MCP server ·
6
- 11. When something happens: which tool
3
+ > **Covers:** driving the running game from the terminal: describe, step, press, state, scenarios, snapshots, MCP.
4
+ > **Use when:** checking a change without a screenshot or a browser script.
5
+ > **Shortest:** `threedog describe -w my-game`.
6
+ > **Sections:** 1 Usage · 2 Notes · 2b A scripted playthrough · 3 Windows / PowerShell · 3b Speed, a session · 4 Let describe see · 5 Safety · 6 Reuse in scenario · 7 Describe snapshots instead · 8 Errors carry a · 9 Reusable scenarios · 10 MCP server Claude · 11 When something happens
7
7
 
8
- Purpose: after changing code, don't write a playwright script or take a screenshot; just ask "what does the game look like now", advance time, press
9
- keys, change state. Output is English, three lines or fewer, to save tokens.
8
+ After changing code, ask the running game instead of writing a playwright script or taking a screenshot: look, advance time, press keys, change state. Output is a few English lines.
10
9
 
11
10
  What the bridge changes lives in this session only: `op`, `step`, `state` and `js` alter the running game and its saves, never the level. To change
12
11
  the level, edit `content/*.js` (templates, props, npcs…) or the level model and reload the page.
@@ -25,7 +24,7 @@ Every command and its options are in `../COMMANDS.md`. What each does to the gam
25
24
  |---|---|---|
26
25
  | `step`, `press`, `hold`, `skip`, and `scenario` / `verify`, which use them | `op`, `state` (only its `wait=` moves the clock), `js` | `describe`, `ops`, `inspect`, `pick`, `explain`, `errors`, `loading`, `snap`, `snap-describe` |
27
26
 
28
- - `describe` is one line: position, time and weather, nearby, quest. `describe player.position` or any dotted path of `engine.describe()` reads one item (`--max characters`). `describe --full` is the state as text in at most 30 lines (`engine.describeText()`: the nearest things, the game's `describe.add` sections, one line per module, the engine tables as one count line, and how to expand); `--all` is everything and large, so prefer a path. In code: `engine.describe('picture')`, `describe({ only: ['picture', 'shared'] })`. `describe render` lists how the picture is set; it informs and never warns.
27
+ - `describe` is one line: position, time and weather, nearby, quest. `describe player.position` or any dotted path of `engine.describe()` reads one item (`--max characters`). `describe --full` is the state as text in at most 30 lines (`engine.describeText()`: nearest things, the game's `describe.add` sections, one line per module, engine tables as one count line, how to expand); `--all` is large, prefer a path. In code: `engine.describe('picture')`, `describe({ only: ['picture', 'shared'] })`. `describe render` lists how the picture is set; it informs and never warns.
29
28
  - `step 2` is deterministic; a real-time page is halted first.
30
29
  - `press interact` takes an action name or key (`KeyE`, `e`, `Escape`). **It advances game time**: 0.1 s held + one rendered frame of 1/60 s, about 0.117 s; shorten the hold with `--for 0.02` when timing matters.
31
30
  - `op shop.buy shop=trader item=medkit n=2` runs as source `bridge`. Values follow the op's `args` shape (`n=2` a number, `position=3,0,-2` an array). **Change state with this, not `js`**: `js` writes skip the op log.
@@ -38,28 +37,23 @@ Every command and its options are in `../COMMANDS.md`. What each does to the gam
38
37
  - **Smallest scenario** (`tests/scenarios/coins.json` <!-- r18-ignore-line -->, then `threedog verify coins` or `scenario coins`; `verify` with no file says "Have: none"):
39
38
  `{ "name": "coins", "url": "/", "state": { "pos": "6,4" }, "steps": [ { "step": 1 }, { "expect": { "inventory.items.coin": 1 } } ] }`
40
39
  - **Position formats**: `pos=x,z` (state, shot, `applyState`) is two numbers on the ground plane, and the height is looked up; an op argument such as `position=3,0,-2` is `x,y,z`. Both are meters, north is -z. `describe` reports the player as `{ x, y, z }` (`describe player.position`).
41
- - **Teleport the player**: `threedog state "pos=40,-20"` on the bridge, `await engine.applyState({ pos: '40,-20' })` in a test or `js` (both wait for the
42
- ground there to load). A bare `player.placeAt` from the bridge or a test is a gameplay write outside an op and prints the ops-guard warning; in the
43
- game itself it belongs in an op (a teleporter pad). `step 1` after it collects `auto` pickups: the pickup check runs in the fixed step after any move.
40
+ - **Teleport the player**: `threedog state "pos=40,-20"`, or `await engine.applyState({ pos: '40,-20' })` in a test or `js` (both wait for the ground to load). A bare
41
+ `player.placeAt` outside an op prints the ops-guard warning. `step 1` after it collects `auto` pickups.
44
42
  - **Ops with a reach** (`interaction.use`, `pickup.take`) check the player's distance as a key press would, also from the bridge: put the player next
45
43
  to the thing first (`threedog state "pos=x,z"`), then `threedog op interaction.use id=gate`. A `tooFar` result carries `facts: { distance, radius, at }`.
46
44
  - **`shot` always starts a fresh game** (`?save=slot1` loads one); after playing use `snap name`. Every shot prints the picture numbers and hints (recipes/35 "Picture check after every shot").
47
45
  - **`step` / `press` halt the real page's loop**; resume with `threedog resume` when done (they halt as owner `threedog`, so nothing of the game's is touched). A headless page only advances on step anyway.
48
- - **Run state** is printed after `step` / `press` / `skip` / `resume` and by `threedog status`: `running`, `title-frozen` (title screen waiting for start), `halted` (the loop is stopped: the bridge, a test or a headless page), `frozen(by owners)` (every `freeze` owner, e.g. `ui-inventory` or `page`) or `loading`. The same object is `engine.runState` and `describe().time.run`: `{ state, owners, blockedBy }`, where `blockedBy` lists what keeps input from driving the game (opaque input contexts such as `win-settings`, `ui-title`, `dialogue`, `cutscene`, plus `error` and `loading`); the bridge and the MCP tools copy it as-is.
49
- - **Who holds what**: `describe().holds` lists every holder in one place: `halt / freeze / camera / debugView` as `[{ owner, at }]` (`at` = game clock time of the take, `engine.clock.now`, so two new games read the same), `input` (pushed contexts `[{ context, owner, pass }]`), `gates` (`input.gate` owners by action) and `stacks` (every other `engine.mod` quantity), so a stuck pause, a closed jump or a camera nobody gave back has a name.
46
+ - **Run state** is printed after `step` / `press` / `skip` / `resume` and by `threedog status`: `running`, `title-frozen` (title screen waiting for start), `halted` (loop stopped by the bridge, a test or a headless page), `frozen(by owners)` (every `freeze` owner, e.g. `ui-inventory` or `page`) or `loading`. The same object is `engine.runState` and `describe().time.run`: `{ state, owners, blockedBy }`, where `blockedBy` lists what keeps input from driving the game (opaque input contexts such as `win-settings`, `ui-title`, `dialogue`, `cutscene`, plus `error` and `loading`); the bridge and the MCP tools copy it as-is.
47
+ - **Who holds what**: `describe().holds` lists every holder in one place: `halt / freeze / camera / debugView` as `[{ owner, at }]` (`at` = game clock time of the take, `engine.clock.now`), `input` (pushed contexts `[{ context, owner, pass }]`), `gates` (`input.gate` owners by action) and `stacks` (every other `engine.mod` quantity), so a stuck pause, jump or camera has a name.
50
48
  - **`snap` on a real page captures only the canvas** (not the HTML UI); on a headless page it captures the whole page. To see UI state use `describe`
51
49
  (`ui.windows`, dialogue).
52
50
  - **Keys go through `engine.input` like a real keyboard**: action names are translated to keyboard keys (gamepad buttons are ignored); when a window
53
51
  locks input, menu-type actions (`pressedRaw`) are still received.
54
- - **In your own page scripts and tests do the same with `engine.input.simulate(action, down = true)`** (it goes through the same path as `press`, and
55
- works with `engine.step`): `engine.input.simulate('jump'); engine.step(1 / 60); engine.input.simulate('jump', false)`. Never call `_keyDown` /
56
- `_keyUp` (internal).
52
+ - **In your own page scripts and tests use `engine.input.simulate(action, down = true)`** (the same path as `press`): `engine.input.simulate('jump'); engine.step(1 / 60); engine.input.simulate('jump', false)`.
57
53
  - `describe` by default gives only the 3 nearest things and the first quest; for detail use a path (`quests.active`, `nearby`, `world`) or `--full`.
58
54
  - Several pages: `--page /<page>.html` picks the path; `-w name` picks the workspace.
59
- - To change the port: `npm run dev -- my-game --port 5000`; the CLI finds the port from `.threedog/dev.json`, so you don't need to specify it again.
60
- - If a command never becomes ready: most likely `main.js` doesn't set `window.engine = engine;` (it must come before `await engine.start()`). Under
61
- the dev server `engine.start()` attaches it automatically, but the bundled build used by npm test does not; the timeout error says whether the page
62
- has `window.engine`, `engine.ready`, and the latest page errors.
55
+ - Another port (`npm run dev -- my-game --port 5000`) is found through `.threedog/dev.json`.
56
+ - Never ready: the dev server attaches `window.engine` itself, but a bundled build (npm test) needs `window.engine = engine;` before `await engine.start()`; the timeout error says which is missing.
63
57
 
64
58
  ## 2b. A scripted playthrough, and three kinds of check
65
59
  ```
@@ -73,10 +67,10 @@ threedog snap after-walk # only now look at pixels
73
67
  ```
74
68
  The same steps as a file: `tests/scenarios/<name>.json` with `{ "press": … }`, `{ "step": … }`, `{ "until": …, "within": s }`, `{ "expect": { path: value } }` (section 9; no `hold` there).
75
69
  - **State checks** (`op`, `expect`, `describe`, `js`): fast and exact, but they skip input. They prove rules, not that the player can reach them.
76
- - **Simulated-input checks** (`press`, `hold`, `engine.input.simulate`): bridge key events through the game's input path, never a physical keyboard/mouse. `verify` prints which layer each check ran on, what it did **not** prove (pointer lock and mouse look, real GPU/visuals, real FPS) and coverage (ops run vs defined; modules tested, indirect or untested; uses `engine.catalog()`); `scenario` prints the same coverage, and `--json` has the full lists.
70
+ - **Simulated-input checks** (`press`, `hold`, `engine.input.simulate`): bridge key events through the game's input path, never a physical keyboard/mouse. `verify` prints which layer each check ran on, what it did **not** prove (pointer lock and mouse look, real GPU/visuals, real FPS) and coverage (ops run vs defined; modules tested, indirect or untested; from `engine.catalog()`); `scenario` prints the same, `--json` the full lists.
77
71
  - **Visual checks** (`snap`, `shot`): the only ones that see the picture (exposure, color, UI overlap). Slowest; take them last.
78
72
 
79
- **Script the failures, not only the win.** A run that only wins says nothing about the routes a player takes after a mistake. Every end state gets a scenario: lose, die and respawn, retry, reload mid-run (`threedog reload` between bridge commands; a scenario file has no reload step). After each run, read `ops never run` in the `verify` report: each op there is a rule no script reached. Then check what the player stands in after the failure: a respawn point the level has since closed off, a hit that lands the step after a blow that should have ended the contact, a timer or lock left over from the last attempt.
73
+ **Script the failures, not only the win.** Every end state gets a scenario: lose, die and respawn, retry, reload mid-run (`threedog reload` between bridge commands; a scenario file has no reload step). Read `ops never run` in the `verify` report (rules no script reached), then check what the player stands in after the failure: a closed-off respawn point, a hit landing after the blow that should end contact, a timer or lock left from the last attempt.
80
74
 
81
75
  Playing a game through from a script, the five things that cost the most time:
82
76
  - **Start clean.** Enter on a title picks Continue when a save exists, so a rerun by keys plays the last autosave. `state fresh=1` deletes the saves and
@@ -93,15 +87,14 @@ Playing a game through from a script, the five things that cost the most time:
93
87
  reports an error and shows this tip when pos is not two numbers).
94
88
  - Wrap the whole `js` expression in **double quotes** and use single quotes for strings inside: `threedog js "engine.vars.counter('score')"`.
95
89
  PowerShell expands `$variables` inside double quotes; to pass `$` literally wrap the whole thing in single quotes.
96
- - **Write a command on a single line**: a multi-line here-string passed to a native command often silently returns nothing in PowerShell. Put several
97
- statements on one line separated by semicolons, or write them to a file and use `threedog js --file script.js` (no quoting or newline worries).
90
+ - **Write a command on a single line** (a multi-line here-string to a native command often returns nothing): separate statements with semicolons, or use `threedog js --file script.js`.
98
91
  - Some terminal sandboxes (Bash) block commands containing the word `eval`: use `js`, not `eval`.
99
92
 
100
93
  ## 3b. Speed, a session, and checks in one call
101
94
 
102
95
  The bin called directly is the fastest route (COMMANDS.md, first lines); `threedog session` saves a little more per command. Commands behave identically with or without it.
103
96
 
104
- - `threedog js --file steps.js`: put the whole test in one file and run it once. Inside: `assert(cond, msg)`, `expect(v).toBe(x)` (also `toEqual`, `toBeCloseTo(x, tol)`, `toBeGreaterThan`), `step(seconds)`, `log(...)`, and `engine`. The output is only the failures and one summary line, exit code 1 on failure, so ten steps cost one round trip and a few tokens:
97
+ - `threedog js --file steps.js`: the whole test in one file, one round trip. Inside: `assert(cond, msg)`, `expect(v).toBe(x)` (also `toEqual`, `toBeCloseTo(x, tol)`, `toBeGreaterThan`), `step(seconds)`, `log(...)`, and `engine`. It prints the failures and one summary line, exit code 1 on failure:
105
98
 
106
99
  ```js fragment
107
100
  step(2);
@@ -113,12 +106,10 @@ expect(engine.time.tick).toBeGreaterThan(before, 'time advanced');
113
106
  ## 4. Let describe see the game's own state
114
107
  A game's own state (score, number of targets, crops) is not in `describe` by default. **Small games use this**: register it in one line, no module needed:
115
108
  ```js
116
- engine.describe.add('range', () => ({ score, targets: targets.length })); // the returned handle's .remove() cancels it
109
+ engine.describe.add('range', () => ({ score, targets: targets.length })); // the returned handle's .remove() cancels it
117
110
  ```
118
- After that `threedog describe range` shows it, and `describeText()` includes it too (listed before the module lines, so the 30-line cut never drops it). The name must not collide with a core field (player, time...)
119
- or a module name; if the callback throws, only this item shows `{ error }` and the rest are unaffected.
120
- **Large games write their systems as modules** (see 14-custom-module.md) and use the module's `describe(e, ctx)` hook: the return value likewise goes
121
- into `describe().<module name>`, and `ctx.near()` can report "things nearby".
111
+ After that `threedog describe range` shows it, and `describeText()` lists it before the module lines. The name must not collide with a core field or a module name;
112
+ a callback that throws shows `{ error }` for this item only. **Large games use modules** (14-custom-module.md): the module's `describe(e, ctx)` hook goes into `describe().<module name>`.
122
113
 
123
114
  ## 5. Safety
124
115
  The bridge exists only in the dev server (`apply: 'serve'`); built and preview output contains no bridge code. The command entry point `POST /__threedog/cmd` accepts only local connections, requires the random token in `.threedog/dev.json`, the Host must
@@ -142,11 +133,10 @@ Options: `--only a,b.c` (compare just these fields; dotted paths allowed), `--ig
142
133
 
143
134
  In a test, one line (the page must already be in the state to freeze; use `engine.haltLoop()` and `engine.step()` first):
144
135
  ```
145
- import { expectDescribe } from '@threedog/tools/describe-snapshot'; // in the engine's own specs: '../../../tools/describe-snapshot.mjs'
136
+ import { expectDescribe } from '@threedog/tools/describe-snapshot'; // in the engine's own specs: '../../../tools/describe-snapshot.mjs'
146
137
  await expectDescribe({ check, ev }, 'market-noon', { only: ['player', 'quests', 'nearby'], tolerance: { default: 0.5, player: 1 } });
147
138
  ```
148
- Update after an intended change: `threedog test <name> --update-snapshots` (writes instead of comparing) or `threedog snap-describe save <name>`.
149
- Review the JSON diff in git before committing. Take a screenshot only when the picture changed.
139
+ Update after an intended change: `threedog test <name> --update-snapshots` or `threedog snap-describe save <name>`, and review the JSON diff before committing.
150
140
 
151
141
  ## 8. Errors carry a code, a fix and a doc page
152
142
  Every error and warning the engine raises carries a stable **code**: `err.code`, `err.fix` (what to do) and `err.docs` (pages to read), and its message
@@ -174,7 +164,7 @@ Cursor, `.cursor/mcp.json` in the game folder: <!-- r18-ignore-line -->
174
164
  ```
175
165
  { "mcpServers": { "threedog": { "command": "node", "args": ["node_modules/@threedog/tools/bin/threedog.mjs", "mcp"] } } }
176
166
  ```
177
- Plain node is the same on every OS (no `cmd /c` on Windows). The server starts once per session. `npm run new-game` writes a `.mcp.json` like this into the new game, so opening the game folder in Claude Code picks it up.
167
+ Plain node is the same on every OS. `npm run new-game` writes a `.mcp.json` like this into the new game, so Claude Code picks it up.
178
168
 
179
169
  The `js` tool (arbitrary code in the page) is off by default; `threedog mcp --allow-js` enables it, for development only. Other options: `-w name`
180
170
  (workspace), `--page /<page>.html` (page path).
@@ -1,85 +1,79 @@
1
1
  # World data: things that must be saved, grow, and keep changing while far away
2
2
 
3
- **In this recipe**: 1. Three steps · 2. How to change data · 3. Example: a crop grows on the calendar, press E to… · 4. Data written in content ·
4
- 4b. One object from start to end · 5. Example: something that wanders · 6. Near, far, camera, player · 7. Time and ordering rules · 8. Querying nearby things ·
5
- 9. zone and data limits
6
-
7
- Requires module `world()` (already included in the `openWorld()` preset). The interaction prompts in the examples need
8
- `interactions({ ...presets.interactions.nearest })`, the inventory needs `inventory()` (keys: `presets.bindings.interact` / `.inventory`). The API list is in
9
- `../api/world.md`; this page explains how to use it and what the rules are.
10
-
11
- Anything in the game that "must remember its state, survive level changes, and keep changing while far away" (chests, NPCs, zombies, crops, trees the
12
- player planted, the player itself) is one **plain data record** in `engine.world`: a stable id, a kind, a position, plus your own fields. The model is
13
- just how it looks when the camera is near; unloading a chunk / level tears down only the model and never loses the data; a save stores only data; far
14
- away, with no model, the data is still simulated.
15
- A decorative rock is a props entry in `content/props.js` (an authored record, saved only if play moves or removes it); `engine.add(mesh)` is for
16
- transient effects. Everything placed in a level comes from content, so a new game equals the content.
17
- Many copies of one interactive object (chests, beds, campfires) with the same model, interaction and container: define it once as a content template
18
- and place instances (recipe 30-templates.md); the template is the shared read-only definition, the record holds only the instance state.
3
+ > **Covers:** world records: things that are saved, grow and change while far away.
4
+ > **Use when:** an object must live on outside the view or across levels.
5
+ > **Shortest:** `engine.world.add({ id, kind, position })`.
6
+ > **Sections:** 1 Three steps data · 2 How to change · 3 Example a crop · 4 Data written in · 4b One object from · 5 Example something that · 6 Near, far, camera · 7 Time and ordering · 8 Querying nearby things · 9 zone and data
7
+
8
+ Requires `world()` (part of `openWorld()`); the examples also use `interactions({ ...presets.interactions.nearest })` and `inventory()`. API: `../api/world.md`.
9
+
10
+ Anything that must remember its state, survive level changes and keep changing while far away (chests, NPCs, crops, the player itself) is one **plain data
11
+ record** in `engine.world`: a stable id, a kind, a position, plus your own fields. The model is only how it looks when near; unloading tears down the model,
12
+ never the data; a save stores only data; far away the data is still simulated. A decorative rock is a props entry (recipe 05); many copies of one interactive
13
+ object are a content template with instances (recipe 30-templates.md), whose records hold only the instance state.
19
14
 
20
15
  ## 1. Three steps: data, picture, change
21
16
  ```js
22
17
  const W = engine.world;
23
- W.add({ id: 'zombie_1', kind: 'zombie', position: [10, 0, -4], hp: 10 }); // fields must be plain values; without an id one is numbered automatically (saved)
18
+ W.add({ id: 'zombie_1', kind: 'zombie', position: [10, 0, -4], hp: 10 }); // fields must be plain values; without an id one is numbered automatically (saved)
24
19
  W.present('zombie', {
25
- build: rec => new THREE.Mesh(zombieGeo, zombieMat), // required: built when the camera is near (may be async); world adds it to the scene at rec.position
26
- update: (rec, obj, dt) => { obj.visible = rec.hp > 0; }, // optional: called every frame for records that have a model; change the picture from the data
27
- dispose: (rec, obj) => engine.remove(obj), // optional: first argument is the data, second the model; this is the default
28
- show: rec => rec.hp > 0, // optional: false = this record has no model right now (picked up, waiting to respawn)
29
- radius: 40, // optional: how near to build the model (meters or a function); default world.radius (60)
20
+ build: rec => new THREE.Mesh(zombieGeo, zombieMat), // required: built when the camera is near (may be async); world adds it to the scene at rec.position
21
+ update: (rec, obj, dt) => { obj.visible = rec.hp > 0; }, // optional: called every frame for records that have a model; change the picture from the data
22
+ dispose: (rec, obj) => engine.remove(obj), // optional: first argument is the data, second the model; this is the default
23
+ show: rec => rec.hp > 0, // optional: false = this record has no model right now (picked up, waiting to respawn)
24
+ radius: 40, // optional: how near to build the model (meters or a function); default world.radius (60)
30
25
  });
31
26
  W.simulate('zombie', {
32
- near: (rec, dt, obj) => { W.move(rec.id, { x: rec.position.x + dt, z: rec.position.z }); }, // near the player: every fixed step; obj may not be built yet (null), gameplay must not depend on it
33
- far: (rec, dt) => { rec.hp = Math.min(10, rec.hp + dt * 0.1); }, // far away: once every farEvery seconds; dt is accumulated seconds (it can catch up a long time at once)
27
+ near: (rec, dt, obj) => { W.move(rec.id, { x: rec.position.x + dt, z: rec.position.z }); }, // near the player: every fixed step; obj may not be built yet (null), gameplay must not depend on it
28
+ far: (rec, dt) => { rec.hp = Math.min(10, rec.hp + dt * 0.1); }, // far away: once every farEvery seconds; dt is accumulated seconds (it can catch up a long time at once)
34
29
  });
35
30
  ```
36
31
  - If `build` throws, fails, or returns something that is not an object, the error is reported once and does not block the loading screen
37
32
  (`world.ready`); it retries when you walk away and come back.
38
33
  - `show` is re-evaluated when `world.set` changes data of that kind. Calling `present` again for the same kind tears down old models with the old
39
34
  dispose and rebuilds them with the new one.
40
- - Animation, particles and other things that only matter per frame go in `present.update`, not in simulate. It runs after world placed the model
41
- on its record, so picture-only motion written there stays: `update: (rec, obj, dt) => { obj.getObjectByName('legL').rotation.x = Math.sin(rec.walk * 9) * 0.5;
35
+ - Per-frame picture work (animation, particles) goes in `present.update`, which runs after world placed the model, so motion written there stays: `update: (rec, obj, dt) => { obj.getObjectByName('legL').rotation.x = Math.sin(rec.walk * 9) * 0.5;
42
36
  obj.position.x += rec.stagger * 0.1; }` (a leg swing, a stagger offset). Moving the model from anywhere else is put back next frame, with a warning.
37
+ - world places only the position of a model your `build` returns: apply `rec.rot` / `rec.scale` yourself (your units, on the root or a child),
38
+ and again in `update` to follow later writes. Content props and templates turn and size theirs.
43
39
 
44
40
  ## 2. How to change data
45
41
  - Discrete changes (open a chest, switch growth stage, get picked up, change direction) use `W.set(id, { opened: true })`: it emits `world:change` and
46
42
  re-evaluates `show`. Don't `set` every step. id / kind cannot be changed (to change the kind, remove then add).
47
43
  - Things that change every step (position, timers, pathfinding state) are changed directly on the rec's fields inside simulate, and position with
48
44
  `W.move`: no event, cheap.
49
- - Both ways are saved (a save compares contents, it does not rely on events). `move` emits no event: if the picture needs to follow position, compare in
50
- `update`.
45
+ - Both ways are saved (a save compares contents). `move` emits no event: a picture that follows position compares in `update`.
51
46
  - Don't hold a rec object for long: loading a save replaces it with a new object. Keep the id and call `W.get(id)` when you need it.
52
47
  - Position forms: Vector3 / object / `[x, y, z]` / `{ x, z }` (a missing y keeps the old one). NaN or an array with only two numbers
53
48
  throws immediately, in release too, and writes nothing.
54
49
 
55
50
  ## 3. Example: a crop grows on the calendar, press E to harvest when ripe
56
- The key idea: **don't accumulate every step; record the time it was planted, `plantedAt = clock.now`, and growth = now - planted time**. Whether the
57
- player walked away, loaded a save, or fast-forwarded with `engine.step(60)`, the result is right, and no simulate is needed.
51
+ The key idea: **record `plantedAt = clock.now` and compute growth = now - planted time** instead of accumulating every step: right after walking away, a save load or `engine.step(60)`, with no simulate.
58
52
  ```js
59
53
  import { presets, THREE } from 'threedog';
60
54
 
61
- const GROW = 120; // ripe after 120 calendar seconds (the unit of clock.now)
62
- const growth = rec => Math.min(1, (engine.clock.now - rec.plantedAt) / GROW); // 0..1
55
+ const GROW = 120; // ripe after 120 calendar seconds (the unit of clock.now)
56
+ const growth = rec => Math.min(1, (engine.clock.now - rec.plantedAt) / GROW); // 0..1
63
57
  const geo = new THREE.ConeGeometry(0.25, 0.8, 6);
64
58
 
65
59
  engine.world.present('crop', {
66
60
  build(rec) {
67
61
  const m = new THREE.Mesh(geo, new THREE.MeshLambertMaterial({ color: 0x6aa84f }));
68
62
  m.castShadow = true;
69
- m.userData.use = engine.interactions.add(m, { label: 'Harvest', radius: 2, enabled: () => growth(rec) >= 1, onUse: () => harvest(rec) }); // can be harvested only when ripe
63
+ m.userData.use = engine.interactions.add(m, { label: 'Harvest', radius: 2, enabled: () => growth(rec) >= 1, onUse: () => harvest(rec) }); // can be harvested only when ripe
70
64
  return m;
71
65
  },
72
- update(rec, obj) { // grows bigger, changes color when ripe
66
+ update(rec, obj) { // grows bigger, changes color when ripe
73
67
  const g = growth(rec);
74
68
  obj.scale.setScalar(0.3 + 0.7 * g);
75
69
  obj.material.color.setHex(g >= 1 ? 0xe8a33d : 0x6aa84f);
76
70
  },
77
- dispose(rec, obj) { obj.userData.use.remove(); engine.remove(obj); }, // an interaction you registered yourself must be removed yourself
71
+ dispose(rec, obj) { obj.userData.use.remove(); engine.remove(obj); }, // an interaction you registered yourself must be removed yourself
78
72
  });
79
73
 
80
74
  function harvest(rec) {
81
75
  engine.inventory.add('carrot', 2);
82
- engine.world.remove(rec.id); // delete the data after harvesting (the model goes with it). To "grow back after a while": world.set(rec.id, { plantedAt: engine.clock.now }); to hide temporarily: return false from show
76
+ engine.world.remove(rec.id); // delete the data after harvesting (the model goes with it). To "grow back after a while": world.set(rec.id, { plantedAt: engine.clock.now }); to hide temporarily: return false from show
83
77
  }
84
78
 
85
79
  // the player plants one: an op, because saved state changes only in a fixed step or an op (recipe 23 §5); a key, a button or a test runs it
@@ -147,8 +141,8 @@ avoidance), see recipe 02 "Changing behavior / custom behavior"; below is the pu
147
141
  ```js
148
142
  engine.world.present('chicken', { build: rec => makeChicken() });
149
143
  engine.world.simulate('chicken', {
150
- near: (rec, dt) => wander(rec, dt), // near: a small step every fixed step
151
- far: (rec, dt) => wander(rec, dt), // far: catch up once every farEvery seconds
144
+ near: (rec, dt) => wander(rec, dt), // near: a small step every fixed step
145
+ far: (rec, dt) => wander(rec, dt), // far: catch up once every farEvery seconds
152
146
  farEvery: 2,
153
147
  });
154
148
  function wander(rec, dt) {
@@ -162,7 +156,7 @@ function wander(rec, dt) {
162
156
  - **Near / far is decided by the gameplay anchor `world.anchor`**: by default the position of the player record (`engine.focus` when there is no
163
157
  player). A cutscene or photo mode moves the camera away, but the player's surroundings are still simulated as near: gameplay results do not depend
164
158
  on the camera. For a top-down strategy game centered on a base, set `W.anchor = baseObject`; set it back to `null` to restore the default.
165
- - **The player is a record too**: the id and kind added by `createPlayer` are both `'player'`; position, facing, motion state (vx, vz, vy, facing,
159
+ - **The player is a record too**: the id and kind added by `addPlayer` are both `'player'`; position, facing, motion state (vx, vz, vy, facing,
166
160
  grounded...) and which vehicle it is on (vehicle) live in the record and are saved, and it is never torn down by walking away. Only the character's
167
161
  mover changes the position and then writes it back to the record. `world.move`, `world.set` and `thing.set` on a live character (the player, an NPC with
168
162
  a model) are its `placeAt`: it goes there, standing on what is there, and the record says where it stands. A seated rider gets out to go there; undo of that `thing.set`
@@ -179,7 +173,7 @@ function wander(rec, dt) {
179
173
  copies the model position back to the data at the end of every fixed step; when not simulated near, the data decides and the model follows the data.
180
174
  A write to the record (`world.move`, `world.set`, `thing.set`, or `rec.position` itself, seen at the end of the step) moves the model, and a rigid body on
181
175
  that model goes along at rest, however the body was made. `rot` and `scale` on a template with a `body` build a new body where the record stands; with your
182
- own `present` they are your fields, so read them there.
176
+ own `present` and `positionFrom: 'view'` they are your fields, so read them there.
183
177
  A model moved by a physics body saves its position, not the physics solver state: after a load, resting bodies settle again and can differ by ~0.01
184
178
  mm, so replays that must match exactly should not depend on physics props.
185
179
  - Radius: present / simulate each take their own `radius` (meters or a function); without it they follow `world.radius` (default 60).
@@ -201,14 +195,14 @@ function wander(rec, dt) {
201
195
  - The owed time and the simulation step count are saved: after loading they are caught up the same way, and the same save gives the same result
202
196
  however many fixed steps run per frame. For things measured on the calendar (grows in a few days, respawns at a time), record `engine.clock.now` and compare.
203
197
  - **Far in workers** (thousands of crops, spawners or machines): `W.simulate('crop', { far, worker: true })`. Each step's far batch runs in `engine.threads` workers and is written
204
- back 4 fixed steps later through `engine.commits`; a late reply runs on the main thread, so threads on / off / slow give **bit-identical** records, and only fields far changed are written
198
+ back 4 fixed steps later through `ctx.commits`; a late reply runs on the main thread, so threads on / off / slow give **bit-identical** records, and only fields far changed are written
205
199
  back. `far` must be self-contained: it is recompiled from source and sees only `(rec, dt)` and globals like `Math`; an outside variable throws (also with `threads: false`, so you find
206
200
  it in development). Limit: a save taken while a batch is in flight re-simulates that stretch after loading (equal within float tolerance, not bit-identical).
207
201
 
208
202
  ## 8. Querying nearby things
209
203
  ```js
210
204
  let crowd = 0;
211
- engine.world.forEachNear(engine.player, 5, (rec, d2) => { if (rec.kind === 'zombie') crowd++; }); // no allocation, no sorting; world.query sorts nearest first and returns an array
205
+ engine.world.forEachNear(engine.player, 5, (rec, d2) => { if (rec.kind === 'zombie') crowd++; }); // no allocation, no sorting; world.query sorts nearest first and returns an array
212
206
  ```
213
207
  For things that query neighbors every step (hundreds of zombies avoiding each other) use `forEachNear`; inside the callback don't add / remove / move,
214
208
  note them down and change them after the loop.