threedog 0.8.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/CHANGELOG.md +223 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -19,7 +19,7 @@ class Task {
19
19
  this.source = { manifest, url, version: null, bytes: null, animations: null };
20
20
  }
21
21
  /** @param {string} p queued | download | decode | upload | build | done | failed @param {number} [progress] */
22
- phase(p, progress = 0) { this.state = p; this.progress = progress; }
22
+ phase(p, progress = 0) { this.state = p; this.progress = progress; this.at = performance.now(); } // measure: at, the last sign of life the load limit reads
23
23
  toJSON() {
24
24
  const o = { name: this.name, kind: this.kind, phase: this.state, progress: Math.round(this.progress * 100) / 100, critical: this.critical };
25
25
  if (this.error) o.error = this.error;
@@ -35,7 +35,7 @@ export class Loading {
35
35
  constructor(engine) {
36
36
  this.engine = engine; this.tasks = new Map();
37
37
  this._inits = new Set(); // init() of modules installed after start(), in flight
38
- /** How long start() waits for modules whose isReady stays false before it rejects naming them (ms) @type {number} */
38
+ /** The one limit on every wait for a load (ms): a file that gives no sign of life, a module's init or a settle that does not end fail by name after it @type {number} */
39
39
  this.timeoutMs = 120000;
40
40
  }
41
41
 
@@ -45,10 +45,35 @@ export class Loading {
45
45
  * Resolves when every module installed after start() has finished its init() (also when one failed: its state is then 'failed' in engine.moduleStates and the error went through the error tiers).
46
46
  * engine.use() returns the engine, so await this to know a late module is running.
47
47
  * @returns {Promise<void>}
48
- * @example engine.use(shop()); await engine.loading.settled(); engine.moduleStates.shop // 'running'
48
+ * @example engine.use(shop()); await engine.loading.settled(); engine.explain({ module: 'shop' }).ok // true
49
49
  */
50
50
  async settled() { while (this._inits.size) await Promise.allSettled([...this._inits]); }
51
51
 
52
+ /**
53
+ * @internal The one limit: p, or fail()'s error once lastSign() (the time of the last sign of life, null: stop watching) is older than timeoutMs. It only answers the waiter; p goes on unless fail ends it.
54
+ * @template T
55
+ * @param {Promise<T>} p
56
+ * @param {() => number | null} lastSign
57
+ * @param {() => any} fail
58
+ * @returns {Promise<T>}
59
+ */
60
+ _limit(p, lastSign, fail) {
61
+ let timer;
62
+ const over = new Promise((_, rej) => {
63
+ const look = () => {
64
+ const last = lastSign();
65
+ if (last == null || this.engine.disposed) return;
66
+ const left = this.timeoutMs - (performance.now() - last); // measure
67
+ if (left > 0) timer = setTimeout(look, Math.min(left, 2 ** 31 - 1)); // main-loop: a wall clock, because what it guards may be why no frame runs
68
+ else rej(fail());
69
+ };
70
+ look();
71
+ });
72
+ const end = () => clearTimeout(timer);
73
+ p.then(end, end);
74
+ return Promise.race([p, over]);
75
+ }
76
+
52
77
  /** Start (or restart) a task; engine-internal callers keep the returned task and move its phase */
53
78
  _begin(name, kind, opts) { const t = new Task(name, kind, opts); this.tasks.set(kind + ':' + name, t); return t; } // keyed by kind too: a module and a model may share a name
54
79
  _done(t) { t.phase('done', 1); }
@@ -150,3 +175,5 @@ export function failureText(t) {
150
175
  const where = [err.url && err.url !== s.url ? `missing ${err.url}` : null, s.manifest ? `manifest "${s.manifest}"` : null].filter(Boolean);
151
176
  return `${j.kind} "${j.name}" <- ${s.url ?? j.name}: ${err.message}${where.length ? ` [${where.join(', ')}]` : ''}`;
152
177
  }
178
+
179
+ export const handRolled = [{ kind: 'loading', seen: 'a loading screen of its own', use: 'engine.loading: tracks what is loading, shows progress and has a view you can replace (recipe 07)', quiet: /\bengine\.loading\b/, code: /\b(createElement|innerHTML|className|classList|getElementById|querySelector|\.id)\b/, raw: /(?:createElement|innerHTML|className|classList|getElementById|querySelector|\.id\b)[^,;{}]*(?:loading|loader|load-?bar|progress-?bar)|(?:loading|loader|load-?bar|progress-?bar)[^,;{}]*(?:createElement|innerHTML|className|classList|getElementById|querySelector|\.id\b)/i }];
@@ -6,7 +6,7 @@
6
6
  // A hot reload re-runs the same file (same path, a ?t= query): that is one copy, not two, so the path without the query decides.
7
7
  import { coded } from '../base/errorHints.js';
8
8
 
9
- export const VERSION = '0.8.0'; // kept equal to package.json by the "[guard] engine copies" spec
9
+ export const VERSION = '0.9.0'; // kept equal to package.json by the "[guard] engine copies" spec
10
10
 
11
11
  const KEY = Symbol.for('threedog.engine.copies');
12
12
 
@@ -1,6 +1,6 @@
1
1
  // Headless loading after start: a headless engine (?threedog-headless, createEngine({ headless: true })) has no real-time loop, so after start()
2
2
  // nothing runs frames unless someone calls step(). Anything that makes the world load again after start (a species added with
3
- // vegetation.define, terrain.setDensity, a teleport, a level swap) queued its work and waited for frames that never came: the page sat on
3
+ // vegetation.define, terrain.density, a teleport, a level swap) queued its work and waited for frames that never came: the page sat on
4
4
  // "waiting for module terrain" forever, while the same page in a live browser loaded within a second.
5
5
  //
6
6
  // Why a load pump and not "step more" in the tools: step() is synchronous, and chunk results come back from workers between tasks, so no
@@ -9,10 +9,9 @@
9
9
  // dt 0, jobs drain deterministically), on a timer. A settled world runs nothing, so step()-driven tests keep their exact frame count.
10
10
  //
11
11
  // stateApplied waits for it too (Engine.js): screenshots, npm test and the dev bridge wait on stateApplied, so a load that began after
12
- // start is finished before they capture. A load that never settles stops holding stateApplied after engine.loading.timeoutMs (same limit
13
- // as start()) with one warning naming who is still waiting, so a stuck module cannot hang a tool.
12
+ // start is finished before they capture. A load that never settles stops holding stateApplied at whenSettled's limit with one warning naming who is still waiting, so a stuck module cannot hang a tool.
14
13
  import { DEV, warnOnce } from '../base/validate.js';
15
- import { coded } from '../base/errorHints.js';
14
+ import { coded, codedError } from '../base/errorHints.js';
16
15
 
17
16
  const TICK_MS = 16; // one loading frame per ~60 Hz tick: the same pace a live loop gives the workers
18
17
 
@@ -24,24 +23,42 @@ export function unsettled(e) {
24
23
  return who;
25
24
  }
26
25
 
26
+ /** The error of a settle that did not come, in the words unsettled() gives */
27
+ const stalled = e => codedError('module-not-ready', `Still waiting after ${Math.round(e.loading.timeoutMs / 1000)} s for: ${unsettled(e).join(', ')}. A module's isReady(e) keeps returning false (or the world never finished its nearby builds); fix that, or raise engine.loading.timeoutMs if the load is only slow`);
28
+
29
+ /**
30
+ * @internal The one wait for "ready to play": true once nothing is unsettled, checked per engine frame so step() advances it too; false as soon as valid() stops holding. It rejects (module-not-ready,
31
+ * naming who still waits) after engine.loading.timeoutMs. start(), flow's transition, level:playable and the headless pump all read this, so the question has one answer and one limit.
32
+ */
33
+ export function whenSettled(e, valid = () => true) {
34
+ const now = () => !valid() ? false : unsettled(e).length ? null : true;
35
+ const first = now();
36
+ if (first !== null) return Promise.resolve(first);
37
+ const since = performance.now(); // measure: wall clock, so a wait with no frames to run on still ends
38
+ let h;
39
+ const settled = new Promise((res, rej) => {
40
+ h = e.onFrame(() => {
41
+ try { const r = now(); if (r !== null) { h.remove(); res(r); } } catch (err) { h.remove(); rej(err); } // a throwing isReady ends the wait: this hook's error would reach no waiter
42
+ });
43
+ });
44
+ return e.loading._limit(settled, () => now() === null ? since : null, () => { h.remove(); return stalled(e); });
45
+ }
46
+
27
47
  /** @internal start(): begin pumping loading frames for a headless engine (no-op for a live one, its loop already runs frames) */
28
48
  export function startHeadlessLoad(e) {
29
49
  if (!e.headless || e._headlessLoad) return;
30
- const s = e._headlessLoad = { since: -1, stalled: false };
50
+ const s = e._headlessLoad = { watching: false, stalled: false };
31
51
  const tick = () => {
32
52
  if (e.disposed) return;
33
- if (!unsettled(e).length) { s.since = -1; s.stalled = false; }
53
+ if (!unsettled(e).length) s.stalled = false;
34
54
  else {
35
- const now = performance.now(); // measure: wall clock, only to stop a stuck load from holding stateApplied forever
36
- if (s.since < 0) s.since = now;
55
+ if (!s.watching && !s.stalled) {
56
+ s.watching = true;
57
+ whenSettled(e).catch(err => { s.stalled = true; if (DEV) warnOnce(coded('module-not-ready', `headless load after start: ${err.message}; stateApplied no longer waits for it`)); }).finally(() => { s.watching = false; });
58
+ }
37
59
  // the same loading frame start() runs while it waits (startup.js _waitReady): frame hooks, stream, jobs; game time stays put
38
60
  // (no input.endFrame: a key a test pressed before its next step() must still read as just pressed there)
39
61
  e._frameHooks(0, true);
40
- if (!s.stalled && now - s.since > e.loading.timeoutMs) {
41
- s.stalled = true;
42
- const who = unsettled(e);
43
- if (DEV && who.length) warnOnce(coded('module-not-ready', `headless load after start stalled: still waiting after ${Math.round(e.loading.timeoutMs / 1000)} s for: ${who.join(', ')}; stateApplied no longer waits for it. A module's isReady(e) keeps returning false; fix that module, or raise engine.loading.timeoutMs if the load is just slow`));
44
- }
45
62
  }
46
63
  setTimeout(tick, TICK_MS); // main-loop: a headless engine's stand-in for the live frame loop while something is loading
47
64
  };
@@ -10,6 +10,9 @@
10
10
  // ctx.track (modules.js), so they also leave when its install rolls back or its init fails, and go before its dispose hook runs.
11
11
  // - Things core does not know about (Worker, physics world, Audio nodes, real-time timers): clean up in the module's dispose(e) hook, called in reverse install order.
12
12
  // - GPU memory: every geometry, material and texture in the scene, the assets cache, the post composer, then renderer.dispose().
13
+ // Waits across dispose, one rule: a wait in game code (model(), jobs.add, nextFixed, a cutscene, an await of what those feed) stays pending for good, because the code after it
14
+ // belongs to a dead engine (assetEntry.js says why not reject). Two waits have to answer instead: start(), for whoever booted the engine (startup.js), and a stream source's whenReady,
15
+ // which rejects stream-removed: dispose removes every source, and a source made afterwards is born removed.
13
16
  // Level changes do not come through here: things inside a level register with level.track(handle), and the level removes them itself on change.
14
17
 
15
18
  import { coded, codedError } from '../base/errorHints.js';
@@ -23,7 +26,7 @@ export function clearHooks(e) {
23
26
  e._fixed = []; e._fixedLate = []; e._frame = []; e._animate = []; e._onRender = { before: [], after: [] }; e._hooks = { fixed: [], frame: [], afterRender: [], skip: [] };
24
27
  }
25
28
 
26
- const STRINGS = { failed: '[engine] dispose hook of module {name} threw (the rest are still cleaned up)',
29
+ const STRINGS = { failed: '[engine] dispose hook of module {name} threw (the rest are still cleaned up)', part: '[engine] a cleanup step of engine.dispose() threw, {why} (the rest are still cleaned up)',
27
30
  released: 'createEngine(): this canvas lost its WebGL context in an earlier engine.dispose(), so a new engine cannot draw on it; use a new canvas, or dispose the old engine with dispose({ keepContext: true })',
28
31
  opts: 'engine.dispose(opts): opts is { keepContext?: boolean }; got {v}' };
29
32
 
@@ -33,18 +36,20 @@ const released = new WeakSet();
33
36
  export function checkCanvasUsable(canvas) { if (canvas && released.has(canvas)) throw codedError('canvas-released', STRINGS.released); }
34
37
 
35
38
  /** Dispose the GPU data of one scene object: geometry, materials and their textures, instance buffers, shadow map, bone texture */
36
- function disposeObject(o) {
37
- o.geometry?.dispose(); if (o.isInstancedMesh || o.isBatchedMesh || o.isLight) o.dispose(); o.skeleton?.dispose(); // instance buffers, batch textures, a light's shadow map, the bone texture
39
+ function disposeObject(o, tidy) {
40
+ tidy(() => o.geometry?.dispose());
41
+ tidy(() => { if (o.isInstancedMesh || o.isBatchedMesh || o.isLight) o.dispose(); }); // instance buffers, batch textures, a light's shadow map
42
+ tidy(() => o.skeleton?.dispose()); // the bone texture
38
43
  for (const m of [].concat(o.material || [])) {
39
- for (const k in m) if (m[k]?.isTexture) m[k].dispose();
40
- m.dispose();
44
+ for (const k in m) if (m[k]?.isTexture) tidy(() => m[k].dispose());
45
+ tidy(() => m.dispose());
41
46
  }
42
47
  }
43
48
 
44
49
  export const lifecycleMethods = {
45
50
  /**
46
51
  * Destroy the engine: stop the main loop, call each module's dispose(e) in reverse install order, then clean up core (listeners, timers, sound, UI, GPU memory).
47
- * No callbacks fire afterwards and engine.disposed becomes true. Safe to call repeatedly.
52
+ * No callbacks fire afterwards and engine.disposed becomes true. Safe to call repeatedly. start() rejects with engine-disposed; awaits in game code (a model, a job, nextFixed) stay pending for good.
48
53
  * The engine's own renderer also gives its WebGL context back (renderer.forceContextLoss): browsers keep only about 16 live contexts, so a page that
49
54
  * creates and disposes engines (level editor, tests, restart) would otherwise lose the oldest one. That canvas cannot host a new engine afterwards;
50
55
  * keepContext: true keeps the context for a new engine on the same canvas. A renderer the game passed in (createEngine({ renderer })) is never released.
@@ -53,9 +58,11 @@ export const lifecycleMethods = {
53
58
  dispose(opts = {}) {
54
59
  if (opts === null || typeof opts !== 'object' || Object.keys(opts).some(k => k !== 'keepContext')) throw codedError('dispose-options', fmt(STRINGS.opts, { v: String(JSON.stringify(opts)) }));
55
60
  if (this.disposed) return;
56
- this.phase = 'disposed'; this.halted = true;
61
+ this.phase = 'disposed'; this.halted = true; this._starting = null; // a finished start() must not answer a later call as if the engine were alive
57
62
  cancelAnimationFrame(this._raf);
58
- dropOwned(this, [...(this._owned?.values() ?? [])]); // owned.js keeps a page-wide list for allowOwned
63
+ // one step that throws must not leave the renderer, the UI and the listeners alive: a game's 'dispose' listener on a material reaches here, and three calls it inside m.dispose()
64
+ const tidy = fn => { try { fn(); } catch (err) { reportError(this, err, coded('module-dispose', fmt(STRINGS.part, { why: String(err?.message ?? err) })), { soft: true }); } };
65
+ tidy(() => dropOwned(this, [...(this._owned?.values() ?? [])])); // owned.js keeps a page-wide list for allowOwned
59
66
  for (const m of [...this.modules.values()].reverse()) {
60
67
  this._modState.set(m.name, 'disposed');
61
68
  this._dropTracked(m.name); // its listeners / timers go first, so nothing calls into the module while its dispose tears it down
@@ -63,27 +70,25 @@ export const lifecycleMethods = {
63
70
  try { m.dispose(this); } catch (err) { reportError(this, err, coded('module-dispose', fmt(STRINGS.failed, { name: m.name })), { soft: true }); }
64
71
  }
65
72
  this._abort.abort();
66
- this._untrackValidate();
67
- this._wraps?.dispose(); // engine.wrap: every wrapped method back on its object (a game object or api may outlive the engine)
68
- this._picture?.dispose(); // dev tool: its scene watchers go with the engine
69
- this.debug.dispose(); // before the scene is disposed: undoes every diagnostic override and view (puts swapped materials back)
70
- for (const part of [this.saves, this.audio, this.time, this.commits, this.jobs, this.threads, this.stream, this.batching, this.rays, this.events]) part.dispose();
73
+ tidy(() => this._untrackValidate());
74
+ tidy(() => this._wraps?.dispose()); // engine.wrap: every wrapped method back on its object (a game object or api may outlive the engine)
75
+ tidy(() => this._picture?.dispose()); // dev tool: its scene watchers go with the engine
76
+ tidy(() => this.debug.dispose()); // before the scene is disposed: undoes every diagnostic override and view (puts swapped materials back)
77
+ for (const part of [this.saves, this.audio, this.time, this.commits, this.jobs, this.threads, this.stream, this.batching, this.rays, this.events]) tidy(() => part.dispose());
71
78
  clearHooks(this); this._afterTick = null;
72
- this.scene.traverse(disposeObject);
79
+ this.scene.traverse(o => disposeObject(o, tidy));
73
80
  // scene.environment is never disposed here: the engine's own maps (sky PMREM targets, the baseline room map) were freed above by their
74
81
  // owners, and anything else is the game's texture (a direct scene.environment write), which stays the game's to free
75
82
  this.scene.environment = null;
76
- if (this.scene.background?.isTexture) this.scene.background.dispose();
77
- this.assets.dispose();
78
- this.occlusion.dispose();
79
- this.post.dispose();
80
- this._webglOnlyView?.remove(); this._webglOnlyView = null;
81
- this._gpu?.dispose();
82
- this.renderer.dispose();
83
- if (this._ownsRenderer && !opts.keepContext) { releaseContext(this.renderer); released.add(this.renderer.domElement); }
84
- this.ui._dispose();
85
- this._materials.remove();
86
- this._uiStyle.remove();
83
+ tidy(() => { if (this.scene.background?.isTexture) this.scene.background.dispose(); });
84
+ for (const part of [this.assets, this.occlusion, this.post]) tidy(() => part.dispose());
85
+ tidy(() => this._webglOnlyView?.remove()); this._webglOnlyView = null;
86
+ tidy(() => this._gpu?.dispose());
87
+ tidy(() => this.renderer.dispose());
88
+ tidy(() => { if (this._ownsRenderer && !opts.keepContext) { releaseContext(this.renderer); released.add(this.renderer.domElement); } });
89
+ tidy(() => this.ui._dispose());
90
+ tidy(() => this._materials.remove());
91
+ tidy(() => this._uiStyle.remove());
87
92
  this.uiRoot.remove();
88
93
  },
89
94
 
@@ -12,6 +12,7 @@
12
12
  //
13
13
  // Determinism: in engine.step() and headless loading frames, jobs ignore the real-time budget and drain the queue (see Jobs.js),
14
14
  // and stream's synchronous builds are attached to the scene before step returns: same input and same seed (engine.random) give the same result.
15
+ import { Vector4 } from 'three';
15
16
  import { reportError } from '../base/errors.js';
16
17
  import { DEV, warnOnce, fmt } from '../base/validate.js';
17
18
  import { coded, codedError } from '../base/errorHints.js';
@@ -33,19 +34,34 @@ const MAX_CATCHUP = 0.1;
33
34
  const CATCHUP_MS = STEP * 2000;
34
35
  // Dev message (console): which hook failed
35
36
  const STRINGS = {
36
- onFixed: 'onFixed callback', commits: 'background result apply (commits)', onFrame: 'onFrame callback', animate: 'animator update', onRender: 'onRender callback', clock: 'clock timer', render: 'render',
37
+ onFixed: 'onFixed callback', onFrame: 'onFrame callback', animate: 'animator update', onRender: 'onRender callback', clock: 'clock timer', render: 'render',
37
38
  hook: '{kind} hook of module {name}',
38
39
  stepStart: 'engine.step() ran while start() is still loading: no game time passes, only frame hooks run. Wait for it first: await engine.start(); engine.step(1)',
39
40
  stepSession: 'engine.step() ran while a new game, load or quit is still replacing the state: the step plays on a half-replaced world. Wait for it first: await engine.session.load(slot); engine.step(1)',
40
41
  };
41
42
 
42
43
  const SOFT = { soft: true }; // core steps (render, stream): report once only
44
+ const _viewport = new Vector4(), _scissor = new Vector4();
43
45
  /** Call a hook fn.call(self, a, b); errors go to reportError for tiering.
44
46
  * opts: { module } the failing module / SOFT / null (game callback, counts as gameplay).
45
47
  * Takes no ...args and needs no caller closure: the main loop calls this many times a frame, so it must not allocate each time. */
46
48
  function safe(engine, key, fn, opts, self, a, b) {
47
49
  try { fn.call(self, a, b); } catch (err) { reportError(engine, err, key, opts ?? undefined); }
48
50
  }
51
+ /**
52
+ * One engine.onRender hook. What a hook borrows to draw (the target, viewport, scissor, autoClear, scene.overrideMaterial, camera.layers) it gives back on its last lines, which a
53
+ * throw skips, and the engine's frame then draws into an 8-pixel corner or in one flat material from there on. So a hook that throws has them put back. One that returns
54
+ * is taken at its word: what it left is the game's choice.
55
+ */
56
+ function drawHook(f, ctx) {
57
+ const { renderer: r, scene, camera } = ctx, target = r.getRenderTarget(), viewport = r.getViewport(_viewport), scissor = r.getScissor(_scissor), scissorTest = r.getScissorTest();
58
+ const { autoClear } = r, { overrideMaterial } = scene, { mask } = camera.layers;
59
+ try { f(ctx); } catch (err) {
60
+ r.setRenderTarget(target); r.setViewport(viewport); r.setScissor(scissor); r.setScissorTest(scissorTest);
61
+ r.autoClear = autoClear; scene.overrideMaterial = overrideMaterial; camera.layers.mask = mask;
62
+ throw err;
63
+ }
64
+ }
49
65
  /** Run one game callback list. remove() replaces the list, so a hook an earlier one removed in this pass (or a dispose) is skipped: it may sit on what its remover just tore down */
50
66
  function runList(e, name, key, a) {
51
67
  const list = e[name];
@@ -74,7 +90,7 @@ export const loopMethods = {
74
90
  this.time._beginStep(); // the one counter (core/time/time.js): this step's commits, ops and input records carry the new tick
75
91
  this._inFixed = true; // ops log phase 'fixed' and the dev guard lets gameplay writes through
76
92
  // due background results first, so this step's gameplay sees them; an engine stepped by hand before start() applies none (start() rebases them)
77
- if (this.ready) safe(this, STRINGS.commits, this.commits.tick, null, this.commits, this.time.tick);
93
+ if (this.ready) this.commits.tick(this.time.tick);
78
94
  runList(this, '_fixed', STRINGS.onFixed, STEP);
79
95
  this._runHooks('fixed', STEP);
80
96
  runList(this, '_fixedLate', STRINGS.onFixed, STEP); // onFixed({ phase: 'late' }): reads this step's result
@@ -120,14 +136,14 @@ export const loopMethods = {
120
136
  if (own) own.inside++;
121
137
  this._poses.draw(); // moving things draw between the last two fixed steps (stepPoses.js); undone below, gameplay never sees it
122
138
  try {
123
- for (const f of before) { safe(this, STRINGS.onRender, f, null, undefined, ctx); r.setRenderTarget(null); }
139
+ for (const f of before) { safe(this, STRINGS.onRender, drawHook, null, undefined, f, ctx); r.setRenderTarget(null); }
124
140
  this.shadows._frame(); // a game light's cascades, after 'before': picture code aims its light there, and the placement must be what is drawn (render/shadows.js)
125
141
  this._checkBackendAdds(); // WebGPU route: a WebGL-only material added since the last frame is named, not drawn blank (startup.js)
126
142
  freshFrame(r); // WebGPU: step() several times in one task, or a renderOnce() earlier in this tick, must not reuse that scene pass
127
143
  if (this._picture) this._picture.drawing = true;
128
144
  if (draws) { this.batching.skip(); try { this.post.render(dt); } finally { this.batching.unskip(); } }
129
145
  if (this._picture) this._picture.drawing = false;
130
- for (const f of after) safe(this, STRINGS.onRender, f, null, undefined, ctx);
146
+ for (const f of after) safe(this, STRINGS.onRender, drawHook, null, undefined, f, ctx);
131
147
  } finally { this._poses.undraw(); if (own) own.inside--; this._picture?.frameEnd(); }
132
148
  gpu?.end();
133
149
  // frames that first draw new objects pay their GPU upload here (Budget.js ApplyCost); a frame that compiled shaders is not judged by adaptive resolution
@@ -290,3 +306,5 @@ export const loopMethods = {
290
306
  // Adaptive resolution (core/scene/adaptive.js): judged on frame cost; tests drive it with explicit cost / compiled values
291
307
  _adapt(dt, cost = Math.max(this._cpuMs, this._gpu?.ms ?? 0), compiled = !!this._compiled, gpuKnown = this._gpu?.ms != null) { adapt(this, dt, cost, compiled, gpuKnown); },
292
308
  };
309
+
310
+ export const handRolled = [{ kind: 'loop', seen: 'a requestAnimationFrame game loop of its own', use: 'engine.onFrame(dt => ...) for what is seen, engine.onFixed(dt => ...) for rules: pause, step, tests and saves follow them', code: /\brequestAnimationFrame\s*\(\s*[\w.]+\s*\)|\.setAnimationLoop\s*\(/ }];
@@ -15,13 +15,31 @@ const STRINGS = {
15
15
  notSlot: 'module {name} provides \'{slot}\', but \'{slot}\' is a shared value (kind {kind}), not an exclusive slot; pick a slot name of its own, or change the value with ctx.mod(\'{slot}\', { ... })',
16
16
  noHolder: 'engine.use(..., { replaces: \'{slot}\' }): no installed module provides \'{slot}\', so there is nothing to replace. Fix: drop { replaces }, or check the slot name (describe().shared lists the slots held now)',
17
17
  notProvided: 'engine.use(..., { replaces: \'{slot}\' }): none of the modules in this call provides \'{slot}\', so the swap would leave it empty. Fix: add provides: [\'{slot}\'] to the module that takes over from {holder}',
18
- byName: 'engine.use(..., { replaces }): module {name} requires module \'{dep}\' by its name, and the swap unloads {dep}. Fix: in {name}, require the slot (requires: [\'<slot>\']) instead of the module name',
18
+ tooLate: "this module change takes '{slot}' away: {why}, and '{slot}' owns what they stand on, so it cannot leave or be replaced under them; nothing was changed. Fix: install your {slot} before the modules that need it: engine.use(my{slot}(), ...) first, or { replaces: '{slot}' } while nothing else is installed and before start()",
19
+ nameTaken: 'engine.use(..., { replaces: \'{slot}\' }): module {name} is already installed and does not hold \'{slot}\', so this call would unload {holder} and install nothing. Fix: give the newcomer another name, or unload the installed {name} first',
19
20
  unuse: 'dispose hook of module {name} (unloaded by replaces)',
20
21
  misspelt: "picture module {name} provides '{slot}', which is not a picture slot, so no other part collides with it and the writers tool cannot see it. Fix: provides: ['{hint}'] (the slots: {list})",
22
+ taken: "slot '{slot}' is held by module {holder}, so module {name} cannot provide it. Fix: engine.use({name}(), { replaces: '{slot}' }) (unloads {holder} cleanly), or install only one of them",
21
23
  notIn: "engine.unuse('{name}'): no such module is installed. Installed: {list}",
22
- needed: "engine.unuse('{name}'): module {dep} requires '{slot}', and nothing else provides it. Fix: unload {dep} first, or swap in another provider: engine.use(mine(), { replaces: '{slot}' })",
24
+ needed: "engine.unuse('{gone}'): module {name} requires '{dep}', and nothing else provides it. Fix: unload {name} first, or swap in another provider: engine.use(mine(), { replaces: '{dep}' })",
25
+ gaps: "module {name} provides '{cap}' but lacks {missing}, which the '{cap}' contract lists; a caller of one of those crashes. Fix: add them to {name}'s API (engine.catalog('{name}').problems lists them)",
23
26
  };
24
27
 
28
+ /** Slots named after a core service: the claim is exclusive like any other, but engine.<slot> stays the core API (engine.ground is what everyone reads,
29
+ * and a provider writes it with ctx.ground.provide), so it never becomes an alias of the provider */
30
+ export const CORE_SLOTS = new Set(['ground']);
31
+ /** Slots whose holder owns what every other module stands on: what they built in it cannot move to a new holder, so a swap comes before they are there or not at all */
32
+ const FOUNDATION_SLOTS = new Set(['world']);
33
+
34
+ /** capability -> its contract (the existing contract files, filled by index.js: core imports no module). Read only where a capability binds, on module changes */
35
+ export const CAP_CONTRACTS = new Map();
36
+
37
+ /** Who answers to a capability in this list: the module of that name, or the module that provides it. The one reading of a name in requires, before, after, has and usable */
38
+ export const giversOf = (mods, cap) => mods.filter(m => m.name === cap || m.provides?.includes(cap));
39
+
40
+ /** The error for a second provider of a slot, found in the graph before anything is touched */
41
+ export const slotTaken = (slot, holder, name) => codedError('shared-taken', fmt(STRINGS.taken, { slot, holder, name }));
42
+
25
43
  /** engine.use(a(), b(), { replaces: 'sky' }): the options object is the last argument and has `replaces` (a module always has a name) */
26
44
  export const isUseOpts = o => !!o && typeof o === 'object' && !Array.isArray(o) && !('name' in o) && 'replaces' in o;
27
45
 
@@ -39,23 +57,62 @@ export function checkProvides(m) {
39
57
  export const slotMethods = {
40
58
  /**
41
59
  * @internal engine.use(mod, { replaces }): the installed modules that hold these slots, after checking the swap is well formed
42
- * (the slot is held, the newcomer provides it, no installed module requires the old one by its module name).
60
+ * (the slot is held, the newcomer provides it); what else the holder gave is _planChange's to check.
43
61
  * @returns {Set<string>} module names to unload
44
62
  */
45
63
  _replaced(list, replaces) {
46
64
  const gone = new Set();
47
65
  if (replaces == null) return gone;
48
- const provided = new Set(list.flatMap(m => m?.provides ?? []));
49
- for (const slot of [].concat(replaces)) {
50
- const holder = this.stacks.has(slot) && this.stacks.get(slot).kind === 'one' ? this.stacks.get(slot).value() : null;
51
- if (!holder || !this.modules.has(holder)) throw codedError('module-replaces', fmt(STRINGS.noHolder, { slot }));
52
- if (!provided.has(slot)) throw codedError('module-replaces', fmt(STRINGS.notProvided, { slot, holder }));
66
+ const slots = [].concat(replaces), holderOf = slot => [...this.modules.values()].find(m => m.provides?.includes(slot))?.name;
67
+ for (const slot of slots) {
68
+ // read from the module table, not the shared point: a provider whose init failed gave its slot back but is still what a replaces swaps out
69
+ const holder = holderOf(slot);
70
+ if (!holder) throw codedError('module-replaces', fmt(STRINGS.noHolder, { slot }));
53
71
  gone.add(holder);
54
72
  }
55
- for (const m of this.modules.values()) for (const dep of m.requires ?? []) if (gone.has(dep) && !gone.has(m.name) && !list.some(n => n?.name === dep) && !provided.has(dep))
56
- throw codedError('module-replaces', fmt(STRINGS.byName, { name: m.name, dep }));
73
+ // a factory's sibling: listed again under its name and built on a module that leaves. _planUse skips a name that stays, which would leave the old sibling bound to the holder
74
+ // that went and the new one never installed. Each pass may reach a sibling of a sibling
75
+ const leaving = dep => gone.has(dep) || [...gone].some(n => this.modules.get(n).provides?.includes(dep));
76
+ for (let grew = true; grew;) {
77
+ grew = false;
78
+ for (const m of list) {
79
+ const old = m?.name && this.modules.get(m.name);
80
+ if (old && old !== m && !gone.has(m.name) && old.requires?.some(leaving)) { gone.add(m.name); grew = true; }
81
+ }
82
+ }
83
+ for (const slot of slots) {
84
+ const givers = list.filter(m => m?.provides?.includes(slot)), holder = holderOf(slot);
85
+ if (!givers.length) throw codedError('module-replaces', fmt(STRINGS.notProvided, { slot, holder }));
86
+ // _planUse skips a name that stays installed, so that newcomer would never come
87
+ if (givers.every(m => this.modules.has(m.name) && !gone.has(m.name))) throw codedError('module-replaces', fmt(STRINGS.nameTaken, { slot, name: givers[0].name, holder }));
88
+ }
57
89
  return gone;
58
90
  },
91
+ /** @internal a foundation slot leaves or is swapped only before start and before a module that stays names it in requires or optional. engine.dispose does not pass here */
92
+ _refuseLate(slot, holder, gone, code) {
93
+ const names = m => [...(m.requires ?? []), ...(Array.isArray(m.optional) ? m.optional : Object.keys(m.optional ?? {}))];
94
+ const users = [...this.modules.values()].filter(m => !gone.has(m.name) && names(m).some(n => n === slot || n === holder)).map(m => m.name);
95
+ const why = users.length ? `${users.join(', ')} already use it` : this.ready || this._starting ? 'the game has started' : null;
96
+ if (why) throw codedError(code, fmt(STRINGS.tooLate, { slot, why }));
97
+ },
98
+ /**
99
+ * @internal the one gate of every module change (use, unuse, replaces, plugin on / off): the batch is validated, then the graph after the change is worked out and every
100
+ * module in it, kept or new, must still find what it requires. Nothing is touched before this returns. A whole set goes in at once: a plugin may own both provider and consumer.
101
+ * @param {any[]} list modules to add
102
+ * @param {Set<string>} gone modules that leave
103
+ * @param {{ code: string, text: string }} refusal the error when a consumer would lose a provider; text gets {gone}, {name}, {dep}
104
+ * @returns {any[]} the modules to install
105
+ */
106
+ _planChange(list, gone, refusal) {
107
+ const plan = this._planUse(list, gone);
108
+ if (!gone.size) return plan; // nothing leaves, so no kept module can lose anything
109
+ for (const name of gone) for (const slot of this.modules.get(name)?.provides ?? []) if (FOUNDATION_SLOTS.has(slot)) this._refuseLate(slot, name, gone, refusal.code);
110
+ const after = [...[...this.modules.values()].filter(m => !gone.has(m.name)), ...plan];
111
+ const caps = new Set(after.flatMap(m => [m.name, ...(m.provides ?? [])]));
112
+ for (const m of after) for (const dep of m.requires ?? []) if (!caps.has(dep))
113
+ throw codedError(refusal.code, fmt(refusal.text, { gone: [...gone].join(', '), name: m.name, dep }));
114
+ return plan;
115
+ },
59
116
  /**
60
117
  * Unload one installed module: its tracked handles, its slots and ctx.mod entries, its dispose. What it added some other way stays (dev reports a picture module's
61
118
  * leftovers). To swap a holder use engine.use(mine(), { replaces: 'slot' }).
@@ -65,10 +122,8 @@ export const slotMethods = {
65
122
  unuse(name) {
66
123
  const m = this.modules.get(name);
67
124
  if (!m) throw codedError('module-unuse', fmt(STRINGS.notIn, { name, list: [...this.modules.keys()].join(', ') || 'none' }));
68
- const gives = [name, ...(m.provides ?? [])], others = [...this.modules.values()].filter(o => o !== m);
69
- for (const o of others) for (const dep of o.requires ?? []) if (gives.includes(dep) && !others.some(p => p.name === dep || p.provides?.includes(dep)))
70
- throw codedError('module-unuse', fmt(STRINGS.needed, { name, dep: o.name, slot: dep }));
71
- this._unuse(name);
125
+ const gone = new Set([name]);
126
+ this._applyChange(this._planChange([], gone, { code: 'module-unuse', text: STRINGS.needed }), gone);
72
127
  },
73
128
  /**
74
129
  * @internal unload one installed module (engine.unuse, replaces, a plugin taken out): tracked handles and slots, drawing parts, its dispose, the engine property;
@@ -79,7 +134,7 @@ export const slotMethods = {
79
134
  this._dropTracked(name);
80
135
  try { m.dispose?.(this); } catch (err) { reportError(this, err, fmt(STRINGS.unuse, { name }), { soft: true }); }
81
136
  this._picture?.partGone(m, swapping);
82
- this.modules.delete(name); this._modState.delete(name); this._modInst.delete(name); this.disabledModules.delete(name); delete this[name];
137
+ this.modules.delete(name); this._modState.delete(name); this._modInst.delete(name); delete this[name];
83
138
  this._sortHooks();
84
139
  return m;
85
140
  },
@@ -90,6 +145,27 @@ export const slotMethods = {
90
145
  },
91
146
  /** @internal is this capability provided by an installed module? */
92
147
  _provided(slot) { for (const m of this.modules.values()) if (m.provides?.includes(slot)) return true; return false; },
148
+ /**
149
+ * @internal every bound capability whose running provider lacks part of its contract: [{ cap, module, missing }]. Bound means a module says provides or requires, so a game's own
150
+ * module that merely shares a name with an engine capability is left alone. Why running and not installed: a provider may fill its API in init. Why this reads the API and calls
151
+ * nothing: the behavior half of a contract is the tools/contract check, and a method on a live game must not run just to be looked at.
152
+ */
153
+ _contractGaps() {
154
+ const mods = [...this.modules.values()], gaps = new Map();
155
+ for (const cap of new Set(mods.flatMap(m => [...(m.provides ?? []), ...(m.requires ?? [])]))) {
156
+ const c = CAP_CONTRACTS.get(cap), p = c && giversOf(mods, cap).find(g => this._modState.get(g.name) === 'running');
157
+ if (!p) continue;
158
+ const api = Object(this[p.name]);
159
+ const missing = [...c.api.filter(k => typeof api[k] !== 'function'), ...(c.fields ?? []).filter(k => !(k in api))];
160
+ if (missing.length) gaps.set(cap, { cap, module: p.name, missing });
161
+ }
162
+ return [...gaps.values()];
163
+ },
164
+ /** @internal dev: say each gap once. A warning and not a refusal: a partial provider that serves its game ran before this check existed, and only the game knows what it calls */
165
+ _warnContractGaps() {
166
+ if (DEV) for (const g of this._contractGaps())
167
+ warnOnce(coded('module-contract', fmt(STRINGS.gaps, { name: g.module, cap: g.cap, missing: g.missing.join(', ') })), `module-contract:${g.cap}:${g.module}`);
168
+ },
93
169
  /** @internal the exclusive slot a module provides (a 'one' shared point, made on first use) */
94
170
  _slot(slot, by) {
95
171
  if (!this.stacks.has(slot)) return this.stacks.define(slot, { kind: 'one', save: false });
@@ -24,7 +24,13 @@ export const MODULE_TYPES = {
24
24
  tool: 'a one-shot job (a photo, a bake) that undoes itself when it ends or fails',
25
25
  };
26
26
 
27
+ /** How engine.skip advances a module (the skipKind field): what each word means is on ModuleDefinition in types/core.d.ts */
28
+ export const SKIP_KINDS = ['exact', 'approx', 'step', 'none'];
29
+ /** The time hooks a module definition may carry (engine.catalog and the generated metadata list the ones a module has) */
30
+ export const TIME_HOOKS = ['fixed', 'frame', 'afterRender', 'skip', 'afterLoad'];
31
+
27
32
  const STRINGS = {
33
+ badSkip: "module {name} has skipKind '{kind}'. Fix: use one of {list}",
28
34
  unknown: "module {name} has type '{type}', which is not a module type. Fix: use one of {list}",
29
35
  // rule broken at runtime: module, type, what it did, why not, the fix
30
36
  broke: "module {name} (type '{type}') {did}: {why}. Fix: {fix}",
@@ -45,6 +51,7 @@ const RULES = {
45
51
  export function checkType(m) {
46
52
  m.type ??= 'rules';
47
53
  if (!Object.hasOwn(MODULE_TYPES, m.type)) throw codedError('module-type', fmt(STRINGS.unknown, { name: m.name, type: String(m.type), list: Object.keys(MODULE_TYPES).map(t => `'${t}'`).join(' | ') }));
54
+ if (m.skipKind !== undefined && !SKIP_KINDS.includes(m.skipKind)) throw codedError('module-type', fmt(STRINGS.badSkip, { name: m.name, kind: String(m.skipKind), list: SKIP_KINDS.map(k => `'${k}'`).join(' | ') }));
48
55
  }
49
56
 
50
57
  /**
@@ -67,6 +74,12 @@ export function asModule(e, m, fn) {
67
74
  try { return fn(); } finally { e._curModule = was; }
68
75
  }
69
76
 
77
+ /**
78
+ * @internal For a shared service a module calls without its ctx (engine.settings.define): the handle goes on the running module's ctx.track, the one list its things leave by.
79
+ * Nothing when no module is running. The engine knows the module only during its synchronous code, so what an async callback makes counts as the game's.
80
+ */
81
+ export function trackForModule(e, h) { if (e._curModule) e._modCtx(e._curModule).track(h); }
82
+
70
83
  /**
71
84
  * @internal dev: a frame hook registered while a module installs stays that module's: it runs as the module, so the picture writers tool can tell two parts in one
72
85
  * file apart (a stack cannot) and the type checks reach it. part / at let the leftovers check find a hook that outlived its module. Outside dev fn stays as it is.