threedog 0.7.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 (593) hide show
  1. package/CHANGELOG.md +411 -1
  2. package/README.md +8 -11
  3. package/core/{Animator.js → assets/Animator.js} +30 -18
  4. package/core/{Assets.js → assets/Assets.js} +131 -56
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +302 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +9 -7
  8. package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
  9. package/core/assets/assetLod.js +113 -0
  10. package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
  11. package/core/{assetReport.js → assets/assetReport.js} +7 -14
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +47 -25
  14. package/core/{audioRules.js → audio/audioRules.js} +8 -5
  15. package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
  16. package/core/{Events.js → base/Events.js} +3 -3
  17. package/core/{I18n.js → base/I18n.js} +15 -12
  18. package/core/{Random.js → base/Random.js} +7 -4
  19. package/core/{Vars.js → base/Vars.js} +14 -4
  20. package/core/{easing.js → base/easing.js} +1 -1
  21. package/core/{errorCodes.js → base/errorCodes.js} +151 -125
  22. package/core/{errorHints.js → base/errorHints.js} +17 -10
  23. package/core/{errors.js → base/errors.js} +12 -10
  24. package/core/{events.generated.js → base/events.generated.js} +11 -0
  25. package/core/base/follows.js +26 -0
  26. package/core/base/math.js +66 -0
  27. package/core/{params.js → base/params.js} +5 -6
  28. package/core/base/saveValues.js +81 -0
  29. package/core/base/sections.js +97 -0
  30. package/core/base/spelling.js +32 -0
  31. package/core/base/util.js +32 -0
  32. package/core/{validate.js → base/validate.js} +34 -34
  33. package/core/{Engine.js → engine/Engine.js} +137 -91
  34. package/core/{Loading.js → engine/Loading.js} +34 -5
  35. package/core/{copies.js → engine/copies.js} +4 -4
  36. package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
  37. package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
  38. package/core/{loop.js → engine/loop.js} +88 -49
  39. package/core/engine/moduleSlots.js +176 -0
  40. package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
  41. package/core/engine/modules.js +503 -0
  42. package/core/{page.js → engine/page.js} +59 -29
  43. package/core/{plugins.js → engine/plugins.js} +21 -12
  44. package/core/{services.js → engine/services.js} +50 -40
  45. package/core/{startup.js → engine/startup.js} +66 -54
  46. package/core/{Input.js → input/Input.js} +67 -39
  47. package/core/{inputContext.js → input/inputContext.js} +14 -5
  48. package/core/input/inputKeyboard.js +39 -0
  49. package/core/{inputPad.js → input/inputPad.js} +24 -3
  50. package/core/{inputPointer.js → input/inputPointer.js} +11 -3
  51. package/core/input/inputSeat.js +66 -0
  52. package/core/{inputTouch.js → input/inputTouch.js} +24 -7
  53. package/core/{Budget.js → inspect/Budget.js} +21 -20
  54. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
  55. package/core/{Describe.js → inspect/Describe.js} +34 -26
  56. package/core/{Inspect.js → inspect/Inspect.js} +39 -10
  57. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  58. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  59. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  60. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  61. package/core/{UrlState.js → inspect/UrlState.js} +60 -24
  62. package/core/{catalog.js → inspect/catalog.js} +15 -8
  63. package/core/{checks.js → inspect/checks.js} +7 -5
  64. package/core/{debugView.js → inspect/debugView.js} +4 -4
  65. package/core/{describeRender.js → inspect/describeRender.js} +24 -22
  66. package/core/{describeText.js → inspect/describeText.js} +17 -8
  67. package/core/inspect/geometryWatch.js +38 -0
  68. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  69. package/core/inspect/metadata.generated.js +4140 -0
  70. package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
  71. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  72. package/core/inspect/toolDoor.js +21 -0
  73. package/core/inspect/valueHistory.js +35 -0
  74. package/core/{Ops.js → ops/Ops.js} +44 -14
  75. package/core/{control.js → ops/control.js} +57 -31
  76. package/core/ops/holds.js +140 -0
  77. package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
  78. package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
  79. package/core/{opsFail.js → ops/opsFail.js} +5 -7
  80. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  81. package/core/{opsRun.js → ops/opsRun.js} +9 -6
  82. package/core/{owned.js → ops/owned.js} +33 -19
  83. package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
  84. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  85. package/core/{stacks.js → ops/stacks.js} +34 -15
  86. package/core/{wrap.js → ops/wrap.js} +8 -6
  87. package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
  88. package/core/{Saves.js → saves/Saves.js} +171 -54
  89. package/core/saves/saveApply.js +312 -0
  90. package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
  91. package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
  92. package/core/saves/session.js +231 -0
  93. package/core/saves/stateReplace.js +184 -0
  94. package/core/{Rays.js → scene/Rays.js} +44 -30
  95. package/core/{Views.js → scene/Views.js} +16 -8
  96. package/core/{adaptive.js → scene/adaptive.js} +19 -9
  97. package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
  98. package/core/scene/compositeGround.js +72 -0
  99. package/core/scene/floor.js +17 -0
  100. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  101. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  102. package/core/{grid.js → scene/grid.js} +6 -4
  103. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  104. package/core/scene/ground.contract.js +14 -0
  105. package/core/scene/ground.js +139 -0
  106. package/core/{movement.js → scene/movement.js} +3 -3
  107. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  108. package/core/scene/pixel.js +154 -0
  109. package/core/scene/pixelRatio.js +167 -0
  110. package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
  111. package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
  112. package/core/scene/stepPoses.js +60 -0
  113. package/core/{targeting.js → scene/targeting.js} +4 -5
  114. package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
  115. package/core/{thingOps.js → scene/thingOps.js} +25 -16
  116. package/core/{things.js → scene/things.js} +18 -5
  117. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  118. package/core/{tier.js → scene/tier.js} +10 -0
  119. package/core/scene/view.js +161 -0
  120. package/core/{Batching.js → stream/Batching.js} +85 -28
  121. package/core/{Stream.js → stream/Stream.js} +80 -38
  122. package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
  123. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  124. package/core/{scatter.js → stream/scatter.js} +7 -4
  125. package/core/{streamSources.js → stream/streamSources.js} +14 -8
  126. package/core/{Commits.js → threads/Commits.js} +17 -11
  127. package/core/{Jobs.js → threads/Jobs.js} +25 -13
  128. package/core/{Threads.js → threads/Threads.js} +21 -18
  129. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  130. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  131. package/core/{Clock.js → time/Clock.js} +20 -11
  132. package/core/{dayTime.js → time/dayTime.js} +5 -1
  133. package/core/{skip.js → time/skip.js} +28 -21
  134. package/core/{time.js → time/time.js} +32 -20
  135. package/core/{uiClock.js → time/uiClock.js} +4 -4
  136. package/docs/AI.md +92 -72
  137. package/docs/API.md +33 -28
  138. package/docs/CODEMAP.md +121 -200
  139. package/docs/COMMANDS.md +77 -70
  140. package/docs/CONVENTIONS.md +167 -24
  141. package/docs/MIGRATING-0.8.md +171 -0
  142. package/docs/MIGRATING-1.0.md +101 -0
  143. package/docs/THREE.md +140 -38
  144. package/docs/api/assets.md +12 -13
  145. package/docs/api/audio.md +6 -5
  146. package/docs/api/budget.md +4 -4
  147. package/docs/api/calendar.md +10 -11
  148. package/docs/api/cameraRig.md +32 -29
  149. package/docs/api/characters.md +35 -24
  150. package/docs/api/clock.md +1 -1
  151. package/docs/api/collider3d.md +9 -0
  152. package/docs/api/collision.md +12 -9
  153. package/docs/api/content.md +18 -17
  154. package/docs/api/dialogue.md +5 -4
  155. package/docs/api/engine.md +58 -54
  156. package/docs/api/events.md +17 -6
  157. package/docs/api/flow.md +1 -1
  158. package/docs/api/grids.md +1 -1
  159. package/docs/api/ground.md +6 -7
  160. package/docs/api/hud.md +2 -2
  161. package/docs/api/i18n.md +6 -6
  162. package/docs/api/input.md +9 -8
  163. package/docs/api/interactions.md +5 -5
  164. package/docs/api/inventory.md +10 -10
  165. package/docs/api/jobs.md +5 -5
  166. package/docs/api/level.md +10 -9
  167. package/docs/api/lightPool.md +1 -6
  168. package/docs/api/music.md +3 -3
  169. package/docs/api/nav.md +14 -12
  170. package/docs/api/openWorld.md +1 -1
  171. package/docs/api/particles.md +10 -7
  172. package/docs/api/photo.md +4 -2
  173. package/docs/api/pickups.md +3 -3
  174. package/docs/api/post.md +21 -5
  175. package/docs/api/quests.md +7 -5
  176. package/docs/api/rays.md +7 -7
  177. package/docs/api/rigid.md +29 -19
  178. package/docs/api/saves.md +13 -11
  179. package/docs/api/settings.md +9 -8
  180. package/docs/api/sky.md +8 -7
  181. package/docs/api/stream.md +8 -9
  182. package/docs/api/swarm.md +34 -0
  183. package/docs/api/terrain.md +6 -8
  184. package/docs/api/terrainDraw.md +2 -2
  185. package/docs/api/timeline.md +4 -4
  186. package/docs/api/tools.md +27 -22
  187. package/docs/api/triggers.md +2 -0
  188. package/docs/api/vars.md +1 -1
  189. package/docs/api/vegetation.md +4 -3
  190. package/docs/api/vegetationDraw.md +2 -2
  191. package/docs/api/water.md +7 -3
  192. package/docs/api/weather.md +27 -12
  193. package/docs/api/weatherDraw.md +4 -4
  194. package/docs/api/world.md +6 -6
  195. package/docs/recipes/01-new-game.md +28 -43
  196. package/docs/recipes/02-npc.md +21 -23
  197. package/docs/recipes/03-items-pickups.md +37 -53
  198. package/docs/recipes/04-quests.md +5 -4
  199. package/docs/recipes/05-props-bake.md +34 -44
  200. package/docs/recipes/06-clock-events.md +31 -22
  201. package/docs/recipes/07-flow-scenes-pause.md +30 -32
  202. package/docs/recipes/08-weather-sky.md +91 -37
  203. package/docs/recipes/09-materials-lights-models.md +25 -39
  204. package/docs/recipes/10-blender-level.md +22 -11
  205. package/docs/recipes/11-vehicles.md +44 -24
  206. package/docs/recipes/12-navmesh.md +60 -15
  207. package/docs/recipes/13-animation.md +70 -22
  208. package/docs/recipes/14-custom-module.md +33 -20
  209. package/docs/recipes/15-perf.md +51 -28
  210. package/docs/recipes/16-dev-bridge.md +39 -58
  211. package/docs/recipes/18-world.md +49 -28
  212. package/docs/recipes/19-shooting-picking.md +7 -4
  213. package/docs/recipes/20-content-actions-save.md +55 -40
  214. package/docs/recipes/21-camera.md +47 -25
  215. package/docs/recipes/22-shop-gold.md +21 -16
  216. package/docs/recipes/23-ops.md +28 -24
  217. package/docs/recipes/26-ui-parts.md +25 -14
  218. package/docs/recipes/27-net.md +3 -5
  219. package/docs/recipes/28-terrain.md +119 -23
  220. package/docs/recipes/29-grid.md +3 -3
  221. package/docs/recipes/30-templates.md +63 -30
  222. package/docs/recipes/31-audio.md +7 -7
  223. package/docs/recipes/32-action-game.md +21 -11
  224. package/docs/recipes/33-stream-sources.md +6 -3
  225. package/docs/recipes/34-environment-lighting.md +72 -25
  226. package/docs/recipes/35-picture-from-reference.md +20 -23
  227. package/docs/recipes/36-ground-plants.md +106 -0
  228. package/docs/recipes/40-scene.md +18 -21
  229. package/docs/recipes/43-shader-patches-surfaces.md +27 -48
  230. package/docs/recipes/44-water-weather-hooks.md +56 -50
  231. package/docs/recipes/45-cascaded-shadows.md +41 -20
  232. package/docs/recipes/46-blender-art-route.md +9 -10
  233. package/docs/recipes/49-game-module-contract.md +7 -6
  234. package/docs/recipes/50-own-renderer.md +3 -2
  235. package/docs/recipes/51-capability-catalog.md +14 -8
  236. package/docs/recipes/52-around-the-picture.md +56 -100
  237. package/docs/recipes/53-ground-up-close.md +61 -24
  238. package/docs/recipes/55-mods-time-wrap.md +17 -20
  239. package/docs/recipes/56-webgpu-tsl.md +28 -15
  240. package/docs/recipes/57-control.md +39 -12
  241. package/docs/recipes/58-input.md +15 -2
  242. package/docs/recipes/59-depth-post-effects.md +1 -1
  243. package/docs/recipes/60-judge-the-picture.md +30 -25
  244. package/docs/recipes/62-picture-code.md +129 -39
  245. package/docs/recipes/63-third-person-start.md +19 -5
  246. package/docs/recipes/64-particles.md +54 -5
  247. package/docs/recipes/65-swarm.md +140 -0
  248. package/docs/recipes/66-common-tasks.md +313 -0
  249. package/examples/action/.threedog/content-index.json +1 -1
  250. package/examples/action/GAMEMAP.md +5 -5
  251. package/examples/perf-island/.threedog/content-index.json +1 -0
  252. package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
  253. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  254. package/examples/{sheepisland → perf-island}/main.js +8 -8
  255. package/examples/{sheepisland → perf-island}/models.js +1 -1
  256. package/examples/{sheepisland → perf-island}/params.js +1 -1
  257. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  258. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  259. package/examples/{sheepisland → perf-island}/views.js +1 -1
  260. package/examples/plain-picture/GAMEMAP.md +4 -1
  261. package/examples/rc2d/GAMEMAP.md +4 -3
  262. package/examples/rc2d/main.js +1 -3
  263. package/examples/rc2d/rc2d.js +1 -1
  264. package/examples/styletest/.threedog/content-index.json +1 -1
  265. package/examples/styletest/GAMEMAP.md +6 -5
  266. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  267. package/examples/techniques/contact-shadows/main.js +1 -1
  268. package/examples/techniques/interior-light/main.js +1 -1
  269. package/examples/techniques/modular-building/README.md +7 -6
  270. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  271. package/examples/techniques/procedural-animation/README.md +1 -1
  272. package/examples/webgpu-tsl/GAMEMAP.md +2 -1
  273. package/examples/world/.threedog/content-index.json +1 -1
  274. package/examples/world/GAMEMAP.md +9 -7
  275. package/examples/world/main.js +3 -3
  276. package/examples/world/picture/sky.js +1 -1
  277. package/index.d.ts +16 -12
  278. package/index.js +53 -32
  279. package/llms.txt +11 -14
  280. package/modules/ambience/Ambience.js +16 -11
  281. package/modules/calendar/Calendar.js +19 -19
  282. package/modules/calendar/index.js +18 -16
  283. package/modules/calendar/schedule.js +11 -6
  284. package/modules/calendar/seasons.js +7 -7
  285. package/modules/camera/FirstPersonCamera.js +5 -5
  286. package/modules/camera/FixedCamera.js +43 -30
  287. package/modules/camera/FollowCamera.js +24 -15
  288. package/modules/camera/RtsCamera.js +12 -11
  289. package/modules/camera/common.js +72 -37
  290. package/modules/camera/contract.js +1 -0
  291. package/modules/camera/pixelSnap.js +62 -0
  292. package/modules/characters/Character.js +166 -70
  293. package/modules/characters/NPC.js +84 -44
  294. package/modules/characters/assetModel.js +16 -12
  295. package/modules/characters/astar.js +48 -27
  296. package/modules/characters/behaviors.js +4 -5
  297. package/modules/characters/character.contract.js +21 -0
  298. package/modules/characters/contract.js +17 -3
  299. package/modules/characters/index.js +240 -226
  300. package/modules/characters/moveHelpers.js +88 -12
  301. package/modules/characters/mover.contract.js +14 -0
  302. package/modules/characters/movers/common.js +22 -18
  303. package/modules/characters/movers/manual.js +1 -1
  304. package/modules/characters/movers/rapier.js +18 -10
  305. package/modules/characters/movers/simple.js +26 -13
  306. package/modules/characters/movers/support.js +24 -13
  307. package/modules/characters/npcAvoid.js +19 -16
  308. package/modules/characters/npcSim.js +88 -32
  309. package/modules/characters/npcView.js +19 -11
  310. package/modules/characters/pathAsync.js +81 -29
  311. package/modules/characters/pathJob.js +38 -21
  312. package/modules/characters/pathWorker.js +1 -1
  313. package/modules/characters/player.js +120 -0
  314. package/modules/characters/playerStrings.js +2 -2
  315. package/modules/characters/proceduralRig.js +2 -2
  316. package/modules/characters/seat.js +56 -0
  317. package/modules/characters/useModel.js +3 -3
  318. package/modules/characters/vehicle.contract.js +8 -5
  319. package/modules/characters/walkTo.js +40 -33
  320. package/modules/collision/Collision.js +69 -45
  321. package/modules/collision/contract.js +15 -0
  322. package/modules/collision/grid.js +6 -1
  323. package/modules/content/explain.js +2 -3
  324. package/modules/content/fields.js +24 -3
  325. package/modules/content/ids.js +5 -3
  326. package/modules/content/index.js +132 -114
  327. package/modules/content/loader.js +117 -140
  328. package/modules/content/markers.js +25 -0
  329. package/modules/content/models.js +54 -17
  330. package/modules/content/packs.js +5 -4
  331. package/modules/content/parts.js +2 -2
  332. package/modules/content/places.js +36 -0
  333. package/modules/content/props.js +22 -17
  334. package/modules/content/rules.js +47 -61
  335. package/modules/content/stages.js +7 -7
  336. package/modules/content/templates.js +80 -49
  337. package/modules/content/words.js +47 -0
  338. package/modules/debug/DebugPanel.js +14 -45
  339. package/modules/flow/contract.js +2 -1
  340. package/modules/flow/index.js +30 -16
  341. package/modules/gameplay/Container.js +17 -13
  342. package/modules/gameplay/Containers.js +23 -6
  343. package/modules/gameplay/Dialogue.js +93 -34
  344. package/modules/gameplay/Interactions.js +93 -51
  345. package/modules/gameplay/Inventory.js +64 -22
  346. package/modules/gameplay/Quests.js +146 -30
  347. package/modules/gameplay/boxOps.js +8 -1
  348. package/modules/gameplay/dialogueBubbles.js +16 -12
  349. package/modules/gameplay/inventoryOps.js +11 -8
  350. package/modules/gameplay/pickups.js +63 -37
  351. package/modules/gameplay/questLog.js +4 -2
  352. package/modules/gameplay/questSave.js +9 -4
  353. package/modules/gameplay/quests.contract.js +1 -1
  354. package/modules/grid/Grid.js +2 -2
  355. package/modules/grid/Layer.js +12 -8
  356. package/modules/grid/index.js +28 -23
  357. package/modules/grid/ops.js +43 -46
  358. package/modules/grid/preview.js +7 -7
  359. package/modules/grid/tiles.js +6 -6
  360. package/modules/hlod/index.js +42 -57
  361. package/modules/hud/index.js +22 -14
  362. package/modules/hud/parts.js +8 -8
  363. package/modules/level/contract.js +16 -0
  364. package/modules/level/heightfield.js +29 -31
  365. package/modules/level/index.js +113 -161
  366. package/modules/level/load.js +196 -0
  367. package/modules/level/meshes.js +65 -0
  368. package/modules/level/nodes.js +40 -23
  369. package/modules/lights/index.js +33 -183
  370. package/modules/lights/slots.js +93 -0
  371. package/modules/lights/sources.js +90 -0
  372. package/modules/music/Music.js +34 -28
  373. package/modules/music/rules.js +1 -1
  374. package/modules/nav/contract.js +16 -0
  375. package/modules/nav/index.js +180 -49
  376. package/modules/nav/navPath.js +45 -10
  377. package/modules/net/Client.js +7 -7
  378. package/modules/net/Host.js +7 -7
  379. package/modules/net/Net.js +1 -1
  380. package/modules/net/index.js +6 -5
  381. package/modules/net/sync.js +2 -2
  382. package/modules/net/transports.js +2 -2
  383. package/modules/particles/Particles.js +95 -29
  384. package/modules/particles/effect.js +86 -32
  385. package/modules/particles/shaders.js +19 -1
  386. package/modules/photo/Photo.js +23 -23
  387. package/modules/rigid/RigidBodies.js +255 -89
  388. package/modules/rigid/Vehicles.js +17 -8
  389. package/modules/rigid/collider3d.contract.js +26 -0
  390. package/modules/rigid/ragdoll.js +298 -0
  391. package/modules/rigid/ragdollBones.js +209 -0
  392. package/modules/rigid/refresh.js +10 -0
  393. package/modules/rigid/sync.js +51 -20
  394. package/modules/settings/Settings.js +177 -61
  395. package/modules/settings/apply.js +20 -13
  396. package/modules/settings/sections.js +19 -14
  397. package/modules/settings/strings.js +2 -2
  398. package/modules/settings/view.js +3 -3
  399. package/modules/sky/Sky.js +29 -22
  400. package/modules/sky/clouds.js +7 -7
  401. package/modules/sky/dome.js +33 -20
  402. package/modules/sky/domeLayers.js +9 -9
  403. package/modules/sky/environment.js +6 -6
  404. package/modules/sky/frame.js +19 -10
  405. package/modules/sky/season.js +7 -1
  406. package/modules/sky/shader.js +24 -25
  407. package/modules/sky/skyModule.js +17 -28
  408. package/modules/sky/tint.js +1 -1
  409. package/modules/swarm/Swarm.js +356 -0
  410. package/modules/swarm/draw.js +68 -0
  411. package/modules/swarm/grid.js +63 -0
  412. package/modules/terrain/ChunkManager.js +71 -59
  413. package/modules/terrain/chunkQueries.js +7 -24
  414. package/modules/terrain/chunkWorker.js +1 -1
  415. package/modules/terrain/draw.js +14 -11
  416. package/modules/terrain/index.js +42 -42
  417. package/modules/terrain/terrainColorMap.js +6 -3
  418. package/modules/terrain/terrainDefaults.js +2 -1
  419. package/modules/terrain/terrainEdit.js +45 -29
  420. package/modules/terrain/terrainGen.js +19 -12
  421. package/modules/terrain/terrainIsland.js +2 -2
  422. package/modules/terrain/terrainMesh.js +7 -6
  423. package/modules/terrain/terrainShape.js +8 -10
  424. package/modules/terrain/terrainShapeMain.js +3 -3
  425. package/modules/timeline/Timeline.js +83 -43
  426. package/modules/timeline/Tween.js +25 -19
  427. package/modules/timeline/shots.js +24 -17
  428. package/modules/triggers/index.js +95 -28
  429. package/modules/vegetation/Vegetation.js +34 -26
  430. package/modules/vegetation/densityMap.js +4 -7
  431. package/modules/vegetation/draw.js +39 -18
  432. package/modules/vegetation/groundChunks.js +21 -38
  433. package/modules/vegetation/index.js +37 -12
  434. package/modules/vegetation/modelGeometry.js +3 -6
  435. package/modules/vegetation/nearFade.js +1 -1
  436. package/modules/water/Water.js +20 -16
  437. package/modules/water/surface.js +3 -3
  438. package/modules/weather/Weather.js +52 -40
  439. package/modules/weather/particles.js +8 -8
  440. package/modules/weather/weatherDraw.js +28 -23
  441. package/modules/world/World.js +28 -15
  442. package/modules/world/explain.js +1 -1
  443. package/modules/world/index.js +30 -17
  444. package/modules/world/persist.js +90 -27
  445. package/modules/world/pos.js +5 -5
  446. package/modules/world/records.js +37 -11
  447. package/modules/world/sim.js +78 -27
  448. package/modules/world/simFar.js +2 -2
  449. package/modules/world/state.js +43 -11
  450. package/modules/world/thingSource.js +20 -5
  451. package/modules/world/views.js +27 -14
  452. package/package.json +48 -7
  453. package/presets.js +1 -3
  454. package/render/PostFX.js +83 -53
  455. package/render/backend.js +31 -33
  456. package/render/cascades.js +17 -12
  457. package/render/cascades.tsl.js +5 -8
  458. package/render/daylight.js +20 -3
  459. package/render/detail.js +8 -7
  460. package/render/effects.js +28 -25
  461. package/render/fuse.js +3 -3
  462. package/render/fx/cloudShadow.tsl.js +3 -3
  463. package/render/fx/detail.tsl.js +1 -1
  464. package/render/fx/index.js +5 -10
  465. package/render/fx/library.tsl.js +11 -0
  466. package/render/fx/lighting.tsl.js +2 -1
  467. package/render/fx/nodeErrors.tsl.js +2 -2
  468. package/render/fx/objectOrigin.tsl.js +1 -2
  469. package/render/fx/particles.tsl.js +8 -6
  470. package/render/fx/patchNodes.tsl.js +5 -15
  471. package/render/fx/postWebGPU.tsl.js +30 -26
  472. package/render/fx/sky.tsl.js +15 -17
  473. package/render/fx/uniforms.tsl.js +4 -4
  474. package/render/fx/wind.tsl.js +1 -1
  475. package/render/fxNumbers.js +3 -0
  476. package/render/layers.js +2 -2
  477. package/render/lighting.js +5 -3
  478. package/render/lightmap.js +41 -21
  479. package/render/lights.js +6 -6
  480. package/render/lit.js +24 -0
  481. package/render/materials.js +8 -7
  482. package/render/mergeCommon.js +22 -0
  483. package/render/modeling.js +2 -2
  484. package/render/occlusion.js +62 -15
  485. package/render/ownFrame.js +4 -4
  486. package/render/patches.js +15 -15
  487. package/render/postWebGL.js +15 -12
  488. package/render/probes.js +41 -19
  489. package/render/recordSweep.js +117 -0
  490. package/render/shaderErrors.js +10 -9
  491. package/render/shadowCache.tsl.js +107 -0
  492. package/render/shadowTypes.js +9 -0
  493. package/{core → render}/shadows.js +59 -13
  494. package/render/slots.js +7 -7
  495. package/render/terms.js +22 -24
  496. package/render/uniformDecl.js +1 -1
  497. package/types/core.d.ts +336 -202
  498. package/types/gameplay.d.ts +254 -130
  499. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  500. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  501. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  502. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
  503. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  504. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  505. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
  506. package/types/generated/core/input/inputSeat.d.ts +26 -0
  507. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  508. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
  509. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
  510. package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
  511. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
  512. package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
  513. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  514. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
  515. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  516. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
  517. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  518. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  519. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  520. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  521. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  522. package/types/generated/modules/grid/Grid.d.ts +1 -0
  523. package/types/generated/modules/grid/Layer.d.ts +1 -1
  524. package/types/generated/modules/grid/index.d.ts +3 -3
  525. package/types/generated/modules/music/Music.d.ts +7 -5
  526. package/types/generated/modules/particles/Particles.d.ts +5 -4
  527. package/types/generated/modules/sky/Sky.d.ts +21 -10
  528. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  529. package/types/generated/modules/timeline/Timeline.d.ts +7 -5
  530. package/types/generated/modules/water/Water.d.ts +1 -0
  531. package/types/generated/modules/weather/Weather.d.ts +14 -16
  532. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  533. package/types/generated/modules/world/World.d.ts +11 -7
  534. package/types/generated/render/PostFX.d.ts +21 -23
  535. package/types/generated/render/materials.d.ts +1 -0
  536. package/types/generated/render/occlusion.d.ts +9 -0
  537. package/types/generated/render/patches.d.ts +1 -0
  538. package/types/generated/ui/Focus.d.ts +1 -0
  539. package/types/generated/ui/UI.d.ts +1 -0
  540. package/types/nav.d.ts +47 -15
  541. package/types/physics.d.ts +150 -73
  542. package/types/pixel.d.ts +75 -0
  543. package/types/tsl.d.ts +37 -4
  544. package/types/world.d.ts +48 -75
  545. package/ui/Focus.js +10 -9
  546. package/ui/Parts.js +13 -5
  547. package/ui/UI.js +7 -7
  548. package/ui/defaults.js +3 -2
  549. package/ui/theme.js +7 -5
  550. package/core/assetEntry.js +0 -109
  551. package/core/engineCamera.js +0 -32
  552. package/core/ground.js +0 -104
  553. package/core/holds.js +0 -134
  554. package/core/math.js +0 -48
  555. package/core/moduleSlots.js +0 -100
  556. package/core/modules.js +0 -314
  557. package/core/saveApply.js +0 -210
  558. package/core/saveValues.js +0 -46
  559. package/core/session.js +0 -174
  560. package/core/shadowTypes.js +0 -16
  561. package/core/util.js +0 -17
  562. package/core/view.js +0 -43
  563. package/docs/MIGRATING-0.3.md +0 -248
  564. package/docs/MIGRATING-0.4.md +0 -320
  565. package/docs/MIGRATING-0.5.md +0 -68
  566. package/docs/MIGRATING-0.6.md +0 -126
  567. package/docs/PERF.md +0 -245
  568. package/docs/recipes/36-sky-ground-plants.md +0 -158
  569. package/docs/recipes/37-terrain-hooks.md +0 -115
  570. package/docs/recipes/38-environment-hooks.md +0 -67
  571. package/docs/recipes/42-terrain-shape.md +0 -64
  572. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  573. package/docs/recipes/54-three-idioms.md +0 -88
  574. package/examples/plain-picture/FINDINGS.md +0 -53
  575. package/examples/sheepisland/.threedog/content-index.json +0 -1
  576. package/modules/camera/projection.js +0 -21
  577. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  578. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  579. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  580. /package/core/{actor.js → ops/actor.js} +0 -0
  581. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  582. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  583. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  584. /package/core/{cells.js → stream/cells.js} +0 -0
  585. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  586. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  587. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  588. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  589. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  590. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  591. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  592. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  593. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
