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
@@ -6,17 +6,24 @@
6
6
  // Versus engine.saves.load(slot): that applies a save onto the running playthrough (quick load) and keeps what the game added during play.
7
7
  // Deleting a save is engine.saves.remove(slot); none of these touch stored saves.
8
8
  //
9
- // What ending a playthrough clears: handles passed to track(), clock function timers added after start() (boot-time ones come back with their original delay),
9
+ // What ending a playthrough clears: handles passed to track() and clock function timers added after start() (boot-time ones and a module's install-time ones, ctx.track, follow the module: they come back with their original delay while it stays; what a part's load() or an afterLoad sets up belongs to the new playthrough and stays),
10
10
  // a running engine.skip (cancelled), background results not yet applied (commits: worker / job results requested in the old playthrough never land), and every
11
11
  // save part (the state captured when start() finished is applied). Modules end their own part on 'session:end' (a cutscene is skipped, the music stops),
12
12
  // and the camera starts over on 'session:start' (the same rig object, as installed, keeping the view the load left on it). Listeners and hooks the game registered at boot stay: they belong to the game, not the playthrough.
13
13
  // engine.time.tick and every time view (core/time/time.js) start again from 0 or the save's value, and physics (rigid) rebuilds its world (velocities, sleep, solver caches), as on a fresh page.
14
14
  // Events: 'session:end' (before the reset; flow returns to its start state), 'session:start' { kind: 'new' | 'load', slot? } (after; flow goes to 'playing').
15
+ // Around a state replacement, one list for every door (saves.apply, saves.load, session.newGame / load / quit):
16
+ // a save put back 'save:loaded' with its slot ('(data)' for saves.apply): what is not saved ends, what is derived rebuilds. The playthrough runs from here: the title closes (_started)
17
+ // a new state session.* also end the old playthrough first ('session:end') and announce the new one ('session:start')
18
+ // rolled back 'session:failed' { kind, slot? }, kind 'quick' from saves.load / apply: what an end or a load took down comes back on this event, whichever door it was
19
+ // quit no playthrough runs until a new one starts: session.playing is false even with no title part, so autosave cannot write the blank state over a save
15
20
  // A replacement that fails (a save part's load() threw: saveApply rolled the data back) keeps the old playthrough: tracked handles, function timers
16
- // and clocks stay as they were, no 'session:start' fires, 'session:failed' { kind, slot? } does instead (flow goes back to the state it left).
21
+ // and clocks stay as they were, background results still land, no 'session:start' or title follows, 'session:failed' { kind, slot? } fires instead (flow goes back to the state it left).
17
22
  // What session:end already ended stays ended (the music stopped, a running cutscene was skipped to its end).
18
23
  import { codedError } from '../base/errorHints.js';
19
- import { DEV as IS_DEV, fmt } from '../base/validate.js';
24
+ import { DEV as IS_DEV, fmt, warnOnce } from '../base/validate.js';
25
+ import { applySave, partData } from './saveApply.js';
26
+ import { readSave } from './saveVersions.js';
20
27
 
