threedog 0.8.0 → 1.0.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 (372) hide show
  1. package/CHANGELOG.md +219 -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
@@ -18,8 +18,13 @@ export class StepPoses {
18
18
  /** objects whose matrix is held for this draw */ this.held = [];
19
19
  engine.time.onMove(() => this.end());
20
20
  }
21
- add(o) { this.map.set(o, { o, last: o.position.clone(), lastRot: o.quaternion.clone(), pos: o.position.clone(), rot: o.quaternion.clone(), moved: false }); }
21
+ /** place(at): how to move o if a solver owns its pose (a rigid body); gone(): what that solver does when o leaves for good. Core names no module, so the solver says both here */
22
+ add(o, place = null, gone = null) { this.map.set(o, { o, place, gone, last: o.position.clone(), lastRot: o.quaternion.clone(), pos: o.position.clone(), rot: o.quaternion.clone(), moved: false }); }
22
23
  remove(o) { this.map.delete(o); }
24
+ /** o and all under it left for good (engine.remove): a level's root takes the crates placed in it along, and a solver must not keep them solid and unseen */
25
+ forget(o) { if (this.map.size) o.traverse(c => this.map.get(c)?.gone?.()); }
26
+ /** A write moves o outside any step: the object goes there, and whatever solves it too, or the solver's next pose would undo the write */
27
+ place(o, at) { o.position.copy(at); this.map.get(o)?.place?.(at); }
23
28
  /** End of a fixed step: the latest pose becomes the start of the blend */