package/core/modules.js DELETED
@@ -1,314 +0,0 @@
1
- // Module installation (part of Engine, mixed into Engine.prototype): engine.use(...) / engine.has(name) / engine.moduleOrder.
2
- // See CLAUDE.md "writing a module" for the module shape; dispose is called by lifecycle.js in reverse install order.
3
- //
4
- // Run order (fixed / frame / afterRender / skip hooks): by stage first, then before / after within a stage, then install order.
5
- // stage only orders hooks; what a module may own and what happens when it throws come from its type (moduleTypes.js, errors.js).
6
- // Stages (first to last): control timeline, camera -> ground terrain, level -> environment weather, sky, water
7
- // -> gameplay interactions, dialogue, trigger zones -> effects particles, settings, objective markers
8
- // -> late (the default) characters, physics, navigation... -> audio music
9
- // before / after: lists of module names (not-installed names are ignored); they order modules only inside one stage.
10
- // One that contradicts the stage order (a 'control' module with after: ['sky']) makes use() throw naming both modules and stages;
11
- // a cycle makes use() throw on the spot, naming the modules on it.
12
- // Install is all-or-nothing per engine.use(...) call: the whole batch is validated (names, requires, stage, before / after, cycles)
13
- // before anything installs; if a module's install() then throws, the modules this call already installed are removed again
14
- // (engine.name, module table, hooks; their dispose() runs) and the error is rethrown.
15
- // Module state (engine.moduleStates): registered -> initializing -> running | failed; disposed after engine.dispose(). Modules without init() are
16
- // running at once. fixed / frame / afterRender / skip hooks run only for running modules, so no module gets a hook before its init() finished
17
- // (during start() or when installed later).
18
- // Ownership: install(e, ctx) and init(e, ctx) get ctx = { name, track(handle), mod(point, o), control.take(character, o) }. A handle passed to ctx.track (events.on, onFixed, onFrame,
19
- // clock timers, audio.measure... anything with remove()) belongs to the module and is removed with it: when the use() batch rolls back,
20
- // when its init fails, and on engine.dispose() (before the module's own dispose). Listeners a module adds go through it, so an install
21
- // that fails halfway leaves no ghost listener behind (review 0.4 A; the rollback spec checks every built-in module).
22
- // ctx.mod(point, o) = ctx.track(engine.mod(point, { ...o, owner: ctx.name })): a module's changes to shared values go with it too.
23
- // ctx.input.action(name, { context }) / ctx.input.bind(name, keys): the module's input declarations and bindings, gone with it too.
24
- // Every install is its own instance (engine._modInst: name -> token): a ctx belongs to one install, not to a name. An async init that resumes after
25
- // its module was unloaded (replaces, a plugin removed) and a same-named one installed must not act on the newcomer: what the stale ctx tracks is
26
- // removed at once (dev warning naming the module), and its completion or failure changes no state and drops no handle of the newcomer.
27
- // Exclusive slots: provides: ['inventory'] takes each named slot (a kind 'one' shared point, core/sharedPoint.js) for the module before its install;
28
- // a second provider is shared-taken. requires may name a slot instead of a module. engine.use(mine(), { replaces: 'inventory' }) unloads the
29
- // holder first (its handles, slot, drawing parts, dispose), and puts it back if the new install fails.
30
- // critical: true on a module makes a failed init() stop engine.start() with the reason; without it a failed init is reported (picture / ui: disabled;
31
- // other types: error tiers in errors.js) and start() goes on.
32
- // Dependencies: requires must be installed first (throws if missing). optional is a soft dependency: an array is only recorded (for GAMEMAP and rule R16);
33
- // written as { module: 'what is lost without it' }, start() warns once in dev when it is missing: use this form for optional dependencies
34
- // that change gameplay results, which must not be skipped silently.
35
- import { warnOnce, DEV, fmt, closest } from './validate.js';
36
- import { codedError, coded } from './errorHints.js';
37
- import { reportError } from './errors.js';
38
- import { catalog, catalogSnap, catalogClaim } from './catalog.js';
39
- import { readParams } from './params.js';
40
- import { slotMethods, isUseOpts, checkProvides } from './moduleSlots.js';
41
- import { checkType, asModule } from './moduleTypes.js';
42
-
43
- /** Stage -> sort position */
44
- const STAGES = { control: 100, ground: 200, environment: 300, gameplay: 400, effects: 450, late: 500, audio: 510 };
45
- const HOOKS = ['fixed', 'frame', 'afterRender', 'skip'];
46
- const STRINGS = {
47
- cycle: 'module order forms a cycle: {path} (check before / after on these modules)',
48
- stage: 'module {name} has stage "{stage}", which is not a stage; available stages: {list}',
49
- order: 'module {name} sets order, which is not supported; modules do not sort by number. Set stage ({list}) and use before / after within a stage',
50
- optional: 'optional dependency {dep} of module {name} is not installed: {what} (ignore if not needed; otherwise call engine.use({dep}()))',
51
- called: 'engine.use received the module function {name} itself; call it: {name}()',
52
- twice: 'module {name} is already installed; the second engine.use({name}()) is ignored',
53
- readyHook: 'module {name}: the load-complete hook is named isReady(e) (ready is always a boolean property in the engine); ready(e) will not be called',
54
- // both ways out: the engine's part of that name, or the game's own provider (requires names a capability, never a particular module)
55
- needs: "module {name} requires '{dep}', which no installed module provides. Fix: install the engine's part first, engine.use({dep}(), {name}(...)), "
56
- + "or your own module with provides: ['{dep}'] (then engine.{dep} is your module's API){typo}",
57
- typo: " (did you mean '{hint}'? installed: {list})",
58
- clash: 'module name {name} clashes with an existing engine property; pick another name',
59
- slotClash: "module {name} provides '{slot}', but engine.{slot} is already an engine property, so dependents could not reach it there. Fix: pick another slot name",
60
- lateInit: 'init of module {name} (installed after start)',
61
- conflict: 'module {a} (stage "{sa}") sets {kind}: ["{b}"], but module {b} is in stage "{sb}", which always runs {kind} stage "{sa}" (stage order: {list}); '
62
- + 'before / after only order modules inside one stage. Fix: give both modules the same stage, or remove {kind}: ["{b}"] from {a}',
63
- };
64
- const CTX_OWNER = "ctx.mod('{point}', { owner }) in module {name}: ctx.mod names the module as the owner itself; drop owner (use engine.mod for another owner name)";
65
- const BAD_HANDLE = 'ctx.track(handle) in module {name}: handle must have remove(), like the result of engine.events.on / onFixed / clock.after; got {got}';
66
- const STALE = 'module {name} registered something after it was unloaded (its async init or a callback resumed after replaces / unload); it was removed at once. '
67
- + 'The module installed under that name now is not affected';
68
- const STALE_INIT = 'init of module {name}, which was unloaded before it finished';
69
- const hookCache = new WeakMap(); // module definition -> { fixed, frame, afterRender, skip } hook entries (reused when re-sorting)
70
-
71
- /** Sort modules by stage, before / after and install order (Kahn topological sort; among the ready ones take the earliest stage,
72
- * then earliest installed); throws on a cycle. */
73
- function sortModules(list) {
74
- const idx = new Map(list.map((m, i) => [m.name, i])), byName = new Map(list.map(m => [m.name, m]));
75
- const rank = m => STAGES[m.stage] ?? STAGES.late;
76
- const succ = new Map(list.map(m => [m.name, new Set()])), indeg = new Map(list.map(m => [m.name, 0]));
77
- const edge = (a, b) => { if (!idx.has(a) || !idx.has(b) || succ.get(a).has(b)) return; succ.get(a).add(b); indeg.set(b, indeg.get(b) + 1); };
78
- for (const m of list) { for (const b of m.before || []) edge(m.name, b); for (const a of m.after || []) edge(a, m.name); }
79
- const cmp = (a, b) => rank(a) - rank(b) || idx.get(a.name) - idx.get(b.name);
80
- const ready = list.filter(m => !indeg.get(m.name)), out = [];
81
- while (ready.length) {
82
- ready.sort(cmp);
83
- const m = ready.shift(); out.push(m);
84
- for (const n of succ.get(m.name)) { indeg.set(n, indeg.get(n) - 1); if (!indeg.get(n)) ready.push(byName.get(n)); }
85
- }
86
- if (out.length === list.length) return out;
87
- // What is left is on a cycle or behind one: walk edges from any node; revisiting a node closes the cycle
88
- const left = new Set(list.filter(m => !out.includes(m)).map(m => m.name)), path = [];
89
- for (let n = left.values().next().value; !path.includes(n); n = [...succ.get(n)].find(x => left.has(x))) path.push(n);
90
- const cyc = path.slice(path.indexOf([...succ.get(path.at(-1))].find(x => path.includes(x))));
91
- throw codedError('module-cycle', STRINGS.cycle.replace('{path}', [...cyc, cyc[0]].join(' -> ')));
92
- }
93
-
94
- /** before / after across stages must agree with the stage order (the stage always wins), else the declaration would be silently ignored:
95
- * throw naming both modules */
96
- function checkStages(list) {
97
- const byName = new Map(list.map(m => [m.name, m])), rank = m => STAGES[m.stage] ?? STAGES.late, stage = m => m.stage ?? 'late';
98
- const order = Object.keys(STAGES).join(' -> ');
99
- const fail = (a, kind, b) => {
100
- throw codedError('module-order', fmt(STRINGS.conflict, { a: a.name, sa: stage(a), kind, b: b.name, sb: stage(b), list: order }));
101
- };
102
- for (const m of list) {
103
- for (const n of m.before || []) { const o = byName.get(n); if (o && rank(m) > rank(o)) fail(m, 'before', o); }
104
- for (const n of m.after || []) { const o = byName.get(n); if (o && rank(o) > rank(m)) fail(m, 'after', o); }
105
- }
106
- }
107
-
108
- export const moduleMethods = {
109
- ...slotMethods, // provides / replaces (moduleSlots.js)
110
- /**
111
- * Install one or more modules in order; dependencies must be installed first; hook order is described at the top of this file.
112
- * All-or-nothing: the batch is validated first, and if an install() throws, the modules this call installed are removed again.
113
- * A module installed after start() has its init(e) run at once (a task in engine.loading; an error goes through the error tiers) and gets no hooks
114
- * until it succeeded:
115
- * `await engine.loading.settled()` waits for it; engine.moduleStates shows where each module is.
116
- */
117
- use(...mods) {
118
- const opts = isUseOpts(mods.at(-1)) ? mods.pop() : null;
119
- const list = mods.flat(Infinity), gone = this._replaced(list, opts?.replaces);
120
- const plan = this._planUse(list, gone), done = [];
121
- // replaces: the holder goes first (its tracked handles, its slot, its drawing parts, its dispose), so the newcomer's install sees a free slot
122
- const removed = [...gone].map(n => this._unuse(n, true));
123
- try {
124
- for (const m of plan) {
125
- const had = Object.hasOwn(this, m.name), prev = this[m.name], snap = catalogSnap(this);
126
- done.push({ m, had, prev }); // before install(): what it tracked before throwing is removed too
127
- this._modInst.set(m.name, {}); // this install's identity: install and init ctx check it, so a stale async init cannot act on a later install
128
- const ctx = this._modCtx(m);
129
- this._picture?.installing(m);
130
- for (const slot of m.provides ?? []) ctx.track(this._slot(slot, m.name).take({ owner: m.name })); // shared-taken when another module holds it
131
- const api = asModule(this, m, () => m.install?.(this, ctx)) ?? m; // asModule: the type checks know who is installing (moduleTypes.js)
132
- catalogClaim(this, m.name, snap); // ops / save parts / describe names it registered show under it in engine.catalog()
133
- this.modules.set(m.name, m);
134
- if (m.name) this[m.name] = api;
135
- // engine.<slot> is the provider's API too, so a module that requires 'inventory' reaches the game's own bag at engine.inventory after
136
- // a replaces: dependents name the capability, never the module that gives it
137
- for (const slot of m.provides ?? []) if (slot !== m.name) { this[slot] = api; ctx.track(this._aliasSlot(slot, api)); }
138
- this._modState.set(m.name, m.init ? (this._started ? 'initializing' : 'registered') : 'running');
139
- }
140
- } catch (err) {
141
- for (const { m, had, prev } of done.reverse()) { // undo in reverse install order, like dispose
142
- const installed = this.modules.get(m.name) === m;
143
- this.modules.delete(m.name); this._modState.delete(m.name); this._modInst.delete(m.name);
144
- if (had) this[m.name] = prev; else delete this[m.name]; // put back what was there (an undefined slot stays undefined), never blank it
145
- this._dropTracked(m.name);
146
- if (installed) try { m.dispose?.(this); } catch { /* the install error below is the one to report */ }
147
- }
148
- this._sortHooks();
149
- // a replaced module comes back, so a failed swap leaves the game as it was (it installs fresh: its old handles already went)
150
- if (removed.length) try { this.use(...removed); } catch (e2) { reportError(this, e2, 'putting back the module a failed replaces removed', { soft: true }); }
151
- throw err;
152
- }
153
- this._sortHooks();
154
- if (this._started) for (const m of plan) if (m.init) this._lateInit(m);
155
- return this;
156
- },
157
- /** @internal validate a batch without touching the engine (so a failure leaves nothing half-installed);
158
- * returns the modules to install */
159
- _planUse(list, gone = new Set()) {
160
- const names = new Set([...this.modules.keys()].filter(n => !gone.has(n))), plan = [];
161
- // requires names a module or a capability: another module's provides (depend on 'inventory', not on whichever module gives it)
162
- const caps = new Set(names);
163
- for (const n of names) for (const s of this.modules.get(n).provides ?? []) caps.add(s);
164
- for (const m of list) {
165
- if (!m) continue;
166
- if (typeof m === 'function') throw codedError('module-called', fmt(STRINGS.called, { name: m.name }));
167
- if (names.has(m.name)) { warnOnce(coded('module-name', fmt(STRINGS.twice, { name: m.name }))); continue; }
168
- if (typeof m.ready === 'function') warnOnce(coded('engine-misuse', fmt(STRINGS.readyHook, { name: m.name })));
169
- if (m.order != null) throw codedError('module-stage', fmt(STRINGS.order, { name: m.name, list: Object.keys(STAGES).join(', ') }));
170
- if (m.stage != null && !(m.stage in STAGES))
171
- throw codedError('module-stage', fmt(STRINGS.stage, { name: m.name, stage: m.stage, list: Object.keys(STAGES).join(', ') }));
172
- checkType(m);
173
- for (const dep of m.requires || []) if (!caps.has(dep)) {
174
- const hint = closest(dep, [...caps]);
175
- throw codedError('module-requires', fmt(STRINGS.needs, { name: m.name, dep, typo: hint ? fmt(STRINGS.typo, { hint, list: [...caps].join(', ') }) : '' }));
176
- }
177
- checkProvides(m);
178
- for (const slot of m.provides ?? []) if (slot !== m.name && !gone.has(slot) && !names.has(slot) && slot in this && this[slot] !== undefined && !this._slotAlias?.has(slot))
179
- throw codedError('module-provides', fmt(STRINGS.slotClash, { name: m.name, slot }));
180
- if (DEV && m.params && m.options) readParams(m.name, m.params, m.options); // a definition built by hand still gets its options checked
181
- if (!gone.has(m.name) && m.name in this && this[m.name] !== undefined) throw codedError('module-name', fmt(STRINGS.clash, { name: m.name }));
182
- names.add(m.name); caps.add(m.name); for (const s of m.provides ?? []) caps.add(s);
183
- plan.push(m);
184
- }
185
- if (plan.length) { const all = [...[...this.modules.values()].filter(m => !gone.has(m.name)), ...plan]; checkStages(all); sortModules(all); }
186
- return plan;
187
- },
188
- /** @internal init of a module installed after start(): run now, tracked in engine.loading, errors through the error tiers;
189
- * its hooks join only after it succeeded */
190
- _lateInit(m) {
191
- const L = this.loading, task = L._begin(m.name, 'module');
192
- task.phase('build');
193
- const snap = catalogSnap(this);
194
- // the instance and its ctx are taken now, not when the microtask runs: by then a same-named module may be installed in its place
195
- const inst = this._modInst.get(m.name), ctx = this._modCtx(m, inst), live = () => this._isLive(m.name, inst);
196
- L._track(Promise.resolve().then(() => asModule(this, m, () => m.init(this, ctx))).then(
197
- () => { L._done(task); if (live()) { catalogClaim(this, m.name, snap); this._setModState(m, 'running'); } },
198
- e => {
199
- L._fail(task, e);
200
- // unloaded meanwhile: its handles already went with it, and the state / handles under this name belong to the newcomer now
201
- if (!live()) return reportError(this, e, fmt(STALE_INIT, { name: m.name }), { soft: true });
202
- this._setModState(m, 'failed'); this._dropTracked(m.name); reportError(this, e, fmt(STRINGS.lateInit, { name: m.name }), { module: m });
203
- }));
204
- },
205
- /** @internal is this install (token from engine._modInst) still the module installed under its name? */
206
- _isLive(name, inst) { return !this.disposed && inst !== undefined && this._modInst.get(name) === inst; },
207
- /** @internal the ctx install / init receive: track(handle) ties a handle to the module's life (see the top of this file) */
208
- _modCtx(m, inst = this._modInst.get(m.name)) {
209
- const name = m.name;
210
- const track = h => {
211
- if (typeof h?.remove !== 'function') throw codedError('module-handle', fmt(BAD_HANDLE, { name, got: String(h) }));
212
- if (this.disposed) { h.remove(); return h; } // a late registration after dispose: nothing will ever remove it otherwise
213
- // a registration from an install that is gone (replaced / unloaded while its async init awaited): filing it under the name would hand it
214
- // to the newcomer, which would then own a listener it never made; remove it now instead
215
- if (!this._isLive(name, inst)) { if (DEV) warnOnce(coded('module-handle', fmt(STALE, { name }))); h.remove(); return h; }
216
- let set = this._modTracked.get(name);
217
- if (!set) this._modTracked.set(name, set = new Set());
218
- set.add(h);
219
- if (this._curModule === m) this._picture?.learn(m); // the module's own code called this: its file is the part's (core/pictureWriters.js)
220
- return h;
221
- };
222
- // mod: engine.mod with the module as owner, tracked. Why a ctx verb and not "guess the running module": in an async callback the guess is wrong;
223
- // and a handle that is not tracked is a weather multiplier still on after the module went
224
- const mod = (point, o) => {
225
- if (o?.owner !== undefined) throw codedError('mod-owner', fmt(CTX_OWNER, { point, name }));
226
- return track(this.mod(point, { ...o, owner: name }));
227
- };
228
- // input: declare actions / bind the keys the game handed the module, owned by the module (removed with it); never a key of its own
229
- const input = {
230
- action: (n, o) => track(this.input.action(n, { ...o, owner: name })),
231
- bind: (n, keys) => track(this.input.bind(n, keys, { owner: name })),
232
- };
233
- // control: engine.control.take with the module as default owner, tracked, so a module that goes (unload, rollback, replaces) hands back every
234
- // character it was steering. Unlike mod an owner may be given: one module can hold several characters on its own names (one per cutscene run).
235
- // A hold that ends by itself leaves the tracked set too, so a module taking control often (a cutscene a minute) does not pile up dead handles.
236
- // Taking the same character again under the same owner replaces the hold, so the stale handle leaves the tracked set as well.
237
- const held = new Map(); // `${id} ${owner}` -> the live handle
238
- const control = {
239
- take: (who, o = {}) => {
240
- const h = this.control.take(who, { ...o, owner: o.owner ?? name }), end = h.remove, key = `${h.id} ${h.owner}`;
241
- const old = held.get(key);
242
- if (old) this._modTracked.get(name)?.delete(old);
243
- held.set(key, h);
244
- h.remove = () => { end(); if (held.get(key) === h) held.delete(key); this._modTracked.get(name)?.delete(h); };
245
- return track(h);
246
- },
247
- has: (who, owner = name) => this.control.has(who, owner),
248
- };
249
- // whileCompiling: a one-time warm-up (a WASM library's first call) run while start() waits for the GPU to compile shaders, when the page's
250
- // thread is idle anyway (startup.js); after start() it runs at once
251
- // It checks the install like track does: a warm-up queued by an install that was unloaded before start() ran the queue must not run
252
- // (it would touch state of an install that is gone), and one asked for by an install that is already stale is not queued at all
253
- const whileCompiling = fn => {
254
- if (!this._isLive(name, inst)) return;
255
- const run = () => { if (this._isLive(name, inst)) fn(); };
256
- if (this.ready) run(); else this._whileCompiling.push(run);
257
- };
258
- return { name, track, mod, input, control, whileCompiling };
259
- },
260
- /** @internal remove every handle a module tracked; one that throws is reported and the rest still go */
261
- _dropTracked(name) {
262
- const set = this._modTracked.get(name);
263
- if (!set) return;
264
- this._modTracked.delete(name);
265
- for (const h of set) { try { h.remove(); } catch (err) { reportError(this, err, `remove() of a handle module ${name} tracked`, { soft: true }); } }
266
- },
267
- /** @internal move a module to a new state and refresh the hooks (initializing / failed modules run none) */
268
- _setModState(m, state) {
269
- if (this.disposed || this._modState.get(m.name) === state) return;
270
- this._modState.set(m.name, state);
271
- this._sortHooks();
272
- },
273
- /**
274
- * Where each module is: 'registered' (init not started yet), 'initializing', 'running', 'failed' (init threw: no hooks) or 'disposed'.
275
- * @returns {Record<string, string>}
276
- * @example engine.use(shop()); await engine.loading.settled(); engine.moduleStates.shop // 'running'
277
- */
278
- get moduleStates() { return Object.fromEntries(this._modState); },
279
- /**
280
- * What this game can do, read from the registrations (see core/catalog.js): no argument = short list, a module id or op name = that entry expanded.
281
- * @param {string | { find?: string }} [id]
282
- * @returns {any}
283
- * @example engine.catalog(); engine.catalog('sky'); engine.catalog('shop.buy'); engine.catalog({ find: 'buy' })
284
- */
285
- catalog(id) { return catalog(this, id); },
286
- /** Is this module installed? */
287
- has(name) { return this.modules.has(name); },
288
- /** Run order of module hooks (module names, first to last), for debugging "who runs first". */
289
- get moduleOrder() { return this._moduleOrder ?? []; },
290
-
291
- /** Re-sort the module hooks in the main loop (disabled picture / ui modules are not put back). */
292
- _sortHooks() {
293
- const order = sortModules([...this.modules.values()]);
294
- this._moduleOrder = order.map(m => m.name);
295
- for (const k of HOOKS) this._hooks[k] = [];
296
- for (const m of order) {
297
- const st = this._modState.get(m.name);
298
- if (this.disabledModules.has(m.name) || st !== 'running') continue; // registered (init not run yet), initializing, failed: no hooks
299
- let c = hookCache.get(m);
300
- if (!c) hookCache.set(m, c = {});
301
- for (const k of HOOKS) if (m[k]) this._hooks[k].push(c[k] ??= { fn: m[k].bind(m), name: m.name, mod: m });
302
- }
303
- },
304
- /** Called by start(): warn once in dev when an optional dependency written as { module: 'what is lost' } is not installed. */
305
- _checkOptional() {
306
- if (!DEV) return;
307
- for (const m of this.modules.values()) {
308
- const opt = m.optional;
309
- if (!opt || Array.isArray(opt)) continue;
310
- for (const [dep, what] of Object.entries(opt)) if (!this.modules.has(dep) && !this._provided(dep))
311
- warnOnce(coded('module-requires', fmt(STRINGS.optional, { name: m.name, dep, what })));
312
- }
313
- },
314
- };
package/core/saveApply.js DELETED
@@ -1,210 +0,0 @@
1
- // Applying a save (split out of Saves.js): every part is checked and migrated before anything changes (saveVersions.js), then loaded in order;
2
- // if anything in the load throws, every part reloads the state from just before the load (rollback), so a game is never left half-loaded.
3
- // "Anything" is the whole load, not only load() itself: a listener of an event a part emits while loading (world:load) and the modules' afterLoad
4
- // hooks count too. Reported on their own they let the load carry on: a hand-edited player position threw in a world:load listener and left the game
5
- // frozen half-loaded (durability audit 2026-11-02).
6
- // The capture lasts the whole load, past every await: an async part that emits after `await` (async load(d) { apply(d); await res(); emit(...) })
7
- // is part of the load as much as its first line. The browser has no async context to tell whose code emitted after an await, so each load
8
- // carries its own capture scope (Events._scopes): a part's synchronous run puts its load's scope on top; between awaits the load started last
9
- // gets the errors. Loads are not queued: apply changes the state synchronously when every part is synchronous (callers rely on that), and two
10
- // overlapping loads were never sound anyway (the second one's rollback point is the first one's half-applied state). An unrelated listener that
11
- // throws while a load is still settling fails that load too; gameplay is frozen while parts load, so that is rare, and the error is reported.
12
- // The rollback point is a copy (structuredClone of every part's save()): save() may return the live object, which load() then writes into.
13
- import { toast } from '../ui/UI.js';
14
- import { fmt, warnOnce } from './validate.js';
15
- import { reportError } from './errors.js';
16
- import { codedError, coded } from './errorHints.js';
17
- import { FORMAT, readSave, parseSave, upgradePart } from './saveVersions.js';
18
- import { PARTS_LOADING } from './opsFail.js';
19
-
20
- const DEV_STRINGS = {
21
- loadThrew: "load() of save part '{k}' threw ({msg}); the game was rolled back to how it was before loading '{slot}'",
22
- partAt: "load() of save part '{k}'", adoptAt: "load() of save part '{k}' (registered after the save was loaded)",
23
- rollback: "rollback of save part '{k}' after a failed load (that part may be half-loaded; the other parts rolled back)",
24
- listener: 'a listener of event {name} threw while the part loaded: {msg}',
25
- hook: "afterLoad of module '{k}' threw ({msg}); the game was rolled back to how it was before loading '{slot}'",
26
- notPlain: "save() of save part '{k}' returned data that cannot be copied ({msg}), so loading '{slot}' could not keep a rollback point and was refused "
27
- + 'before anything changed. save() must return plain data (no functions, DOM nodes, three objects); return a copy of what the save needs',
28
- };
29
-
30
- /** A save part's load threw: the error named after the part (thrown on, so the caller can roll back) */
31
- const loadError = (k, err, slot) => Object.assign(codedError('save-load-threw', fmt(DEV_STRINGS.loadThrew, { k, slot, msg: err?.message ?? String(err) })), { part: k, cause: err });
32
-
33
- /**
34
- * Implementation of saves.apply (see its JSDoc): checked first, applied part by part, rolled back to the pre-load state if any part throws.
35
- * @param {any} s the Saves instance
36
- * @param {any} data
37
- * @param {string} slot
38
- * @returns {Promise<boolean>}
39
- * @internal
40
- */
41
- export function applySave(s, data, slot) {
42
- const r = readSave(data, s.providers, slot);
43
- if ('reason' in r) {
44
- if (r.reason !== 'missing') { warnOnce(coded('save-refused', r.dev)); // handled: the player is told, nothing changed
45
- toast(s.engine, s.engine.t('saves.' + r.reason), { kind: 'error', ms: 5000 }); }
46
- return Promise.resolve(false);
47
- }
48
- const e = s.engine, foreign0 = s._foreign;
49
- let before; // the rollback point, a copy (rollbackPoint)
50
- try { before = rollbackPoint(s, slot); } catch (err) { reportError(e, err, `saves.apply('${slot}')`); return Promise.resolve(false); }
51
- const ev = e.events, scope = []; // this load's capture scope: listener errors from now until the load settled (top of the file)
52
- ev._scopes.push(scope);
53
- const settled = () => { const i = ev._scopes.lastIndexOf(scope); if (i >= 0) ev._scopes.splice(i, 1); };
54
- return Promise.resolve(applyParts(s, e, r, slot, before, foreign0, scope)).finally(settled);
55
- }
56
-
57
- /** The rest of applySave, under the load's capture scope */
58
- function applyParts(s, e, r, slot, before, foreign0, scope) {
59
- e.commits.invalidate(); e.ops._mark('(load)'); // old background results die with the old world; the op log shows where the load cut in
60
- s._foreign = r.foreign;
61
- const fail = err => {
62
- // a malformed save (world/persist.js save-bad-record) is the save's fault, not the game's: refused like a corrupt save (warning + toast), so it
63
- // does not freeze gameplay as a code error would; a load() / listener / afterLoad that throws is a bug and goes through the error tiers
64
- if (err?.cause?.code === 'save-bad-record') { warnOnce(err.message); toast(e, e.t('saves.corrupt'), { kind: 'error', ms: 5000 }); }
65
- else reportError(e, err, err?.part ? fmt(DEV_STRINGS.partAt, { k: err.part }) : `saves.apply('${slot}')`);
66
- s._foreign = foreign0;
67
- const back = readSave(before, s.providers, '(rollback)');
68
- // every part reloads its pre-load state; a part that throws again is reported (once) and the rest still roll back
69
- const onPart = er => reportError(e, er, fmt(DEV_STRINGS.rollback, { k: er.part }), { soft: true });
70
- return Promise.resolve('list' in back ? e.ops.allow(() => runParts(e, back.list, '(rollback)', scope, onPart)) : null).then(() => false);
71
- };
72
- let out;
73
- try { out = e.ops.allow(() => runParts(e, r.list, slot, scope)); } catch (err) { return fail(err); } // loading writes state outside ops on purpose (guard allows it)
74
- // a part still loading (its load() returned a Promise): gameplay waits until every part is applied -- no fixed step, no op (opsFail.js
75
- // PARTS_LOADING). Held through a rollback too, since that may wait on async parts as well. A fully sync load never takes it.
76
- const fz = out !== true ? e.freeze(PARTS_LOADING) : null;
77
- const partsDone = () => { fz?.remove(); };
78
- // a load is a state change: ops.revision moves. afterLoad belongs to the load (Saves.apply doc): a hook that throws fails it like a part's load()
79
- return Promise.resolve(out).then(() => { partsDone(); e.ops.revision++; return afterLoad(e, slot, scope).then(() => true, fail); },
80
- err => Promise.resolve(fail(err)).finally(partsDone));
81
- }
82
-
83
- /** The rollback point: every part's save(), copied so a load() writing into the object its save() returned cannot change it.
84
- * A part whose data cannot be copied throws (save-part-threw): without a true copy a failed load could not be undone */
85
- function rollbackPoint(s, slot) {
86
- const data = s._collect().data;
87
- for (const k of Object.keys(data.parts)) {
88
- try { data.parts[k] = structuredClone(data.parts[k]); }
89
- catch (err) { throw Object.assign(codedError('save-part-threw', fmt(DEV_STRINGS.notPlain, { k, slot, msg: err?.message ?? String(err) })), { cause: err }); }
90
- }
91
- return data;
92
- }
93
-
94
- /** A listener error collected in scope since index from: the first counts as the load throwing (and the scope forgets them) */
95
- function takeListenerError(scope, from) {
96
- if (scope.length <= from) return;
97
- const { name, err } = scope[from];
98
- scope.length = from;
99
- throw Object.assign(new Error(fmt(DEV_STRINGS.listener, { name, msg: err?.message ?? String(err) })), { cause: err });
100
- }
101
-
102
- /** Run one part's load with event-listener errors collected in the load's scope (on top while it runs synchronously, see the top of the file);
103
- * an async load is checked once it settled, so a listener that throws after its await fails the part too */
104
- function callLoad(e, fn, scope) {
105
- const ev = e.events, from = scope.length;
106
- ev._scopes.push(scope);
107
- let r;
108
- try { r = fn(); } catch (err) { scope.length = from; throw err; } finally { ev._scopes.splice(ev._scopes.lastIndexOf(scope), 1); }
109
- if (r && typeof r.then === 'function') return r.then(v => { takeListenerError(scope, from); return v; }, err => { scope.length = from; throw err; });
110
- takeListenerError(scope, from);
111
- return r;
112
- }
113
-
114
- /**
115
- * Load parts in order; a part returning a Promise makes the rest wait for it. A failing part throws (or rejects) with the part named,
116
- * unless onFail is given (rollback): then onFail(err) is called and the next part loads anyway.
117
- */
118
- function runParts(e, list, slot, scope, onFail = null) {
119
- const failed = (k, err) => { const er = loadError(k, err, slot); if (!onFail) throw er; onFail(er); };
120
- const step = i => {
121
- for (; i < list.length; i++) {
122
- const [k, p, d] = list[i];
123
- let r;
124
- try { r = callLoad(e, () => p.load(d), scope); } catch (err) { failed(k, err); continue; }
125
- if (r && typeof r.then === 'function') return r.then(() => step(i + 1), err => { failed(k, err); return step(i + 1); });
126
- }
127
- return true;
128
- };
129
- return step(0);
130
- }
131
-
132
- /**
133
- * A part registered after a save was loaded (a module installed later): hand it its data from that save now.
134
- * @param {any} s the Saves instance
135
- * @param {string} key
136
- * @internal
137
- */
138
- export function adoptPart(s, key) {
139
- const p = s.providers.get(key), d = s._foreign.parts[key], v = s._foreign.versions[key] ?? 1;
140
- delete s._foreign.parts[key]; delete s._foreign.versions[key];
141
- const where = fmt(DEV_STRINGS.adoptAt, { k: key });
142
- try {
143
- if (v > p.version) throw codedError('save-refused', `save part '${key}' is version ${v}, this build reads up to ${p.version}`);
144
- const r = s.engine.ops.allow(() => p.load(upgradePart(key, p, d, v, s._foreign.whole)));
145
- if (r && typeof r.then === 'function') r.catch(err => reportError(s.engine, err, where));
146
- } catch (err) { reportError(s.engine, err, where); }
147
- }
148
-
149
-
150
- /**
151
- * Load a slot; with base (a collect() result) the save goes on top of it, so a part missing from the save gets base's state (session.load).
152
- * @param {any} s the Saves instance
153
- * @param {string} slot
154
- * @param {any} [base]
155
- * @returns {Promise<boolean>}
156
- * @internal
157
- */
158
- export function loadSlot(s, slot, base) {
159
- let data = s._json.get(slot);
160
- if (base && data != null) {
161
- try {
162
- const sv = parseSave(data);
163
- if (sv?.parts && typeof sv.parts === 'object' && !Array.isArray(sv.parts)) {
164
- const own = Object.fromEntries(Object.keys(sv.parts).map(k => [k, sv.versions?.[k] ?? 1])); // a part without a version is version 1, not base's
165
- data = { ...sv, parts: { ...base.parts, ...sv.parts }, versions: { ...base.versions, ...own } };
166
- }
167
- } catch { /* unreadable: apply refuses the text itself with the reason */ }
168
- }
169
- return s.apply(data, slot).then(ok => { // apply already ran the modules' afterLoad hooks
170
- if (ok) { s._adopt(slot); s.engine.events.emit('save:loaded', slot); } // continuing from it: this tab may overwrite it now (Saves._put)
171
- return ok;
172
- });
173
- }
174
-
175
- /** Modules with an afterLoad hook rebuild what the loaded state needs nearby (models and the colliders their build adds); gameplay waits frozen
176
- * until every one resolves, so the first step after `await saves.load()` never runs on missing ground or walls.
177
- * applySave runs it (not only saves.load): session.newGame() / quit() apply the base data the same way and need the same rebuild.
178
- * Every hook settles before the result (allSettled): a rollback must not start while another hook is still building the state being replaced.
179
- * The first failure rejects, named after its module (save-load-threw), and applySave rolls back. Rollback itself does not rerun afterLoad
180
- * (the world rebuilds nearby models over the next frames).
181
- * The hooks run side by side, so a listener error in this phase is not pinned on one hook: once all settled, any error the load's scope
182
- * collected since its parts finished fails the load (the last check before apply resolves true). */
183
- async function afterLoad(e, slot, scope) {
184
- const hooks = [...e.modules.values()].filter(m => m.afterLoad);
185
- let res = [];
186
- if (hooks.length) {
187
- const fz = e.freeze('threedog:load'); // a namespaced owner: a game's own freeze('load') must not be released by (or release) the engine's
188
- try { res = await Promise.allSettled(hooks.map(m => Promise.resolve().then(() => m.afterLoad(e)))); } finally { fz.remove(); }
189
- }
190
- const i = res.findIndex(r => r.status === 'rejected');
191
- if (i >= 0) {
192
- scope.length = 0;
193
- const err = /** @type {PromiseRejectedResult} */ (res[i]).reason, k = hooks[i].name;
194
- throw Object.assign(codedError('save-load-threw', fmt(DEV_STRINGS.hook, { k, slot, msg: err?.message ?? String(err) })), { cause: err });
195
- }
196
- takeListenerError(scope, 0);
197
- }
198
-
199
- /** Collect every part: { data, failed: [[key, error]] }. Parts of the loaded save that no module owns are carried along. */
200
- export function collectParts(s) {
201
- const f = s._foreign, failed = [];
202
- const data = { format: FORMAT, savedAt: Date.now(), versions: { ...f.versions }, parts: { ...f.parts } }; // wall-clock: real time of the save
203
- for (const [k, p] of s.providers) {
204
- // a part with nothing to save (save() returns null / undefined) is left out, so a null part in a save always means damage (readSave refuses it);
205
- // loading a save without it keeps that part as it is (saves.load) or gives it its new-game state (session.load)
206
- try { const d = p.save(); if (d == null) { delete data.parts[k]; delete data.versions[k]; } else { data.parts[k] = d; data.versions[k] = p.version; } }
207
- catch (e) { failed.push([k, e]); delete data.parts[k]; delete data.versions[k]; }
208
- }
209
- return { data, failed };
210
- }
@@ -1,46 +0,0 @@
1
- // Load-time number checks. A part's load() passes each saved number through here, so a hand-edited or damaged value (a negative clock, a random
2
- // state 'abc', a count of 1e308) never reaches the running game. Each bad value is clamped to its range (or replaced by a fallback when it is not
3
- // a finite number at all), the rest of the part loads, and the part prints ONE warning listing what it fixed (save-value).
4
- // Why clamp and not refuse: these are scalars with an obvious safe value; refusing the whole save over a clock of -1000 would cost the player the
5
- // rest of the playthrough. Shapes that have no safe value (a record position, world/persist.js) are refused instead (save-bad-record).
6
- //
7
- // const v = saveValues('clock');
8
- // this._now = v.num(d?.now, 'now', { min: 0, fallback: 0 });
9
- // v.done(); // one warning for the part, only when something was fixed
10
- import { warnOnce } from './validate.js';
11
- import { coded } from './errorHints.js';
12
-
13
- const STRINGS = {
14
- warn: "[saves] save part '{part}' had {n} bad value(s), fixed while loading: {list}. The save was edited by hand or damaged; the next save writes the fixed values",
15
- };
16
-
17
- /**
18
- * A checker for one part's load: num() clamps / replaces, done() warns once when anything was fixed.
19
- * @param {string} part
20
- * @internal
21
- */
22
- export function saveValues(part) {
23
- const fixed = [];
24
- return {
25
- /**
26
- * @param {any} v the saved value
27
- * @param {string} path for the warning
28
- * @param {{ min?: number, max?: number, int?: boolean, fallback: number }} o
29
- * @returns {number}
30
- */
31
- num(v, path, { min = -Infinity, max = Infinity, int = false, fallback }) {
32
- if (typeof v !== 'number' || !Number.isFinite(v)) { fixed.push(`${path} ${JSON.stringify(v) ?? 'undefined'} -> ${fallback}`); return fallback; }
33
- let n = int ? Math.round(v) : v;
34
- n = Math.min(max, Math.max(min, n));
35
- if (n !== v) fixed.push(`${path} ${v} -> ${n}`);
36
- return n;
37
- },
38
- /** Note a value dropped by the caller (a timer without a due time) */
39
- drop(path, v) { fixed.push(`${path} ${String(JSON.stringify(v)).slice(0, 60)} dropped`); },
40
- /** One warning for the part when anything was fixed; returns how many */
41
- done() {
42
- if (fixed.length) warnOnce(coded('save-value', STRINGS.warn.replace('{part}', part).replace('{n}', String(fixed.length)).replace('{list}', fixed.slice(0, 6).join('; ') + (fixed.length > 6 ? '; …' : ''))));
43
- return fixed.length;
44
- },
45
- };
46
- }