21
28
  const DEV = {
22
29
  early: 'engine.session.{fn}() was called before engine.start() finished: the new-game state is captured when loading completes. Call it from a button or after `await engine.start()`.',
@@ -36,7 +43,7 @@ export function autosaveHook(saves, every, onRemove) {
36
43
  let t = 0;
37
44
  const tick = e.onFixed(dt => {
38
45
  if (!e.session.playing || e.error) { t = 0; return; } // nothing of a playthrough to keep: start counting again once one runs
39
- if ((t += dt) < every) return;
46
+ if ((t += dt) < every || saves._replace.turns) return; // in a door trip or a cutscene it waits, and goes on the first step after (stateReplace.js)
40
47
  t = 0; saves.save('auto');
41
48
  });
42
49
  return { remove: () => { tick.remove(); onRemove(); } };
@@ -50,36 +57,64 @@ export class Session {
50
57
  /** @internal JSON of the state when start() finished */ this._base = null;
51
58
  /** @internal clock function timers at that moment, with their remaining delay */ this._timers = [];
52
59
  /** @internal */ this._tracked = new Set();
53
- /** @internal true while newGame / load / quit replace the state */ this._busy = false;
54
- /** @internal the replacement running now */ this._running = null;
60
+ /** @internal parts _late captured from a module still installing */ this._lateParts = new Set();
61
+ /** @internal true after a quit with no title to stand for it, until a save or new game starts a playthrough: nothing else would say no playthrough runs */ this._over = false;
62
+ /** @internal true while newGame / load / quit replace the state. Shorter than the turn (stateReplace.js): session:start listeners run inside the turn and are in play */ this._busy = false;
63
+ /** @internal Which playthrough this is: 1 after the page opens, one more with each newGame / load / quit that went through (a quick saves.load stays in the playthrough). Not saved. Ops carry it as ctx.session */
64
+ this.id = 1;
55
65
  }
56
66
 
57
67
  /**
58
- * True while a playthrough runs: start() has finished, no newGame / load / quit is replacing the state, and the title screen is not up.
68
+ * True while a playthrough runs: start() has finished, no newGame / load / quit is replacing the state, and neither the title screen nor a finished quit stands in its place.
59
69
  * Autosave and other "only during play" work check it.
60
70
  * @type {boolean}
61
71
  * @experimental
62
72
  */
63
- get playing() { return !!this._base && !this._busy && !this.engine.ui.isOpen('title'); }
73
+ get playing() { return !!this._base && !this._busy && !this._over && !this.engine.ui.isOpen('title'); }
74
+
75
+ /** @internal start() finished: what changes now is not in the new-game state */
76
+ get captured() { return !!this._base; }
77
+ /** @internal newGame / load / quit are replacing the state; saves.load and saves.apply are not this */
78
+ get replacing() { return this._busy; }
79
+
80
+ /** @internal A state to play went in, by any door: it runs from here. The door decides, not each menu: a load from the settings over the title left the title up on a frozen game */
81
+ _started() { this._over = false; this.engine.ui.close('title'); }
64
82
 
65
83
  /** @internal Called by start() once the world is ready: what newGame returns to */
66
84
  _capture() {
67
85
  const base = this.engine.saves.collect();
68
86
  // each part checks its own new-game data (world: no records placed by code). Core only hands the data over: it never reads a part's format
69
- if (IS_DEV) for (const [key, p] of this.engine.saves.providers) if (p.checkNewGame && key in base.parts) p.checkNewGame(base.parts[key]);
87
+ if (IS_DEV) for (const [key, p] of this.engine.saves.providers) if (p.checkNewGame && Object.hasOwn(base.parts, key)) p.checkNewGame(base.parts[key]);
70
88
  this._base = JSON.stringify(base);
71
89
  this._timers = this.engine.time._snapshotFn();
72
90
  }
73
91
 
74
- /** @internal A save part registered after start() (engine.use later): its state now is its new-game state, so newGame resets it too */
92
+ /**
93
+ * @internal A save part registered after start() (engine.use later): its state now is its new-game state, so newGame resets it too. Data of that key stays while this part can
94
+ * read it, by the same check a load makes; left from a part it replaced at another version, it would refuse every new game for good.
95
+ */
75
96
  _late(key) {
76
97
  if (!this._base) return;
77
98
  const base = JSON.parse(this._base), p = this.engine.saves.providers.get(key);
78
- if (key in base.parts) return;
79
- try { const d = p.save(); if (d == null) return; base.parts[key] = d; base.versions[key] = p.version; } catch { return; } // its save() cannot run yet (or has nothing to save, like collectParts): newGame leaves this part as it is
99
+ if (Object.hasOwn(base.parts, key) && 'list' in readSave(base, new Map([[key, p]]), '(new game)')) return;
100
+ delete base.parts[key]; delete base.versions[key];
101
+ this._lateParts.add(key);
102
+ // its save() cannot run yet, or has nothing to save (like collectParts): newGame leaves this part as it is. Data a save cannot hold is said now: it would refuse every save too
103
+ try { const d = partData(key, p); if (d != null) { base.parts[key] = d; base.versions[key] = p.version; } } catch (err) { if (err?.code === 'save-part-threw') warnOnce(err.message); }
80
104
  this._base = JSON.stringify(base);
81
105
  }
82
106
 
107
+ /** @internal A module used after start() finished init: what its parts took from install was half built, and boot parts are captured after init too */
108
+ _lateInit(keys) {
109
+ for (const key of keys) if (this._lateParts.delete(key) && this.engine.saves.providers.has(key)) { const b = JSON.parse(this._base); delete b.parts[key]; delete b.versions[key]; this._base = JSON.stringify(b); this._late(key); this._lateParts.delete(key); }
110
+ }
111
+
112
+ /** @internal A module tracked this function timer while it installed after start(): install() will not run again to set it up, so it comes back at every new playthrough like a boot-time one */
113
+ _keepTimer(t) { if (this._base && !t.event) this._timers.push({ t, rem: t.due - this.engine.time.now(t.ch) }); }
114
+
115
+ /** @internal The module of this timer left: it stays gone */
116
+ _dropTimer(t) { this._timers = this._timers.filter(x => x.t !== t); }
117
+
83
118
  /**
84
119
  * Keep a handle only for this playthrough: newGame / load / quit call handle.remove(). Returns the handle.
85
120
  * @template {{ remove(): void }} H
@@ -95,6 +130,9 @@ export class Session {
95
130
  return handle;
96
131
  }
97
132
 
133
+ /** @internal A handle that outlives the playthrough after all (a module's hold), or that ended by itself. Returns the handle */
134
+ _untrack(handle) { this._tracked.delete(handle); return handle; }
135
+
98
136
  /**
99
137
  * Start a new playthrough from the state the game had right after start(). Returns Promise<boolean> (false only if a save part failed to load: the
100
138
  * old playthrough then goes on, with its data, listeners and timers, and 'session:failed' fires instead of 'session:start').
@@ -103,7 +141,7 @@ export class Session {
103
141
  * // a "Restart" button in a game-over screen
104
142
  * restartBtn.onclick = () => engine.session.newGame();
105
143
  */
106
- newGame() { return this._one('new', () => this._begin('newGame', () => this.engine.saves.apply(this._baseData(), '(new game)'), { kind: 'new' })); }
144
+ newGame() { return this._turn('new', () => this._begin('newGame', () => this._applyBase(), { kind: 'new' })); }
107
145
 
108
146
  /**
109
147
  * Continue from a save (or retry from a checkpoint) with nothing of the current playthrough left over: the new-game state with the save on top,
@@ -114,10 +152,13 @@ export class Session {
114
152
  * @example
115
153
  * engine.events.on('player:dead', () => engine.session.load('checkpoint')); // retry; the checkpoint was saved with engine.saves.save('checkpoint')
116
154
  */
117
- async load(slot = 'auto') {
118
- const S = this.engine.saves, bad = S.check(slot);
119
- if (bad) return bad === 'missing' ? false : S.load(slot); // load shows the message and changes nothing
120
- return this._one(`load ${slot}`, () => this._begin('load', () => S._load(slot, this._baseData()), { kind: 'load', slot }));
155
+ load(slot = 'auto') {
156
+ const S = this.engine.saves;
157
+ return this._turn(`load ${slot}`, () => {
158
+ const bad = S.check(slot);
159
+ if (bad) return bad === 'missing' ? false : S._load(slot); // load shows the message and changes nothing
160
+ return this._begin('load', () => S._load(slot, this._baseData()), { kind: 'load', slot });
161
+ });
121
162
  }
122
163
 
123
164
  /**
@@ -127,31 +168,30 @@ export class Session {
127
168
  * @example settingsBackToTitle.onclick = () => engine.session.quit();
128
169
  */
129
170
  quit() {
130
- return this._one('quit', async () => {
131
- const ok = await this._reset('quit', () => this.engine.saves.apply(this._baseData(), '(new game)'));
132
- this.engine.ui.open('title');
171
+ return this._turn('quit', async () => {
172
+ const ok = await this._reset('quit', () => this._applyBase());
173
+ if (ok) this._over = !this.engine.ui.open('title'); // ui.open answers false with no title part
174
+ else this.engine.events.emit('session:failed', { kind: 'quit' }); // rolled back: the old playthrough goes on, so no title over it
133
175
  return ok;
134
176
  });
135
177
  }
136
178
 
137
179
  /**
138
- * @internal One replacement at a time (two overlapping applies are unsound, saveApply.js). The same request joins the one running (a double-clicked
139
- * Restart); another one waits its turn: joined, a load asked during ?play's new game answered true and never loaded.
180
+ * @internal A session replacement takes its turn with every other one (stateReplace.js). The same request joins the last in line (a double-clicked
181
+ * Restart); another one waits: joined, a load asked during ?play's new game answered true and never loaded.
140
182
  */
141
- _one(what, run) {
142
- const last = this._running;
143
- if (last?.what === what) return last.done;
144
- const done = (last ? last.done.then(run, run) : run()).finally(() => { if (this._running?.done === done) this._running = null; });
145
- this._running = { what, done };
146
- return done;
147
- }
183
+ _turn(what, run) { return this.engine.saves._replace.run(what, run); }
148
184
 
149
185
  /** @internal the new-game state as save data (_reset already refused a call before start() finished) */
150
186
  _baseData() { return JSON.parse(this._base); }
151
187
 
188
+ /** @internal apply the new-game state, in the turn already taken */
189
+ _applyBase() { return applySave(this.engine.saves, this._baseData(), '(new game)'); }
190
+
152
191
  /** @internal end the playthrough, apply, then announce the new one */
153
192
  async _begin(fn, apply, info) {
154
193
  const ok = await this._reset(fn, apply);
194
+ if (ok) this._started();
155
195
  this.engine.events.emit(ok ? 'session:start' : 'session:failed', info);
156
196
  return ok;
157
197
  }
@@ -164,20 +204,23 @@ export class Session {
164
204
  try {
165
205
  e.events.emit('session:end'); // modules end their part: a running engine.skip is cancelled, a cutscene skipped, the music stopped
166
206
  await new Promise(r => setTimeout(r, 0)); // main-loop: one macrotask, so what session:end listeners started (a skipped cutscene's last steps) settles first
167
- e.commits.invalidate(); // apply invalidates too, but a refused apply must not let old results land either
207
+ if (e.disposed) return false; // disposed in that macrotask: there is no state left to replace
208
+ // background results die inside apply (saveApply), which gives them back when it fails, before its rollback: a second epoch held here made what the rollback asked for look old
168
209
  // tick, real and ambient start from 0 like a fresh page, in one call (core/time/time.js; channels and the calendar come with the save part):
169
210
  // a swimmer's bob, a pickup's spin and a 'real'-clock mod read them, so a new game after 10 minutes of play diverged from the same new game on
170
211
  // a fresh page (durability audit). Before apply: the stacks part re-times its 'real' mods from the clock as it is now.
171
212
  const undo = e.time._restart();
213
+ // what the old playthrough holds now: a part's load() or an afterLoad may set up handles and timers for the new one while apply runs, and those stay
214
+ const oldHandles = [...this._tracked], oldTimers = e.time._snapshotFn();
172
215
  let ok = false;
173
216
  // a refused or rolled-back load leaves the game as it was, so its clocks go back too (else 'real' mods and shader time restart mid-play)
174
217
  try { ok = await apply(); } finally { if (!ok) undo(); }
175
218
  if (!ok) return false; // rolled back: the old playthrough's tracked handles and timers stay, so it goes on as it was (review 0.4 core B3)
176
219
  // shortcut: tracked handles stay registered while apply runs, so one may hear the load's own events (world:load); removing them first
177
220
  // would make a failed load unrecoverable. Upgrade if a game needs it: suspend tracked handles during apply instead
178
- for (const h of this._tracked) h.remove();
179
- this._tracked.clear();
180
- e.time._restoreFn(this._timers); // event timers came back with the save; function timers are exactly the boot-time ones, each with its original delay
221
+ for (const h of oldHandles) { h.remove(); this._tracked.delete(h); }
222
+ this.id++;
223
+ e.time._restoreFn(this._timers, oldTimers); // event timers came back with the save; function timers are the boot-time ones, each with its original delay, and those apply set up
181
224
  e.commits.rebase(); // requests that outlived the load (a nextFixed, terrain colliders) were due on the old tick count, minutes away now that tick restarted
182
225
  return true;
183
226
  } finally { this._busy = false; }
@@ -0,0 +1,184 @@
1
+ // Replacing the game state is one transaction, owned here. saves.apply, saves.load, session.newGame / load / quit all enter through run(), so:
2
+ // - One at a time. A request made while another runs waits its turn, in order, and only then reads its save and takes its rollback point:
3
+ // two overlapping loads left a mix of both saves (X from one, Y from the other), and the second one's rollback point was the first one's half.
4
+ // A request with a key joins the last one in line when the key is the same (a double-clicked Restart). Nothing is refused for being busy.
5
+ // - Idle means now. run() calls fn synchronously and a job that returns a plain value ends before run() returns. A save whose parts are all
6
+ // synchronous is applied on the line after apply, and replays rely on apply, step, apply, step in one stretch of code. So when only its afterLoad
7
+ // is left, which starts a microtask later, the job is paused: the marker is off (no click or net message can arrive before a microtask, only
8
+ // the caller's next lines) and a direct apply / load on those lines runs at once and takes over. The older job's hooks are then skipped:
9
+ // they would rebuild for a state that is gone, and the newer job's hooks rebuild for the one that stayed. Not past something already in line:
10
+ // apply(x); save('s'); apply(y) would store y.
11
+ // - One marker. `replacing` is true from reading the save through its parts, afterLoad and any rollback; begin() / end() bracket that span
12
+ // (saveApply.js). Ops read it (opsFail.js) instead of knowing freeze names, so a game's own freeze never looks like a load and a load never
13
+ // looks like a menu. A session's turn is longer than the marker on purpose: session:end listeners (a skipped cutscene's last steps) and
14
+ // session:start listeners still run ops, while the turn stays taken so the next replacement cannot cut in between.
15
+ // - One read rule. saves.save asks through read(): a save collected while parts are half loaded would mix two states, so it waits for every replacement
16
+ // already in line. It never takes over a paused job (that job's hooks must still run) and holds the turn only for the collect, not for the disk write.
17
+ // - One freeze. hold() stops fixed steps while the replacement waits on something; it is the only freeze a load takes, and end() drops it.
18
+ // - One identity, passed by hand. A part's load(data, turn) and a module's afterLoad(engine, turn) get the turn of their replacement, and level.load / content.load take it back as { turn }:
19
+ // that call belongs to the replacement and goes at once, before or after any await. Nothing else can say so. A browser has no async context, so what runs after an await looks like a click;
20
+ // a marker held across the await would let the click in as well. No turn, or one that ended, is an outside request and waits in line, however it was made. The cost is the one a caller
21
+ // can forget: an awaited request without its turn waits for itself. Dev names it when something stalls in line (save-nested). The rule is the same before and after the first await, so
22
+ // a load() does not start hanging on the day it gains an await.
23
+ // Async rebuild work needs no other stamp: a part's load() and every afterLoad settle inside their turn (saveApply.js waits for all of them, even when one failed), and a late part
24
+ // loads in a turn of its own, whole (adoptPart). What a module starts and does not return (a background job) is engine.commits' case: invalidate() drops it unless its valid() says otherwise.
25
+ // - One word for a change that takes several steps. A door trip or a cutscene holds a stateTurn: between its first and last line the world is between two states no load could continue from, so
26
+ // an autosave waits for it to end. Only the autosave: a save the game asks for itself picked its moment, and may be awaited inside that very trip. A replacement does not wait either, a new game
27
+ // is how a cutscene ends. The owners call stateTurn; this file does not know who they are.
28
+ // - A level change waits for a replacement already in line (whenTurnFree) and does not take the turn: two doors in a row still overtake each other, and a save made while a file downloads
29
+ // stores the level that stands, whole. What a part's load() or afterLoad asks with its turn goes at once: it is inside the turn and cannot wait for itself.
30
+ // - One word for "the state was replaced". A job that changed the state emits the internal state:replaced { undone } as it ends, last, whichever door it came through, so derived state listens to
31
+ // that alone. undone: a failed load put the old state back. A job that refused before changing anything says nothing; a job taken over is announced by the one that took over.
32
+ // - One way back. A failed pack that has to wait for its old level holds everything in line and gameplay until the old state is whole again (restoring): a save or a load in the gap would
33
+ // read or write half of it. Nothing about the saved state changed, so no state:replaced.
34
+ // A new replacement has no place inside a running one: it starts after, so a load() may ask for it and not await it (or ask from a save:loaded or session:start listener).
35
+ import { DEV, warnOnce } from '../base/validate.js';
36
+ import { coded, codedError } from '../base/errorHints.js';
37
+
38
+ const NESTED = "something has waited long behind a state replacement that has not ended. If it was asked inside a save part's load() or a module's afterLoad and awaited, it waits for itself: "
39
+ + 'pass the turn they get to level.load / content.load ({ turn }) and it goes at once; a new saves.apply / load / save or session.newGame / load / quit starts after the running one, so do '
40
+ + 'not await it there, or ask from a save:loaded or session:start listener';
41
+ const STALL_MS = 3000; // a dev hint only: a slow download behind a load is told too, and the words say "if"
42
+ const FREEZE = 'threedog:state-replace'; // a namespaced owner: a game's own freeze('load') must not be released by (or release) the engine's
43
+
44
+ /** @internal One state replacement at a time, and the marker that says one is under way (top of the file) */
45
+ export class StateReplace {
46
+ constructor(engine) {
47
+ this.engine = engine;
48
+ /** The job holding the turn, or null */ this.job = null;
49
+ /** Jobs waiting for the turn, oldest first */ this.waiting = [];
50
+ /** When the turn last changed hands (performance.now) */ this.moved = 0;
51
+ /** True from reading a save until its load or rollback ended */ this.replacing = false;
52
+ /** The freeze while the replacement waits on something */ this.freeze = null;
53
+ /** How many stateTurns are open */ this.turns = 0;
54
+ /** Which saved state the game holds: moves when a load starts changing parts, goes back when it fails. A level change does not move it, so what a level load's caller asked next survives (commits.epoch moves for both) */ this.generation = 0;
55
+ }
56
+
57
+ /**
58
+ * Run fn when its turn comes: at once when idle, else after the jobs before it. Returns what fn returned, as a Promise.
59
+ * @param {string | null} key same key as the last job in line: join it instead of running again
60
+ * @param {() => any} fn
61
+ * @param {boolean} [behind] never take over a paused job: fn adds to the state that job leaves, it does not replace it (adoptPart)
62
+ * @returns {Promise<any>}
63
+ */
64
+ run(key, fn, behind = false) {
65
+ const last = this.waiting.at(-1) ?? this.job;
66
+ if (key && last?.key === key) return last.done;
67
+ const job = { key, fn, done: null, settle: null, paused: false, turn: Object.freeze({}) };
68
+ job.done = new Promise(res => { job.settle = res; });
69
+ if (this.job && (behind || !this.job.paused || this.waiting.length)) this._line(job); else this._start(job);
70
+ return job.done;
71
+ }
72
+
73
+ /**
74
+ * Read the whole state when no replacement is under way or waiting: at once when idle, else in line (top of the file).
75
+ * @param {() => Promise<any>} fn its collect runs in the turn; what it returns settles outside it
76
+ * @returns {Promise<any>}
77
+ */
78
+ read(fn) {
79
+ if (!this.job) return fn();
80
+ let give;
81
+ const job = { key: null, fn: () => { try { give(fn()); } catch (err) { give(Promise.reject(err)); } }, done: new Promise(res => { give = res; }), settle() {}, paused: false }; // a throw reaches the one who asked, and the line goes on
82
+ this._line(job);
83
+ return job.done;
84
+ }
85
+
86
+ /**
87
+ * A failed pack is putting the old state back: gameplay and everything in line wait until p settled (top of the file). Next in line, so the transaction it ends is not overtaken.
88
+ * @param {Promise<any>} p
89
+ */
90
+ restoring(p) {
91
+ const job = { key: null, fn: () => p, done: p, settle() {}, paused: false };
92
+ this.begin(); this.hold();
93
+ const over = () => this.endOf(job);
94
+ p.then(over, over); // before _start's own: the job still holds the turn when the marker goes off
95
+ if (this.job) this.waiting.unshift(job); else this._start(job);
96
+ }
97
+
98
+ /**
99
+ * Wait in line. An awaited request a load() made without its turn waits for itself, and nothing can tell it from a click: dev says so when it stalls, and with no sign of
100
+ * life for loading.timeoutMs the job fails, in every build. Life is the line moving or a load task's phase: a replacement awaiting something no task reports shows none.
101
+ */
102
+ _line(job) {
103
+ const L = this.engine.loading, since = performance.now(); // measure: the limit is a wall clock, a stepped or frozen engine runs no frames
104
+ this.waiting.push(job);
105
+ if (DEV) setTimeout(() => { if (this.waiting.includes(job)) warnOnce(coded('save-nested', NESTED), 'save-nested'); }, STALL_MS); // debug: a dev hint on real time, gameplay never reads it
106
+ job.done = L._limit(job.done, () => this.waiting.includes(job) ? Math.max(since, this.moved, ...[...L.tasks.values()].map(t => t.at)) : null, () => {
107
+ this.waiting.splice(this.waiting.indexOf(job), 1);
108
+ return codedError('save-nested', NESTED);
109
+ });
110
+ }
111
+
112
+ /** Start a job; its turn ends when fn's result settled, whichever way (a failed job must not block the next) */
113
+ _start(job) {
114
+ this.job = job; this.moved = performance.now(); // measure: a sign of life for those in line
115
+ const next = () => {
116
+ if (this.job !== job) return;
117
+ this.job = null;
118
+ if (job.changed) this.engine.events.emit('state:replaced', { undone: job.changed === 'undone' });
119
+ const n = this.waiting.shift();
120
+ if (n) this._start(n);
121
+ }; // not its turn any more: taken over
122
+ let out;
123
+ try { out = job.fn(); } catch (err) { out = Promise.reject(err); }
124
+ if (typeof out?.then === 'function') out.then(next, next);
125
+ else next();
126
+ job.settle(out);
127
+ }
128
+
129
+ /** The state starts being replaced (the marker's span: top of the file) */
130
+ begin() { this.replacing = true; }
131
+ /** This turn's job changed the state, or (undone) put the old one back: state:replaced says so when it ends */
132
+ changed(undone = false) { this.job.changed = undone ? 'undone' : true; }
133
+ /** Only a microtask's wait is left: a direct apply / load may take over until resume (top of the file). A session's job has more to do after its
134
+ * apply, and a job already holding the freeze is mid-load, so neither pauses. Returns the job, for resume */
135
+ pause() {
136
+ const job = this.job;
137
+ if (!job.key && !this.freeze) { job.paused = true; this.replacing = false; }
138
+ return job;
139
+ }
140
+ /** The wait ended: false when a newer job took over, else the marker is back on */
141
+ resume(job) {
142
+ if (this.job !== job) return false;
143
+ job.paused = false; this.replacing = true;
144
+ return true;
145
+ }
146
+ /** The job whose apply this is ended: the marker goes off, unless a newer job took over and owns it now */
147
+ endOf(job) { if (this.job === job) this.end(); }
148
+ /** The replacement waits on something: stop fixed steps until end() */
149
+ hold() { this.freeze ??= this.engine.freeze(FREEZE); }
150
+ /** The load or its rollback ended */
151
+ end() { this.replacing = false; this.freeze?.remove(); this.freeze = null; }
152
+ }
153
+
154
+ /**
155
+ * @internal A change of several steps is under way until the handle's remove() (top of the file).
156
+ * @param {any} e
157
+ * @returns {{ remove(): void }}
158
+ */
159
+ export function stateTurn(e) {
160
+ const q = e.saves._replace;
161
+ let open = true;
162
+ q.turns++;
163
+ return { remove() { if (open) { open = false; q.turns--; } } };
164
+ }
165
+
166
+ /**
167
+ * @internal A failed pack is putting the old state back: everything in line and gameplay wait until p settled (top of the file).
168
+ * @param {any} e
169
+ * @param {Promise<any>} p
170
+ */
171
+ export function whileRestoring(e, p) { e.saves._replace.restoring(p); }
172
+
173
+ /**
174
+ * @internal Run fn behind the replacements in line (at once when none is), or at once when turn is the one running (top of the file).
175
+ * @template T
176
+ * @param {any} e
177
+ * @param {() => T | Promise<T>} fn
178
+ * @param {object} [turn] what the caller's load() or afterLoad was given
179
+ * @returns {T | Promise<T>}
180
+ */
181
+ export function whenTurnFree(e, fn, turn) { return liveTurn(e, turn) ? fn() : e.saves._replace.read(fn); }
182
+
183
+ /** @internal Is this the turn of the replacement running now? A turn kept after its load ended is an outside request, like no turn at all @param {any} e @param {object} [turn] */
184
+ export const liveTurn = (e, turn) => !!turn && e.saves._replace.job?.turn === turn;
@@ -24,7 +24,7 @@ import { DEV, warnOnce } from '../base/validate.js';
24
24
  // Meshes under this many triangles get no BVH (blocky buildings etc.: the per-triangle check is faster)
25
25
  const BVH_MIN = 256;
26
26
  const triangles = g => (g.index ? g.index.count : g.attributes.position.count) / 3;
27
- const _v = new THREE.Vector3(), _d = new THREE.Vector3(), _ndc = new THREE.Vector2(), _sph = new THREE.Sphere();
27
+ const _v = new THREE.Vector3(), _d = new THREE.Vector3(), _ndc = new THREE.Vector2(), _sph = new THREE.Sphere(), _m = new THREE.Matrix4(), _i = new THREE.Matrix4(), _n = new THREE.Matrix3();
28
28
 
29
29
  /** Cheap broadphase per static: does the ray pass the mesh's world bounding sphere within far? (the same test Mesh.raycast starts with, done before the parent walk) */
30
30
  // Measured (5000 statics, 4 casts a frame, node): about 12 ms -> 3-5 ms per frame; caching the world sphere per static was slower than recomputing it.
@@ -43,13 +43,13 @@ export class Rays {
43
43
  constructor(engine) {
44
44
  /** @internal */ this.engine = engine;
45
45
  /** @internal */ this.providers = [];
46
+ /** @internal the tick the statics' world matrices were last brought up to date */ this.fresh = -1;
46
47
  /** Registered mesh -> { refs: registration count, occ: camera-blocker registration count } @type {Map<THREE.Object3D, { refs: number, occ: number }>} @experimental */
47
48
  this.statics = new Map();
48
49
  /** The three.js Raycaster (firstHitOnly is on) @type {any} @experimental */
49
50
  this.ray = new THREE.Raycaster();
50
51
  this.ray.firstHitOnly = true; // only the nearest hit per mesh (faster with a BVH)
51
52
  this.ray.layers.enable(RESERVED_LAYERS.batched); // originals drawn through engine.batching sit here and must still be hit
52
- this.ray.layers.enable(RESERVED_LAYERS.occlusionHidden); // so must what occlusion culling is not drawing this frame
53
53
  }
54
54
  /**
55
55
  * Register a static object and every mesh under it (an array also works; meshes over 256 triangles get a BVH); occluder: true also blocks the camera. Returns a handle { remove() }.
@@ -63,6 +63,7 @@ export class Rays {
63
63
  addStatic(obj, opts = {}) {
64
64
  const { occluder = false } = opts;
65
65
  const added = [];
66
+ this.fresh = -1;
66
67
  for (const o of [].concat(obj)) o.traverse(m => {
67
68
  if (DEV && (m.isInstancedMesh || m.isSkinnedMesh)) warnOnce(`engine.rays.addStatic: skipped ${m.isInstancedMesh ? 'an InstancedMesh' : 'a SkinnedMesh'} ("${m.name}"): rays do not hit these and they do not block the camera. Use a collider, or register a plain stand-in mesh.`, 'rays-skip-' + m.type);
68
69
  if (!m.isMesh || m.isInstancedMesh || m.isSkinnedMesh || m.userData.lodLevel || !m.geometry?.attributes.position) return; // a low level stands in on screen only: rays use the full model
@@ -121,6 +122,7 @@ export class Rays {
121
122
  */
122
123
  _rayAt(ndcX, ndcY, opts = {}) {
123
124
  const { far = Infinity, targets = 'static', filter = null, occluders = false } = opts;
125
+ this.engine.camera.updateWorldMatrix(true, false); // moved in this step: the matrix is only refreshed by the render
124
126
  this.ray.setFromCamera(_ndc.set(ndcX, ndcY), this.engine.camera);
125
127
  this.ray.far = far;
126
128
  return this._cast(this.ray.ray.origin, this.ray.ray.direction, far, targets, filter, occluders);
@@ -132,11 +134,15 @@ export class Rays {
132
134
  let best = null;
133
135
  const take = h => { if (h && h.distance <= far && (!best || h.distance < best.distance) && (!filter || filter(h))) best = h; };
134
136
  if (Array.isArray(targets)) {
137
+ for (const t of targets) t.updateWorldMatrix(true, true);
135
138
  this.ray.firstHitOnly = false;
136
139
  for (const h of this.ray.intersectObjects(targets, true)) { if (shown(h.object)) { take(toHit(h)); if (best) break; } }
137
140
  this.ray.firstHitOnly = true;
138
141
  } else {
139
- const ray = this.ray.ray;
142
+ const ray = this.ray.ray, tick = this.engine.time.tick;
143
+ // matrices are refreshed by the render, and a fixed step runs before it: what moved or was added since would answer from where it was.
144
+ // shortcut: once per tick and not per ray (a walk up the parents of 5000 statics costs more than the rays): something moved between two rays of one step answers from the next tick
145
+ if (this.fresh !== tick) { this.fresh = tick; for (const m of this.statics.keys()) m.updateWorldMatrix(true, false); }
140
146
  for (const [m, s] of this.statics) {
141
147
  if (occluders && !s.occ) continue; // first: a camera ray then pays one flag check for every mesh that is no blocker
142
148
  if (!mayHit(ray, m, far)) continue; // most statics are nowhere near the ray: skip them before walking parents
@@ -157,7 +163,17 @@ function shown(o, scene) {
157
163
  for (let p = o; p; p = p.parent) { if (!p.visible) return false; if (p === scene) return true; }
158
164
  return !scene;
159
165
  }
166
+ /** three's hit as it came (instanceId, batchId, uv stay on it), with the normal in the world: an instance has a matrix of its own, and an uneven scale needs the normal matrix */
160
167
  function toHit(h) {
161
- const normal = h.face ? h.face.normal.clone().transformDirection(h.object.matrixWorld) : null;
162
- return { point: h.point, distance: h.distance, normal, object: h.object, face: h.face };
168
+ const o = h.object;
169
+ let normal = null;
170
+ if (h.face) {
171
+ _m.copy(o.matrixWorld);
172
+ const id = o.isInstancedMesh ? h.instanceId : o.isBatchedMesh ? h.batchId : undefined;
173
+ if (id !== undefined) { o.getMatrixAt(id, _i); _m.multiply(_i); }
174
+ normal = h.face.normal.clone().applyNormalMatrix(_n.getNormalMatrix(_m));
175
+ }
176
+ return { ...h, normal };
163
177
  }
178
+
179
+ export const handRolled = [{ kind: 'picking', seen: 'a pointer-to-object raycast of its own', use: 'engine.pick(x, y), or engine.raycast / engine.rays: colliders and moving things are in the same query (recipe 19)', quiet: /\b(engine|e|eng|ctx)\.(rays|raycast|pick)\b/, code: /\.setFromCamera\s*\(/ }];
@@ -6,7 +6,7 @@
6
6
  import { warnMissing } from '../base/validate.js';
7
7
  import { readParams, keysSchema } from '../base/params.js';
8
8
  import { codedError } from '../base/errorHints.js';
9
- import { setFov } from './view.js';
9
+ import { holdFov } from './view.js';
10
10
 
11
11
  const vec3 = a => Array.isArray(a) && a.length === 3 && a.every(Number.isFinite);
12
12
 
@@ -14,8 +14,8 @@ export class Views {
14
14
  /** @param {any} engine */
15
15
  constructor(engine) {
16
16
  /** @internal */ this.engine = engine;
17
- this.map = new Map(); this.current = null; this._cam = null;
18
- /** @internal the camera's fov before a view changed it: release() gives it back */ this._fov = null;
17
+ this.map = new Map(); this._cam = null;
18
+ /** Name of the view in use, null while none is @type {string | null} */ this.current = null;
19
19
  }
20
20
  /**
21
21
  * Declare a view. position and target are [x, y, z]; fov (degrees) is optional (the camera's own when left out). Returns { remove() } (undeclares it).
@@ -47,15 +47,15 @@ export class Views {
47
47
  this._cam = e.takeCamera('views', { focus });
48
48
  e.focus.copy(focus);
49
49
  c.position.fromArray(v.position); c.lookAt(...v.target);
50
- if (v.fov != null && c.isPerspectiveCamera) { this._fov ??= c.fov; setFov(e, v.fov); } // yields to a fov the game took (engine.autoView.manual('fov'))
50
+ if (v.fov != null) holdFov(e, v.fov);
51
51
  c.updateMatrixWorld(true);
52
52
  this.current = name;
53
53
  e.events.emit('camera:shot', { name }); // a cut: what follows the camera (the light pool) settles at once instead of easing over
54
- return { remove: () => { if (this.current === name) this.release(); } };
54
+ const cam = this._cam; // this showing, not the name: a handle kept from an earlier one must not end a later one
55
+ return { remove: () => { if (this._cam === cam) this.release(); } };
55
56
  }
56
57
  /** Give the camera back (to the previous holder, e.g. a running cutscene, or to the rig) */
57
58
  release() {
58
- if (this._fov != null) { setFov(this.engine, this._fov); this._fov = null; }
59
59
  this._cam?.remove(); this._cam = null; this.current = null;
60
60
  }
61
61
  }
@@ -10,6 +10,8 @@
10
10
  // shortcut: only the resolution is adjusted. A tier ladder (resolution -> shadows -> view distance -> vegetation) would hang off decide() below as
11
11
  // further steps once a game needs it; until then the other knobs stay the game's (settings / engine.autoView).
12
12
  import { DEV, warnOnce } from '../base/validate.js';
13
+ import { coded } from '../base/errorHints.js';
14
+ import { writeRatio } from './pixelRatio.js';
13
15
 
14
16
  const GRACE = 3; // s after ready that are not judged (warm-up compiles, first uploads, stream fill)
15
17
  const WINDOW = 1; // s of samples per decision
@@ -17,19 +19,20 @@ const HEAVY = 0.85; // cost above this share of the frame budget = overloa
17
19
  const LIGHT = 0.6; // cost under this share = headroom (raise after RAISE_AFTER windows in a row)
18
20
  const RAISE_AFTER = 4;
19
21
  const LOCK_TOL = 0.08; // intervals within 8 % of the window median count as "clustered"
20
-
21
- /** The engine.adaptive state object: the public fields (on, target, min, max, base, lowered, from; base is what this device or game starts at, the settings presets' base) plus the controller's own counters */
22
- export function createAdaptive({ on, target, max }) {
23
- return { on, target, min: 0.6, max, base: max, t: 0, good: 0, cooldown: 0, lowered: false, from: null,
24
- age: 0, costs: [], gaps: [], refresh: Infinity, reason: null };
25
- }
22
+ const HELD = coded('pixel-conflict', 'engine.adaptive.on = true does nothing while pixelSize is on; it comes back with engine.setPixelSize(null)');
26
23
 
27
24
  /**
28
- * The one engine write of the ratio; re-reading it after keeps this from counting as an outside write. Skips an equal value because three's
29
- * setPixelRatio resizes the canvas, which clears the drawing buffer.
30
- * @param {any} e @param {number} p
25
+ * The engine.adaptive state object: the public fields (on, target, min, max, base, lowered, from; base is what this device or game starts at, the settings presets' base) plus the
26
+ * controller's own counters. on is an accessor because every reader (the loop's GPU timer, describe, settings) must see false under pixelSize; what was asked for stays and returns with setPixelSize(null).
27
+ * @param {{ on: boolean, target: number, max: number, held: () => boolean }} o held: pixelSize decides the ratio now
31
28
  */
32
- export function writeRatio(e, p) { if (Math.abs(e.renderer.getPixelRatio() - p) > 0.001) e.renderer.setPixelRatio(p); e._oPixelRatio.mark(); }
29
+ export function createAdaptive({ on, target, max, held }) {
30
+ let wanted = on;
31
+ return { get on() { return wanted && !held(); },
32
+ set on(v) { wanted = v; if (DEV && v && held()) warnOnce(HELD); },
33
+ target, min: 0.6, max, base: max, t: 0, good: 0, cooldown: 0, lowered: false, from: null,
34
+ age: 0, costs: [], gaps: [], refresh: Infinity, reason: null };
35
+ }
33
36
 
34
37
  const median = a => { const s = a.slice().sort((x, y) => x - y); return s.length ? s[s.length >> 1] : 0; };
35
38
 
@@ -1,6 +1,7 @@
1
1
  // The canvas's CSS box and the UI root laid over it (split out of Engine.js: all about "how big is the canvas on the page").
2
2
  import * as THREE from 'three';
3
3
  import { warnOnce } from '../base/validate.js';
4
+ import { fitPixelSize } from './pixelRatio.js';
4
5
 
5
6
  const _size = new THREE.Vector2();
6
7
  const NO_CSS_SIZE = 'createEngine(): the canvas has no CSS size of its own (it would take its size from its pixel buffer), so the engine sizes it to the window. '
@@ -53,6 +54,7 @@ export const resizeMethods = {
53
54
  _resize() {
54
55
  const { w, h } = canvasBox(this);
55
56
  placeUI(this);
57
+ if (fitPixelSize(this, w, h)) return;
56
58
  const now = this.renderer.getSize(_size);
57
59
  if (now.x === w && now.y === h) return; // ResizeObserver and the window event can both fire for one change
58
60
  this.renderer.setSize(w, h, !!this._autoSize); // the post chain follows the renderer on its next draw (postWebGL.js follow)