24
29
  end() {
25
30
  for (const p of this.map.values()) {
@@ -1,4 +1,4 @@
1
- // engine.thing(id).explain(): everything known about one id in one plain object (JSON-able, same for the CLI `threedog thing <id>`, MCP and tests).
1
+ // engine.explain({ thing: id }): everything known about one id in one plain object (JSON-able, same for the CLI `threedog explain thing <id> --full`, MCP and tests).
2
2
  // Why one object: an AI asked "why is this crate here, blocking me, and how do I change it?" otherwise joins thing(), world.origin, material info, the
3
3
  // template, collision settings and the op list by hand. Each part reads an existing source; nothing here is stored or changes any state.
4
4
  import { Box3, Vector3 } from 'three';
@@ -7,7 +7,9 @@ import { Things, snap, write, moduleOwnerOf } from './things.js';
7
7
  import { closest, DEV, goodPos } from '../base/validate.js';
8
8
  import { onSceneRoot } from './sceneDelta.js';
9
9
  import { codedError } from '../base/errorHints.js';
10
- import { explainThing } from './thingExplain.js';
10
+
11
+ // ops.undo of a run that failed has no value to reverse: an answer, not a crash
12
+ const NOTHING_TO_UNDO = { code: 'nothingToUndo' };
11
13
 
12
14
  const SAY = {
13
15
  record: { keeps: ['record fields and position (world save part)'], loses: ['the built model itself: it is rebuilt from its template / present after a load'] },
@@ -27,16 +29,13 @@ function editText(en, tier, rec) {
27
29
  return `made during play${en.op ? ` by op ${en.op}` : ''}${at}: to keep it, make it a template and create it inside the op with engine.content.spawn(name, at)`;
28
30
  }
29
31
 
30
- /** thing.explain(): the whole story of the id in one object (thingExplain.js); a method, not a field, so the thing stays small */
31
- const withExplain = (e, t) => Object.defineProperty(t, 'explain', { value: () => explainThing(e, t), enumerable: false });
32
-
33
32
  /** A registered plain object as a thing (same shape as hit.thing); `object` is a non-enumerable getter so the result stays JSON-able */
34
33
  function nativeThing(e, en, root) {
35
34
  const tier = e._things.tier(en), say = SAY[tier];
36
35
  const out = { id: en.id, kind: root.type, owner: en.owner, at: en.at, phase: en.phase, ...(en.op && { op: en.op, tick: en.tick }), saved: tier,
37
36
  keeps: say.keeps, loses: say.loses, edit: editText(en, tier), removed: e._things.gone.has(en.id),
38
37
  template: null, definedAt: null, model: null, fields: {} };
39
- return withExplain(e, Object.defineProperty(out, 'object', { get: () => root, enumerable: false }));
38
+ return Object.defineProperty(out, 'object', { get: () => root, enumerable: false });
40
39
  }
41
40
 
42
41
  /**
@@ -60,7 +59,7 @@ const native = (e, hit) => hit && hit[0].owner !== 'world' ? nativeThing(e, hit[
60
59
  function recordAsThing(e, id) {
61
60
  const src = e._things.source(id), r = src.explain(id);
62
61
  const out = { ...r, owner: 'world', at: r.definedAt ?? null, phase: r.spawned ? 'play' : 'setup', saved: 'record', ...SAY.record, edit: editText(null, 'record', r.edit) };
63
- return withExplain(e, Object.defineProperty(out, 'object', { get: () => src.view(id), enumerable: false }));
62
+ return Object.defineProperty(out, 'object', { get: () => src.view(id), enumerable: false });
64
63
  }
65
64
  /** Every id engine.thing knows (for "did you mean") */
66
65
  function thingIds(e) { return [...e._things.recordIds(), ...e._things.byId.keys()]; }
@@ -76,8 +75,8 @@ function patchOf(o, a) {
76
75
  return p;
77
76
  }
78
77
  const xyz = p => Array.isArray(p) ? { x: p[0], y: p[1], z: p[2] } : p;
79
- const yaw = r => typeof r === 'number' ? r : r[1];
80
- const uni = s => typeof s === 'number' ? s : s[0];
78
+ /** thing.set args as a record patch. rotation and scale pass as given, a number or [x, y, z], as the record's rot and scale read them */
79
+ const recordPatch = a => ({ ...(a.position && { position: xyz(a.position) }), ...(a.rotation != null && { rot: a.rotation }), ...(a.scale != null && { scale: a.scale }) });
81
80
 
82
81
  /** Register the registry, engine.thing's ops, the 'scene' save part and the session:start setup window (called once by the Engine constructor) */
83
82
  export function installThings(e) {
@@ -108,12 +107,12 @@ export function installThings(e) {
108
107
  for (const o of e.scene.children) { const owner = moduleOwnerOf(o); if (owner && !T.byObj.has(o)) T.add(o, { owner }, null); }
109
108
  T.explainers = []; // explain contributions from modules (see thingExplain.js)
110
109
  /**
111
- * Add a contribution to engine.thing(id).explain(): fn(engine, thing, out) may fill out.state / out.rules (or add keys) for the things its module owns.
110
+ * Add a contribution to engine.explain({ thing: id }): fn(engine, thing, out) may fill out.state / out.rules (or add keys) for the things its module owns.
112
111
  * For module authors: core never reads another module's record or template shape, the module hands it over here. A throwing fn is skipped.
113
112
  * @param {(e: any, t: any, out: any) => void} fn
114
113
  * @example engine.explainWith((e, t, out) => { const r = e.myRecords.get(t.id); if (r) out.state = { ...r }; });
115
114
  */
116
- e.explainWith = fn => { T.explainers.push(fn); };
115
+ e.explainWith = fn => { T.explainers.push(fn); return { remove: () => { T.explainers = T.explainers.filter(x => x !== fn); } }; };
117
116
  e.saves.register('scene', { atomic: true, save: () => T.save(), load: d => T.load(d) });
118
117
  const kindOf = id => T.source(id) ? 'record' : T.live(id) ? T.tier(T.byObj.get(T.live(id))) : null;
119
118
  const reasons = {
@@ -121,16 +120,23 @@ export function installThings(e) {
121
120
  engineOwned: 'an engine module manages this object (water, particles, physics…); change it through that module',
122
121
  recordVisible: 'a world record has no visible flag: hide its model with present({ show: rec => … }) and a field set by world.set',
123
122
  badPosition: 'position takes [x, y, z] or { x, y, z } with finite numbers (y may be left out of the object)',
123
+ ownerRefuses: 'what owns this record cannot apply the change (facts.why says why and what to do instead)',
124
124
  };
125
125
  e.ops.define('thing.set', {
126
126
  targets: '*',
127
- desc: 'Move / turn / scale / show or hide a thing: a world record (via world.set / move) or an engine.add object (saved as an override when it has an id)',
127
+ desc: 'Move / turn / scale / show or hide a thing: a world record (via world.set / move; a live character or a body gets it through its owner) or an engine.add object (saved as an override when it has an id)',
128
128
  args: { id: 'string', position: 'any?', rotation: 'any?', scale: 'any?', visible: 'bool?' },
129
- can: (_, a) => { const k = kindOf(a.id); return !k ? 'noThing' : k === 'engine' ? 'engineOwned' : k === 'record' && a.visible != null ? 'recordVisible' : a.position != null && !goodPos(a.position) ? 'badPosition' : true; },
129
+ can: (_, a) => {
130
+ const k = kindOf(a.id);
131
+ if (!k || k === 'engine') return k ? 'engineOwned' : 'noThing';
132
+ if (k === 'record' && a.visible != null) return 'recordVisible';
133
+ if (a.position != null && !goodPos(a.position)) return 'badPosition';
134
+ const why = k === 'record' && T.source(a.id).refuses(a.id, recordPatch(a));
135
+ return why ? { code: 'ownerRefuses', facts: { why } } : true;
136
+ },
130
137
  run(eng, a) {
131
138
  if (kindOf(a.id) === 'record') {
132
- const patch = { ...(a.position && { position: xyz(a.position) }), ...(a.rotation != null && { rot: yaw(a.rotation) }), ...(a.scale != null && { scale: uni(a.scale) }) };
133
- return { record: true, before: T.source(a.id).set(a.id, patch) };
139
+ return { record: true, before: T.source(a.id).set(a.id, recordPatch(a)) };
134
140
  }
135
141
  const obj = T.live(a.id), p = patchOf(obj, a);
136
142
  if (T.tier(T.byObj.get(obj)) === 'code') return T.override(a.id, obj, p);
@@ -138,6 +144,7 @@ export function installThings(e) {
138
144
  write(obj, p);
139
145
  return before;
140
146
  },
147
+ canUndo(_, a, v) { if (!v) return NOTHING_TO_UNDO; const why = v.record && T.source(a.id)?.refusesUndo(a.id, v.before); return why ? { code: 'ownerRefuses', facts: { why } } : true; },
141
148
  undo(eng, a, v) {
142
149
  if (v.record) { T.source(a.id).set(a.id, v.before); return; }
143
150
  const obj = T.live(a.id); if (!obj) return;
@@ -160,6 +167,7 @@ export function installThings(e) {
160
167
  T.hide(a.id, T.live(a.id), T.tier(T.byObj.get(T.live(a.id))) === 'code');
161
168
  return {};
162
169
  },
170
+ canUndo: (_, a, v) => v ? true : NOTHING_TO_UNDO,
163
171
  undo(eng, a, v) {
164
172
  if (!v.record) { T.unhide(a.id); return; }
165
173
  v.src.restore(v.record);
@@ -8,7 +8,7 @@ import { DEV, warnOnce } from '../base/validate.js';
8
8
  import { codedError, coded } from '../base/errorHints.js';
9
9
  import { stackFrames, frameText } from '../ops/stackFrames.js';
10
10
  import { isPlainObject } from '../base/util.js';
11
- import { refuseSave } from '../saves/saveValues.js';
11
+ import { refuseSave } from '../base/saveValues.js';
12
12
 
13
13
  /** Throw save-bad-record when the 'scene' part is not { set: { id: { prop: value } }, removed: [id] } (same refusal as the world part, world/persist.js) */
14
14
  function checkSceneSave(d) {
@@ -11,6 +11,16 @@ export function forcedTier(search = typeof location === 'undefined' ? '' : locat
11
11
  return TIERS.includes(t) ? t : null;
12
12
  }
13
13
 
14
+ /** The name under engine.saves.storageKey of a player's MSAA choice */
15
+ export const MSAA_KEY = 'msaa';
16
+ /**
17
+ * The player's MSAA choice for this game, or null. Read in createEngine before the renderer, and so before saves exist: the key is storageKey(MSAA_KEY) spelled from saveKey.
18
+ * @param {string} saveKey @returns {boolean | null}
19
+ */
20
+ export function storedMsaa(saveKey) {
21
+ try { const v = localStorage.getItem(`${saveKey}-${MSAA_KEY}`); return v == null ? null : v === '1'; } catch { return null; }
22
+ }
23
+
14
24
  /**
15
25
  * Default render scale. High tier: the display scale up to 1.5. Low tier: at least 0.75 x display scale (1.5 on a 2x screen; a fixed 1 there
16
26
  * would be an upscaled blurry picture), never above 1.5 or the display scale.
@@ -1,28 +1,145 @@
1
1
  // engine.autoView: the camera and drawing-buffer values the engine changes on its own (camera.far for the view range, camera.fov for the settings slider and camera
2
2
  // modules, the pixel ratio for adaptive resolution). Each is an owned property (core/ops/owned.js): a game's direct write wins, manual() takes one on purpose.
3
+ import * as THREE from 'three';
3
4
  import { codedError } from '../base/errorHints.js';
4
5
  import { defineOwned, manualVerb } from '../ops/owned.js';
5
6
 
6
7
  /**
7
- * Every engine write of camera.fov (settings menu slider, camera modules) goes through here: it yields to a fov the game set itself.
8
+ * What engine.camera accepts: exactly THREE.PerspectiveCamera or THREE.OrthographicCamera. Exactly, because a subclass (ArrayCamera, a game's own) may draw by rules the engine's
9
+ * cameras, shadows and post chain never read.
10
+ * @param {any} cam
11
+ */
12
+ export function checkCamera(cam) {
13
+ if (cam?.constructor === THREE.PerspectiveCamera || cam?.constructor === THREE.OrthographicCamera) return;
14
+ throw codedError('camera-option', `engine.camera takes a THREE.PerspectiveCamera or THREE.OrthographicCamera, got ${cam?.constructor?.name ?? cam}. Make one of those two, or keep a `
15
+ + `subclass of your own out of engine.camera: render with it into a target in engine.onRender(({ renderer, scene }) => ...)`);
16
+ }
17
+
18
+ /**
19
+ * Give a real orthographic camera a view height and shape around its own center, before camera.zoom.
20
+ * @param {THREE.OrthographicCamera} c @param {number} height world units @param {number} [aspect] width / height, left out: as it is
21
+ */
22
+ export function fitOrtho(c, height, aspect = (c.right - c.left) / (c.top - c.bottom)) {
23
+ const x = (c.left + c.right) / 2, y = (c.top + c.bottom) / 2, w = height * aspect;
24
+ c.left = x - w / 2; c.right = x + w / 2; c.top = y + height / 2; c.bottom = y - height / 2;
25
+ c.updateProjectionMatrix();
26
+ }
27
+
28
+ /** The one place that writes camera.fov. A real orthographic camera has none @param {any} e @param {number} v */
29
+ function writeLens(e, v) { const c = e.camera; if ('fov' in c && c.fov !== v) { c.fov = v; c.updateProjectionMatrix(); } }
30
+
31
+ /**
32
+ * Every engine write of camera.fov that is the base view (settings menu slider, camera modules) goes through here: it yields to a fov the game set itself.
33
+ * While someone holds the camera the value is what the view goes back to, not what it shows now (viewHold).
8
34
  * @param {any} e @param {number} v
9
35
  */
10
- export function setFov(e, v) { e._oFov.drive(v); }
36
+ export function setFov(e, v) {
37
+ if (v == null) return;
38
+ const h = e._viewHold, o = e._oFov;
39
+ if (!h) { o.drive(v); return; }
40
+ o.check();
41
+ if (o.on) h.fov = v;
42
+ }
43
+
44
+ /**
45
+ * The fov a holder of the camera shows (a shot, a named view): a layer on the base view, gone when the last holder leaves. It goes on even over a fov the game owns, because the
46
+ * game asked for this shot; the game's value is what the hold recorded, so it comes back with the rest.
47
+ * @param {any} e @param {number} v only with the camera held
48
+ */
49
+ export function holdFov(e, v) {
50
+ e._oFov.check();
51
+ writeLens(e, v);
52
+ e._oFov.mark();
53
+ e._viewHold.shown = e.camera.fov;
54
+ }
55
+
56
+ /**
57
+ * The fov of a rig's shot. A shot with one is a layer on the base view like a holder's, so the slider's value waits under it; null, a shot without one, lets the base view show.
58
+ * It yields to a fov the game took, as setFov does. Why not setFov: a rig writes every frame, and what it writes there is the base, so nothing else could ever change it.
59
+ * @param {any} e @param {number | null} v
60
+ */
61
+ export function shotFov(e, v) {
62
+ e._oFov.check();
63
+ e._shotLens = v != null && e._oFov.on;
64
+ viewHold(e);
65
+ if (e._shotLens) holdFov(e, v);
66
+ }
67
+
68
+ /**
69
+ * The 'camera' stack changed. Why here and not in each holder: every holder used to record the fov it found and write it back when it left, so two overlapping shots handed back
70
+ * each other's half-way value and a slider moved meanwhile was lost. The first holder records the view it took, whatever asks for the view during the hold changes that record, and
71
+ * the last one out lands it. A fov someone else wrote during the hold differs from what the holders showed, and stays.
72
+ * @param {any} e
73
+ */
74
+ export function viewHold(e) {
75
+ const held = e.stacks.get('camera').size() > 0 || !!e._shotLens, h = e._viewHold;
76
+ if (held === !!h) return;
77
+ if (held) { e._viewHold = { fov: e.camera.fov, shown: e.camera.fov, projection: null }; return; }
78
+ e._viewHold = null;
79
+ if (h.projection) setProjection(e, ...h.projection);
80
+ if (e.camera.fov !== h.shown || h.fov === undefined) return;
81
+ writeLens(e, h.fov);
82
+ e._oFov.mark(); // the record is the engine's own write; a fov that differed above stays for check() to see
83
+ }
84
+
85
+ /** The fov of the perspective view: while a rig's orthographic camera stands in, that is the camera it stands in for @param {any} e @returns {number | undefined} */
86
+ export const lensFov = e => (e._ortho?.home ?? e.camera).fov;
87
+
88
+ /** The base view's fov, what a shot with none blends to @param {any} e @returns {number | undefined} */
89
+ export const baseFov = e => e._viewHold?.fov ?? lensFov(e);
90
+
91
+ /** Hand everything a camera carries that its class does not decide to the next one, and make it engine.camera @param {any} e @param {any} to */
92
+ function swapCamera(e, to) {
93
+ const from = e.camera;
94
+ to.near = from.near; to.far = from.far; to.zoom = from.zoom; to.layers.mask = from.layers.mask;
95
+ to.position.copy(from.position); to.quaternion.copy(from.quaternion); to.up.copy(from.up);
96
+ if (from.parent) { from.parent.add(to); from.removeFromParent(); }
97
+ if (from.children.length) to.add(...from.children); // what a game hung on the camera stays on the view
98
+ e.camera = to;
99
+ }
100
+
101
+ /**
102
+ * A rig's projection option, as a thin call into the one way to an orthographic view: a real THREE.OrthographicCamera in engine.camera (the setter in core/engine/Engine.js, where
103
+ * everything that draws, picks or owns a camera value already follows). The option stays because a view is not only a camera: a shot, a rig switch and a new playthrough each ask
104
+ * for theirs, and going back needs someone who remembers what was there. That memory is engine._ortho: the one orthographic camera the rigs share, and the camera it stands in for.
105
+ * A camera the game assigned is never overruled: 'perspective' is the rigs' "back to the default" and leaves a real orthographic camera as it is, and 'orthographic' on one only
106
+ * sets its height.
107
+ * @param {any} e the engine
108
+ * @param {'perspective' | 'orthographic'} [projection]
109
+ * @param {number} [size] orthographic only: world units covered by the view height (before camera.zoom)
110
+ */
111
+ export function setProjection(e, projection = 'perspective', size = 20) {
112
+ if (projection !== 'perspective' && projection !== 'orthographic') throw codedError('camera-option', `projection must be 'perspective' or 'orthographic', got '${projection}'`);
113
+ if (e._viewHold) { e._viewHold.projection = [projection, size]; return; } // a swap would pull the camera out from under the holder: it lands with the rest of the view
114
+ const cam = e.camera;
115
+ if (projection === 'perspective') { if (cam === e._ortho?.camera) swapCamera(e, e._ortho.home); return; }
116
+ if (!(size > 0)) throw codedError('camera-option', `orthographic projection needs size > 0 (world units of view height), got ${size}`);
117
+ if (cam.isOrthographicCamera) { if (cam.top - cam.bottom !== size) fitOrtho(cam, size); return; }
118
+ e._ortho ??= { camera: new THREE.OrthographicCamera(), home: null };
119
+ e._ortho.home = cam;
120
+ fitOrtho(e._ortho.camera, size, cam.aspect);
121
+ swapCamera(e, e._ortho.camera);
122
+ }
11
123
 
12
124
  /** @param {any} e */
13
125
  export function defineView(e) {
14
126
  const cam = () => e.camera;
127
+ // A real THREE.OrthographicCamera has no fov and no aspect, and its depth range is the game's: the engine leaves its far and fov alone, and its aspect is the frustum's shape.
128
+ // The one a rig's projection made (setProjection) stands in for the perspective camera, so its far stays the view range's and goes back with the swap.
129
+ // Rounded because a new view height writes the frustum again, and float noise there is not a game's write
130
+ const lens = () => 'fov' in cam(), shape = c => Math.round((c.right - c.left) / (c.top - c.bottom) * 1e6) / 1e6;
15
131
  e._oFar = defineOwned(e, { id: 'view.far', part: 'view', key: 'far', read: () => cam().far, objects: [e.camera],
16
- write: v => { cam().far = v; cam().updateProjectionMatrix(); }, levels: { manual: "engine.autoView.manual('far')" } });
132
+ write: v => { if (lens() || cam() === e._ortho?.camera) { cam().far = v; cam().updateProjectionMatrix(); } }, levels: { manual: "engine.autoView.manual('far')" } });
17
133
  e._oPixelRatio = defineOwned(e, { id: 'view.pixelRatio', part: 'view', key: 'pixelRatio', read: () => e.renderer.getPixelRatio(), objects: [e.renderer],
18
134
  levels: { manual: "engine.autoView.manual('pixelRatio')", set: 'engine.setPixelRatio(1.5)' } });
19
- // fov: the settings menu slider and camera modules (first person / rts / fixed shots, and restoring the fov at uninstall) write it.
20
- // They all go through setFov, so a game that sets camera.fov itself (a zoom, a cutscene) is not undone by the next camera switch.
135
+ // fov: the settings menu slider and camera modules (first person / rts / fixed shots, and restoring the fov at uninstall) go through setFov, and a holder's shot through holdFov,
136
+ // so a game that sets camera.fov itself (a zoom) is not undone by the next camera switch.
21
137
  e._oFov = defineOwned(e, { id: 'view.fov', part: 'view', key: 'fov', read: () => cam().fov, objects: [e.camera],
22
- write: v => { if (cam().fov !== v) { cam().fov = v; cam().updateProjectionMatrix(); } }, levels: { manual: "engine.autoView.manual('fov')" } });
23
- // aspect: the engine writes it on every resize. A game's own (letterbox, split view) stays, the same as far and fov
24
- e._oAspect = defineOwned(e, { id: 'view.aspect', part: 'view', key: 'aspect', read: () => cam().aspect, objects: [e.camera],
25
- write: v => { cam().aspect = v; cam().updateProjectionMatrix(); }, levels: { manual: "engine.autoView.manual('aspect')" } });
138
+ write: v => writeLens(e, v), levels: { manual: "engine.autoView.manual('fov')" } });
139
+ // aspect: the engine writes it on every resize and when engine.camera is assigned. A game's own (letterbox, split view) stays, the same as far and fov.
140
+ // A real orthographic camera keeps its view height and its width follows; left / right the game wrote itself count as its own aspect
141
+ e._oAspect = defineOwned(e, { id: 'view.aspect', part: 'view', key: 'aspect', read: () => (lens() ? cam().aspect : shape(cam())), objects: [e.camera],
142
+ write: v => { const c = cam(); if (lens()) { c.aspect = v; c.updateProjectionMatrix(); } else fitOrtho(c, c.top - c.bottom, v); }, levels: { manual: "engine.autoView.manual('aspect')" } });
26
143
  e._oFar.mark(); e._oPixelRatio.mark(); e._oFov.mark(); e._oAspect.mark();
27
144
  e.autoView = {
28
145
  /**
@@ -102,7 +102,6 @@ export class Batching {
102
102
  this._on = on;
103
103
  if (on) {
104
104
  s.addEventListener('childadded', this._add); s.addEventListener('childremoved', this._rem);
105
- s.add(this.root);
106
105
  for (const c of s.children) if (c !== this.root) this.incoming.add(c);
107
106
  } else {
108
107
  s.removeEventListener('childadded', this._add); s.removeEventListener('childremoved', this._rem);
@@ -2,7 +2,7 @@
2
2
  // camera focus, a teleport destination)
3
3
  // and the result unloads when far from all of them. Ten thousand entries build only the nearby ones.
4
4
  // const h = engine.stream.add({ position: [40, 0, -20], radius: 8, build: () => makeHouse() }); // the object build returns is added to the scene automatically
5
- // engine.stream.setRadius(200); // how far from each stream source to build (meters); defaults to the terrain view distance, or the signal uViewDistance
5
+ // engine.stream.radius = 200; // how far from each stream source to build (meters); defaults to the terrain view distance, or the signal uViewDistance
6
6
  // without terrain
7
7
  // h.remove(); // no longer needed (a built one is unloaded)
8
8
  // Stream sources (stream.player, stream.camera, stream.source(...), stream.teleport(...)) are the one list every distance-based loader reads: stream entries,
@@ -45,6 +45,7 @@ export class Stream {
45
45
  /** @internal */ this._radiusDirty = false;
46
46
  /** @internal what the sources looked like at the last check */ this._memo = {};
47
47
  /** @internal */ this._dirty = true;
48
+ /** @internal the radius the last pass reached with */ this._passR = null;
48
49
  /** @internal */ this._sources = new Set();
49
50
  /** @internal Bumps when a source is added, removed or moved with at() */ this._version = 0;
50
51
  /** @internal name -> (source) => boolean */ this._checks = new Map();
@@ -53,6 +54,7 @@ export class Stream {
53
54
  /** Built-in source at the camera focus engine.focus: full detail, no physics @type {StreamSource} */
54
55
  this.camera = this.source(engine.focus, { name: 'camera', physics: false });
55
56
  this.addReadyCheck('stream', s => s.detail !== 'full' || this.ready);
57
+ this.addReadyCheck('state', s => !s._waitsForLoad || !engine.saves.replacing);
56
58
  }
57
59
  /** The build radius actually in use, in meters @returns {number} @experimental */
58
60
  get activeRadius() {
@@ -78,26 +80,24 @@ export class Stream {
78
80
  this._dirty = true;
79
81
  return h;
80
82
  }
81
- /** @internal Clear all entries and drop added sources (called by engine.dispose; built objects are released with the scene; the two built-in sources stay) */
83
+ /** @internal Clear all entries and remove every source, so no whenReady is left waiting for a frame (called by engine.dispose; built objects are released with the scene) */
82
84
  dispose() {
83
85
  this.entries.clear(); this.cells.clear(); this.live.clear(); this.queued = 0;
84
- for (const s of [...this._sources]) if (s !== this.player && s !== this.camera) s.remove();
86
+ for (const s of [...this._sources]) s.remove();
85
87
  this._checks.clear();
86
88
  }
87
89
  /**
88
90
  * Build radius in meters around each full-detail stream source (a source radius caps it); null = follow the terrain view distance (the uViewDistance signal
89
- * without terrain). Writing it takes effect like setRadius.
91
+ * without terrain).
90
92
  * @type {number | null}
91
93
  */
92
94
  get radius() { return this._radius; }
93
95
  set radius(m) {
94
96
  // Infinity would hang _update's cell walk and NaN would build nothing, without a word
95
97
  if (m != null && !(m >= 0 && Number.isFinite(m))) throw codedError('stream-option', `stream.radius is a finite number of meters >= 0, or null to follow the view distance; got ${m}`);
96
- this._radius = m; this._dirty = true;
98
+ this._radius = m;
97
99
  }
98
- /** Set the build radius in meters @param {number} m @experimental */
99
- setRadius(m) { this.radius = m; }
100
- /** Everything registered within radius is built (start() waits for it before the loading screen goes away) @returns {boolean} */
100
+ /** 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) @returns {boolean} */
101
101
  get ready() { return this.queued === 0; }
102
102
  /** entries is the registered count, built the built count, queued the queued count @returns {{ entries: number, built: number, queued: number }} */
103
103
  get stats() { return { entries: this.entries.size, built: this.live.size - this.queued, queued: this.queued }; }
@@ -120,6 +120,7 @@ export class Stream {
120
120
  if (opts.detail != null && opts.detail !== 'full' && opts.detail !== 'simple') throw codedError('stream-option', fmt(SOURCE_STRINGS.detail, { got: String(JSON.stringify(opts.detail)) }));
121
121
  const s = new Source(this, position, opts);
122
122
  this._sources.add(s); this._version++;
123
+ if (this.engine.disposed) s.remove(); // no frame will ever settle it
123
124
  return /** @type {any} */ (s);
124
125
  }
125
126
 
@@ -128,6 +129,10 @@ export class Stream {
128
129
  * (terrain chunks, collision, nearby models) the player stays where it is. move replaces the default placement (for a vehicle or a custom character).
129
130
  * timeout (seconds of frame time, default 60; Infinity waits forever): when the destination is still not ready, the Promise rejects (code stream-timeout,
130
131
  * naming the loaders still waiting) and the player is not moved.
132
+ * 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
133
+ * 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)).
134
+ * A trip belongs to the state it was asked in: it does not land while a load runs, and a newGame, load or saves.load that goes through abandons it (it rejects with
135
+ * code stream-removed and the player stays where the new state put it). A load that fails leaves it going.
131
136
  * @example await engine.stream.teleport([800, 0, 300]);
132
137
  * @example await engine.stream.teleport(door.target, { radius: 40, move: p => engine.player.placeAt(p) });
133
138
  * @param {any} position
@@ -138,14 +143,20 @@ export class Stream {
138
143
  async teleport(position, opts = {}) {
139
144
  readParams('stream.teleport()', keysSchema(['radius', 'move', 'timeout']), opts);
140
145
  const e = this.engine, s = this.source(position, { radius: opts.radius ?? 64, name: 'teleport' }), limit = opts.timeout ?? 60;
146
+ // session.id would miss saves.load. A load under way may still fail and give this state back, so the move waits for its end; one asked inside the load (a part's load awaiting it) cannot wait for itself.
147
+ // Rejecting, not resolving: the caller's next line belongs to the old state too
148
+ s._waitsForLoad = !e.saves.replacing;
149
+ const generation = e.saves.generation, abandoned = () => codedError('stream-removed', fmt(SOURCE_STRINGS.abandoned, { x: s.x.toFixed(1), z: s.z.toFixed(1) }));
141
150
  let waited = 0;
142
151
  const watch = e.onFrame(dt => {
152
+ if (e.saves.generation !== generation && !e.saves.replacing) { s._settle(abandoned()); return; } // no reason to keep loading a place nobody is going to
143
153
  if ((waited += dt) <= limit || s.ready) return;
144
154
  const checks = [...this._checks].filter(([, fn]) => !fn(s)).map(([n]) => n).join(', ') || 'one more frame';
145
155
  s._settle(codedError('stream-timeout', fmt(SOURCE_STRINGS.timeout, { x: s.x.toFixed(1), z: s.z.toFixed(1), t: String(limit), checks })));
146
156
  });
147
157
  try {
148
158
  await s.whenReady;
159
+ if (e.saves.generation !== generation) throw abandoned();
149
160
  // the move lands frames after the call (and after the op that asked for it has returned): it finishes that request, so the ops guard lets it through
150
161
  e.ops.allow(() => {
151
162
  if (opts.move) opts.move(position);
@@ -238,11 +249,12 @@ export class Stream {
238
249
  this._radiusDirty = false; this._maxRadius = 0;
239
250
  for (const h of this.entries) this._maxRadius = Math.max(this._maxRadius, h.def.radius ?? 0);
240
251
  }
241
- const cs = this.cellSize;
242
- if (!this.changed(this._memo, cs / 8, FULL) && !this._dirty) return;
243
- this._dirty = false;
252
+ const cs = this.cellSize, R = this.activeRadius;
253
+ // the radius follows the view distance, which a settings menu moves while the player stands still
254
+ if (!this.changed(this._memo, cs / 8, FULL) && !this._dirty && R === this._passR) return;
255
+ this._dirty = false; this._passR = R;
244
256
  // full-detail sources only: a 'simple' source (far view) gets terrain and hlod proxies, not props
245
- const src = this.sources(FULL), R = this.activeRadius;
257
+ const src = this.sources(FULL);
246
258
  const dist = h => this._dist(h, src, R);
247
259
  // unload what is far from every source
248
260
  for (const h of this.live) if (!h.def.keep && dist(h) > R * this.unloadFactor) this._leave(h);
@@ -19,6 +19,7 @@ function makeMesh(B, g, capacity) {
19
19
  im.matrixAutoUpdate = false; im.raycast = noRaycast; // rays hit the originals (on BATCH_LAYER), never the batch
20
20
  im.userData = { budgetTag: 'batch', cell: g.cell };
21
21
  g.mesh = im; B.byMesh.set(im, g); B.root.add(im);
22
+ if (!B.root.parent) B.engine.scene.add(B.root); // joins at the first batch: a scene with none is the game's alone
22
23
  g.watch?.remove();
23
24
  let version = -1; // the box follows the instances: a stale one would hide what stands elsewhere now
24
25
  g.watch = B.engine.occlusion.watch([im], () => {
@@ -55,12 +55,15 @@ function bucketsOf(rule, CHUNK) {
55
55
  /**
56
56
  * Placement over one ground. chunk: edge length (m); seed: placement seed; surface / slope / typeAt (x, z): the ground;
57
57
  * skip(x, z): true where nothing may grow (edited terrain cells, flattened plots when the rule says avoidFlat), optional.
58
- * place(cx, cz, rule, density) returns instance matrices (column-major, chunk-local x / z), instance colors, collision circles (world x, z, radius)
58
+ * place(cx, cz, rule, density) (density thins only rules without a collider: blocking plants are the same at every quality) returns instance matrices (column-major, chunk-local x / z), instance colors, collision circles (world x, z, radius)
59
59
  * and stable ids (the attempt index, independent of density; with rule.positions the index in that list).
60
60
  * rule.positions replaces the random attempts: every listed spot in this chunk gets one instance at the ground height (scale / yaw from the entry
61
61
  * or the rule's random ranges); the scatter filters (perChunk, chance, cluster, heights, slope, biomes, avoidFlat) and density do not apply --
62
62
  * the game already chose the spot. skip still applies: dug or raised ground loses what grew there either way.
63
63
  */
64
+ /** How many attempts of a scatter rule a density keeps. One formula, because the vegetation draw side cuts by the same number: placing and drawing must agree on which plants a density means */
65
+ export const scatterAttempts = (rule, density) => Math.round((rule.perChunk ?? RULE.perChunk) * density);
66
+
64
67
  export function makePlacer({ chunk: CHUNK, seed, surface, slope, typeAt, fbm, skip = null, flat = null }) {
65
68
  const SEED = seed | 0;
66
69
  return function place(cx, cz, rule, density = 1) {
@@ -68,7 +71,7 @@ export function makePlacer({ chunk: CHUNK, seed, surface, slope, typeAt, fbm, sk
68
71
  const base = Math.imul(cx, 92821) ^ Math.imul(cz, 68917) ^ SEED ^ Math.imul(r.salt + 1, 40503), rnd = stream();
69
72
  const ox = cx * CHUNK, oz = cz * CHUNK;
70
73
  const listed = rule?.positions ? bucketsOf(rule, CHUNK).get(cx + ',' + cz) ?? [] : null;
71
- const attempts = listed ? listed.length : Math.round(r.perChunk * density);
74
+ const attempts = listed ? listed.length : scatterAttempts(r, r.collider ? 1 : density); // a plant that blocks (or is felled by id) is part of the world: quality density thins only what is decoration
72
75
  const m = new Float32Array(attempts * 16), c = new Float32Array(attempts * 3), k = new Float32Array(r.collider ? attempts * 3 : 0), ids = new Uint32Array(attempts);
73
76
  let n = 0;
74
77
  // one instance at local (lx, lz) on height h; s / yaw null = drawn from the rule's ranges. The same code for both paths, so a listed plant
@@ -15,7 +15,8 @@ const removedError = s => codedError('stream-removed', fmt(SOURCE_STRINGS.remove
15
15
  export const SOURCE_KEYS = ['radius', 'detail', 'physics', 'until', 'name'];
16
16
  export const SOURCE_STRINGS = {
17
17
  detail: 'stream.source(): detail must be \'full\' (models, stream entries, physics) or \'simple\' (terrain and hlod proxies only), got {got}',
18
- removed: 'stream source "{name}" was removed before it was ready (remove() or its until); nothing waits for it any more',
18
+ removed: 'stream source "{name}" was removed before it was ready (remove(), its until, or engine.dispose()); nothing waits for it any more',
19
+ abandoned: 'stream.teleport(): the game state was replaced (new game, load) before the destination ({x}, {z}) was ready; the trip was abandoned and the player was not moved',
19
20
  timeout: 'stream.teleport(): the destination ({x}, {z}) was not ready after {t} s; still waiting on: {checks}. The player was not moved',
20
21
  };
21
22
 
@@ -5,7 +5,7 @@
5
5
  // when the background work finishes: t.resolve(result); when no longer wanted: t.remove()
6
6
  // At the due tick (engine.time.tick at request + lag, default 30 steps = 0.5 s) requests take effect in a stable order (due tick, then request order):
7
7
  // finished -> apply(result); not finished -> apply(fallback()) (stats.late +1; a background result that arrives later is ignored); valid() false -> dropped.
8
- // A save load or level change (invalidate) drops the requests that have no valid: they were made for the old world. A request with valid decides itself
8
+ // A save load or level change (invalidate) drops the requests that have no valid: they were made for the old world (a load that fails gives them back: the old world stays). A request with valid decides itself
9
9
  // (terrain colliders survive a load because the terrain is the same; pass valid when your result belongs to state a load replaces).
10
10
  // So sync, async, delayed or out-of-order returns all give the same gameplay state at the same tick for the same input. Fixed steps do not run while frozen, so due time stops too.
11
11
  // Requests registered during loading (before engine.ready): start() calls rebase() when done and timing restarts from the playable moment (load time varies by machine and must not count); lag 0 takes effect right then.
@@ -17,6 +17,7 @@ const STRINGS = { noFallback: 'commits.request() needs a fallback: it is compute
17
17
  * Sync, async, delayed and out-of-order returns give the same gameplay state at the same tick for the same input. Results that only affect visuals need not go through here.
18
18
  */
19
19
  import { codedError } from '../base/errorHints.js';
20
+ import { reportError } from '../base/errors.js';
20
21
 
21
22
  export class Commits {
22
23
  /** @internal */
@@ -59,10 +60,13 @@ export class Commits {
59
60
  while (this.queue.length && this.queue[0].due <= now) {
60
61
  const t = this.queue.shift();
61
62
  if (t.canceled || (t.valid ? !t.valid() : t.epoch !== this.epoch)) { this.stats.dropped++; continue; }
62
- if (!t.done) { t.result = t.fallback(); t.done = true; this.stats.late++; }
63
- if (t.canceled) { this.stats.dropped++; continue; } // the fallback itself gave up on the request (a job that failed): nothing to apply
64
- t.apply(t.result);
65
- this.stats.applied++;
63
+ // each request on its own: one that throws must not push the next ones due to a later tick, or to never, in a frozen dev game
64
+ try {
65
+ if (!t.done) { t.result = t.fallback(); t.done = true; this.stats.late++; }
66
+ if (t.canceled) { this.stats.dropped++; continue; } // the fallback itself gave up on the request (a job that failed): nothing to apply
67
+ t.apply(t.result);
68
+ this.stats.applied++;
69
+ } catch (err) { reportError(this.engine, err, 'background result apply (commits)'); }
66
70
  }
67
71
  }
68
72
  /** @internal Called when start() finishes loading and when a new playthrough restarts the tick: pending requests restart timing from now (due = now + lag); lag 0 takes effect immediately */
@@ -73,6 +77,7 @@ export class Commits {
73
77
  }
74
78
  /** @internal Drop all requests (engine.dispose calls it) */
75
79
  dispose() { this.queue.length = 0; }
76
- /** @internal A save load or level change replaced the world: results requested for the old one must not land on the new one (counted as dropped) */
77
- invalidate() { this.epoch++; }
80
+ /** @internal A save load or level change replaced the world: results requested for the old one must not land on the new one (counted as dropped).
81
+ * Returns undo() for a load that failed; a level change since then keeps them dropped, the world they were for has been rebuilt */
82
+ invalidate() { const was = this.epoch, mine = ++this.epoch; return () => { if (this.epoch === mine) this.epoch = was; }; }
78
83
  }
@@ -6,6 +6,7 @@
6
6
  // Jobs that change gameplay state pass apply: the result takes effect on a fixed tick through engine.commits, not on whichever frame the work finished (machine speed must not affect gameplay):
7
7
  // engine.jobs.add(function* () { ...compute...; yield; ...; return result; }, { apply: result => changeGameplayState })
8
8
  // If the job is not done by the due tick, the remaining steps run to completion on the spot, so such a job must be a plain function or generator (it cannot return a Promise).
9
+ // Those steps are capped by maxSteps too: a generator that never ends would hang the fixed step, so past the cap its promise rejects with jobs-endless and apply does not run.
9
10
  // With apply, the returned Promise resolves when the work finishes, which may be before apply runs (it waits for the fixed tick); put anything that needs "state already changed" inside apply, do not assume it after await.
10
11
  // A single step that is too slow (one next() over slowStepMs in the real-time loop) warns once in dev: add more yields to a loop to slice it, since the budget only limits how many steps run, it cannot split one step.
11
12
  // Two ways to advance:
@@ -16,7 +17,10 @@
16
17
  import { warnOnce, fmt } from '../base/validate.js';
17
18
  import { codedError, coded } from '../base/errorHints.js';
18
19
 
19
- const STRINGS = { slow: 'engine.jobs: one job step took {ms} ms (over {max}) and will hitch the frame; add more yield calls in the loop to slice it', async: 'engine.jobs.add(..., { apply }): a job that changes gameplay state cannot return a Promise (it must be finishable on the spot when due); make it a plain function or generator', tooMany: 'engine.jobs: deterministic advance (step / headless) did not finish within {n} steps; the rest continues next frame (is a job endlessly adding new jobs?)' };
20
+ const STRINGS = { slow: 'engine.jobs: a step of {who} took {ms} ms (over {max}) and will hitch the frame; add more yield calls in its loop to slice it, or give the function a name so this line can say which', async: 'engine.jobs.add(..., { apply }): a job that changes gameplay state cannot return a Promise (it must be finishable on the spot when due); make it a plain function or generator', endless: 'engine.jobs: {who} with apply was due and did not finish within {n} steps (engine.jobs.maxSteps), so it was stopped and its apply will not run. Make the generator end, or give it a later lag', tooMany: 'engine.jobs: deterministic advance (step / headless) did not finish within {n} steps, next up {who}; the rest continues next frame. If that job adds new jobs each time, end the chain' };
21
+
22
+ /** A job as a message names it: the function it was given */
23
+ const jobName = j => j.work?.name ? `job ${j.work.name}` : 'an unnamed job';
20
24
 
21
25
  // a runs before b: higher priority first, then earlier insertion
22
26
  const before = (a, b) => a.priority > b.priority || (a.priority === b.priority && a.seq < b.seq);
@@ -67,7 +71,11 @@ export class Jobs {
67
71
  }
68
72
  /** @internal Not done by the due tick: run the remaining steps now and return the result */
69
73
  _finishNow(j) {
70
- while (!j.finished && !j.failed) this._step(j);
74
+ // same cap as run(): the fixed step cannot wait for "next frame", so an endless generator fails here instead of hanging the page
75
+ for (let n = 0; !j.finished && !j.failed; n++) {
76
+ if (n >= this.maxSteps) { this._fail(j, codedError('jobs-endless', fmt(STRINGS.endless, { who: jobName(j), n: this.maxSteps }))); break; }
77
+ this._step(j);
78
+ }
71
79
  // A job that fails here already told its caller through the promise (j.rej). Throwing again from the fixed step would freeze the game a second time
72
80
  // for the same error, and apply(undefined) must not run: cancel the ticket, and Commits.tick drops a canceled request after its fallback
73
81
  if (j.failed) { j.ticket?.remove(); return undefined; }
@@ -83,7 +91,7 @@ export class Jobs {
83
91
  if (deterministic) {
84
92
  let n = 0;
85
93
  while (this.heap.length && n++ < this.maxSteps) this._stepTop();
86
- if (this.heap.length) warnOnce(coded('jobs-slow', fmt(STRINGS.tooMany, { n: this.maxSteps })));
94
+ if (this.heap.length) warnOnce(coded('jobs-slow', fmt(STRINGS.tooMany, { n: this.maxSteps, who: jobName(this.heap[0]) })));
87
95
  return;
88
96
  }
89
97
  const end = performance.now() + (this.engine.ready ? this.budgetMs : Math.max(this.budgetMs, this.loadingMs)); // measure: frame budget
@@ -103,11 +111,13 @@ export class Jobs {
103
111
  }
104
112
  const s = j.it.next();
105
113
  if (s.done) this._finish(j, s.value);
106
- } catch (err) { this._removeJob(j); j.failed = true; j.error = err; j.rej(err); }
114
+ } catch (err) { this._fail(j, err); }
107
115
  const ms = performance.now() - t0; // measure: step time
108
- if (ms > this.slowStepMs && this.engine.ready) warnOnce(coded('jobs-slow', fmt(STRINGS.slow, { ms: Math.round(ms), max: this.slowStepMs })));
116
+ if (ms > this.slowStepMs && this.engine.ready) warnOnce(coded('jobs-slow', fmt(STRINGS.slow, { who: jobName(j), ms: Math.round(ms), max: this.slowStepMs })));
109
117
  }
110
118
  /** @internal */
119
+ _fail(j, err) { this._removeJob(j); j.failed = true; j.error = err; j.rej(err); }
120
+ /** @internal */
111
121
  _finish(j, v) {
112
122
  if (j.ticket && typeof v?.then === 'function') throw codedError('engine-misuse', STRINGS.async);
113
123
  this._removeJob(j); this.doneCount++; j.finished = true; j.value = v; j.ticket?.resolve(v); j.res(v);
@@ -74,7 +74,10 @@ class Lane {
74
74
  return this.handler;
75
75
  }
76
76
  // The message is cloned like postMessage would, so a handler that changes its input behaves the same in both places
77
- _runLocal(msg) { return Promise.resolve().then(() => this._local()(structuredClone(msg))); }
77
+ // A lane disposed meanwhile answers nothing, like a worker it terminated: the code after this wait belongs to a dead engine (lifecycle.js)
78
+ _runLocal(msg) {
79
+ return new Promise((res, rej) => { Promise.resolve().then(() => this._local()(structuredClone(msg))).then(v => { if (!this._gone) res(v); }, err => { if (!this._gone) rej(err); }); });
80
+ }
78
81
  /**
79
82
  * Send a task; resolves with the handler's reply. Typed arrays you list in transfer move to the worker (unusable here afterwards);
80
83
  * if that worker then crashes, the task rejects (code threads-transfer) instead of rerunning on the main thread with emptied buffers.
@@ -119,7 +122,7 @@ class Lane {
119
122
  if (this.handler) this.handler(structuredClone(msg));
120
123
  }
121
124
  /** Stop the workers; open tasks never settle */
122
- dispose() { clearTimeout(this._watch); for (const s of this.workers) s.w.terminate(); this.workers = []; this.tasks.clear(); this.max = 0; this.threads.lanes.delete(this); }
125
+ dispose() { this._gone = true; clearTimeout(this._watch); for (const s of this.workers) s.w.terminate(); this.workers = []; this.tasks.clear(); this.max = 0; this.threads.lanes.delete(this); }
123
126
  }
124
127
 
125
128
  /**